main.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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 = 3000
  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("/make_video_long", response_class=HTMLResponse)
  93. async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  94. try:
  95. Authorize.jwt_required()
  96. except Exception as e:
  97. print(e)
  98. return '請先登入帳號'
  99. current_user = Authorize.get_jwt_subject()
  100. return templates.TemplateResponse("make_video_long.html", {"request": request, "response": response})
  101. @app.get("/make_video_slide", response_class=HTMLResponse)
  102. async def make_video_slide(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  103. try:
  104. Authorize.jwt_required()
  105. except Exception as e:
  106. print(e)
  107. return '請先登入帳號'
  108. current_user = Authorize.get_jwt_subject()
  109. return templates.TemplateResponse("make_video_slide.html", {"request": request, "response": response})
  110. @app.get('/user_profile', response_class=HTMLResponse)
  111. def protected(request: Request, Authorize: AuthJWT = Depends()):
  112. Authorize.jwt_required()
  113. current_user = Authorize.get_jwt_subject()
  114. return current_user
  115. # login & register page
  116. @app.get("/login", response_class=HTMLResponse)
  117. async def get_login_and_register_page(request: Request):
  118. return templates.TemplateResponse("login.html", {"request": request})
  119. @app.post("/login")
  120. async def login_for_access_token(request: Request, 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. table = db['users']
  134. user.token = access_token
  135. table.update(dict(user), ['username'])
  136. access_token = Authorize.create_access_token(subject=user.username)
  137. refresh_token = Authorize.create_refresh_token(subject=user.username)
  138. Authorize.set_access_cookies(access_token)
  139. Authorize.set_refresh_cookies(refresh_token)
  140. #return templates.TemplateResponse("index.html", {"request": request, "msg": 'Login'})
  141. return {"access_token": access_token, "token_type": "bearer"}
  142. @app.post("/token")
  143. async def access_token(form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  144. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  145. user = authenticate_user(form_data.username, form_data.password)
  146. if not user:
  147. raise HTTPException(
  148. status_code=status.HTTP_401_UNAUTHORIZED,
  149. detail="Incorrect username or password",
  150. headers={"WWW-Authenticate": "Bearer"},
  151. )
  152. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  153. access_token = create_access_token(
  154. data={"sub": user.username}, expires_delta=access_token_expires
  155. )
  156. return {"access_token": access_token, "token_type": "bearer"}
  157. @app.post("/register")
  158. async def register(request: Request):
  159. user = models.User(**await request.form())
  160. user_register(user)
  161. return templates.TemplateResponse("login.html", {'request': request,"success": True}, status_code=status.HTTP_302_FOUND)
  162. @app.get('/user_profile', response_class=HTMLResponse)
  163. def protected(request: Request, Authorize: AuthJWT = Depends()):
  164. Authorize.jwt_required()
  165. current_user = Authorize.get_jwt_subject()
  166. return current_user
  167. @app.get('/logout')
  168. def logout(request: Request, Authorize: AuthJWT = Depends()):
  169. Authorize.jwt_required()
  170. Authorize.unset_jwt_cookies()
  171. return {"msg": "Successfully logout"}
  172. @app.get("/gen_avatar")
  173. async def avatar():
  174. return FileResponse('static/gen_avatar.html')
  175. @app.post("/swapFace")
  176. async def swapFace(req:models.swap_req):
  177. if 'http' not in req.imgurl:
  178. req.imgurl= 'http://'+req.imgurl
  179. try:
  180. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  181. im= im.convert("RGB")
  182. except:
  183. return {'msg':"無法辨別圖片網址"+req.imgurl}
  184. name_hash = str(time.time()).replace('.','')
  185. x = threading.Thread(target=gen_avatar, args=(name_hash,req.imgurl))
  186. x.start()
  187. return {'msg':'人物生成中,請稍候'}
  188. @app.post("/uploadfile/")
  189. async def create_upload_file(file: UploadFile = File(...)):
  190. img_name = str(time.time()).replace('.','')
  191. try:
  192. if file.content_type=='video/mp4':
  193. async with aiofiles.open(img_upload_folder+img_name+'.mp4', 'wb') as out_file:
  194. content = await file.read()
  195. await out_file.write(content)
  196. return {"msg": 'www.choozmo.com:8168/'+tmp_img_sub_folder+img_name+'.mp4'}
  197. else:
  198. contents = await file.read()
  199. image = Image.open(io.BytesIO(contents))
  200. image= image.convert("RGB")
  201. image.save(img_upload_folder+img_name+'.jpg')
  202. return {"msg": 'www.choozmo.com:8168/'+tmp_img_sub_folder+img_name+'.jpg'}
  203. except Exception as e:
  204. logging.error(traceback.format_exc())
  205. return {'msg':'檔案無法使用'}
  206. @app.post("/make_anchor_video_gSlide")
  207. async def make_anchor_video_gSlide(req:models.gSlide_req,token: str = Depends(oauth2_scheme)):
  208. name, text_content, image_urls = gSlide.parse_slide_url(req.slide_url,eng=False)
  209. if len(image_urls) != len(text_content):
  210. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  211. for idx in range(len(image_urls)):
  212. if 'http' not in image_urls[idx]:
  213. image_urls[idx] = 'http://'+image_urls[idx]
  214. if req.multiLang==0:
  215. for txt in text_content:
  216. if re.search('[a-zA-Z]', txt) !=None:
  217. print('語言錯誤')
  218. return {'msg':'輸入字串不能包含英文字!'}
  219. name_hash = str(time.time()).replace('.','')
  220. for imgu in image_urls:
  221. try:
  222. if get_url_type(imgu) =='video/mp4':
  223. r=requests.get(imgu)
  224. else:
  225. im = Image.open(requests.get(imgu, stream=True).raw)
  226. im= im.convert("RGB")
  227. except:
  228. return {'msg':"無法辨別圖片網址"+imgu}
  229. user_id = get_user_id(token)
  230. proto_req = models.request_normal()
  231. proto_req.text_content = text_content
  232. proto_req.name = name
  233. proto_req.image_urls = image_urls
  234. proto_req.avatar = req.avatar
  235. proto_req.multiLang = req.multiLang
  236. save_history(proto_req,name_hash,user_id)
  237. x = threading.Thread(target=gen_video_queue, args=(name_hash,name, text_content, image_urls,int(req.avatar),req.multiLang,user_id))
  238. x.start()
  239. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  240. @app.post("/make_anchor_video_long")
  241. async def make_anchor_video_long(req:models.request,token: str = Depends(oauth2_scheme)):
  242. if len(req.image_urls) != len(req.text_content):
  243. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  244. for idx in range(len(req.image_urls)):
  245. if 'http' not in req.image_urls[idx]:
  246. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  247. if req.multiLang==0:
  248. for txt in req.text_content:
  249. if re.search('[a-zA-Z]', txt) !=None:
  250. print('語言錯誤')
  251. return {'msg':'輸入字串不能包含英文字!'}
  252. name_hash = str(time.time()).replace('.','')
  253. for imgu in req.image_urls:
  254. try:
  255. if get_url_type(imgu) =='video/mp4':
  256. r=requests.get(imgu)
  257. else:
  258. im = Image.open(requests.get(imgu, stream=True).raw)
  259. im= im.convert("RGB")
  260. except:
  261. return {'msg':"無法辨別圖片網址"+imgu}
  262. user_id = get_user_id(token)
  263. save_history(req,name_hash,user_id)
  264. x = threading.Thread(target=gen_video_long_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.multiLang,user_id))
  265. x.start()
  266. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  267. @app.post("/make_anchor_video")
  268. async def make_anchor_video(req:models.request,token: str = Depends(oauth2_scheme)):
  269. if len(req.image_urls) != len(req.text_content):
  270. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  271. for idx in range(len(req.image_urls)):
  272. if 'http' not in req.image_urls[idx]:
  273. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  274. if req.multiLang==0:
  275. for txt in req.text_content:
  276. if re.search('[a-zA-Z]', txt) !=None:
  277. print('語言錯誤')
  278. return {'msg':'輸入字串不能包含英文字!'}
  279. name_hash = str(time.time()).replace('.','')
  280. for imgu in req.image_urls:
  281. try:
  282. if get_url_type(imgu) =='video/mp4':
  283. r=requests.get(imgu)
  284. else:
  285. im = Image.open(requests.get(imgu, stream=True).raw)
  286. im= im.convert("RGB")
  287. except:
  288. return {'msg':"無法辨別圖片網址"+imgu}
  289. user_id = get_user_id(token)
  290. save_history(req,name_hash,user_id)
  291. 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))
  292. x.start()
  293. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  294. @app.post("/make_anchor_video_eng")
  295. async def make_anchor_video_eng(req:models.request_eng):
  296. if len(req.image_urls) != len(req.sub_titles) or len(req.sub_titles) != len(req.text_content):
  297. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  298. for idx in range(len(req.image_urls)):
  299. if 'http' not in req.image_urls[idx]:
  300. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  301. name_hash = str(time.time()).replace('.','')
  302. for imgu in req.image_urls:
  303. try:
  304. if get_url_type(imgu) =='video/mp4':
  305. r=requests.get(imgu)
  306. else:
  307. im = Image.open(requests.get(imgu, stream=True).raw)
  308. im= im.convert("RGB")
  309. except:
  310. return {'msg':"無法辨別圖片網址"+imgu}
  311. save_history(req,name_hash)
  312. 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)))
  313. x.start()
  314. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  315. @app.get("/history_input")
  316. async def history_input(request: Request, Authorize: AuthJWT = Depends()):
  317. Authorize.jwt_required()
  318. current_user = Authorize.get_jwt_subject()
  319. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  320. user_id = first(db.query('SELECT * FROM users where username="' + current_user +'"'))['id']
  321. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  322. logs = []
  323. for row in db.query(statement):
  324. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  325. return logs
  326. @AuthJWT.load_config
  327. def get_config():
  328. return models.Settings()
  329. @app.exception_handler(AuthJWTException)
  330. def authjwt_exception_handler(request: Request, exc: AuthJWTException):
  331. return JSONResponse(
  332. status_code=exc.status_code,
  333. content={"detail": exc.message}
  334. )
  335. def get_user_id(token):
  336. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  337. credentials_exception = HTTPException(
  338. status_code=status.HTTP_401_UNAUTHORIZED,
  339. detail="Could not validate credentials",
  340. headers={"WWW-Authenticate": "Bearer"},
  341. )
  342. try:
  343. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  344. username: str = payload.get("sub")
  345. if username is None:
  346. raise credentials_exception
  347. token_data = models.TokenData(username=username)
  348. except JWTError:
  349. raise credentials_exception
  350. user = get_user(username=token_data.username)
  351. if user is None:
  352. raise credentials_exception
  353. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  354. return user_id
  355. def check_user_exists(username):
  356. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  357. if int(next(iter(db.query('SELECT COUNT(*) FROM AI_anchor.users WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
  358. return True
  359. else:
  360. return False
  361. def get_user(username: str):
  362. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  363. if not check_user_exists(username): # if user don't exist
  364. return False
  365. user_dict = next(
  366. iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  367. user = models.User(**user_dict)
  368. return user
  369. def user_register(user):
  370. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  371. table = db['users']
  372. user.password = get_password_hash(user.password)
  373. table.insert(dict(user))
  374. def get_password_hash(password):
  375. return pwd_context.hash(password)
  376. def verify_password(plain_password, hashed_password):
  377. return pwd_context.verify(plain_password, hashed_password)
  378. def authenticate_user(username: str, password: str):
  379. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  380. if not check_user_exists(username): # if user don't exist
  381. return False
  382. user_dict = next(iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  383. user = models.User(**user_dict)
  384. if not verify_password(password, user.password):
  385. return False
  386. return user
  387. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  388. to_encode = data.copy()
  389. if expires_delta:
  390. expire = datetime.utcnow() + expires_delta
  391. else:
  392. expire = datetime.utcnow() + timedelta(minutes=15)
  393. to_encode.update({"exp": expire})
  394. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  395. return encoded_jwt
  396. def save_history(req,name_hash,user_id):
  397. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  398. log_table = db['history_input']
  399. txt_content_seperate_by_dot = ''
  400. for txt in req.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 req.image_urls:
  405. img_urls_seperate_by_dot += iurl+","
  406. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  407. time_stamp = datetime.fromtimestamp(time.time())
  408. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  409. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  410. ,'user_id':user_id,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','timestamp':time_stamp})
  411. def get_url_type(url):
  412. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  413. r = urllib.request.urlopen(req)
  414. contentType = r.getheader('Content-Type')
  415. return contentType
  416. def notify_line_user(msg, line_token):
  417. headers = {
  418. "Authorization": "Bearer " + line_token,
  419. "Content-Type": "application/x-www-form-urlencoded"
  420. }
  421. params = {"message": msg}
  422. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  423. def notify_group(msg):
  424. glist=['WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD']
  425. for gid in glist:
  426. headers = {
  427. "Authorization": "Bearer " + gid,
  428. "Content-Type": "application/x-www-form-urlencoded"
  429. }
  430. params = {"message": msg}
  431. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  432. def gen_video(name_hash,name,text_content, image_urls,avatar):
  433. c = rpyc.connect("localhost", 8858)
  434. c._config['sync_request_timeout'] = None
  435. remote_svc = c.root
  436. my_answer = remote_svc.call_video(name_hash,name,text_content, image_urls,avatar) # method call
  437. shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
  438. os.remove(tmp_video_dir+name_hash+'.mp4')
  439. def gen_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar):
  440. c = rpyc.connect("localhost", 8858)
  441. c._config['sync_request_timeout'] = None
  442. remote_svc = c.root
  443. my_answer = remote_svc.call_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar) # method call
  444. shutil.copy(tmp_video_dir+name_hash+'.mp4',video_dest+name_hash+'.mp4')
  445. os.remove(tmp_video_dir+name_hash+'.mp4')
  446. def gen_video_long_queue(name_hash,name,text_content, image_urls,avatar,multiLang,user_id):
  447. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  448. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  449. txt_content_seperate_by_dot = ''
  450. for txt in text_content:
  451. txt_content_seperate_by_dot += txt+","
  452. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  453. img_urls_seperate_by_dot = ''
  454. for iurl in image_urls:
  455. img_urls_seperate_by_dot += iurl+","
  456. img_urls_seperate_by_dot = img_urls_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,'multiLang':multiLang,'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')#1 means already running
  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. # if True:
  468. db.query('UPDATE video_queue_status SET status = 1;')
  469. c = rpyc.connect("localhost", 8858)
  470. c._config['sync_request_timeout'] = None
  471. remote_svc = c.root
  472. my_answer = remote_svc.call_video_gen(top1['name_hash'],top1['name'],top1['text_content'].split(','), top1['image_urls'].split(','),top1['multiLang'],top1['avatar']) # method call
  473. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  474. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  475. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  476. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  477. line_token = user_obj['line_token'] # aa
  478. left_time = user_obj['left_time']
  479. email = user_obj['email']
  480. print('left_time is '+str(left_time))
  481. if left_time is None:
  482. left_time = 5*60
  483. if left_time < vid_duration:
  484. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  485. print(msg)
  486. msg =msg.encode(encoding='utf-8')
  487. mailer.send(msg, email)
  488. #notify_line_user(msg, line_token)
  489. notify_group(name+":帳號餘額不足,請至email查看詳細資訊")
  490. else:
  491. left_time = left_time - vid_duration
  492. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  493. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  494. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  495. except Exception as e:
  496. logging.error(traceback.format_exc())
  497. print('video generation error')
  498. #notify_group('長影片錯誤-測試')
  499. db['video_queue'].delete(id=top1['id'])
  500. db.query('UPDATE video_queue_status SET status = 0')
  501. def gen_video_queue(name_hash,name,text_content, image_urls,avatar,multiLang,user_id):
  502. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  503. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  504. txt_content_seperate_by_dot = ''
  505. for txt in text_content:
  506. txt_content_seperate_by_dot += txt+","
  507. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  508. img_urls_seperate_by_dot = ''
  509. for iurl in image_urls:
  510. img_urls_seperate_by_dot += iurl+","
  511. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  512. 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})
  513. while True:
  514. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  515. print('another process running, leave loop')#1 means already running
  516. break
  517. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  518. print('all finish, leave loop')
  519. break
  520. top1 = first(db.query('SELECT * FROM video_queue'))
  521. try:
  522. # if True:
  523. db.query('UPDATE video_queue_status SET status = 1;')
  524. c = rpyc.connect("localhost", 8858)
  525. c._config['sync_request_timeout'] = None
  526. remote_svc = c.root
  527. 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
  528. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  529. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  530. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  531. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  532. line_token = user_obj['line_token'] # aa
  533. left_time = user_obj['left_time']
  534. email = user_obj['email']
  535. print('left_time is '+str(left_time))
  536. if left_time is None:
  537. left_time = 5*60
  538. if left_time < vid_duration:
  539. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  540. print(msg)
  541. msg =msg.encode(encoding='utf-8')
  542. mailer.send(msg, email)
  543. notify_line_user(msg, line_token)
  544. else:
  545. left_time = left_time - vid_duration
  546. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  547. #notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  548. notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  549. except Exception as e:
  550. logging.error(traceback.format_exc())
  551. print('video generation error')
  552. notify_group('影片錯誤')
  553. db['video_queue'].delete(id=top1['id'])
  554. db.query('UPDATE video_queue_status SET status = 0')
  555. def gen_video_queue_eng(name_hash,name,text_content, image_urls,sub_titles,avatar):
  556. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  557. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  558. txt_content_seperate_by_dot = ''
  559. for txt in text_content:
  560. txt_content_seperate_by_dot += txt+","
  561. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  562. img_urls_seperate_by_dot = ''
  563. for iurl in image_urls:
  564. img_urls_seperate_by_dot += iurl+","
  565. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  566. subtitles_seperate_by_dot = ''
  567. for sub in sub_titles:
  568. subtitles_seperate_by_dot += sub+","
  569. subtitles_seperate_by_dot = subtitles_seperate_by_dot[:-1]
  570. 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})
  571. while True:
  572. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  573. print('another process running, leave loop')
  574. break
  575. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  576. print('all finish, leave loop')
  577. break
  578. top1 = first(db.query('SELECT * FROM video_queue'))
  579. try:
  580. db.query('UPDATE video_queue_status SET status = 1;')
  581. c = rpyc.connect("localhost", 8858)
  582. c._config['sync_request_timeout'] = None
  583. remote_svc = c.root
  584. 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
  585. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  586. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  587. except:
  588. print('video generation error')
  589. notify_group('影片錯誤')
  590. db['video_queue'].delete(id=top1['id'])
  591. db.query('UPDATE video_queue_status SET status = 0')
  592. def gen_avatar(name_hash, imgurl):
  593. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  594. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  595. while True:
  596. statement = 'SELECT * FROM avatar_service_status'#only one row in this table, which is the id 1 one
  597. status = -1
  598. for row in db.query(statement):
  599. status = row['status']
  600. if status == 1:
  601. print('leave process loop')
  602. break
  603. statement = 'SELECT * FROM avatar_queue'
  604. works = []
  605. for row in db.query(statement):
  606. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':row['imgurl']})
  607. if len(works)==0:
  608. print('leave process loop')
  609. break
  610. try:
  611. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  612. db.query(statement)
  613. name_hash = works[0]['name_hash']
  614. imgurl = works[0]['imgurl']
  615. c = rpyc.connect("localhost", 8868)
  616. c._config['sync_request_timeout'] = None
  617. remote_svc = c.root
  618. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  619. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  620. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  621. except:
  622. print('gen error')
  623. notify_group('無法辨識人臉')
  624. db['avatar_queue'].delete(id=works[0]['id'])
  625. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;' #only one row in this table, which id 1 one
  626. db.query(statement)