main.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. @app.get("/index2")
  66. async def index2():
  67. return FileResponse('static/index2.html')
  68. @app.get("/gen_avatar")
  69. async def avatar():
  70. return FileResponse('static/gen_avatar.html')
  71. @app.post("/swapFace")
  72. async def swapFace(req:swap_req):
  73. '''
  74. sf = swap_face(req.imgurl)
  75. result = sf.run()
  76. #notify_group(result)hi
  77. '''
  78. if 'http' not in req.imgurl:
  79. req.imgurl= 'http://'+req.imgurl
  80. try:
  81. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  82. im= im.convert("RGB")
  83. except:
  84. return {'msg':"無法辨別圖片網址"+req.imgurl}
  85. name_hash = str(time.time()).replace('.','')
  86. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  87. im= im.convert("RGB")
  88. im.save('../../face_swap/tmp_face/'+name_hash+'.jpg')
  89. x = threading.Thread(target=gen_avatar, args=(name_hash,req.imgurl))
  90. x.start()
  91. return {'msg':'人物生成中,請稍候'}
  92. @app.post("/uploadfile/")
  93. async def create_upload_file(file: UploadFile = File(...)):
  94. img_name = str(time.time()).replace('.','')
  95. try:
  96. contents = await file.read()
  97. image = Image.open(io.BytesIO(contents))
  98. image= image.convert("RGB")
  99. image.save(img_upload_folder+img_name+'.jpg')
  100. except:
  101. return {'msg':'檔案無法使用'}
  102. return {"msg": 'www.choozmo.com:8168/'+tmp_img_sub_folder+img_name+'.jpg'}
  103. @app.post("/make_anchor_video_v2")
  104. async def make_anchor_video_v2(req:request):
  105. for idx in range(len(req.image_urls)):
  106. if 'http' not in req.image_urls[idx]:
  107. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  108. for txt in req.text_content:
  109. if re.search('[a-zA-Z]', txt) !=None:
  110. return {'msg':'輸入字串不能包含英文字!'}
  111. name_hash = str(time.time()).replace('.','')
  112. for imgu in req.image_urls:
  113. try:
  114. if get_url_type(imgu) =='video/mp4':
  115. r=requests.get(imgu)
  116. else:
  117. im = Image.open(requests.get(imgu, stream=True).raw)
  118. im= im.convert("RGB")
  119. except:
  120. return {'msg':"無法辨別圖片網址"+imgu}
  121. save_history(req,name_hash)
  122. x = threading.Thread(target=gen_video, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.client_id))
  123. x.start()
  124. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  125. @app.get("/history_input")
  126. async def history_input():
  127. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  128. statement = 'SELECT * FROM history_input ORDER BY timestamp DESC LIMIT 50'
  129. logs = []
  130. for row in db.query(statement):
  131. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  132. return logs
  133. def save_history(req,name_hash):
  134. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  135. log_table = db['history_input']
  136. txt_content_seperate_by_dot = ''
  137. for txt in req.text_content:
  138. txt_content_seperate_by_dot += txt+","
  139. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  140. img_urls_seperate_by_dot = ''
  141. for iurl in req.image_urls:
  142. img_urls_seperate_by_dot += iurl+","
  143. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  144. time_stamp = datetime.fromtimestamp(time.time())
  145. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  146. 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})
  147. def get_url_type(url):
  148. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  149. r = urllib.request.urlopen(req)
  150. contentType = r.getheader('Content-Type')
  151. return contentType
  152. def gen_video(name_hash,name,text_content, image_urls,avatar,client_id):
  153. c = rpyc.connect("localhost", 8878)
  154. c._config['sync_request_timeout'] = None
  155. remote_svc = c.root
  156. my_answer = remote_svc.call_video(name_hash,name,text_content, image_urls,avatar,client_id) # method call
  157. shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
  158. os.remove(tmp_video_dir+name_hash+'.mp4')
  159. def gen_avatar(name_hash, imgurl):
  160. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  161. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  162. while True:
  163. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  164. statement = 'SELECT * FROM avatar_service_status'
  165. status = -1
  166. for row in db.query(statement):
  167. status = row['status']
  168. if status == 1:
  169. print('leave process loop')
  170. break
  171. statement = 'SELECT * FROM avatar_queue'
  172. works = []
  173. for row in db.query(statement):
  174. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':['imgurl']})
  175. if len(works)==0:
  176. print('leave process loop')
  177. break
  178. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  179. db.query(statement)
  180. name_hash = works[0]['name_hash']
  181. imgurl = works[0]['imgurl']
  182. c = rpyc.connect("localhost", 8868)
  183. c._config['sync_request_timeout'] = None
  184. remote_svc = c.root
  185. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  186. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  187. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  188. db['avatar_queue'].delete(id=works[0]['id'])
  189. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;'
  190. db.query(statement)