main.py 21 KB

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