main.py 58 KB

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