main.py 14 KB

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