main.py 21 KB

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