main.py 4.3 KB

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