main.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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 pydantic import BaseModel
  5. from typing import List, Optional
  6. from os.path import isfile, isdir, join
  7. import threading
  8. import zhtts
  9. import os
  10. import urllib
  11. import requests
  12. from bs4 import BeautifulSoup
  13. from PIL import Image,ImageDraw,ImageFont
  14. import pyttsx3
  15. import rpyc
  16. import random
  17. import time
  18. import math
  19. import hashlib
  20. import re
  21. import asyncio
  22. import urllib.request
  23. from fastapi.responses import FileResponse
  24. from fastapi.middleware.cors import CORSMiddleware
  25. import dataset
  26. from datetime import datetime, timedelta
  27. from util.swap_face import swap_face
  28. from fastapi.staticfiles import StaticFiles
  29. import shutil
  30. import io
  31. from first import first
  32. from passlib.context import CryptContext
  33. from jose import JWTError, jwt
  34. from fastapi_jwt_auth import AuthJWT
  35. from fastapi_jwt_auth.exceptions import AuthJWTException
  36. from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
  37. import util.models
  38. import pymysql
  39. import mailer
  40. from moviepy.editor import VideoFileClip
  41. import traceback
  42. import logging
  43. import gSlide
  44. import aiofiles
  45. import json
  46. import util.user
  47. pymysql.install_as_MySQLdb()
  48. app = FastAPI()
  49. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  50. print("db loaded")
  51. mode = 'run'
  52. app.add_middleware(
  53. CORSMiddleware,
  54. allow_origins=["*"],
  55. allow_credentials=True,
  56. allow_methods=["*"],
  57. allow_headers=["*"],
  58. )
  59. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  60. ALGORITHM = "HS256"
  61. ACCESS_TOKEN_EXPIRE_DAYS = 5
  62. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  63. app.mount("/static", StaticFiles(directory="static"), name="static")
  64. app.mount("/static/img", StaticFiles(directory="static/img"), name="static/img")
  65. app.mount("/templates", StaticFiles(directory="templates"), name="templates")
  66. templates = Jinja2Templates(directory="templates")
  67. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
  68. tmp_video_dir = '../OpenshotService/tmp_video/'
  69. tmp_avatar_dir = '../../face_swap/tmp_avatar/' #change source face path here
  70. resource_server = 'www.choozmo.com:8168/'
  71. resource_folder = '/var/www/html/'
  72. video_sub_folder = 'ai_anchor_video/'
  73. avatar_sub_folder = 'swap_save/'
  74. tmp_img_sub_folder = 'tmp_img/'
  75. pttx_sub_folder = 'tmp_pttx/'
  76. img_upload_folder = '/var/www/html/'+tmp_img_sub_folder
  77. video_dest = '/var/www/html/'+video_sub_folder
  78. avatar_dest = '/var/www/html/'+avatar_sub_folder
  79. pttx_dest = '/var/www/html/'+pttx_sub_folder
  80. speech_dest = '/var/www/html/speech/'
  81. # @app.get("/index2")
  82. # async def index2():
  83. # return FileResponse('static/index2.html')
  84. @app.get("/index_eng")
  85. async def index2():
  86. return FileResponse('static/index_eng.html')
  87. # home page
  88. @app.get("/index", response_class=HTMLResponse)
  89. async def get_home_page(request: Request, response: Response):
  90. return templates.TemplateResponse("index.html", {"request": request, "response": response})
  91. @app.get("/checkStatus")
  92. async def checkStatus():
  93. errorList = []
  94. try:
  95. conn = rpyc.classic.connect("192.168.1.105",18812)
  96. conn.close()
  97. except:
  98. errorList.append('105:18812 server')
  99. try:
  100. c = rpyc.connect("localhost", 8858)
  101. c.close()
  102. except:
  103. errorList.append('make_video(docker name : new openshot)')
  104. try:
  105. c = rpyc.connect("localhost", 8868)
  106. c.close()
  107. except:
  108. errorList.append('swap_face(docker name : fcontainer)')
  109. return {'errors':errorList}
  110. @app.get("/", response_class=HTMLResponse)
  111. async def get_home_page(request: Request, response: Response):
  112. return templates.TemplateResponse("index.html", {"request": request, "response": response})
  113. @app.get("/make_video")
  114. async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  115. try:
  116. Authorize.jwt_required()
  117. except Exception as e:
  118. print(e)
  119. return {'msg':{'eng':'Please login first','zh':'請先登入帳號'}}
  120. current_user = Authorize.get_jwt_subject()
  121. return templates.TemplateResponse("make_video.html", {"request": request, "response": response})
  122. @app.get("/make_video_long", response_class=HTMLResponse)
  123. async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  124. try:
  125. Authorize.jwt_required()
  126. except Exception as e:
  127. print(e)
  128. return {'msg':{'eng':'Please login first','zh':'請先登入帳號'}}
  129. current_user = Authorize.get_jwt_subject()
  130. return templates.TemplateResponse("make_video_long.html", {"request": request, "response": response})
  131. @app.get("/make_video_slide", response_class=HTMLResponse)
  132. async def make_video_slide(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  133. try:
  134. Authorize.jwt_required()
  135. except Exception as e:
  136. print(e)
  137. return {'msg':{'eng':'Please login first','zh':'請先登入帳號'}}
  138. current_user = Authorize.get_jwt_subject()
  139. return templates.TemplateResponse("make_video_slide.html", {"request": request, "response": response})
  140. @app.post('/user_profile',response_class=HTMLResponse)
  141. async def user_profile(token: str = Depends(oauth2_scheme)):
  142. db_check()
  143. if 'ok'!=verify_jwt_token(token):
  144. return {'msg':{'eng':'Please login first','zh':'請先登入帳號'}}
  145. user_id = get_user_id(token)
  146. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  147. if user_obj is None:
  148. raise HTTPException(
  149. status_code=status.HTTP_401_UNAUTHORIZED,
  150. detail="Missing token",
  151. headers={"WWW-Authenticate": "Bearer"},
  152. )
  153. video_num = str(first(db.query('SELECT COUNT(*) FROM history_input WHERE user_id ='+str(user_obj['id'])))['COUNT(*)'])
  154. total_sec = str(first(db.query('SELECT SUM(duration) FROM history_input where user_id='+str(user_obj['id'])))['SUM(duration)'])
  155. left_sec = user_obj['left_time']
  156. video_info_list = []
  157. statement = 'SELECT * FROM history_input WHERE user_id='+str(user_obj['id'])+' ORDER BY timestamp DESC LIMIT 50'
  158. for row in db.query(statement):
  159. video_info_list.append({'id':row['id'],'title':row['name'],'duration':row['duration'],'url':row['link'],'time_stamp':row['timestamp'].strftime("%m/%d/%Y, %H:%M:%S")})
  160. dic_return = {'user_info':{'id':user_id,'userName':user_obj['username'],'email':user_obj['email'],'video_num':video_num,'total_sec':total_sec,'left_sec':user_obj['left_time']},'video_info':video_info_list}
  161. str_return = json.dumps(dic_return)
  162. return str_return
  163. @app.post('/edit_profile')
  164. async def edit_profile(userModel : util.models.UserProfile ,token: str = Depends(oauth2_scheme)):
  165. db_check()
  166. print(token)
  167. user_id = get_user_id(token)
  168. print(user_id)
  169. user_obj = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  170. user_obj['email'] = userModel.email
  171. db['users'].update(user_obj,['id'])
  172. return {'msg':'ok'}
  173. # login & register page
  174. @app.get("/login", response_class=HTMLResponse)
  175. async def get_login_and_register_page(request: Request):
  176. return templates.TemplateResponse("login.html", {"request": request})
  177. @app.post("/login")
  178. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  179. db_check()
  180. user = authenticate_user(form_data.username, form_data.password)
  181. if not user:
  182. raise HTTPException(
  183. status_code=status.HTTP_401_UNAUTHORIZED,
  184. detail="Incorrect username or password",
  185. headers={"WWW-Authenticate": "Bearer"},
  186. )
  187. access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  188. access_token = create_access_token(
  189. data={"sub": user.username}, expires_delta=access_token_expires
  190. )
  191. table = db['users']
  192. user.token = access_token
  193. table.update(dict(user), ['username'])
  194. expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  195. access_token = Authorize.create_access_token(subject=user.username, expires_time=expires)
  196. refresh_token = Authorize.create_refresh_token(subject=user.username, expires_time =expires)
  197. Authorize.set_access_cookies(access_token)
  198. Authorize.set_refresh_cookies(refresh_token)
  199. #return templates.TemplateResponse("index.html", {"request": request, "msg": 'Login'})
  200. if util.user.email_veri_pass(form_data.username):
  201. return {"access_token": access_token, "token_type": "bearer",'veri':'ok'}
  202. else:
  203. veri_obj = first(db.query('SELECT * FROM register_veri_code where user_id ="'+str(user_dict['id'])+'"'))
  204. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+veri_obj['code'], user.email)
  205. return {"access_token": access_token, "token_type": "bearer",'veri':'fail'}
  206. @app.post("/token")
  207. async def access_token(form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  208. user = authenticate_user(form_data.username, form_data.password)
  209. if not user:
  210. raise HTTPException(
  211. status_code=status.HTTP_401_UNAUTHORIZED,
  212. detail="Incorrect username or password",
  213. headers={"WWW-Authenticate": "Bearer"},
  214. )
  215. access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  216. access_token = create_access_token(
  217. data={"sub": user.username}, expires_delta=access_token_expires
  218. )
  219. return {"access_token": access_token, "token_type": "bearer"}
  220. #前後端分離完全實現後拔除
  221. @app.post("/register_old")
  222. async def register_old(request: Request):
  223. db_check()
  224. user = util.models.User(**await request.form())
  225. user_obj = first(db.query('SELECT * FROM users where username ="'+str(user.username)+'"'))
  226. if user_obj == None:
  227. id = user_register(user)
  228. result = util.user.add_to_basic_role(id)
  229. print(result)
  230. if type(id) is int:
  231. code = str(time.time()).replace('.','')
  232. db['register_veri_code'].insert({'code':code,'user_id':id})
  233. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+code, user.email)
  234. return {'msg':{'eng':'Register success! Please login at previous page','zh':'註冊成功! 請回到上頁登入帳號'}}
  235. else :
  236. return {'msg':{'eng':'error','zh':'error'}}
  237. #return templates.TemplateResponse("make_video.html", {"request": request, "success": True},status_code=status.HTTP_302_FOUND)
  238. #return templates.TemplateResponse("login.html", {'request': request,"success": True}, status_code=status.HTTP_302_FOUND)
  239. else:
  240. return {'msg':{'eng':user.username+' is duplicated user name try another','zh':user.username+'重複,請更改'}}
  241. @app.post("/register")
  242. async def register(request: util.models.register_req):
  243. db_check()
  244. user_obj = first(db.query('SELECT * FROM users where username ="'+str(request.username)+'"'))
  245. if user_obj == None:
  246. id = user_register(request)
  247. result = util.user.add_to_basic_role(id)
  248. print(result)
  249. if type(id) is int:
  250. code = str(time.time()).replace('.','')
  251. db['register_veri_code'].insert({'code':code,'user_id':id})
  252. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+code, request.email)
  253. return {'msg':{'eng':'Register success! Please login at previous page','zh':'註冊成功! 請回到上頁登入帳號'}}
  254. else :
  255. return {'msg':{'eng':'error','zh':'error'}}
  256. else:
  257. return {'msg':{'eng':user.username+' is duplicated user name try another','zh':user.username+'重複,請更改'}}
  258. @app.get('/logout')
  259. def logout(request: Request, Authorize: AuthJWT = Depends()):
  260. Authorize.jwt_required()
  261. Authorize.unset_jwt_cookies()
  262. return {"msg": "ok"}
  263. @app.post('/logout_jwt')
  264. def logout(token: str = Depends(oauth2_scheme)):
  265. db_check()
  266. time_stamp = datetime.fromtimestamp(time.time())
  267. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  268. db['jwt_black_list'].insert({'token':token,'datetime':time_stamp})
  269. return {"msg": "ok"}
  270. @app.post('/get_role')
  271. async def get_role(token: str = Depends(oauth2_scheme)):
  272. user_id = util.user.get_user_id(token)
  273. roles = util.user.get_user_role(user_id)
  274. return roles
  275. @app.post('/create_role')
  276. async def get_role(token: str = Depends(oauth2_scheme)):
  277. user_id = get_user_id(token)
  278. return user_id
  279. @app.post('/get_avatar_by_role')
  280. async def get_role(token: str = Depends(oauth2_scheme)):
  281. user_id = util.user.get_user_id(token)
  282. avatar_info = util.user.get_avatar_by_role(user_id)
  283. return avatar_info
  284. @app.get('/verify_email')
  285. async def verify_email(code):
  286. db_check()
  287. veri_obj = first(db.query('SELECT * FROM register_veri_code where code ="'+str(code)+'"'))
  288. if veri_obj != None:
  289. db['register_veri_code'].delete(code=code)
  290. return {"msg": "ok"}
  291. @app.get("/reset_pwd_page_email")
  292. async def reset_pwd_page():
  293. return FileResponse('static/reset_pwd_email.html')
  294. @app.get("/reset_pwd_page")
  295. async def reset_pwd_page():
  296. return FileResponse('static/reset_pwd.html')
  297. @app.get('/send_reset_pwd')
  298. async def send_reset_pwd(user_id,email):
  299. db_check()
  300. code = str(time.time()).replace('.','')
  301. db['reset_pw_code'].insert({'code':code,'user_id':user_id,'email':email})
  302. msg = '請至點擊網址以重設密碼 : https://www.choozmo.com:8887/reset_pwd_page 通行碼為 '+ code
  303. print(msg)
  304. msg =msg.encode(encoding='utf-8')
  305. print(msg)
  306. print(type(user_id))
  307. if int(user_id) != -1:
  308. print('print at first place')
  309. print(user_id)
  310. user_dict = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  311. else:
  312. user_id = util.user.get_id_by_email(email)
  313. print(user_id)
  314. user_dict = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  315. mailer.send(msg, user_dict['email'])
  316. return {'msg':'ok'}
  317. @app.post('/reset_pwd')
  318. async def reset_password(req :util.models.reset_pwd):
  319. db_check()
  320. print(req.code)
  321. veri_obj = next(iter(db.query('SELECT * FROM reset_pw_code where code ="'+str(req.code)+'"')))
  322. print(veri_obj['user_id'])
  323. user_id = util.user.get_id_by_email(veri_obj['email'])
  324. print(user_id)
  325. db.query('UPDATE users SET password = '+'"'+get_password_hash(req.password)+'" where id ='+str(user_id))
  326. if veri_obj != None:
  327. db['reset_pw_code'].delete(code=req.code)
  328. return {"msg": "ok"}
  329. @app.get("/gen_avatar")
  330. async def avatar():
  331. return FileResponse('static/gen_avatar.html')
  332. @app.post("/swapFace")
  333. async def swapFace(req:util.models.swap_req):
  334. if 'http' not in req.imgurl:
  335. req.imgurl= 'http://'+req.imgurl
  336. try:
  337. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  338. im= im.convert("RGB")
  339. except:
  340. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  341. name_hash = str(time.time()).replace('.','')
  342. x = threading.Thread(target=gen_avatar, args=(name_hash,req.imgurl))
  343. x.start()
  344. return {'msg':'ok'}
  345. @app.post("/uploadfile/")
  346. async def create_upload_file(file: UploadFile = File(...)):
  347. img_name = str(time.time()).replace('.','')
  348. try:
  349. if file.content_type=='video/mp4':
  350. async with aiofiles.open(img_upload_folder+img_name+'.mp4', 'wb') as out_file:
  351. content = await file.read()
  352. await out_file.write(content)
  353. return {"msg": resource_server+tmp_img_sub_folder+img_name+'.mp4'}
  354. else:
  355. contents = await file.read()
  356. image = Image.open(io.BytesIO(contents))
  357. image= image.convert("RGB")
  358. image.save(img_upload_folder+img_name+'.jpg')
  359. return {"msg": resource_server+tmp_img_sub_folder+img_name+'.jpg'}
  360. except Exception as e:
  361. logging.error(traceback.format_exc())
  362. return {'msg':{'eng':'file cant be prossessed','zh':'檔案無法使用'}}
  363. @app.post("/upload_pttx/")
  364. async def upload_pttx(file: UploadFile = File(...)):
  365. try:
  366. if "_" in file.filename:
  367. return {'msg':{'eng':'symbol"_" is not allowed in file name','zh':'檔案無法使用檔名不能含有"_"符號'}}
  368. else:
  369. pttx_name = file.filename+'_'+str(time.time()).replace('.','')
  370. with open(pttx_dest+pttx_name, "wb+") as file_object:
  371. file_object.write(file.file.read())
  372. return {"msg": resource_server+pttx_sub_folder+pttx_name}
  373. except Exception as e:
  374. logging.error(traceback.format_exc())
  375. return {'msg':{'eng':'file cant be prossessed','zh':'檔案無法使用'}}
  376. @app.post("/make_anchor_video_gSlide")
  377. async def make_anchor_video_gSlide(req:util.models.gSlide_req,token: str = Depends(oauth2_scheme)):
  378. if req.url_type == 0:
  379. name, text_content, image_urls = gSlide.parse_slide_url(req.slide_url,eng=False)
  380. else :
  381. filename = req.slide_url.replace(resource_server+pttx_sub_folder,resource_folder+pttx_sub_folder)
  382. name, text_content, image_urls = gSlide.parse_pttx_url(filename,img_upload_folder,resource_server+tmp_img_sub_folder,eng=False)
  383. if len(image_urls) != len(text_content):
  384. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  385. for idx in range(len(image_urls)):
  386. if 'http' not in image_urls[idx]:
  387. image_urls[idx] = 'http://'+image_urls[idx]
  388. if req.multiLang==0:
  389. for txt in text_content:
  390. if re.search('[a-zA-Z]', txt) !=None:
  391. print('語言錯誤')
  392. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  393. if re.search(',', txt) !=None:
  394. print('包含非法符號')
  395. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  396. name_hash = str(time.time()).replace('.','')
  397. for imgu in image_urls:
  398. try:
  399. if get_url_type(imgu) =='video/mp4':
  400. r=requests.get(imgu)
  401. else:
  402. im = Image.open(requests.get(imgu, stream=True).raw)
  403. im= im.convert("RGB")
  404. except:
  405. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  406. user_id = get_user_id(token)
  407. proto_req = util.models.request_normal()
  408. proto_req.text_content = text_content
  409. proto_req.name = name
  410. proto_req.image_urls = image_urls
  411. proto_req.avatar = req.avatar
  412. proto_req.multiLang = req.multiLang
  413. video_id = save_history(proto_req,name_hash,user_id)
  414. x = threading.Thread(target=gen_video_queue, args=(name_hash,name, text_content, image_urls,int(req.avatar),req.multiLang,video_id,user_id))
  415. x.start()
  416. return {"msg":"ok"}
  417. @app.post("/make_anchor_video_long")
  418. async def make_anchor_video_long(req:util.models.request,token: str = Depends(oauth2_scheme)):
  419. db_check()
  420. left_tag = [m.start() for m in re.finditer('{', req.text_content[0])]
  421. if len(req.image_urls) != len(left_tag):
  422. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  423. for idx in range(len(req.image_urls)):
  424. if 'http' not in req.image_urls[idx]:
  425. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  426. if req.multiLang==0:
  427. for txt in req.text_content:
  428. if re.search('[a-zA-Z]', txt) !=None:
  429. print('語言錯誤')
  430. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  431. if re.search(',', txt) !=None:
  432. print('包含非法符號')
  433. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  434. name_hash = str(time.time()).replace('.','')
  435. for imgu in req.image_urls:
  436. try:
  437. if get_url_type(imgu) =='video/mp4':
  438. r=requests.get(imgu)
  439. else:
  440. im = Image.open(requests.get(imgu, stream=True).raw)
  441. im= im.convert("RGB")
  442. except:
  443. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  444. user_id = get_user_id(token)
  445. video_id = save_history(req,name_hash,user_id)
  446. x = threading.Thread(target=gen_video_long_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.multiLang,video_id,user_id))
  447. x.start()
  448. returnMsg = ''
  449. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  450. returnMsg = {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  451. else:
  452. returnMsg = {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  453. return returnMsg
  454. @app.post("/make_anchor_video")
  455. async def make_anchor_video(req:util.models.request,token: str = Depends(oauth2_scheme)):
  456. db_check()
  457. if len(req.image_urls) != len(req.text_content):
  458. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  459. for idx in range(len(req.image_urls)):
  460. if 'http' not in req.image_urls[idx]:
  461. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  462. if req.multiLang==0:
  463. for txt in req.text_content:
  464. if re.search('[a-zA-Z]', txt) !=None:
  465. print('語言錯誤')
  466. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  467. if re.search(',', txt) !=None:
  468. print('包含非法符號')
  469. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  470. name_hash = str(time.time()).replace('.','')
  471. for imgu in req.image_urls:
  472. try:
  473. if get_url_type(imgu) =='video/mp4':
  474. r=requests.get(imgu)
  475. else:
  476. im = Image.open(requests.get(imgu, stream=True).raw)
  477. im= im.convert("RGB")
  478. except:
  479. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  480. user_id = get_user_id(token)
  481. video_id = save_history(req,name_hash,user_id)
  482. x = threading.Thread(target=gen_video_queue, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.multiLang,video_id,user_id))
  483. x.start()
  484. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  485. return {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  486. else:
  487. return {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  488. return {'msg':'ok'}
  489. @app.post("/make_anchor_video_eng")
  490. async def make_anchor_video_eng(req:util.models.request_eng,token: str = Depends(oauth2_scheme)):
  491. db_check()
  492. if len(req.image_urls) != len(req.sub_titles) or len(req.sub_titles) != len(req.text_content):
  493. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  494. for idx in range(len(req.image_urls)):
  495. if 'http' not in req.image_urls[idx]:
  496. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  497. name_hash = str(time.time()).replace('.','')
  498. for imgu in req.image_urls:
  499. try:
  500. if get_url_type(imgu) =='video/mp4':
  501. r=requests.get(imgu)
  502. else:
  503. im = Image.open(requests.get(imgu, stream=True).raw)
  504. im= im.convert("RGB")
  505. except:
  506. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  507. user_id = get_user_id(token)
  508. video_id = save_history(req,name_hash, user_id)
  509. 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),video_id))
  510. x.start()
  511. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  512. return {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  513. else:
  514. return {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  515. return {"msg":"ok"}
  516. @app.post("/save_draft")
  517. async def save_draft(req:util.models.video_draft,token: str = Depends(oauth2_scheme)):
  518. db_check()
  519. user_id = get_user_id(token)
  520. txt_content_seperate_by_dot = ''
  521. for txt in req.text_content:
  522. txt_content_seperate_by_dot += txt+","
  523. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  524. img_urls_seperate_by_dot = ''
  525. for iurl in req.image_urls:
  526. img_urls_seperate_by_dot += iurl+","
  527. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  528. time_stamp = datetime.fromtimestamp(time.time())
  529. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  530. if req.id==-1:
  531. pk = db['draft'].insert({'title':req.title,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  532. ,'user_id':user_id,'avatar':req.avatar,'multiLang':req.multiLang,'time_stamp':time_stamp})
  533. else:
  534. db['draft'].update({'id':req.id,'title':req.title,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  535. ,'user_id':user_id,'avatar':req.avatar,'multiLang':req.multiLang,'time_stamp':time_stamp},['id'])
  536. return {'msg':'ok'}
  537. @app.post('/draft_list')
  538. async def draft_list(token: str = Depends(oauth2_scheme)):
  539. db_check()
  540. user_id = get_user_id(token)
  541. statement = 'SELECT * FROM draft WHERE user_id='+str(user_id)+' ORDER BY time_stamp DESC LIMIT 50'
  542. logs = []
  543. for row in db.query(statement):
  544. logs.append({'id':row['id'],'title':row['title'],'avatar':row['avatar'],'mulitLang':row['multiLang']
  545. ,'text_content':row['text_content'].split(','),'image_urls':row['image_urls'].split(',')})
  546. return logs
  547. @app.post('/del_draft')
  548. async def del_draft(id_obj:util.models.id_obj,token: str = Depends(oauth2_scheme)):
  549. db_check()
  550. user_id = get_user_id(token)
  551. statement = 'SELECT * FROM draft WHERE user_id="'+str(user_id)+'" and id ="'+str(id_obj.id)+'"'
  552. if first(db.query(statement)) is not None:
  553. db['draft'].delete(id=id_obj.id)
  554. else:
  555. return {'msg':'wrong id'}
  556. return {'msg':'ok'}
  557. @app.get("/history_input_old")
  558. async def history_input_old(request: Request, Authorize: AuthJWT = Depends()):
  559. db_check()
  560. Authorize.jwt_required()
  561. current_user = Authorize.get_jwt_subject()
  562. user_id = first(db.query('SELECT * FROM users where username="' + current_user +'"'))['id']
  563. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  564. logs = []
  565. for row in db.query(statement):
  566. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  567. return logs
  568. @app.post("/history_input")
  569. async def history_input(token: str = Depends(oauth2_scheme)):
  570. db_check()
  571. user_id = get_user_id(token)
  572. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  573. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  574. logs = []
  575. for row in db.query(statement):
  576. logs.append({'id':row['id'],'name':row['name'],'avatar':row['avatar'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  577. return logs
  578. @AuthJWT.load_config
  579. def get_config():
  580. return util.models.Settings()
  581. @app.exception_handler(AuthJWTException)
  582. def authjwt_exception_handler(request: Request, exc: AuthJWTException):
  583. return JSONResponse(
  584. status_code=exc.status_code,
  585. content={"detail": exc.message}
  586. )
  587. def get_user_id(token):
  588. db_check()
  589. credentials_exception = HTTPException(
  590. status_code=status.HTTP_401_UNAUTHORIZED,
  591. detail="Could not validate credentials",
  592. headers={"WWW-Authenticate": "Bearer"},
  593. )
  594. try:
  595. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  596. username: str = payload.get("sub")
  597. if username is None:
  598. raise credentials_exception
  599. token_data = util.models.TokenData(username=username)
  600. except JWTError:
  601. raise credentials_exception
  602. user = get_user(username=token_data.username)
  603. if user is None:
  604. raise credentials_exception
  605. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  606. return user_id
  607. def check_user_exists(username):
  608. db_check()
  609. if int(next(iter(db.query('SELECT COUNT(*) FROM AI_anchor.users WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
  610. return True
  611. else:
  612. return False
  613. def get_user(username: str):
  614. if not check_user_exists(username): # if user don't exist
  615. return False
  616. user_dict = next(
  617. iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  618. user = util.models.User(**user_dict)
  619. return user
  620. def user_register(user):
  621. db_check()
  622. table = db['users']
  623. user.password = get_password_hash(user.password)
  624. id = table.insert(dict(user))
  625. return id
  626. def get_password_hash(password):
  627. return pwd_context.hash(password)
  628. def verify_password(plain_password, hashed_password):
  629. return pwd_context.verify(plain_password, hashed_password)
  630. def authenticate_user(username: str, password: str):
  631. db_check()
  632. if not check_user_exists(username): # if user don't exist
  633. return False
  634. user_dict = next(iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  635. user = util.models.User(**user_dict)
  636. if not verify_password(password, user.password):
  637. return False
  638. return user
  639. def create_access_token(data: dict, expires_delta):
  640. to_encode = data.copy()
  641. expire = datetime.utcnow() + expires_delta
  642. to_encode.update({"exp": expire})
  643. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  644. return encoded_jwt
  645. def save_history(req,name_hash,user_id):
  646. db_check()
  647. log_table = db['history_input']
  648. txt_content_seperate_by_dot = ''
  649. for txt in req.text_content:
  650. txt_content_seperate_by_dot += txt+","
  651. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  652. img_urls_seperate_by_dot = ''
  653. for iurl in req.image_urls:
  654. img_urls_seperate_by_dot += iurl+","
  655. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  656. time_stamp = datetime.fromtimestamp(time.time())
  657. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  658. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  659. ,'user_id':user_id,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','avatar':req.avatar,'timestamp':time_stamp})
  660. return pk
  661. def get_url_type(url):
  662. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  663. r = urllib.request.urlopen(req)
  664. contentType = r.getheader('Content-Type')
  665. return contentType
  666. def notify_group(msg):
  667. #'WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD' is ChoozmoTeam
  668. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']
  669. for gid in glist:
  670. headers = {"Authorization": "Bearer " + gid,"Content-Type": "application/x-www-form-urlencoded"}
  671. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params={"message": msg})
  672. def gen_video_long_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  673. db_check()
  674. if name_hash == 'keepRunning':
  675. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="longvideo"'))['COUNT(1)'] == 0:
  676. return
  677. db.query('UPDATE video_queue_status SET status = 0;')
  678. print('start clear long video')
  679. else:
  680. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  681. txt_content_seperate_by_dot = ''
  682. for txt in text_content:
  683. txt_content_seperate_by_dot += txt+","
  684. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  685. img_urls_seperate_by_dot = ''
  686. for iurl in image_urls:
  687. img_urls_seperate_by_dot += iurl+","
  688. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  689. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot
  690. ,'image_urls':img_urls_seperate_by_dot,'multiLang':multiLang,'video_type':'longvideo','avatar':avatar,'timestamp':time_stamp})
  691. while True:
  692. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  693. print('another process running, leave loop')#1 means already running
  694. break
  695. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="longvideo"'))['COUNT(1)'] == 0:
  696. print('all finish, leave loop')
  697. break
  698. top1 = first(db.query('SELECT * FROM video_queue where video_type="longvideo"'))
  699. try:
  700. # if True:
  701. db.query('UPDATE video_queue_status SET status = 1;')
  702. c = rpyc.connect("localhost", 8858)
  703. c._config['sync_request_timeout'] = None
  704. remote_svc = c.root
  705. 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
  706. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  707. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  708. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  709. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  710. line_token = user_obj['line_token'] # aa
  711. left_time = user_obj['left_time']
  712. email = user_obj['email']
  713. print('left_time is '+str(left_time))
  714. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  715. if left_time is None:
  716. left_time = 5*60
  717. if left_time < vid_duration:
  718. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  719. print(msg)
  720. msg =msg.encode(encoding='utf-8')
  721. mailer.send_left_not_enough(msg, email)
  722. #notify_line_user(msg, line_token)
  723. notify_group(name+":帳號餘額不足,請至email查看詳細資訊")
  724. else:
  725. left_time = left_time - vid_duration
  726. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  727. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  728. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  729. except Exception as e:
  730. logging.error(traceback.format_exc())
  731. print('video generation error')
  732. notify_group('長影片錯誤-測試')
  733. db['video_queue'].delete(id=top1['id'])
  734. db.query('UPDATE video_queue_status SET status = 0')
  735. def gen_video_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  736. db_check()
  737. if name_hash == 'keepRunning':
  738. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="short"'))['COUNT(1)'] == 0:
  739. return
  740. db.query('UPDATE video_queue_status SET status = 0;')
  741. print('start clear short video')
  742. else:
  743. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  744. txt_content_seperate_by_dot = ''
  745. for txt in text_content:
  746. txt_content_seperate_by_dot += txt+","
  747. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  748. img_urls_seperate_by_dot = ''
  749. for iurl in image_urls:
  750. img_urls_seperate_by_dot += iurl+","
  751. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  752. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot
  753. ,'image_urls':img_urls_seperate_by_dot,'multiLang':multiLang,'video_type':'short','avatar':avatar,'timestamp':time_stamp})
  754. while True:
  755. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  756. print('another process running, leave loop')#1 means already running
  757. break
  758. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="short"'))['COUNT(1)'] == 0:
  759. print('all finish, leave loop')
  760. break
  761. top1 = first(db.query('SELECT * FROM video_queue where video_type="short"'))
  762. try:
  763. # if True:
  764. db.query('UPDATE video_queue_status SET status = 1;')
  765. c = rpyc.connect("localhost", 8858)
  766. c._config['sync_request_timeout'] = None
  767. remote_svc = c.root
  768. 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
  769. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  770. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  771. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  772. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  773. line_token = user_obj['line_token'] # aa
  774. left_time = user_obj['left_time']
  775. email = user_obj['email']
  776. print('left_time is '+str(left_time))
  777. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  778. if left_time is None:
  779. left_time = 5*60
  780. if left_time < vid_duration:
  781. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  782. print(msg)
  783. msg =msg.encode(encoding='utf-8')
  784. mailer.send_left_not_enough(msg, email)
  785. notify_group(msg)
  786. #notify_line_user(msg, line_token)
  787. else:
  788. left_time = left_time - vid_duration
  789. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  790. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  791. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  792. except Exception as e:
  793. logging.error(traceback.format_exc())
  794. print('video generation error')
  795. notify_group('影片錯誤')
  796. db['video_queue'].delete(id=top1['id'])
  797. db.query('UPDATE video_queue_status SET status = 0')
  798. def gen_video_queue_eng(name_hash,name,text_content, image_urls,sub_titles,avatar,video_id):
  799. db_check()
  800. if name_hash == 'keepRunning':
  801. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="eng"'))['COUNT(1)'] == 0:
  802. return
  803. db.query('UPDATE video_queue_status SET status = 0;')
  804. print('start clear eng video')
  805. else:
  806. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  807. txt_content_seperate_by_dot = ''
  808. for txt in text_content:
  809. txt_content_seperate_by_dot += txt+","
  810. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  811. img_urls_seperate_by_dot = ''
  812. for iurl in image_urls:
  813. img_urls_seperate_by_dot += iurl+","
  814. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  815. subtitles_seperate_by_dot = ''
  816. for sub in sub_titles:
  817. subtitles_seperate_by_dot += sub+","
  818. subtitles_seperate_by_dot = subtitles_seperate_by_dot[:-1]
  819. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot,
  820. 'image_urls':img_urls_seperate_by_dot,'subtitles':subtitles_seperate_by_dot,'video_type':'eng','avatar':avatar,'timestamp':time_stamp})
  821. while True:
  822. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  823. print('another process running, leave loop')
  824. break
  825. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type=="eng"'))['COUNT(1)'] == 0:
  826. print('all finish, leave loop')
  827. break
  828. top1 = first(db.query('SELECT * FROM video_queue where video_type=="eng"'))
  829. try:
  830. db.query('UPDATE video_queue_status SET status = 1;')
  831. c = rpyc.connect("localhost", 8858)
  832. c._config['sync_request_timeout'] = None
  833. remote_svc = c.root
  834. 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
  835. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  836. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  837. notify_group(name+"(ENG)的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  838. except:
  839. print('video generation error')
  840. notify_group('影片錯誤')
  841. db['video_queue'].delete(id=top1['id'])
  842. db.query('UPDATE video_queue_status SET status = 0')
  843. def gen_avatar(name_hash, imgurl):
  844. db_check()
  845. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  846. while True:
  847. statement = 'SELECT * FROM avatar_service_status'#only one row in this table, which is the id 1 one
  848. status = -1
  849. for row in db.query(statement):
  850. status = row['status']
  851. if status == 1:
  852. print('leave process loop')
  853. break
  854. statement = 'SELECT * FROM avatar_queue'
  855. works = []
  856. for row in db.query(statement):
  857. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':row['imgurl']})
  858. if len(works)==0:
  859. print('leave process loop')
  860. break
  861. try:
  862. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  863. db.query(statement)
  864. name_hash = works[0]['name_hash']
  865. imgurl = works[0]['imgurl']
  866. c = rpyc.connect("localhost", 8868)
  867. c._config['sync_request_timeout'] = None
  868. remote_svc = c.root
  869. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  870. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  871. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  872. except:
  873. print('gen error')
  874. notify_group('無法辨識人臉')
  875. db['avatar_queue'].delete(id=works[0]['id'])
  876. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;' #only one row in this table, which id 1 one
  877. db.query(statement)
  878. def call_voice(text):
  879. print(text)
  880. print(len(text))
  881. print(type(text))
  882. c = rpyc.connect("localhost", 8858)
  883. c._config['sync_request_timeout'] = None
  884. remote_svc = c.root
  885. my_answer = remote_svc.make_speech(text) # method call
  886. src_path = '/home/ming/AI_Anchor/OpenshotService/speech.mp3'
  887. shutil.copy(src_path,'/home/ming/speech.mp3')
  888. os.remove(src_path)
  889. class text_in(BaseModel):
  890. text: str
  891. @app.post("/make_voice")
  892. async def make_voice(in_text:text_in):
  893. x = threading.Thread(target=call_voice, args=(in_text.text,))
  894. x.start()
  895. @app.post("/gen_speech")
  896. async def make_voice(req:util.models.speech_req):
  897. call_speech(req.text,req.speaker)
  898. return {'msg':'wait please'}
  899. def call_speech(text,speaker):
  900. conn = rpyc.classic.connect("192.168.1.105",8838)
  901. ros = conn.modules.os
  902. ros.system('docker exec -it mingc_tts bash gen_speech.sh '+text+' '+speaker)
  903. while True:
  904. print('waiting...')
  905. if ros.path.exists('/home/ming/workspace/TTS_fs2/fast_speech2_ming024/output/result/AISHELL3/'+text+'.wav'):
  906. break
  907. time.sleep(5)
  908. print('waiting...')
  909. fr=conn.builtins.open('/home/ming/workspace/TTS_fs2/fast_speech2_ming024/output/result/AISHELL3/'+text+'.wav','rb')
  910. fw=open(text+'.wav','wb')
  911. while True:
  912. b=fr.read(1024)
  913. if b:
  914. fw.write(b)
  915. else:
  916. break
  917. fr.close()
  918. fw.close()
  919. shutil.copy(text+'.wav',speech_dest+text+'.wav')
  920. os.remove(text+'.wav')
  921. notify_group("speech at www.choozmo.com:8168/speech/"+text+".wav")
  922. def verify_jwt_token(token):
  923. for row in db.query('SELECT * FROM jwt_black_list'):
  924. print(row)
  925. print(first(db.query('SELECT COUNT(*) FROM jwt_black_list where token="'+token+'"'))['COUNT(*)'])
  926. if first(db.query('SELECT COUNT(*) FROM jwt_black_list where token="'+token+'"'))['COUNT(*)'] == 0:
  927. return 'ok'
  928. else:
  929. return 'please login again'
  930. def db_check():
  931. global db
  932. db.close()
  933. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  934. def clear_video_queue():
  935. x = threading.Thread(target=gen_video_queue_eng, args=('keepRunning','', '', '','','',''))
  936. x.start()
  937. x2 = threading.Thread(target=gen_video_queue, args=('keepRunning','', '', '','','','',''))
  938. x2.start()
  939. x3 = threading.Thread(target=gen_video_long_queue, args=('keepRunning','', '', '','','','',''))
  940. x3.start()
  941. clear_video_queue()