main.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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.111",18812)
  96. conn.close()
  97. except:
  98. errorList.append('111: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['invite_code'] is None:
  148. util.user.init_invite_code(user_id)
  149. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  150. if user_obj is None:
  151. raise HTTPException(
  152. status_code=status.HTTP_401_UNAUTHORIZED,
  153. detail="Missing token",
  154. headers={"WWW-Authenticate": "Bearer"},
  155. )
  156. video_num = str(first(db.query('SELECT COUNT(*) FROM history_input WHERE user_id ='+str(user_obj['id'])))['COUNT(*)'])
  157. total_sec = str(first(db.query('SELECT SUM(duration) FROM history_input where user_id='+str(user_obj['id'])))['SUM(duration)'])
  158. left_sec = user_obj['left_time']
  159. video_info_list = []
  160. statement = 'SELECT * FROM history_input WHERE user_id='+str(user_obj['id'])+' ORDER BY timestamp DESC LIMIT 50'
  161. for row in db.query(statement):
  162. 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")})
  163. dic_return = {'user_info':{'id':user_id,'userName':user_obj['username'],'email':user_obj['email']
  164. ,'video_num':video_num,'total_sec':total_sec,'left_sec':user_obj['left_time'],'invite_code':user_obj['invite_code']}
  165. ,'video_info':video_info_list}
  166. str_return = json.dumps(dic_return)
  167. return str_return
  168. @app.post('/edit_profile')
  169. async def edit_profile(userModel : util.models.UserProfile ,token: str = Depends(oauth2_scheme)):
  170. db_check()
  171. print(token)
  172. user_id = get_user_id(token)
  173. print(user_id)
  174. user_obj = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  175. user_obj['email'] = userModel.email
  176. db['users'].update(user_obj,['id'])
  177. return {'msg':'ok'}
  178. # login & register page
  179. @app.get("/login", response_class=HTMLResponse)
  180. async def get_login_and_register_page(request: Request):
  181. return templates.TemplateResponse("login.html", {"request": request})
  182. @app.post("/login")
  183. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  184. db_check()
  185. user = authenticate_user(form_data.username, form_data.password)
  186. if not user:
  187. raise HTTPException(
  188. status_code=status.HTTP_401_UNAUTHORIZED,
  189. detail="Incorrect username or password",
  190. headers={"WWW-Authenticate": "Bearer"},
  191. )
  192. access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  193. access_token = create_access_token(
  194. data={"sub": user.username}, expires_delta=access_token_expires
  195. )
  196. table = db['users']
  197. user.token = access_token
  198. table.update(dict(user), ['username'])
  199. expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  200. access_token = Authorize.create_access_token(subject=user.username, expires_time=expires)
  201. refresh_token = Authorize.create_refresh_token(subject=user.username, expires_time =expires)
  202. Authorize.set_access_cookies(access_token)
  203. Authorize.set_refresh_cookies(refresh_token)
  204. #return templates.TemplateResponse("index.html", {"request": request, "msg": 'Login'})
  205. if util.user.email_veri_pass(form_data.username):
  206. return {"access_token": access_token, "token_type": "bearer",'veri':'ok'}
  207. else:
  208. veri_obj = first(db.query('SELECT * FROM register_veri_code where user_id ="'+str(user_dict['id'])+'"'))
  209. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+veri_obj['code'], user.email)
  210. return {"access_token": access_token, "token_type": "bearer",'veri':'fail'}
  211. @app.post("/token")
  212. async def access_token(form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  213. user = authenticate_user(form_data.username, form_data.password)
  214. if not user:
  215. raise HTTPException(
  216. status_code=status.HTTP_401_UNAUTHORIZED,
  217. detail="Incorrect username or password",
  218. headers={"WWW-Authenticate": "Bearer"},
  219. )
  220. access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  221. access_token = create_access_token(
  222. data={"sub": user.username}, expires_delta=access_token_expires
  223. )
  224. return {"access_token": access_token, "token_type": "bearer"}
  225. #前後端分離完全實現後拔除
  226. @app.post("/register_old")
  227. async def register_old(request: Request):
  228. db_check()
  229. user = util.models.User(**await request.form())
  230. user_obj = first(db.query('SELECT * FROM users where username ="'+str(user.username)+'"'))
  231. if user_obj == None:
  232. id = user_register(user)
  233. result = util.user.add_to_basic_role(id)
  234. print(result)
  235. if type(id) is int:
  236. code = str(time.time()).replace('.','')
  237. db['register_veri_code'].insert({'code':code,'user_id':id})
  238. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+code, user.email)
  239. return {'msg':{'eng':'Register success! Please login at previous page','zh':'註冊成功! 請回到上頁登入帳號'}}
  240. else :
  241. return {'msg':{'eng':'error','zh':'error'}}
  242. #return templates.TemplateResponse("make_video.html", {"request": request, "success": True},status_code=status.HTTP_302_FOUND)
  243. #return templates.TemplateResponse("login.html", {'request': request,"success": True}, status_code=status.HTTP_302_FOUND)
  244. else:
  245. return {'msg':{'eng':user.username+' is duplicated user name try another','zh':user.username+'重複,請更改'}}
  246. @app.post("/register")
  247. async def register(request: util.models.register_req):
  248. db_check()
  249. user_obj = first(db.query('SELECT * FROM users where username ="'+str(request.username)+'"'))
  250. if user_obj == None:
  251. id = user_register(request)
  252. result = util.user.add_to_basic_role(id)
  253. print(result)
  254. if type(id) is int:
  255. code = str(time.time()).replace('.','')
  256. db['register_veri_code'].insert({'code':code,'user_id':id})
  257. try:
  258. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+code, request.email)
  259. return {'msg':{'eng':'Register success! Please check your mailbox to verify your email','zh':'註冊成功! 請至信箱收取驗證信'}}
  260. except:
  261. return {'msg':{'eng':'Invalid email address','zh':'無法寄送認證信!'}}
  262. else :
  263. return {'msg':{'eng':'error','zh':'error'}}
  264. else:
  265. return {'msg':{'eng':user_obj['username']+' is duplicated user name try another','zh':user_obj['username']+'重複,請更改'}}
  266. @app.post("/register_by_invite")
  267. async def register_by_invite(request: util.models.register_invite_req):
  268. db_check()
  269. user_obj = first(db.query('SELECT * FROM users where username ="'+str(request.username)+'"'))
  270. if user_obj == None:
  271. invcode = request.invite_code
  272. sha = hashlib.sha256()
  273. sha.update(str(time.time()).replace('.','').encode())
  274. request.invite_code = sha.hexdigest()
  275. id = user_register(request)
  276. result = util.user.add_to_basic_role(id)
  277. if type(id) is int:
  278. code = str(time.time()).replace('.','')
  279. db['register_veri_code'].insert({'code':code,'user_id':id})
  280. try:
  281. mailer.register_verify('請至點擊網址驗證 : https://www.choozmo.com:8887/verify_email?code='+code, request.email)
  282. except:
  283. return {'msg':{'eng':'Invalid email address','zh':'無法寄送認證信!'}}
  284. util.user.add_time_by_invite(invcode)
  285. return {'msg':{'eng':'Register success! Please login at previous page','zh':'註冊成功! 請回到上頁登入帳號'}}
  286. else :
  287. return {'msg':{'eng':'error','zh':'error'}}
  288. else:
  289. return {'msg':{'eng':user_obj['username']+' is duplicated user name try another','zh':user_obj['username']+'重複,請更改'}}
  290. @app.get('/logout')
  291. def logout(request: Request, Authorize: AuthJWT = Depends()):
  292. Authorize.jwt_required()
  293. Authorize.unset_jwt_cookies()
  294. return {"msg": "ok"}
  295. @app.post('/logout_jwt')
  296. def logout(token: str = Depends(oauth2_scheme)):
  297. db_check()
  298. time_stamp = datetime.fromtimestamp(time.time())
  299. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  300. db['jwt_black_list'].insert({'token':token,'datetime':time_stamp})
  301. return {"msg": "ok"}
  302. @app.post('/get_role')
  303. async def get_role(token: str = Depends(oauth2_scheme)):
  304. user_id = util.user.get_user_id(token)
  305. roles = util.user.get_user_role(user_id)
  306. return roles
  307. @app.post('/create_role')
  308. async def get_role(token: str = Depends(oauth2_scheme)):
  309. user_id = get_user_id(token)
  310. return user_id
  311. @app.post('/get_avatar_by_role')
  312. async def get_role(token: str = Depends(oauth2_scheme)):
  313. user_id = util.user.get_user_id(token)
  314. avatar_info = util.user.get_avatar_by_role(user_id)
  315. return avatar_info
  316. @app.get('/verify_email')
  317. async def verify_email(code):
  318. db_check()
  319. veri_obj = first(db.query('SELECT * FROM register_veri_code where code ="'+str(code)+'"'))
  320. if veri_obj != None:
  321. db['register_veri_code'].delete(code=code)
  322. return {"msg": "ok"}
  323. @app.get("/reset_pwd_page_email")
  324. async def reset_pwd_page():
  325. return FileResponse('static/reset_pwd_email.html')
  326. @app.get("/reset_pwd_page")
  327. async def reset_pwd_page():
  328. return FileResponse('static/reset_pwd.html')
  329. @app.get('/send_reset_pwd')
  330. async def send_reset_pwd(user_id,email):
  331. db_check()
  332. code = str(time.time()).replace('.','')
  333. db['reset_pw_code'].insert({'code':code,'user_id':user_id,'email':email})
  334. msg = '請至點擊網址以重設密碼 : https://www.choozmo.com:8887/reset_pwd_page 通行碼為 '+ code
  335. print(msg)
  336. msg =msg.encode(encoding='utf-8')
  337. print(msg)
  338. print(type(user_id))
  339. if int(user_id) != -1:
  340. print('print at first place')
  341. print(user_id)
  342. user_dict = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  343. else:
  344. user_id = util.user.get_id_by_email(email)
  345. print(user_id)
  346. user_dict = next(iter(db.query('SELECT * FROM users where id ="'+str(user_id)+'"')))
  347. mailer.send(msg, user_dict['email'])
  348. return {'msg':'ok'}
  349. @app.post('/reset_pwd')
  350. async def reset_password(req :util.models.reset_pwd):
  351. db_check()
  352. print(req.code)
  353. veri_obj = next(iter(db.query('SELECT * FROM reset_pw_code where code ="'+str(req.code)+'"')))
  354. print(veri_obj['user_id'])
  355. user_id = util.user.get_id_by_email(veri_obj['email'])
  356. print(user_id)
  357. db.query('UPDATE users SET password = '+'"'+get_password_hash(req.password)+'" where id ='+str(user_id))
  358. if veri_obj != None:
  359. db['reset_pw_code'].delete(code=req.code)
  360. return {"msg": "ok"}
  361. @app.get("/gen_avatar")
  362. async def avatar():
  363. return FileResponse('static/gen_avatar.html')
  364. @app.post("/swapFace")
  365. async def swapFace(req:util.models.swap_req):
  366. if 'http' not in req.imgurl:
  367. req.imgurl= 'http://'+req.imgurl
  368. try:
  369. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  370. im= im.convert("RGB")
  371. except:
  372. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  373. name_hash = str(time.time()).replace('.','')
  374. x = threading.Thread(target=gen_avatar, args=(name_hash,req.imgurl))
  375. x.start()
  376. return {'msg':'ok'}
  377. @app.post("/uploadfile/")
  378. async def create_upload_file(file: UploadFile = File(...)):
  379. img_name = str(time.time()).replace('.','')
  380. try:
  381. if file.content_type=='video/mp4':
  382. async with aiofiles.open(img_upload_folder+img_name+'.mp4', 'wb') as out_file:
  383. content = await file.read()
  384. await out_file.write(content)
  385. return {"msg": resource_server+tmp_img_sub_folder+img_name+'.mp4'}
  386. else:
  387. contents = await file.read()
  388. image = Image.open(io.BytesIO(contents))
  389. image= image.convert("RGB")
  390. image.save(img_upload_folder+img_name+'.jpg')
  391. return {"msg": resource_server+tmp_img_sub_folder+img_name+'.jpg'}
  392. except Exception as e:
  393. logging.error(traceback.format_exc())
  394. return {'msg':{'eng':'file cant be prossessed','zh':'檔案無法使用'}}
  395. @app.post("/upload_pttx/")
  396. async def upload_pttx(file: UploadFile = File(...)):
  397. try:
  398. if "#" in file.filename:
  399. return {'msg':{'eng':'symbol"#" is not allowed in file name','zh':'檔案無法使用檔名不能含有"#"符號'}}
  400. else:
  401. pttx_name = file.filename.replace('.pptx','#')+str(time.time()).replace('.','')+'.pptx'
  402. with open(pttx_dest+pttx_name, "wb+") as file_object:
  403. file_object.write(file.file.read())
  404. return {"msg": resource_server+pttx_sub_folder+pttx_name}
  405. except Exception as e:
  406. logging.error(traceback.format_exc())
  407. return {'msg':{'eng':'file cant be prossessed','zh':'檔案無法使用'}}
  408. @app.post("/make_anchor_video_gSlide")
  409. async def make_anchor_video_gSlide(req:util.models.gSlide_req,token: str = Depends(oauth2_scheme)):
  410. if req.url_type == 0:
  411. name, text_content, image_urls = gSlide.parse_slide_url(req.slide_url,eng=False)
  412. else :
  413. filename = req.slide_url.replace(resource_server+pttx_sub_folder,resource_folder+pttx_sub_folder)
  414. name, text_content, image_urls = gSlide.parse_pttx_url(filename,img_upload_folder,resource_server+tmp_img_sub_folder,eng=False)
  415. if len(image_urls) != len(text_content):
  416. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  417. for idx in range(len(image_urls)):
  418. if 'http' not in image_urls[idx]:
  419. image_urls[idx] = 'http://'+image_urls[idx]
  420. mulitLang, hasError = Check_text_content(text_content)
  421. if hasError is not False :
  422. return hasError
  423. imgError = Check_image_url(image_urls)
  424. if imgError is not False :
  425. return imgError
  426. name_hash = str(time.time()).replace('.','')
  427. user_id = get_user_id(token)
  428. proto_req = util.models.request_normal()
  429. proto_req.text_content = text_content
  430. proto_req.name = name
  431. proto_req.image_urls = image_urls
  432. proto_req.avatar = req.avatar
  433. proto_req.multiLang = req.multiLang
  434. video_id = save_history(proto_req,name_hash,user_id)
  435. x = threading.Thread(target=gen_video_queue, args=(name_hash,name, text_content, image_urls,int(req.avatar),req.multiLang,video_id,user_id))
  436. x.start()
  437. return {"msg":"ok"}
  438. @app.post("/make_anchor_video_long")
  439. async def make_anchor_video_long(req:util.models.request,token: str = Depends(oauth2_scheme)):
  440. db_check()
  441. left_tag = [m.start() for m in re.finditer('{', req.text_content[0])]
  442. if len(req.image_urls) != len(left_tag):
  443. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  444. for idx in range(len(req.image_urls)):
  445. if 'http' not in req.image_urls[idx]:
  446. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  447. if req.multiLang==0:
  448. for txt in req.text_content:
  449. if re.search('[a-zA-Z]', txt) !=None:
  450. print('語言錯誤')
  451. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  452. if re.search(',', txt) !=None:
  453. print('包含非法符號')
  454. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  455. name_hash = str(time.time()).replace('.','')
  456. for imgu in req.image_urls:
  457. try:
  458. if get_url_type(imgu) =='video/mp4':
  459. r=requests.get(imgu)
  460. else:
  461. im = Image.open(requests.get(imgu, stream=True).raw)
  462. im= im.convert("RGB")
  463. except:
  464. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  465. user_id = get_user_id(token)
  466. video_id = save_history(req,name_hash,user_id)
  467. 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))
  468. x.start()
  469. returnMsg = ''
  470. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  471. returnMsg = {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  472. else:
  473. returnMsg = {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  474. return returnMsg
  475. @app.post("/make_anchor_video")
  476. async def make_anchor_video(req:util.models.request,token: str = Depends(oauth2_scheme)):
  477. db_check()
  478. if len(req.image_urls) != len(req.text_content):
  479. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  480. for idx in range(len(req.image_urls)):
  481. if 'http' not in req.image_urls[idx]:
  482. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  483. if req.multiLang==0:
  484. for txt in req.text_content:
  485. if re.search('[a-zA-Z]', txt) !=None:
  486. print('語言錯誤')
  487. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  488. if re.search(',', txt) !=None:
  489. print('包含非法符號')
  490. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  491. name_hash = str(time.time()).replace('.','')
  492. for imgu in req.image_urls:
  493. try:
  494. if get_url_type(imgu) =='video/mp4':
  495. r=requests.get(imgu)
  496. else:
  497. im = Image.open(requests.get(imgu, stream=True).raw)
  498. im= im.convert("RGB")
  499. except:
  500. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  501. user_id = get_user_id(token)
  502. video_id = save_history(req,name_hash,user_id)
  503. 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))
  504. x.start()
  505. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  506. return {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  507. else:
  508. return {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  509. return {'msg':'ok'}
  510. #not auth
  511. @app.post("/make_anchor_video_noAuth")
  512. async def make_anchor_video_noAuth(req:util.models.request):
  513. db_check()
  514. if len(req.image_urls) != len(req.text_content):
  515. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  516. for idx in range(len(req.image_urls)):
  517. if 'http' not in req.image_urls[idx]:
  518. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  519. if req.multiLang==0:
  520. for txt in req.text_content:
  521. if re.search('[a-zA-Z]', txt) !=None:
  522. print('語言錯誤')
  523. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  524. if re.search(',', txt) !=None:
  525. print('包含非法符號')
  526. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  527. name_hash = str(time.time()).replace('.','')
  528. for imgu in req.image_urls:
  529. try:
  530. if get_url_type(imgu) =='video/mp4':
  531. r=requests.get(imgu)
  532. else:
  533. im = Image.open(requests.get(imgu, stream=True).raw)
  534. im= im.convert("RGB")
  535. except:
  536. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  537. user_id = get_user_id(token)
  538. video_id = save_history(req,name_hash,user_id)
  539. 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))
  540. x.start()
  541. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  542. return {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  543. else:
  544. return {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  545. return {'msg':'ok'}
  546. @app.post("/make_anchor_video_noAuth2" , response_class=JSONResponse)
  547. async def make_anchor_video_noAuth2(req:util.models.request):
  548. db_check()
  549. if len(req.image_urls) != len(req.text_content):
  550. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  551. for idx in range(len(req.image_urls)):
  552. if 'http' not in req.image_urls[idx]:
  553. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  554. if req.multiLang==0:
  555. for txt in req.text_content:
  556. if re.search('[a-zA-Z]', txt) !=None:
  557. print('語言錯誤')
  558. return {'msg':{'eng':'English is not allowed in subtitles','zh':'輸入字串不能包含英文字!'}}
  559. if re.search(',', txt) !=None:
  560. print('包含非法符號')
  561. return {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  562. name_hash = str(time.time()).replace('.','')
  563. for imgu in req.image_urls:
  564. try:
  565. if get_url_type(imgu) =='video/mp4':
  566. r=requests.get(imgu)
  567. else:
  568. im = Image.open(requests.get(imgu, stream=True).raw)
  569. im= im.convert("RGB")
  570. except:
  571. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  572. video_id = save_history(req,name_hash,-1)
  573. 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,-1))
  574. x.start()
  575. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  576. return {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  577. else:
  578. return {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  579. return {'msg':'ok'}
  580. @app.post("/make_anchor_video_eng")
  581. async def make_anchor_video_eng(req:util.models.request_eng,token: str = Depends(oauth2_scheme)):
  582. db_check()
  583. if len(req.image_urls) != len(req.sub_titles) or len(req.sub_titles) != len(req.text_content):
  584. return {'msg':{'eng':'number of subtitles and images(videos) should be the same','zh':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}}
  585. for idx in range(len(req.image_urls)):
  586. if 'http' not in req.image_urls[idx]:
  587. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  588. name_hash = str(time.time()).replace('.','')
  589. for imgu in req.image_urls:
  590. try:
  591. if get_url_type(imgu) =='video/mp4':
  592. r=requests.get(imgu)
  593. else:
  594. im = Image.open(requests.get(imgu, stream=True).raw)
  595. im= im.convert("RGB")
  596. except:
  597. return {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  598. user_id = get_user_id(token)
  599. video_id = save_history(req,name_hash, user_id)
  600. 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))
  601. x.start()
  602. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] >= 3:
  603. return {'msg':{'eng':'There are many videos have been processing, please wait.','zh':'目前有多部影片處理中,煩請耐心等候'}}
  604. else:
  605. return {'msg':{'eng':'Processing video requires a few minutes, please wait for notification','zh':'影片處理需要數分鐘,請等待通知'}}
  606. return {"msg":"ok"}
  607. @app.post("/save_draft")
  608. async def save_draft(req:util.models.video_draft,token: str = Depends(oauth2_scheme)):
  609. db_check()
  610. user_id = get_user_id(token)
  611. txt_content_seperate_by_dot = ''
  612. for txt in req.text_content:
  613. txt_content_seperate_by_dot += txt+","
  614. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  615. img_urls_seperate_by_dot = ''
  616. for iurl in req.image_urls:
  617. img_urls_seperate_by_dot += iurl+","
  618. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  619. time_stamp = datetime.fromtimestamp(time.time())
  620. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  621. if req.id==-1:
  622. pk = db['draft'].insert({'title':req.title,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  623. ,'user_id':user_id,'avatar':req.avatar,'multiLang':req.multiLang,'time_stamp':time_stamp})
  624. else:
  625. db['draft'].update({'id':req.id,'title':req.title,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  626. ,'user_id':user_id,'avatar':req.avatar,'multiLang':req.multiLang,'time_stamp':time_stamp},['id'])
  627. return {'msg':'ok'}
  628. @app.post('/draft_list')
  629. async def draft_list(token: str = Depends(oauth2_scheme)):
  630. db_check()
  631. user_id = get_user_id(token)
  632. statement = 'SELECT * FROM draft WHERE user_id='+str(user_id)+' ORDER BY time_stamp DESC LIMIT 50'
  633. logs = []
  634. for row in db.query(statement):
  635. logs.append({'id':row['id'],'title':row['title'],'avatar':row['avatar'],'mulitLang':row['multiLang']
  636. ,'text_content':row['text_content'].split(','),'image_urls':row['image_urls'].split(',')})
  637. return logs
  638. @app.post('/del_draft')
  639. async def del_draft(id_obj:util.models.id_obj,token: str = Depends(oauth2_scheme)):
  640. db_check()
  641. user_id = get_user_id(token)
  642. statement = 'SELECT * FROM draft WHERE user_id="'+str(user_id)+'" and id ="'+str(id_obj.id)+'"'
  643. if first(db.query(statement)) is not None:
  644. db['draft'].delete(id=id_obj.id)
  645. else:
  646. return {'msg':'wrong id'}
  647. return {'msg':'ok'}
  648. @app.get("/history_input_old")
  649. async def history_input_old(request: Request, Authorize: AuthJWT = Depends()):
  650. db_check()
  651. Authorize.jwt_required()
  652. current_user = Authorize.get_jwt_subject()
  653. user_id = first(db.query('SELECT * FROM users where username="' + current_user +'"'))['id']
  654. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  655. logs = []
  656. for row in db.query(statement):
  657. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  658. return logs
  659. @app.post("/history_input")
  660. async def history_input(token: str = Depends(oauth2_scheme)):
  661. db_check()
  662. user_id = get_user_id(token)
  663. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  664. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  665. logs = []
  666. for row in db.query(statement):
  667. 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(',')})
  668. return logs
  669. @app.post("/history_input_noAuth")
  670. async def history_input_noAuth():
  671. db_check()
  672. statement = 'SELECT * FROM history_input ORDER BY timestamp DESC LIMIT 50'
  673. logs = []
  674. for row in db.query(statement):
  675. 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(',')})
  676. return logs
  677. @AuthJWT.load_config
  678. def get_config():
  679. return util.models.Settings()
  680. @app.exception_handler(AuthJWTException)
  681. def authjwt_exception_handler(request: Request, exc: AuthJWTException):
  682. return JSONResponse(
  683. status_code=exc.status_code,
  684. content={"detail": exc.message}
  685. )
  686. def get_user_id(token):
  687. db_check()
  688. credentials_exception = HTTPException(
  689. status_code=status.HTTP_401_UNAUTHORIZED,
  690. detail="Could not validate credentials",
  691. headers={"WWW-Authenticate": "Bearer"},
  692. )
  693. try:
  694. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  695. username: str = payload.get("sub")
  696. if username is None:
  697. raise credentials_exception
  698. token_data = util.models.TokenData(username=username)
  699. except JWTError:
  700. raise credentials_exception
  701. user = get_user(username=token_data.username)
  702. if user is None:
  703. raise credentials_exception
  704. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  705. return user_id
  706. def check_user_exists(username):
  707. db_check()
  708. if int(next(iter(db.query('SELECT COUNT(*) FROM AI_anchor.users WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
  709. return True
  710. else:
  711. return False
  712. def get_user(username: str):
  713. if not check_user_exists(username): # if user don't exist
  714. return False
  715. user_dict = next(
  716. iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  717. user = util.models.User(**user_dict)
  718. return user
  719. def user_register(user):
  720. db_check()
  721. table = db['users']
  722. user.password = get_password_hash(user.password)
  723. id = table.insert(dict(user))
  724. return id
  725. def get_password_hash(password):
  726. return pwd_context.hash(password)
  727. def verify_password(plain_password, hashed_password):
  728. return pwd_context.verify(plain_password, hashed_password)
  729. def authenticate_user(username: str, password: str):
  730. db_check()
  731. if not check_user_exists(username): # if user don't exist
  732. return False
  733. user_dict = next(iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  734. user = util.models.User(**user_dict)
  735. if not verify_password(password, user.password):
  736. return False
  737. return user
  738. def create_access_token(data: dict, expires_delta):
  739. to_encode = data.copy()
  740. expire = datetime.utcnow() + expires_delta
  741. to_encode.update({"exp": expire})
  742. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  743. return encoded_jwt
  744. def save_history(req,name_hash,user_id):
  745. db_check()
  746. log_table = db['history_input']
  747. txt_content_seperate_by_dot = ''
  748. for txt in req.text_content:
  749. txt_content_seperate_by_dot += txt+","
  750. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  751. img_urls_seperate_by_dot = ''
  752. for iurl in req.image_urls:
  753. img_urls_seperate_by_dot += iurl+","
  754. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  755. time_stamp = datetime.fromtimestamp(time.time())
  756. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  757. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  758. ,'user_id':user_id,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','avatar':req.avatar,'timestamp':time_stamp})
  759. return pk
  760. def get_url_type(url):
  761. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  762. r = urllib.request.urlopen(req)
  763. contentType = r.getheader('Content-Type')
  764. return contentType
  765. def notify_group(msg):
  766. #'WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD' is ChoozmoTeam
  767. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']
  768. for gid in glist:
  769. headers = {"Authorization": "Bearer " + gid,"Content-Type": "application/x-www-form-urlencoded"}
  770. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params={"message": msg})
  771. def notify_choozmo(msg):
  772. #'WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD' is ChoozmoTeam
  773. glist = ['WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD']
  774. for gid in glist:
  775. headers = {"Authorization": "Bearer " + gid,"Content-Type": "application/x-www-form-urlencoded"}
  776. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params={"message": msg})
  777. def Check_text_content(text_content):
  778. mulitLang = 0
  779. status = False
  780. for txt in text_content:
  781. if re.search('[a-zA-Z]', txt) !=None:
  782. mulitLang = 1
  783. if re.search(',', txt) !=None:
  784. print('包含非法符號')
  785. status = {'msg':{'eng':'symbol "," is not allowede','zh':'輸入不能含有","符號'}}
  786. return mulitLang, status
  787. def Check_image_url(image_urls):
  788. status =False
  789. for imgu in image_urls:
  790. try:
  791. if get_url_type(imgu) =='video/mp4':
  792. r=requests.get(imgu)
  793. else:
  794. im = Image.open(requests.get(imgu, stream=True).raw)
  795. im= im.convert("RGB")
  796. except:
  797. status = {'msg':{'eng':req.imgurl+'cant be proccessed','zh':"無法辨別圖片網址"+req.imgurl}}
  798. return status
  799. def gen_video_long_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  800. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  801. if name_hash == 'keepRunning':
  802. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="longvideo"'))['COUNT(1)'] == 0:
  803. return
  804. db.query('UPDATE video_queue_status SET status = 0;')
  805. print('start clear long video')
  806. else:
  807. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  808. txt_content_seperate_by_dot = ''
  809. for txt in text_content:
  810. txt_content_seperate_by_dot += txt+","
  811. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  812. img_urls_seperate_by_dot = ''
  813. for iurl in image_urls:
  814. img_urls_seperate_by_dot += iurl+","
  815. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  816. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot
  817. ,'image_urls':img_urls_seperate_by_dot,'multiLang':multiLang,'video_type':'longvideo','avatar':avatar,'timestamp':time_stamp})
  818. while True:
  819. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  820. print('another process running, leave loop')#1 means already running
  821. break
  822. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="longvideo"'))['COUNT(1)'] == 0:
  823. print('all finish, leave loop')
  824. break
  825. top1 = first(db.query('SELECT * FROM video_queue where video_type="longvideo"'))
  826. try:
  827. # if True:
  828. db.query('UPDATE video_queue_status SET status = 1;')
  829. c = rpyc.connect("localhost", 8858)
  830. c._config['sync_request_timeout'] = None
  831. remote_svc = c.root
  832. 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
  833. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  834. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  835. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  836. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  837. line_token = user_obj['line_token'] # aa
  838. left_time = user_obj['left_time']
  839. email = user_obj['email']
  840. print('left_time is '+str(left_time))
  841. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  842. if left_time is None:
  843. left_time = 5*60
  844. if left_time < vid_duration:
  845. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.107:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  846. print(msg)
  847. msg =msg.encode(encoding='utf-8')
  848. mailer.send_left_not_enough(msg, email)
  849. #notify_line_user(msg, line_token)
  850. notify_group(name+":帳號餘額不足,請至email查看詳細資訊")
  851. else:
  852. left_time = left_time - vid_duration
  853. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  854. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  855. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  856. except Exception as e:
  857. logging.error(traceback.format_exc())
  858. print('video generation error')
  859. notify_group('長影片錯誤-測試')
  860. db['video_queue'].delete(id=top1['id'])
  861. db.query('UPDATE video_queue_status SET status = 0')
  862. db.close()
  863. def gen_video_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  864. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  865. if name_hash == 'keepRunning':
  866. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="short"'))['COUNT(1)'] == 0:
  867. return
  868. db.query('UPDATE video_queue_status SET status = 0;')
  869. print('start clear short video')
  870. else:
  871. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  872. txt_content_seperate_by_dot = ''
  873. for txt in text_content:
  874. txt_content_seperate_by_dot += txt+","
  875. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  876. img_urls_seperate_by_dot = ''
  877. for iurl in image_urls:
  878. img_urls_seperate_by_dot += iurl+","
  879. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  880. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot
  881. ,'image_urls':img_urls_seperate_by_dot,'multiLang':multiLang,'video_type':'short','avatar':avatar,'timestamp':time_stamp})
  882. while True:
  883. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  884. print('another process running, leave loop')#1 means already running
  885. break
  886. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="short"'))['COUNT(1)'] == 0:
  887. print('all finish, leave loop')
  888. break
  889. top1 = first(db.query('SELECT * FROM video_queue where video_type="short"'))
  890. try:
  891. # if True:
  892. db.query('UPDATE video_queue_status SET status = 1;')
  893. c = rpyc.connect("localhost", 8858)
  894. c._config['sync_request_timeout'] = None
  895. remote_svc = c.root
  896. 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
  897. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  898. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  899. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  900. line_token=''
  901. left_time=10000
  902. email=''
  903. if user_id!=-1:
  904. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  905. line_token = user_obj['line_token'] # aa
  906. left_time = user_obj['left_time']
  907. email = user_obj['email']
  908. print('left_time is '+str(left_time))
  909. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  910. if left_time is None:
  911. left_time = 5*60
  912. if left_time < vid_duration:
  913. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.107:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  914. print(msg)
  915. msg =msg.encode(encoding='utf-8')
  916. mailer.send_left_not_enough(msg, email)
  917. notify_group(msg)
  918. #notify_line_user(msg, line_token)
  919. else:
  920. left_time = left_time - vid_duration
  921. if user_id != -1:
  922. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  923. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  924. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  925. except Exception as e:
  926. logging.error(traceback.format_exc())
  927. print('video generation error')
  928. notify_group('影片錯誤')
  929. db['video_queue'].delete(id=top1['id'])
  930. db.query('UPDATE video_queue_status SET status = 0')
  931. db.close()
  932. def gen_video_queue_eng(name_hash,name,text_content, image_urls,sub_titles,avatar,video_id):
  933. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  934. if name_hash == 'keepRunning':
  935. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type="eng"'))['COUNT(1)'] == 0:
  936. return
  937. db.query('UPDATE video_queue_status SET status = 0;')
  938. print('start clear eng video')
  939. else:
  940. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  941. txt_content_seperate_by_dot = ''
  942. for txt in text_content:
  943. txt_content_seperate_by_dot += txt+","
  944. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  945. img_urls_seperate_by_dot = ''
  946. for iurl in image_urls:
  947. img_urls_seperate_by_dot += iurl+","
  948. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  949. subtitles_seperate_by_dot = ''
  950. for sub in sub_titles:
  951. subtitles_seperate_by_dot += sub+","
  952. subtitles_seperate_by_dot = subtitles_seperate_by_dot[:-1]
  953. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot,
  954. 'image_urls':img_urls_seperate_by_dot,'subtitles':subtitles_seperate_by_dot,'video_type':'eng','avatar':avatar,'timestamp':time_stamp})
  955. while True:
  956. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  957. print('another process running, leave loop')
  958. break
  959. if first(db.query('SELECT COUNT(1) FROM video_queue where video_type=="eng"'))['COUNT(1)'] == 0:
  960. print('all finish, leave loop')
  961. break
  962. top1 = first(db.query('SELECT * FROM video_queue where video_type=="eng"'))
  963. try:
  964. db.query('UPDATE video_queue_status SET status = 1;')
  965. c = rpyc.connect("localhost", 8858)
  966. c._config['sync_request_timeout'] = None
  967. remote_svc = c.root
  968. 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
  969. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  970. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  971. notify_group(name+"(ENG)的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  972. except:
  973. print('video generation error')
  974. notify_group('影片錯誤')
  975. db['video_queue'].delete(id=top1['id'])
  976. db.query('UPDATE video_queue_status SET status = 0')
  977. db.close()
  978. def gen_avatar(name_hash, imgurl):
  979. db_check()
  980. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  981. while True:
  982. statement = 'SELECT * FROM avatar_service_status'#only one row in this table, which is the id 1 one
  983. status = -1
  984. for row in db.query(statement):
  985. status = row['status']
  986. if status == 1:
  987. print('leave process loop')
  988. break
  989. statement = 'SELECT * FROM avatar_queue'
  990. works = []
  991. for row in db.query(statement):
  992. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':row['imgurl']})
  993. if len(works)==0:
  994. print('leave process loop')
  995. break
  996. try:
  997. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  998. db.query(statement)
  999. name_hash = works[0]['name_hash']
  1000. imgurl = works[0]['imgurl']
  1001. c = rpyc.connect("localhost", 8868)
  1002. c._config['sync_request_timeout'] = None
  1003. remote_svc = c.root
  1004. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  1005. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  1006. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  1007. except:
  1008. print('gen error')
  1009. notify_group('無法辨識人臉')
  1010. db['avatar_queue'].delete(id=works[0]['id'])
  1011. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;' #only one row in this table, which id 1 one
  1012. db.query(statement)
  1013. def call_voice(text):
  1014. print(text)
  1015. print(len(text))
  1016. print(type(text))
  1017. c = rpyc.connect("localhost", 8858)
  1018. c._config['sync_request_timeout'] = None
  1019. remote_svc = c.root
  1020. my_answer = remote_svc.make_speech(text) # method call
  1021. src_path = '/home/ming/AI_Anchor/OpenshotService/speech.mp3'
  1022. shutil.copy(src_path,'/home/ming/speech.mp3')
  1023. os.remove(src_path)
  1024. class text_in(BaseModel):
  1025. text: str
  1026. @app.post("/make_voice")
  1027. async def make_voice(in_text:text_in):
  1028. x = threading.Thread(target=call_voice, args=(in_text.text,))
  1029. x.start()
  1030. @app.post("/gen_speech")
  1031. async def make_voice(req:util.models.speech_req):
  1032. call_speech(req.text,req.speaker)
  1033. return {'msg':'wait please'}
  1034. def call_speech(text,speaker):
  1035. conn = rpyc.classic.connect("192.168.1.105",8838)
  1036. ros = conn.modules.os
  1037. ros.system('docker exec -it mingc_tts bash gen_speech.sh '+text+' '+speaker)
  1038. while True:
  1039. print('waiting...')
  1040. if ros.path.exists('/home/ming/workspace/TTS_fs2/fast_speech2_ming024/output/result/AISHELL3/'+text+'.wav'):
  1041. break
  1042. time.sleep(5)
  1043. print('waiting...')
  1044. fr=conn.builtins.open('/home/ming/workspace/TTS_fs2/fast_speech2_ming024/output/result/AISHELL3/'+text+'.wav','rb')
  1045. fw=open(text+'.wav','wb')
  1046. while True:
  1047. b=fr.read(1024)
  1048. if b:
  1049. fw.write(b)
  1050. else:
  1051. break
  1052. fr.close()
  1053. fw.close()
  1054. shutil.copy(text+'.wav',speech_dest+text+'.wav')
  1055. os.remove(text+'.wav')
  1056. notify_choozmo("speech at www.choozmo.com:8168/speech/"+text+".wav")
  1057. def verify_jwt_token(token):
  1058. for row in db.query('SELECT * FROM jwt_black_list'):
  1059. print(row)
  1060. print(first(db.query('SELECT COUNT(*) FROM jwt_black_list where token="'+token+'"'))['COUNT(*)'])
  1061. if first(db.query('SELECT COUNT(*) FROM jwt_black_list where token="'+token+'"'))['COUNT(*)'] == 0:
  1062. return 'ok'
  1063. else:
  1064. return 'please login again'
  1065. def db_check():
  1066. global db
  1067. if db!=None:
  1068. db.close()
  1069. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  1070. def clear_video_queue():
  1071. x = threading.Thread(target=gen_video_queue_eng, args=('keepRunning','', '', '','','',''))
  1072. x.start()
  1073. x2 = threading.Thread(target=gen_video_queue, args=('keepRunning','', '', '','','','',''))
  1074. x2.start()
  1075. x3 = threading.Thread(target=gen_video_long_queue, args=('keepRunning','', '', '','','','',''))
  1076. x3.start()
  1077. clear_video_queue()