main.py 21 KB

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