main.py 25 KB

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