main.py 60 KB

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