main.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. from fastapi import FastAPI,Cookie, Depends, FastAPI, Query, WebSocket, status, WebSocketDisconnect
  2. from os import listdir
  3. from os.path import isfile, isdir, join
  4. import threading
  5. import zhtts
  6. import os
  7. import urllib
  8. from typing import List
  9. import requests
  10. from pydantic import BaseModel
  11. from bs4 import BeautifulSoup
  12. from PIL import Image,ImageDraw,ImageFont
  13. import pyttsx3
  14. import rpyc
  15. import random
  16. import time
  17. import math
  18. import hashlib
  19. import re
  20. import asyncio
  21. import urllib.request
  22. from fastapi.responses import FileResponse
  23. from websocket import create_connection
  24. from fastapi.middleware.cors import CORSMiddleware
  25. import dataset
  26. from datetime import datetime
  27. from util.swap_face import swap_face
  28. from fastapi.staticfiles import StaticFiles
  29. import shutil
  30. #test
  31. app = FastAPI()
  32. origins = [
  33. "https://hhh.com.tw"
  34. "http://172.105.205.52",
  35. "http://172.105.205.52:8001",
  36. "http://172.104.93.163",
  37. ]
  38. app.add_middleware(
  39. CORSMiddleware,
  40. # allow_origins=origins,
  41. allow_origins=["*"],
  42. allow_credentials=True,
  43. allow_methods=["*"],
  44. allow_headers=["*"],
  45. )
  46. app.mount("/static", StaticFiles(directory="static"), name="static")
  47. app.mount("/static/img", StaticFiles(directory="static/img"), name="static/img")
  48. tmp_video_dir = '../OpenshotService/tmp_video/'
  49. video_dest = '/var/www/html/'
  50. class swap_req(BaseModel):
  51. imgurl: str
  52. class request(BaseModel):
  53. name: str
  54. text_content: List[str]
  55. image_urls: List[str]
  56. avatar: str
  57. client_id :str
  58. @app.get("/index2")
  59. async def index2():
  60. return FileResponse('static/index2.html')
  61. @app.get("/gen_avatar")
  62. async def gen_avatar():
  63. return FileResponse('static/gen_avatar.html')
  64. @app.post("/swapFace")
  65. async def swapFace(req:swap_req):
  66. sf = swap_face(req.imgurl)
  67. result = sf.run()
  68. #notify_group(result)hi
  69. return result
  70. @app.post("/make_anchor_video_v2")
  71. async def make_anchor_video_v2(req:request):
  72. for txt in req.text_content:
  73. if re.search('[a-zA-Z]', txt) !=None:
  74. return {'msg':'輸入字串不能包含英文字!'}
  75. name_hash = str(time.time()).replace('.','')
  76. for imgu in req.image_urls:
  77. try:
  78. if get_url_type(imgu) =='video/mp4':
  79. r=requests.get(imgu)
  80. else:
  81. im = Image.open(requests.get(imgu, stream=True).raw)
  82. im= im.convert("RGB")
  83. except:
  84. return {'msg':"無法辨別圖片網址"+imgu}
  85. save_history(req,name_hash)
  86. x = threading.Thread(target=gen_video, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.client_id))
  87. x.start()
  88. return {"msg":"製作影片需要時間,請您耐心等候 稍後可以在www.choozmo.com:8168/"+name_hash+".mp4 中觀看"}
  89. @app.get("/history_input")
  90. async def history_input():
  91. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  92. statement = 'SELECT * FROM history_input ORDER BY timestamp DESC LIMIT 50'
  93. logs = []
  94. for row in db.query(statement):
  95. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  96. return logs
  97. def save_history(req,name_hash):
  98. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  99. log_table = db['history_input']
  100. txt_content_seperate_by_dot = ''
  101. for txt in req.text_content:
  102. txt_content_seperate_by_dot += txt+","
  103. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  104. img_urls_seperate_by_dot = ''
  105. for iurl in req.image_urls:
  106. img_urls_seperate_by_dot += iurl+","
  107. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  108. time_stamp = datetime.fromtimestamp(time.time())
  109. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  110. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'link':'www.choozmo.com:8168/'+name_hash+'.mp4','timestamp':time_stamp})
  111. def get_url_type(url):
  112. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  113. r = urllib.request.urlopen(req)
  114. contentType = r.getheader('Content-Type')
  115. return contentType
  116. def gen_video(name_hash,name,text_content, image_urls,avatar,client_id):
  117. c = rpyc.connect("localhost", 8878)
  118. remote_svc = c.root
  119. my_answer = remote_svc.call_video(name_hash,name,text_content, image_urls,avatar,client_id) # method call
  120. shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
  121. os.remove(tmp_video_dir+name_hash+'.mp4')