main.py 58 KB

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