main.py 58 KB

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