main.py 61 KB

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