main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 typing import List, Optional
  5. from os.path import isfile, isdir, join
  6. import threading
  7. import zhtts
  8. import os
  9. import urllib
  10. import requests
  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 fastapi.middleware.cors import CORSMiddleware
  24. import dataset
  25. from datetime import datetime, timedelta
  26. from util.swap_face import swap_face
  27. from fastapi.staticfiles import StaticFiles
  28. import shutil
  29. import io
  30. from first import first
  31. from passlib.context import CryptContext
  32. from jose import JWTError, jwt
  33. from fastapi_jwt_auth import AuthJWT
  34. from fastapi_jwt_auth.exceptions import AuthJWTException
  35. from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
  36. import models
  37. import pymysql
  38. from first import first
  39. import mailer
  40. from moviepy.editor import VideoFileClip
  41. pymysql.install_as_MySQLdb()
  42. app = FastAPI()
  43. app.add_middleware(
  44. CORSMiddleware,
  45. allow_origins=["*"],
  46. allow_credentials=True,
  47. allow_methods=["*"],
  48. allow_headers=["*"],
  49. )
  50. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  51. ALGORITHM = "HS256"
  52. ACCESS_TOKEN_EXPIRE_MINUTES = 300
  53. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  54. app.mount("/static", StaticFiles(directory="static"), name="static")
  55. app.mount("/static/img", StaticFiles(directory="static/img"), name="static/img")
  56. app.mount("/templates", StaticFiles(directory="templates"), name="templates")
  57. templates = Jinja2Templates(directory="templates")
  58. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
  59. tmp_video_dir = '../OpenshotService/tmp_video/'
  60. tmp_avatar_dir = '../../face_swap/tmp_avatar/' #change source face path here
  61. video_sub_folder = 'ai_anchor_video/'
  62. avatar_sub_folder = 'swap_save/'
  63. tmp_img_sub_folder = 'tmp_img/'
  64. img_upload_folder = '/var/www/html/'+tmp_img_sub_folder
  65. video_dest = '/var/www/html/'+video_sub_folder
  66. avatar_dest = '/var/www/html/'+avatar_sub_folder
  67. @app.get("/index2")
  68. async def index2():
  69. return FileResponse('static/index2.html')
  70. @app.get("/index_eng")
  71. async def index2():
  72. return FileResponse('static/index_eng.html')
  73. # home page
  74. @app.get("/index", response_class=HTMLResponse)
  75. async def get_home_page(request: Request, response: Response):
  76. return templates.TemplateResponse("index.html", {"request": request, "response": response})
  77. @app.get("/", response_class=HTMLResponse)
  78. async def get_home_page(request: Request, response: Response):
  79. return templates.TemplateResponse("index.html", {"request": request, "response": response})
  80. @app.get("/make_video", response_class=HTMLResponse)
  81. async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  82. try:
  83. Authorize.jwt_required()
  84. except:
  85. return '請先登入帳號'
  86. current_user = Authorize.get_jwt_subject()
  87. return templates.TemplateResponse("make_video.html", {"request": request, "response": response})
  88. @app.get('/user_profile', response_class=HTMLResponse)
  89. def protected(request: Request, Authorize: AuthJWT = Depends()):
  90. Authorize.jwt_required()
  91. current_user = Authorize.get_jwt_subject()
  92. return current_user
  93. # login & register page
  94. @app.get("/login", response_class=HTMLResponse)
  95. async def get_login_and_register_page(request: Request):
  96. return templates.TemplateResponse("login.html", {"request": request})
  97. @app.post("/login")
  98. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  99. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  100. user = authenticate_user(form_data.username, form_data.password)
  101. if not user:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED,
  104. detail="Incorrect username or password",
  105. headers={"WWW-Authenticate": "Bearer"},
  106. )
  107. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  108. access_token = create_access_token(
  109. data={"sub": user.username}, expires_delta=access_token_expires
  110. )
  111. table = db['users']
  112. user.token = access_token
  113. table.update(dict(user), ['username'])
  114. access_token = Authorize.create_access_token(subject=user.username)
  115. refresh_token = Authorize.create_refresh_token(subject=user.username)
  116. Authorize.set_access_cookies(access_token)
  117. Authorize.set_refresh_cookies(refresh_token)
  118. #return templates.TemplateResponse("index.html", {"request": request, "msg": 'Login'})
  119. return {"access_token": access_token, "token_type": "bearer"}
  120. @app.post("/token")
  121. async def access_token(form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  122. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  123. user = authenticate_user(form_data.username, form_data.password)
  124. if not user:
  125. raise HTTPException(
  126. status_code=status.HTTP_401_UNAUTHORIZED,
  127. detail="Incorrect username or password",
  128. headers={"WWW-Authenticate": "Bearer"},
  129. )
  130. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  131. access_token = create_access_token(
  132. data={"sub": user.username}, expires_delta=access_token_expires
  133. )
  134. return {"access_token": access_token, "token_type": "bearer"}
  135. @app.post("/register")
  136. async def register(request: Request):
  137. user = models.User(**await request.form())
  138. user_register(user)
  139. return templates.TemplateResponse("login.html", {'request': request,"success": True}, status_code=status.HTTP_302_FOUND)
  140. @app.get('/user_profile', response_class=HTMLResponse)
  141. def protected(request: Request, Authorize: AuthJWT = Depends()):
  142. Authorize.jwt_required()
  143. current_user = Authorize.get_jwt_subject()
  144. return current_user
  145. @app.get('/logout')
  146. def logout(request: Request, Authorize: AuthJWT = Depends()):
  147. Authorize.jwt_required()
  148. Authorize.unset_jwt_cookies()
  149. return {"msg": "Successfully logout"}
  150. @app.get("/gen_avatar")
  151. async def avatar():
  152. return FileResponse('static/gen_avatar.html')
  153. @app.post("/swapFace")
  154. async def swapFace(req:models.swap_req):
  155. if 'http' not in req.imgurl:
  156. req.imgurl= 'http://'+req.imgurl
  157. try:
  158. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  159. im= im.convert("RGB")
  160. except:
  161. return {'msg':"無法辨別圖片網址"+req.imgurl}
  162. name_hash = str(time.time()).replace('.','')
  163. x = threading.Thread(target=gen_avatar, args=(name_hash,req.imgurl))
  164. x.start()
  165. return {'msg':'人物生成中,請稍候'}
  166. @app.post("/uploadfile/")
  167. async def create_upload_file(file: UploadFile = File(...)):
  168. img_name = str(time.time()).replace('.','')
  169. try:
  170. contents = await file.read()
  171. image = Image.open(io.BytesIO(contents))
  172. image= image.convert("RGB")
  173. image.save(img_upload_folder+img_name+'.jpg')
  174. except:
  175. return {'msg':'檔案無法使用'}
  176. return {"msg": 'www.choozmo.com:8168/'+tmp_img_sub_folder+img_name+'.jpg'}
  177. @app.post("/make_anchor_video")
  178. async def make_anchor_video(req:models.request,token: str = Depends(oauth2_scheme)):
  179. if len(req.image_urls) != len(req.text_content):
  180. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  181. for idx in range(len(req.image_urls)):
  182. if 'http' not in req.image_urls[idx]:
  183. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  184. for txt in req.text_content:
  185. if re.search('[a-zA-Z]', txt) !=None:
  186. return {'msg':'輸入字串不能包含英文字!'}
  187. name_hash = str(time.time()).replace('.','')
  188. for imgu in req.image_urls:
  189. try:
  190. if get_url_type(imgu) =='video/mp4':
  191. r=requests.get(imgu)
  192. else:
  193. im = Image.open(requests.get(imgu, stream=True).raw)
  194. im= im.convert("RGB")
  195. except:
  196. return {'msg':"無法辨別圖片網址"+imgu}
  197. user_id = get_user_id(token)
  198. save_history(req,name_hash,user_id)
  199. x = threading.Thread(target=gen_video_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),user_id))
  200. x.start()
  201. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  202. @app.post("/make_anchor_video_eng")
  203. async def make_anchor_video_eng(req:models.request_eng):
  204. if len(req.image_urls) != len(req.sub_titles) or len(req.sub_titles) != len(req.text_content):
  205. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  206. for idx in range(len(req.image_urls)):
  207. if 'http' not in req.image_urls[idx]:
  208. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  209. name_hash = str(time.time()).replace('.','')
  210. for imgu in req.image_urls:
  211. try:
  212. if get_url_type(imgu) =='video/mp4':
  213. r=requests.get(imgu)
  214. else:
  215. im = Image.open(requests.get(imgu, stream=True).raw)
  216. im= im.convert("RGB")
  217. except:
  218. return {'msg':"無法辨別圖片網址"+imgu}
  219. save_history(req,name_hash)
  220. 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)))
  221. x.start()
  222. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  223. @app.get("/history_input")
  224. async def history_input(request: Request, Authorize: AuthJWT = Depends()):
  225. Authorize.jwt_required()
  226. current_user = Authorize.get_jwt_subject()
  227. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  228. user_id = first(db.query('SELECT * FROM users where username="' + current_user +'"'))['id']
  229. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  230. logs = []
  231. for row in db.query(statement):
  232. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  233. return logs
  234. @AuthJWT.load_config
  235. def get_config():
  236. return models.Settings()
  237. @app.exception_handler(AuthJWTException)
  238. def authjwt_exception_handler(request: Request, exc: AuthJWTException):
  239. return JSONResponse(
  240. status_code=exc.status_code,
  241. content={"detail": exc.message}
  242. )
  243. def get_user_id(token):
  244. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  245. credentials_exception = HTTPException(
  246. status_code=status.HTTP_401_UNAUTHORIZED,
  247. detail="Could not validate credentials",
  248. headers={"WWW-Authenticate": "Bearer"},
  249. )
  250. try:
  251. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  252. username: str = payload.get("sub")
  253. if username is None:
  254. raise credentials_exception
  255. token_data = models.TokenData(username=username)
  256. except JWTError:
  257. raise credentials_exception
  258. user = get_user(username=token_data.username)
  259. if user is None:
  260. raise credentials_exception
  261. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  262. return user_id
  263. def check_user_exists(username):
  264. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  265. if int(next(iter(db.query('SELECT COUNT(*) FROM AI_anchor.users WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
  266. return True
  267. else:
  268. return False
  269. def get_user(username: str):
  270. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  271. if not check_user_exists(username): # if user don't exist
  272. return False
  273. user_dict = next(
  274. iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  275. user = models.User(**user_dict)
  276. return user
  277. def user_register(user):
  278. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  279. table = db['users']
  280. user.password = get_password_hash(user.password)
  281. table.insert(dict(user))
  282. def get_password_hash(password):
  283. return pwd_context.hash(password)
  284. def verify_password(plain_password, hashed_password):
  285. return pwd_context.verify(plain_password, hashed_password)
  286. def authenticate_user(username: str, password: str):
  287. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  288. if not check_user_exists(username): # if user don't exist
  289. return False
  290. user_dict = next(iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  291. user = models.User(**user_dict)
  292. if not verify_password(password, user.password):
  293. return False
  294. return user
  295. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  296. to_encode = data.copy()
  297. if expires_delta:
  298. expire = datetime.utcnow() + expires_delta
  299. else:
  300. expire = datetime.utcnow() + timedelta(minutes=15)
  301. to_encode.update({"exp": expire})
  302. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  303. return encoded_jwt
  304. def save_history(req,name_hash,user_id):
  305. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  306. log_table = db['history_input']
  307. txt_content_seperate_by_dot = ''
  308. for txt in req.text_content:
  309. txt_content_seperate_by_dot += txt+","
  310. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  311. img_urls_seperate_by_dot = ''
  312. for iurl in req.image_urls:
  313. img_urls_seperate_by_dot += iurl+","
  314. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  315. time_stamp = datetime.fromtimestamp(time.time())
  316. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  317. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  318. ,'user_id':user_id,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','timestamp':time_stamp})
  319. def get_url_type(url):
  320. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  321. r = urllib.request.urlopen(req)
  322. contentType = r.getheader('Content-Type')
  323. return contentType
  324. def notify_group(msg):
  325. glist=['WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD']
  326. for gid in glist:
  327. headers = {
  328. "Authorization": "Bearer " + gid,
  329. "Content-Type": "application/x-www-form-urlencoded"
  330. }
  331. params = {"message": msg}
  332. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  333. def gen_video(name_hash,name,text_content, image_urls,avatar):
  334. c = rpyc.connect("localhost", 8858)
  335. c._config['sync_request_timeout'] = None
  336. remote_svc = c.root
  337. my_answer = remote_svc.call_video(name_hash,name,text_content, image_urls,avatar) # method call
  338. shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
  339. os.remove(tmp_video_dir+name_hash+'.mp4')
  340. def gen_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar):
  341. c = rpyc.connect("localhost", 8858)
  342. c._config['sync_request_timeout'] = None
  343. remote_svc = c.root
  344. my_answer = remote_svc.call_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar) # method call
  345. shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
  346. os.remove(tmp_video_dir+name_hash+'.mp4')
  347. def gen_video_queue(name_hash,name,text_content, image_urls,avatar,user_id):
  348. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  349. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  350. txt_content_seperate_by_dot = ''
  351. for txt in text_content:
  352. txt_content_seperate_by_dot += txt+","
  353. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  354. img_urls_seperate_by_dot = ''
  355. for iurl in image_urls:
  356. img_urls_seperate_by_dot += iurl+","
  357. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  358. 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})
  359. while True:
  360. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  361. print('another process running, leave loop')#1 means already running
  362. break
  363. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  364. print('all finish, leave loop')
  365. break
  366. top1 = first(db.query('SELECT * FROM video_queue'))
  367. #try:
  368. if True:
  369. db.query('UPDATE video_queue_status SET status = 1;')
  370. c = rpyc.connect("localhost", 8858)
  371. c._config['sync_request_timeout'] = None
  372. remote_svc = c.root
  373. my_answer = remote_svc.call_video(top1['name_hash'],top1['name'],top1['text_content'].split(','), top1['image_urls'].split(','),top1['avatar']) # method call
  374. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  375. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  376. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  377. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  378. left_time = user_obj['left_time']
  379. email = user_obj['email']
  380. print('left_time is '+str(left_time))
  381. if left_time is None:
  382. left_time = 5*60
  383. if left_time < vid_duration:
  384. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 www.choozmo.com:8888/confirm_add_value?name_hash='+name_hash+' 加值'
  385. print(msg)
  386. msg =msg.encode(encoding='utf-8')
  387. mailer.send(msg, email)
  388. else:
  389. left_time = left_time - vid_duration
  390. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  391. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  392. #except:
  393. #print('video generation error')
  394. #notify_group('影片錯誤')
  395. db['video_queue'].delete(id=top1['id'])
  396. db.query('UPDATE video_queue_status SET status = 0')
  397. def gen_video_queue_eng(name_hash,name,text_content, image_urls,sub_titles,avatar):
  398. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  399. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  400. txt_content_seperate_by_dot = ''
  401. for txt in text_content:
  402. txt_content_seperate_by_dot += txt+","
  403. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  404. img_urls_seperate_by_dot = ''
  405. for iurl in image_urls:
  406. img_urls_seperate_by_dot += iurl+","
  407. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  408. subtitles_seperate_by_dot = ''
  409. for sub in sub_titles:
  410. subtitles_seperate_by_dot += sub+","
  411. subtitles_seperate_by_dot = subtitles_seperate_by_dot[:-1]
  412. 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})
  413. while True:
  414. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  415. print('another process running, leave loop')
  416. break
  417. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  418. print('all finish, leave loop')
  419. break
  420. top1 = first(db.query('SELECT * FROM video_queue'))
  421. try:
  422. db.query('UPDATE video_queue_status SET status = 1;')
  423. c = rpyc.connect("localhost", 8858)
  424. c._config['sync_request_timeout'] = None
  425. remote_svc = c.root
  426. 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
  427. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  428. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  429. except:
  430. print('video generation error')
  431. notify_group('影片錯誤')
  432. db['video_queue'].delete(id=top1['id'])
  433. db.query('UPDATE video_queue_status SET status = 0')
  434. def gen_avatar(name_hash, imgurl):
  435. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  436. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  437. while True:
  438. statement = 'SELECT * FROM avatar_service_status'#only one row in this table, which is the id 1 one
  439. status = -1
  440. for row in db.query(statement):
  441. status = row['status']
  442. if status == 1:
  443. print('leave process loop')
  444. break
  445. statement = 'SELECT * FROM avatar_queue'
  446. works = []
  447. for row in db.query(statement):
  448. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':row['imgurl']})
  449. if len(works)==0:
  450. print('leave process loop')
  451. break
  452. try:
  453. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  454. db.query(statement)
  455. name_hash = works[0]['name_hash']
  456. imgurl = works[0]['imgurl']
  457. c = rpyc.connect("localhost", 8868)
  458. c._config['sync_request_timeout'] = None
  459. remote_svc = c.root
  460. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  461. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  462. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  463. except:
  464. print('gen error')
  465. notify_group('無法辨識人臉')
  466. db['avatar_queue'].delete(id=works[0]['id'])
  467. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;' #only one row in this table, which id 1 one
  468. db.query(statement)