main.py 57 KB

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