main.py 22 KB

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