main.py 57 KB

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