main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. from fastapi import FastAPI,Cookie, Depends, FastAPI, Query, WebSocket, status, WebSocketDisconnect,File, UploadFile
  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. import io
  31. #test
  32. app = FastAPI()
  33. origins = [
  34. "https://hhh.com.tw"
  35. "http://172.105.205.52",
  36. "http://172.105.205.52:8001",
  37. "http://172.104.93.163",
  38. ]
  39. app.add_middleware(
  40. CORSMiddleware,
  41. # allow_origins=origins,
  42. allow_origins=["*"],
  43. allow_credentials=True,
  44. allow_methods=["*"],
  45. allow_headers=["*"],
  46. )
  47. app.mount("/static", StaticFiles(directory="static"), name="static")
  48. app.mount("/static/img", StaticFiles(directory="static/img"), name="static/img")
  49. tmp_video_dir = '../OpenshotService/tmp_video/'
  50. tmp_avatar_dir = '../../face_swap/tmp_avatar/' #change source face path here
  51. video_sub_folder = 'ai_anchor_video/'
  52. avatar_sub_folder = 'swap_save/'
  53. tmp_img_sub_folder = 'tmp_img/'
  54. img_upload_folder = '/var/www/html/'+tmp_img_sub_folder
  55. video_dest = '/var/www/html/'+video_sub_folder
  56. avatar_dest = '/var/www/html/'+avatar_sub_folder
  57. class swap_req(BaseModel):
  58. imgurl: str
  59. class request(BaseModel):
  60. name: str
  61. text_content: List[str]
  62. image_urls: List[str]
  63. avatar: str
  64. client_id :str
  65. class request_eng(BaseModel):
  66. name: str
  67. text_content: List[str]
  68. image_urls: List[str]
  69. sub_titles: List[str]
  70. avatar: str
  71. client_id :str
  72. @app.get("/index2")
  73. async def index2():
  74. return FileResponse('static/index2.html')
  75. @app.get("/index_eng")
  76. async def index2():
  77. return FileResponse('static/index_eng.html')
  78. @app.get("/gen_avatar")
  79. async def avatar():
  80. return FileResponse('static/gen_avatar.html')
  81. @app.post("/swapFace")
  82. async def swapFace(req:swap_req):
  83. '''
  84. sf = swap_face(req.imgurl)
  85. result = sf.run()
  86. #notify_group(result)hi
  87. '''
  88. if 'http' not in req.imgurl:
  89. req.imgurl= 'http://'+req.imgurl
  90. try:
  91. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  92. im= im.convert("RGB")
  93. except:
  94. return {'msg':"無法辨別圖片網址"+req.imgurl}
  95. name_hash = str(time.time()).replace('.','')
  96. x = threading.Thread(target=gen_avatar, args=(name_hash,req.imgurl))
  97. x.start()
  98. return {'msg':'人物生成中,請稍候'}
  99. @app.post("/uploadfile/")
  100. async def create_upload_file(file: UploadFile = File(...)):
  101. img_name = str(time.time()).replace('.','')
  102. try:
  103. contents = await file.read()
  104. image = Image.open(io.BytesIO(contents))
  105. image= image.convert("RGB")
  106. image.save(img_upload_folder+img_name+'.jpg')
  107. except:
  108. return {'msg':'檔案無法使用'}
  109. return {"msg": 'www.choozmo.com:8168/'+tmp_img_sub_folder+img_name+'.jpg'}
  110. @app.post("/make_anchor_video_v2")
  111. async def make_anchor_video_v2(req:request):
  112. for idx in range(len(req.image_urls)):
  113. if 'http' not in req.image_urls[idx]:
  114. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  115. for txt in req.text_content:
  116. if re.search('[a-zA-Z]', txt) !=None:
  117. return {'msg':'輸入字串不能包含英文字!'}
  118. name_hash = str(time.time()).replace('.','')
  119. for imgu in req.image_urls:
  120. try:
  121. if get_url_type(imgu) =='video/mp4':
  122. r=requests.get(imgu)
  123. else:
  124. im = Image.open(requests.get(imgu, stream=True).raw)
  125. im= im.convert("RGB")
  126. except:
  127. return {'msg':"無法辨別圖片網址"+imgu}
  128. save_history(req,name_hash)
  129. x = threading.Thread(target=gen_video_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar)))
  130. x.start()
  131. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  132. @app.post("/make_anchor_video_eng")
  133. async def make_anchor_video_eng(req:request_eng):
  134. for idx in range(len(req.image_urls)):
  135. if 'http' not in req.image_urls[idx]:
  136. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  137. name_hash = str(time.time()).replace('.','')
  138. for imgu in req.image_urls:
  139. try:
  140. if get_url_type(imgu) =='video/mp4':
  141. r=requests.get(imgu)
  142. else:
  143. im = Image.open(requests.get(imgu, stream=True).raw)
  144. im= im.convert("RGB")
  145. except:
  146. return {'msg':"無法辨別圖片網址"+imgu}
  147. save_history(req,name_hash)
  148. x = threading.Thread(target=gen_video_eng, args=(name_hash,req.name, req.text_content, req.image_urls,req.sub_titles,int(req.avatar)))
  149. x.start()
  150. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  151. @app.get("/history_input")
  152. async def history_input():
  153. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  154. statement = 'SELECT * FROM history_input ORDER BY timestamp DESC LIMIT 50'
  155. logs = []
  156. for row in db.query(statement):
  157. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  158. return logs
  159. def save_history(req,name_hash):
  160. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  161. log_table = db['history_input']
  162. txt_content_seperate_by_dot = ''
  163. for txt in req.text_content:
  164. txt_content_seperate_by_dot += txt+","
  165. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  166. img_urls_seperate_by_dot = ''
  167. for iurl in req.image_urls:
  168. img_urls_seperate_by_dot += iurl+","
  169. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  170. time_stamp = datetime.fromtimestamp(time.time())
  171. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  172. 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/'+video_sub_folder+name_hash+'.mp4','timestamp':time_stamp})
  173. def get_url_type(url):
  174. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  175. r = urllib.request.urlopen(req)
  176. contentType = r.getheader('Content-Type')
  177. return contentType
  178. def notify_group(msg):
  179. glist=['WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD']
  180. for gid in glist:
  181. headers = {
  182. "Authorization": "Bearer " + gid,
  183. "Content-Type": "application/x-www-form-urlencoded"
  184. }
  185. params = {"message": msg}
  186. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  187. def gen_video(name_hash,name,text_content, image_urls,avatar):
  188. c = rpyc.connect("localhost", 8878)
  189. c._config['sync_request_timeout'] = None
  190. remote_svc = c.root
  191. my_answer = remote_svc.call_video(name_hash,name,text_content, image_urls,avatar) # method call
  192. shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
  193. os.remove(tmp_video_dir+name_hash+'.mp4')
  194. def gen_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar):
  195. c = rpyc.connect("localhost", 8878)
  196. c._config['sync_request_timeout'] = None
  197. remote_svc = c.root
  198. my_answer = remote_svc.call_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar) # method call
  199. shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
  200. os.remove(tmp_video_dir+name_hash+'.mp4')
  201. def gen_video_queue(name_hash,name,text_content, image_urls,avatar):
  202. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  203. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  204. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':text_content,'image_urls':image_urls,'avatar':avatar,'timestamp':time_stamp})
  205. while True:
  206. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  207. print('another process running, leave loop')
  208. break
  209. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  210. print('all finish, leave loop')
  211. break
  212. top1 = first(db.query('SELECT * FROM video_queue'))
  213. try:
  214. db.query('UPDATE video_queue_status SET status = 1;')
  215. c = rpyc.connect("localhost", 8868)
  216. c._config['sync_request_timeout'] = None
  217. remote_svc = c.root
  218. my_answer = remote_svc.call_video(top1['name_hash'],top1['name'],top1['text_content'], top1['image_urls'],top1['avatar']) # method call
  219. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  220. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  221. except:
  222. print('video generation error')
  223. notify_group('影片錯誤')
  224. db['video_queue'].delete(id=top1['id'])
  225. db.query('UPDATE video_queue_status SET status = 0')
  226. def gen_avatar(name_hash, imgurl):
  227. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  228. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  229. while True:
  230. statement = 'SELECT * FROM avatar_service_status'#only one row in this table, which is the id 1 one
  231. status = -1
  232. for row in db.query(statement):
  233. status = row['status']
  234. if status == 1:
  235. print('leave process loop')
  236. break
  237. statement = 'SELECT * FROM avatar_queue'
  238. works = []
  239. for row in db.query(statement):
  240. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':row['imgurl']})
  241. if len(works)==0:
  242. print('leave process loop')
  243. break
  244. try:
  245. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  246. db.query(statement)
  247. name_hash = works[0]['name_hash']
  248. imgurl = works[0]['imgurl']
  249. c = rpyc.connect("localhost", 8868)
  250. c._config['sync_request_timeout'] = None
  251. remote_svc = c.root
  252. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  253. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  254. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  255. except:
  256. print('gen error')
  257. notify_group('無法辨識人臉')
  258. db['avatar_queue'].delete(id=works[0]['id'])
  259. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;' #only one row in this table, which id 1 one
  260. db.query(statement)