main.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. from fastapi import FastAPI,Cookie, Depends, Query, status,File, UploadFile,Request,Response,HTTPException
  2. from fastapi.templating import Jinja2Templates
  3. from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
  4. from pydantic import BaseModel
  5. from typing import List, Optional
  6. from os.path import isfile, isdir, join
  7. import threading
  8. import zhtts
  9. import os
  10. import urllib
  11. import requests
  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 fastapi.middleware.cors import CORSMiddleware
  25. import dataset
  26. from datetime import datetime, timedelta
  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. from passlib.context import CryptContext
  33. from jose import JWTError, jwt
  34. from fastapi_jwt_auth import AuthJWT
  35. from fastapi_jwt_auth.exceptions import AuthJWTException
  36. from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
  37. import util.models
  38. import pymysql
  39. import mailer
  40. from moviepy.editor import VideoFileClip
  41. import traceback
  42. import logging
  43. import gSlide
  44. import aiofiles
  45. import json
  46. import util.user
  47. pymysql.install_as_MySQLdb()
  48. app = FastAPI()
  49. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  50. print("db loaded")
  51. mode = 'run'
  52. app.add_middleware(
  53. CORSMiddleware,
  54. allow_origins=["*"],
  55. allow_credentials=True,
  56. allow_methods=["*"],
  57. allow_headers=["*"],
  58. )
  59. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  60. ALGORITHM = "HS256"
  61. ACCESS_TOKEN_EXPIRE_DAYS = 5
  62. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  63. app.mount("/static", StaticFiles(directory="static"), name="static")
  64. app.mount("/static/img", StaticFiles(directory="static/img"), name="static/img")
  65. app.mount("/templates", StaticFiles(directory="templates"), name="templates")
  66. templates = Jinja2Templates(directory="templates")
  67. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
  68. tmp_video_dir = '../OpenshotService/tmp_video/'
  69. tmp_avatar_dir = '../../face_swap/tmp_avatar/' #change source face path here
  70. resource_server = 'www.choozmo.com:8168/'
  71. resource_folder = '/var/www/html/'
  72. video_sub_folder = 'ai_anchor_video/'
  73. avatar_sub_folder = 'swap_save/'
  74. tmp_img_sub_folder = 'tmp_img/'
  75. pttx_sub_folder = 'tmp_pttx/'
  76. img_upload_folder = '/var/www/html/'+tmp_img_sub_folder
  77. video_dest = '/var/www/html/'+video_sub_folder
  78. avatar_dest = '/var/www/html/'+avatar_sub_folder
  79. pttx_dest = '/var/www/html/'+pttx_sub_folder
  80. # @app.get("/index2")
  81. # async def index2():
  82. # return FileResponse('static/index2.html')
  83. @app.get("/index_eng")
  84. async def index2():
  85. return FileResponse('static/index_eng.html')
  86. # home page
  87. @app.get("/index", response_class=HTMLResponse)
  88. async def get_home_page(request: Request, response: Response):
  89. return templates.TemplateResponse("index.html", {"request": request, "response": response})
  90. @app.get("/checkStatus")
  91. async def checkStatus():
  92. errorList = []
  93. try:
  94. conn = rpyc.classic.connect("192.168.1.105",18812)
  95. conn.close()
  96. except:
  97. errorList.append('105:18812 server')
  98. try:
  99. c = rpyc.connect("localhost", 8858)
  100. c.close()
  101. except:
  102. errorList.append('make_video(docker name : new openshot)')
  103. try:
  104. c = rpyc.connect("localhost", 8868)
  105. c.close()
  106. except:
  107. errorList.append('swap_face(docker name : fcontainer)')
  108. return {'errors':errorList}
  109. @app.get("/", response_class=HTMLResponse)
  110. async def get_home_page(request: Request, response: Response):
  111. return templates.TemplateResponse("index.html", {"request": request, "response": response})
  112. @app.get("/make_video")
  113. async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  114. try:
  115. Authorize.jwt_required()
  116. except Exception as e:
  117. print(e)
  118. return {'msg':{'eng':'Please login first','zh':'請先登入帳號'}}
  119. current_user = Authorize.get_jwt_subject()
  120. return templates.TemplateResponse("make_video.html", {"request": request, "response": response})
  121. @app.get("/make_video_long", response_class=HTMLResponse)
  122. async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  123. try:
  124. Authorize.jwt_required()
  125. except Exception as e:
  126. print(e)
  127. return {'msg':{'eng':'Please login first','zh':'請先登入帳號'}}
  128. current_user = Authorize.get_jwt_subject()
  129. return templates.TemplateResponse("make_video_long.html", {"request": request, "response": response})
  130. @app.get("/make_video_slide", response_class=HTMLResponse)
  131. async def make_video_slide(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  132. try:
  133. Authorize.jwt_required()
  134. except Exception as e:
  135. print(e)
  136. return {'msg':{'eng':'Please login first','zh':'請先登入帳號'}}
  137. current_user = Authorize.get_jwt_subject()
  138. return templates.TemplateResponse("make_video_slide.html", {"request": request, "response": response})
  139. @app.post('/user_profile', response_class=HTMLResponse)
  140. async def user_profile(token: str = Depends(oauth2_scheme)):
  141. db_check()
  142. user_id = get_user_id(token)
  143. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  144. if user_obj is None:
  145. raise HTTPException(
  146. status_code=status.HTTP_401_UNAUTHORIZED,
  147. detail="Missing token",
  148. headers={"WWW-Authenticate": "Bearer"},
  149. )
  150. video_num = str(first(db.query('SELECT COUNT(*) FROM history_input WHERE user_id ='+str(user_obj['id'])))['COUNT(*)'])
  151. total_sec = str(first(db.query('SELECT SUM(duration) FROM history_input where user_id='+str(user_obj['id'])))['SUM(duration)'])
  152. left_sec = user_obj['left_time']
  153. video_info_list = []
  154. statement = 'SELECT * FROM history_input WHERE user_id='+str(user_obj['id'])+' ORDER BY timestamp DESC LIMIT 50'
  155. for row in db.query(statement):
  156. video_info_list.append({'id':row['id'],'title':row['name'],'duration':row['duration'],'url':row['link'],'time_stamp':row['timestamp'].strftime("%m/%d/%Y, %H:%M:%S")})
  157. dic_return = {'user_info':{'id':user_id,'userName':user_obj['username'],'email':user_obj['email'],'video_num':video_num,'total_sec':total_sec,'left_sec':user_obj['left_time']},'video_info':video_info_list}
  158. str_return = json.dumps(dic_return)
  159. return str_return
  160. @app.post('/edit_profile')
  161. async def edit_profile(userModel : util.models.UserProfile ,token: str = Depends(oauth2_scheme)):
  162. db_check()
  163. print(token)
  164. user_id = get_user_id(token)
  165. print(user_id)
  166. user_obj = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  167. user_obj['email'] = userModel.email
  168. db['users'].update(user_obj,['id'])
  169. return {'msg':'ok'}
  170. # login & register page
  171. @app.get("/login", response_class=HTMLResponse)
  172. async def get_login_and_register_page(request: Request):
  173. return templates.TemplateResponse("login.html", {"request": request})
  174. @app.post("/login")
  175. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  176. db_check()
  177. user = authenticate_user(form_data.username, form_data.password)
  178. if not user:
  179. raise HTTPException(
  180. status_code=status.HTTP_401_UNAUTHORIZED,
  181. detail="Incorrect username or password",
  182. headers={"WWW-Authenticate": "Bearer"},
  183. )
  184. access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  185. access_token = create_access_token(
  186. data={"sub": user.username}, expires_delta=access_token_expires
  187. )
  188. table = db['users']
  189. user.token = access_token
  190. table.update(dict(user), ['username'])
  191. expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  192. access_token = Authorize.create_access_token(subject=user.username, expires_time=expires)
  193. refresh_token = Authorize.create_refresh_token(subject=user.username, expires_time =expires)
  194. Authorize.set_access_cookies(access_token)
  195. Authorize.set_refresh_cookies(refresh_token)
  196. #return templates.TemplateResponse("index.html", {"request": request, "msg": 'Login'})
  197. if util.user.email_veri_pass(form_data.username):
  198. return {"access_token": access_token, "token_type": "bearer",'veri':'ok'}
  199. else:
  200. veri_obj = first(db.query('SELECT * FROM register_veri_code where user_id ="'+str(user_dict['id'])+'"'))
  201. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+veri_obj['code'], user.email)
  202. return {"access_token": access_token, "token_type": "bearer",'veri':'fail'}
  203. @app.post("/token")
  204. async def access_token(form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  205. user = authenticate_user(form_data.username, form_data.password)
  206. if not user:
  207. raise HTTPException(
  208. status_code=status.HTTP_401_UNAUTHORIZED,
  209. detail="Incorrect username or password",
  210. headers={"WWW-Authenticate": "Bearer"},
  211. )
  212. access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  213. access_token = create_access_token(
  214. data={"sub": user.username}, expires_delta=access_token_expires
  215. )
  216. return {"access_token": access_token, "token_type": "bearer"}
  217. #前後端分離完全實現後拔除
  218. @app.post("/register_old")
  219. async def register_old(request: Request):
  220. db_check()
  221. user = util.models.User(**await request.form())
  222. user_obj = first(db.query('SELECT * FROM users where username ="'+str(user.username)+'"'))
  223. if user_obj == None:
  224. id = user_register(user)
  225. result = util.user.add_to_basic_role(id)
  226. print(result)
  227. if type(id) is int:
  228. code = str(time.time()).replace('.','')
  229. db['register_veri_code'].insert({'code':code,'user_id':id})
  230. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+code, user.email)
  231. return {'msg':{'eng':'Register success! Please login at previous page','zh':'註冊成功! 請回到上頁登入帳號'}}
  232. else :
  233. return {'msg':{'eng':'error','zh':'error'}}
  234. #return templates.TemplateResponse("make_video.html", {"request": request, "success": True},status_code=status.HTTP_302_FOUND)
  235. #return templates.TemplateResponse("login.html", {'request': request,"success": True}, status_code=status.HTTP_302_FOUND)
  236. else:
  237. return {'msg':{'eng':user.username+' is duplicated user name try another','zh':user.username+'重複,請更改'}}
  238. @app.post("/register")
  239. async def register(request: util.models.register_req):
  240. db_check()
  241. user_obj = first(db.query('SELECT * FROM users where username ="'+str(request.username)+'"'))
  242. if user_obj == None:
  243. id = user_register(request)
  244. result = util.user.add_to_basic_role(id)
  245. print(result)
  246. if type(id) is int:
  247. code = str(time.time()).replace('.','')
  248. db['register_veri_code'].insert({'code':code,'user_id':id})
  249. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+code, request.email)
  250. return {'msg':{'eng':'Register success! Please login at previous page','zh':'註冊成功! 請回到上頁登入帳號'}}
  251. else :
  252. return {'msg':{'eng':'error','zh':'error'}}
  253. else:
  254. return {'msg':{'eng':user.username+' is duplicated user name try another','zh':user.username+'重複,請更改'}}
  255. @app.get('/logout')
  256. def logout(request: Request, Authorize: AuthJWT = Depends()):
  257. Authorize.jwt_required()
  258. Authorize.unset_jwt_cookies()
  259. return {"msg": "ok"}
  260. @app.post('/get_role')
  261. async def get_role(token: str = Depends(oauth2_scheme)):
  262. user_id = util.user.get_user_id(token)
  263. roles = util.user.get_user_role(user_id)
  264. return roles
  265. @app.post('/create_role')
  266. async def get_role(token: str = Depends(oauth2_scheme)):
  267. user_id = get_user_id(token)
  268. return user_id
  269. @app.post('/get_avatar_by_role')
  270. async def get_role(token: str = Depends(oauth2_scheme)):
  271. user_id = util.user.get_user_id(token)
  272. avatar_info = util.user.get_avatar_by_role(user_id)
  273. return avatar_info
  274. @app.get('/verify_email')
  275. async def verify_email(code):
  276. db_check()
  277. veri_obj = first(db.query('SELECT * FROM register_veri_code where code ="'+str(code)+'"'))
  278. if veri_obj != None:
  279. db['register_veri_code'].delete(code=code)
  280. return {"msg": "ok"}
  281. @app.get("/reset_pwd_page_email")
  282. async def reset_pwd_page():
  283. return FileResponse('static/reset_pwd_email.html')
  284. @app.get("/reset_pwd_page")
  285. async def reset_pwd_page():
  286. return FileResponse('static/reset_pwd.html')
  287. @app.get('/send_reset_pwd')
  288. async def send_reset_pwd(user_id,email):
  289. db_check()
  290. code = str(time.time()).replace('.','')
  291. db['reset_pw_code'].insert({'code':code,'user_id':user_id,'email':email})
  292. msg = '請至點擊網址以重設密碼 : https://www.choozmo.com:8887/reset_pwd_page 通行碼為 '+ code
  293. print(msg)
  294. msg =msg.encode(encoding='utf-8')
  295. print(msg)
  296. print(type(user_id))
  297. if int(user_id) != -1:
  298. print('print at first place')
  299. print(user_id)
  300. user_dict = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  301. else:
  302. user_id = util.user.get_id_by_email(email)
  303. print(user_id)
  304. user_dict = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  305. mailer.send(msg, user_dict['email'])
  306. return {'msg':'ok'}
  307. @app.post('/reset_pwd')
  308. async def reset_password(req :util.models.reset_pwd):
  309. db_check()
  310. print(req.code)
  311. veri_obj = next(iter(db.query('SELECT * FROM reset_pw_code where code ="'+str(req.code)+'"')))
  312. print(veri_obj['user_id'])
  313. user_id = util.user.get_id_by_email(veri_obj['email'])
  314. print(user_id)
  315. db.query('UPDATE users SET password = '+'"'+get_password_hash(req.password)+'" where id ='+str(user_id))
  316. if veri_obj != None:
  317. db['reset_pw_code'].delete(code=req.code)
  318. return {"msg": "ok"}
  319. @app.get("/gen_avatar")
  320. async def avatar():
  321. return FileResponse('static/gen_avatar.html')
  322. @app.post("/swapFace")
  323. async def swapFace(req:util.models.swap_req):
  324. if 'http' not in req.imgurl:
  325. req.imgurl= 'http://'+req.imgurl
  326. try:
  327. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  328. im= im.convert("RGB")
  329. except:
  330. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  331. name_hash = str(time.time()).replace('.','')
  332. x = threading.Thread(target=gen_avatar, args=(name_hash,req.imgurl))
  333. x.start()
  334. return {'msg':'ok'}
  335. @app.post("/uploadfile/")
  336. async def create_upload_file(file: UploadFile = File(...)):
  337. img_name = str(time.time()).replace('.','')
  338. try:
  339. if file.content_type=='video/mp4':
  340. async with aiofiles.open(img_upload_folder+img_name+'.mp4', 'wb') as out_file:
  341. content = await file.read()
  342. await out_file.write(content)
  343. return {"msg": resource_server+tmp_img_sub_folder+img_name+'.mp4'}
  344. else:
  345. contents = await file.read()
  346. image = Image.open(io.BytesIO(contents))
  347. image= image.convert("RGB")
  348. image.save(img_upload_folder+img_name+'.jpg')
  349. return {"msg": resource_server+tmp_img_sub_folder+img_name+'.jpg'}
  350. except Exception as e:
  351. logging.error(traceback.format_exc())
  352. return {'msg':{'eng':'file cant be prossessed','zh':'檔案無法使用'}}
  353. @app.post("/upload_pttx/")
  354. async def upload_pttx(file: UploadFile = File(...)):
  355. try:
  356. if "_" in file.filename:
  357. return {'msg':{'eng':'symbol"_" is not allowed in file name','zh':'檔案無法使用檔名不能含有"_"符號'}}
  358. else:
  359. pttx_name = file.filename+'_'+str(time.time()).replace('.','')
  360. with open(pttx_dest+pttx_name, "wb+") as file_object:
  361. file_object.write(file.file.read())
  362. return {"msg": resource_server+pttx_sub_folder+pttx_name}
  363. except Exception as e:
  364. logging.error(traceback.format_exc())
  365. return {'msg':{'eng':'file cant be prossessed','zh':'檔案無法使用'}}
  366. @app.post("/make_anchor_video_gSlide")
  367. async def make_anchor_video_gSlide(req:util.models.gSlide_req,token: str = Depends(oauth2_scheme)):
  368. if req.url_type == 0:
  369. name, text_content, image_urls = gSlide.parse_slide_url(req.slide_url,eng=False)
  370. else :
  371. filename = req.slide_url.replace(resource_server+pttx_sub_folder,resource_folder+pttx_sub_folder)
  372. name, text_content, image_urls = gSlide.parse_pttx_url(filename,img_upload_folder,resource_server+tmp_img_sub_folder,eng=False)
  373. if len(image_urls) != len(text_content):
  374. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  375. for idx in range(len(image_urls)):
  376. if 'http' not in image_urls[idx]:
  377. image_urls[idx] = 'http://'+image_urls[idx]
  378. if req.multiLang==0:
  379. for txt in text_content:
  380. if re.search('[a-zA-Z]', txt) !=None:
  381. print('語言錯誤')
  382. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  383. if re.search(',', txt) !=None:
  384. print('包含非法符號')
  385. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  386. name_hash = str(time.time()).replace('.','')
  387. for imgu in image_urls:
  388. try:
  389. if get_url_type(imgu) =='video/mp4':
  390. r=requests.get(imgu)
  391. else:
  392. im = Image.open(requests.get(imgu, stream=True).raw)
  393. im= im.convert("RGB")
  394. except:
  395. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  396. user_id = get_user_id(token)
  397. proto_req = util.models.request_normal()
  398. proto_req.text_content = text_content
  399. proto_req.name = name
  400. proto_req.image_urls = image_urls
  401. proto_req.avatar = req.avatar
  402. proto_req.multiLang = req.multiLang
  403. video_id = save_history(proto_req,name_hash,user_id)
  404. x = threading.Thread(target=gen_video_queue, args=(name_hash,name, text_content, image_urls,int(req.avatar),req.multiLang,video_id,user_id))
  405. x.start()
  406. return {"msg":"ok"}
  407. @app.post("/make_anchor_video_long")
  408. async def make_anchor_video_long(req:util.models.request,token: str = Depends(oauth2_scheme)):
  409. db_check()
  410. left_tag = [m.start() for m in re.finditer('{', req.text_content[0])]
  411. if len(req.image_urls) != len(left_tag):
  412. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  413. for idx in range(len(req.image_urls)):
  414. if 'http' not in req.image_urls[idx]:
  415. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  416. if req.multiLang==0:
  417. for txt in req.text_content:
  418. if re.search('[a-zA-Z]', txt) !=None:
  419. print('語言錯誤')
  420. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  421. if re.search(',', txt) !=None:
  422. print('包含非法符號')
  423. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  424. name_hash = str(time.time()).replace('.','')
  425. for imgu in req.image_urls:
  426. try:
  427. if get_url_type(imgu) =='video/mp4':
  428. r=requests.get(imgu)
  429. else:
  430. im = Image.open(requests.get(imgu, stream=True).raw)
  431. im= im.convert("RGB")
  432. except:
  433. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  434. user_id = get_user_id(token)
  435. video_id = save_history(req,name_hash,user_id)
  436. x = threading.Thread(target=gen_video_long_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.multiLang,video_id,user_id))
  437. x.start()
  438. returnMsg = ''
  439. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  440. returnMsg = {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  441. else:
  442. returnMsg = {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  443. return returnMsg
  444. @app.post("/make_anchor_video")
  445. async def make_anchor_video(req:util.models.request,token: str = Depends(oauth2_scheme)):
  446. db_check()
  447. if len(req.image_urls) != len(req.text_content):
  448. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  449. for idx in range(len(req.image_urls)):
  450. if 'http' not in req.image_urls[idx]:
  451. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  452. if req.multiLang==0:
  453. for txt in req.text_content:
  454. if re.search('[a-zA-Z]', txt) !=None:
  455. print('語言錯誤')
  456. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  457. if re.search(',', txt) !=None:
  458. print('包含非法符號')
  459. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  460. name_hash = str(time.time()).replace('.','')
  461. for imgu in req.image_urls:
  462. try:
  463. if get_url_type(imgu) =='video/mp4':
  464. r=requests.get(imgu)
  465. else:
  466. im = Image.open(requests.get(imgu, stream=True).raw)
  467. im= im.convert("RGB")
  468. except:
  469. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  470. user_id = get_user_id(token)
  471. video_id = save_history(req,name_hash,user_id)
  472. x = threading.Thread(target=gen_video_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.multiLang,video_id,user_id))
  473. x.start()
  474. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  475. return {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  476. else:
  477. return {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  478. return {'msg':'ok'}
  479. @app.post("/make_anchor_video_eng")
  480. async def make_anchor_video_eng(req:util.models.request_eng,token: str = Depends(oauth2_scheme)):
  481. db_check()
  482. if len(req.image_urls) != len(req.sub_titles) or len(req.sub_titles) != len(req.text_content):
  483. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  484. for idx in range(len(req.image_urls)):
  485. if 'http' not in req.image_urls[idx]:
  486. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  487. name_hash = str(time.time()).replace('.','')
  488. for imgu in req.image_urls:
  489. try:
  490. if get_url_type(imgu) =='video/mp4':
  491. r=requests.get(imgu)
  492. else:
  493. im = Image.open(requests.get(imgu, stream=True).raw)
  494. im= im.convert("RGB")
  495. except:
  496. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  497. user_id = get_user_id(token)
  498. video_id = save_history(req,name_hash, user_id)
  499. 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),video_id))
  500. x.start()
  501. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  502. return {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  503. else:
  504. return {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  505. return {"msg":"ok"}
  506. @app.post("/save_draft")
  507. async def save_draft(req:util.models.video_draft,token: str = Depends(oauth2_scheme)):
  508. db_check()
  509. user_id = get_user_id(token)
  510. txt_content_seperate_by_dot = ''
  511. for txt in req.text_content:
  512. txt_content_seperate_by_dot += txt+","
  513. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  514. img_urls_seperate_by_dot = ''
  515. for iurl in req.image_urls:
  516. img_urls_seperate_by_dot += iurl+","
  517. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  518. time_stamp = datetime.fromtimestamp(time.time())
  519. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  520. if req.id==-1:
  521. pk = db['draft'].insert({'title':req.title,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  522. ,'user_id':user_id,'avatar':req.avatar,'multiLang':req.multiLang,'time_stamp':time_stamp})
  523. else:
  524. db['draft'].update({'id':req.id,'title':req.title,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  525. ,'user_id':user_id,'avatar':req.avatar,'multiLang':req.multiLang,'time_stamp':time_stamp},['id'])
  526. return {'msg':'ok'}
  527. @app.post('/draft_list')
  528. async def draft_list(token: str = Depends(oauth2_scheme)):
  529. db_check()
  530. user_id = get_user_id(token)
  531. statement = 'SELECT * FROM draft WHERE user_id='+str(user_id)+' ORDER BY time_stamp DESC LIMIT 50'
  532. logs = []
  533. for row in db.query(statement):
  534. logs.append({'id':row['id'],'title':row['title'],'avatar':row['avatar'],'mulitLang':row['multiLang']
  535. ,'text_content':row['text_content'].split(','),'image_urls':row['image_urls'].split(',')})
  536. return logs
  537. @app.post('/del_draft')
  538. async def del_draft(id_obj:util.models.id_obj,token: str = Depends(oauth2_scheme)):
  539. db_check()
  540. user_id = get_user_id(token)
  541. statement = 'SELECT * FROM draft WHERE user_id="'+str(user_id)+'" and id ="'+str(id_obj.id)+'"'
  542. if first(db.query(statement)) is not None:
  543. db['draft'].delete(id=id_obj.id)
  544. else:
  545. return {'msg':'wrong id'}
  546. return {'msg':'ok'}
  547. @app.get("/history_input_old")
  548. async def history_input_old(request: Request, Authorize: AuthJWT = Depends()):
  549. db_check()
  550. Authorize.jwt_required()
  551. current_user = Authorize.get_jwt_subject()
  552. user_id = first(db.query('SELECT * FROM users where username="' + current_user +'"'))['id']
  553. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  554. logs = []
  555. for row in db.query(statement):
  556. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  557. return logs
  558. @app.post("/history_input")
  559. async def history_input(token: str = Depends(oauth2_scheme)):
  560. db_check()
  561. user_id = get_user_id(token)
  562. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  563. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  564. logs = []
  565. for row in db.query(statement):
  566. logs.append({'id':row['id'],'name':row['name'],'avatar':row['avatar'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  567. return logs
  568. @AuthJWT.load_config
  569. def get_config():
  570. return util.models.Settings()
  571. @app.exception_handler(AuthJWTException)
  572. def authjwt_exception_handler(request: Request, exc: AuthJWTException):
  573. return JSONResponse(
  574. status_code=exc.status_code,
  575. content={"detail": exc.message}
  576. )
  577. def get_user_id(token):
  578. db_check()
  579. credentials_exception = HTTPException(
  580. status_code=status.HTTP_401_UNAUTHORIZED,
  581. detail="Could not validate credentials",
  582. headers={"WWW-Authenticate": "Bearer"},
  583. )
  584. try:
  585. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  586. username: str = payload.get("sub")
  587. if username is None:
  588. raise credentials_exception
  589. token_data = util.models.TokenData(username=username)
  590. except JWTError:
  591. raise credentials_exception
  592. user = get_user(username=token_data.username)
  593. if user is None:
  594. raise credentials_exception
  595. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  596. return user_id
  597. def check_user_exists(username):
  598. db_check()
  599. if int(next(iter(db.query('SELECT COUNT(*) FROM AI_anchor.users WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
  600. return True
  601. else:
  602. return False
  603. def get_user(username: str):
  604. if not check_user_exists(username): # if user don't exist
  605. return False
  606. user_dict = next(
  607. iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  608. user = util.models.User(**user_dict)
  609. return user
  610. def user_register(user):
  611. db_check()
  612. table = db['users']
  613. user.password = get_password_hash(user.password)
  614. id = table.insert(dict(user))
  615. return id
  616. def get_password_hash(password):
  617. return pwd_context.hash(password)
  618. def verify_password(plain_password, hashed_password):
  619. return pwd_context.verify(plain_password, hashed_password)
  620. def authenticate_user(username: str, password: str):
  621. db_check()
  622. if not check_user_exists(username): # if user don't exist
  623. return False
  624. user_dict = next(iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  625. user = util.models.User(**user_dict)
  626. if not verify_password(password, user.password):
  627. return False
  628. return user
  629. def create_access_token(data: dict, expires_delta):
  630. to_encode = data.copy()
  631. expire = datetime.utcnow() + expires_delta
  632. to_encode.update({"exp": expire})
  633. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  634. return encoded_jwt
  635. def save_history(req,name_hash,user_id):
  636. db_check()
  637. log_table = db['history_input']
  638. txt_content_seperate_by_dot = ''
  639. for txt in req.text_content:
  640. txt_content_seperate_by_dot += txt+","
  641. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  642. img_urls_seperate_by_dot = ''
  643. for iurl in req.image_urls:
  644. img_urls_seperate_by_dot += iurl+","
  645. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  646. time_stamp = datetime.fromtimestamp(time.time())
  647. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  648. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  649. ,'user_id':user_id,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','avatar':req.avatar,'timestamp':time_stamp})
  650. return pk
  651. def get_url_type(url):
  652. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  653. r = urllib.request.urlopen(req)
  654. contentType = r.getheader('Content-Type')
  655. return contentType
  656. def notify_group(msg):
  657. #'WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD' is ChoozmoTeam
  658. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']
  659. for gid in glist:
  660. headers = {"Authorization": "Bearer " + gid,"Content-Type": "application/x-www-form-urlencoded"}
  661. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params={"message": msg})
  662. def gen_video_long_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  663. db_check()
  664. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  665. txt_content_seperate_by_dot = ''
  666. for txt in text_content:
  667. txt_content_seperate_by_dot += txt+","
  668. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  669. img_urls_seperate_by_dot = ''
  670. for iurl in image_urls:
  671. img_urls_seperate_by_dot += iurl+","
  672. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  673. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'multiLang':multiLang,'avatar':avatar,'timestamp':time_stamp})
  674. while True:
  675. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  676. print('another process running, leave loop')#1 means already running
  677. break
  678. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  679. print('all finish, leave loop')
  680. break
  681. top1 = first(db.query('SELECT * FROM video_queue'))
  682. try:
  683. # if True:
  684. db.query('UPDATE video_queue_status SET status = 1;')
  685. c = rpyc.connect("localhost", 8858)
  686. c._config['sync_request_timeout'] = None
  687. remote_svc = c.root
  688. my_answer = remote_svc.call_video_gen(top1['name_hash'],top1['name'],top1['text_content'].split(','), top1['image_urls'].split(','),top1['multiLang'],top1['avatar']) # method call
  689. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  690. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  691. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  692. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  693. line_token = user_obj['line_token'] # aa
  694. left_time = user_obj['left_time']
  695. email = user_obj['email']
  696. print('left_time is '+str(left_time))
  697. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  698. if left_time is None:
  699. left_time = 5*60
  700. if left_time < vid_duration:
  701. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  702. print(msg)
  703. msg =msg.encode(encoding='utf-8')
  704. mailer.send_left_not_enough(msg, email)
  705. #notify_line_user(msg, line_token)
  706. notify_group(name+":帳號餘額不足,請至email查看詳細資訊")
  707. else:
  708. left_time = left_time - vid_duration
  709. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  710. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  711. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  712. except Exception as e:
  713. logging.error(traceback.format_exc())
  714. print('video generation error')
  715. notify_group('長影片錯誤-測試')
  716. db['video_queue'].delete(id=top1['id'])
  717. db.query('UPDATE video_queue_status SET status = 0')
  718. def gen_video_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  719. db_check()
  720. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  721. txt_content_seperate_by_dot = ''
  722. for txt in text_content:
  723. txt_content_seperate_by_dot += txt+","
  724. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  725. img_urls_seperate_by_dot = ''
  726. for iurl in image_urls:
  727. img_urls_seperate_by_dot += iurl+","
  728. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  729. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'multiLang':multiLang,'avatar':avatar,'timestamp':time_stamp})
  730. while True:
  731. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  732. print('another process running, leave loop')#1 means already running
  733. break
  734. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  735. print('all finish, leave loop')
  736. break
  737. top1 = first(db.query('SELECT * FROM video_queue'))
  738. try:
  739. # if True:
  740. db.query('UPDATE video_queue_status SET status = 1;')
  741. c = rpyc.connect("localhost", 8858)
  742. c._config['sync_request_timeout'] = None
  743. remote_svc = c.root
  744. my_answer = remote_svc.call_video(top1['name_hash'],top1['name'],top1['text_content'].split(','), top1['image_urls'].split(','),top1['multiLang'],top1['avatar']) # method call
  745. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  746. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  747. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  748. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  749. line_token = user_obj['line_token'] # aa
  750. left_time = user_obj['left_time']
  751. email = user_obj['email']
  752. print('left_time is '+str(left_time))
  753. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  754. if left_time is None:
  755. left_time = 5*60
  756. if left_time < vid_duration:
  757. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  758. print(msg)
  759. msg =msg.encode(encoding='utf-8')
  760. mailer.send_left_not_enough(msg, email)
  761. notify_group(msg)
  762. #notify_line_user(msg, line_token)
  763. else:
  764. left_time = left_time - vid_duration
  765. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  766. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  767. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  768. except Exception as e:
  769. logging.error(traceback.format_exc())
  770. print('video generation error')
  771. notify_group('影片錯誤')
  772. db['video_queue'].delete(id=top1['id'])
  773. db.query('UPDATE video_queue_status SET status = 0')
  774. def gen_video_queue_eng(name_hash,name,text_content, image_urls,sub_titles,avatar,video_id):
  775. db_check()
  776. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  777. txt_content_seperate_by_dot = ''
  778. for txt in text_content:
  779. txt_content_seperate_by_dot += txt+","
  780. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  781. img_urls_seperate_by_dot = ''
  782. for iurl in image_urls:
  783. img_urls_seperate_by_dot += iurl+","
  784. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  785. subtitles_seperate_by_dot = ''
  786. for sub in sub_titles:
  787. subtitles_seperate_by_dot += sub+","
  788. subtitles_seperate_by_dot = subtitles_seperate_by_dot[:-1]
  789. 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})
  790. while True:
  791. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  792. print('another process running, leave loop')
  793. break
  794. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  795. print('all finish, leave loop')
  796. break
  797. top1 = first(db.query('SELECT * FROM video_queue'))
  798. try:
  799. db.query('UPDATE video_queue_status SET status = 1;')
  800. c = rpyc.connect("localhost", 8858)
  801. c._config['sync_request_timeout'] = None
  802. remote_svc = c.root
  803. 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
  804. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  805. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  806. notify_group(name+"(ENG)的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  807. except:
  808. print('video generation error')
  809. notify_group('影片錯誤')
  810. db['video_queue'].delete(id=top1['id'])
  811. db.query('UPDATE video_queue_status SET status = 0')
  812. def gen_avatar(name_hash, imgurl):
  813. db_check()
  814. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  815. while True:
  816. statement = 'SELECT * FROM avatar_service_status'#only one row in this table, which is the id 1 one
  817. status = -1
  818. for row in db.query(statement):
  819. status = row['status']
  820. if status == 1:
  821. print('leave process loop')
  822. break
  823. statement = 'SELECT * FROM avatar_queue'
  824. works = []
  825. for row in db.query(statement):
  826. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':row['imgurl']})
  827. if len(works)==0:
  828. print('leave process loop')
  829. break
  830. try:
  831. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  832. db.query(statement)
  833. name_hash = works[0]['name_hash']
  834. imgurl = works[0]['imgurl']
  835. c = rpyc.connect("localhost", 8868)
  836. c._config['sync_request_timeout'] = None
  837. remote_svc = c.root
  838. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  839. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  840. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  841. except:
  842. print('gen error')
  843. notify_group('無法辨識人臉')
  844. db['avatar_queue'].delete(id=works[0]['id'])
  845. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;' #only one row in this table, which id 1 one
  846. db.query(statement)
  847. def call_voice(text):
  848. print(text)
  849. print(len(text))
  850. print(type(text))
  851. c = rpyc.connect("localhost", 8858)
  852. c._config['sync_request_timeout'] = None
  853. remote_svc = c.root
  854. my_answer = remote_svc.make_speech(text) # method call
  855. src_path = '/home/ming/AI_Anchor/OpenshotService/speech.mp3'
  856. shutil.copy(src_path,'/home/ming/speech.mp3')
  857. os.remove(src_path)
  858. class text_in(BaseModel):
  859. text: str
  860. @app.post("/make_voice")
  861. async def make_voice(in_text:text_in):
  862. x = threading.Thread(target=call_voice, args=(in_text.text,))
  863. x.start()
  864. def db_check():
  865. global db
  866. try:
  867. db.tables
  868. except:
  869. print("database down")
  870. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')