main.py 15 KB

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