main.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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 models
  38. import pymysql
  39. from first import first
  40. import mailer
  41. from moviepy.editor import VideoFileClip
  42. import traceback
  43. import logging
  44. import gSlide
  45. import aiofiles
  46. import json
  47. pymysql.install_as_MySQLdb()
  48. app = FastAPI()
  49. app.add_middleware(
  50. CORSMiddleware,
  51. allow_origins=["*"],
  52. allow_credentials=True,
  53. allow_methods=["*"],
  54. allow_headers=["*"],
  55. )
  56. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  57. ALGORITHM = "HS256"
  58. ACCESS_TOKEN_EXPIRE_DAYS = 5
  59. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  60. app.mount("/static", StaticFiles(directory="static"), name="static")
  61. app.mount("/static/img", StaticFiles(directory="static/img"), name="static/img")
  62. app.mount("/templates", StaticFiles(directory="templates"), name="templates")
  63. templates = Jinja2Templates(directory="templates")
  64. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
  65. tmp_video_dir = '../OpenshotService/tmp_video/'
  66. tmp_avatar_dir = '../../face_swap/tmp_avatar/' #change source face path here
  67. resource_server = 'www.choozmo.com:8168/'
  68. resource_folder = '/var/www/html/'
  69. video_sub_folder = 'ai_anchor_video/'
  70. avatar_sub_folder = 'swap_save/'
  71. tmp_img_sub_folder = 'tmp_img/'
  72. pttx_sub_folder = 'tmp_pttx/'
  73. img_upload_folder = '/var/www/html/'+tmp_img_sub_folder
  74. video_dest = '/var/www/html/'+video_sub_folder
  75. avatar_dest = '/var/www/html/'+avatar_sub_folder
  76. pttx_dest = '/var/www/html/'+pttx_sub_folder
  77. # @app.get("/index2")
  78. # async def index2():
  79. # return FileResponse('static/index2.html')
  80. @app.get("/index_eng")
  81. async def index2():
  82. return FileResponse('static/index_eng.html')
  83. # home page
  84. @app.get("/index", response_class=HTMLResponse)
  85. async def get_home_page(request: Request, response: Response):
  86. return templates.TemplateResponse("index.html", {"request": request, "response": response})
  87. @app.get("/", response_class=HTMLResponse)
  88. async def get_home_page(request: Request, response: Response):
  89. return templates.TemplateResponse("index.html", {"request": request, "response": response})
  90. @app.get("/make_video", response_class=HTMLResponse)
  91. async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  92. try:
  93. Authorize.jwt_required()
  94. except Exception as e:
  95. print(e)
  96. return '請先登入帳號'
  97. current_user = Authorize.get_jwt_subject()
  98. return templates.TemplateResponse("make_video.html", {"request": request, "response": response})
  99. @app.get("/make_video_long", response_class=HTMLResponse)
  100. async def get_home_page(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  101. try:
  102. Authorize.jwt_required()
  103. except Exception as e:
  104. print(e)
  105. return '請先登入帳號'
  106. current_user = Authorize.get_jwt_subject()
  107. return templates.TemplateResponse("make_video_long.html", {"request": request, "response": response})
  108. @app.get("/make_video_slide", response_class=HTMLResponse)
  109. async def make_video_slide(request: Request, response: Response, Authorize: AuthJWT = Depends()):
  110. try:
  111. Authorize.jwt_required()
  112. except Exception as e:
  113. print(e)
  114. return '請先登入帳號'
  115. current_user = Authorize.get_jwt_subject()
  116. return templates.TemplateResponse("make_video_slide.html", {"request": request, "response": response})
  117. @app.post('/user_profile', response_class=HTMLResponse)
  118. async def user_profile(token: str = Depends(oauth2_scheme)):
  119. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  120. user_id = get_user_id(token)
  121. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  122. if user_obj is None:
  123. raise HTTPException(
  124. status_code=status.HTTP_401_UNAUTHORIZED,
  125. detail="Missing token",
  126. headers={"WWW-Authenticate": "Bearer"},
  127. )
  128. video_num = str(first(db.query('SELECT COUNT(*) FROM history_input WHERE user_id ='+str(user_obj['id'])))['COUNT(*)'])
  129. total_sec = str(first(db.query('SELECT SUM(duration) FROM history_input where user_id='+str(user_obj['id'])))['SUM(duration)'])
  130. left_sec = user_obj['left_time']
  131. video_info_list = []
  132. statement = 'SELECT * FROM history_input WHERE user_id='+str(user_obj['id'])
  133. for row in db.query(statement):
  134. video_info_list.append({'id':row['id'],'title':row['name'],'duration':row['duration'],'url':row['url']})
  135. dic_return = {'user_info':{'userName':user_obj['username'],'email':user_obj['email'],'video_num':video_num,'total_sec':total_sec,'left_sec':user_obj['left_time']},'video_info':video_info_list}
  136. str_return = json.dumps(dic_return)
  137. return str_return
  138. # login & register page
  139. @app.get("/login", response_class=HTMLResponse)
  140. async def get_login_and_register_page(request: Request):
  141. return templates.TemplateResponse("login.html", {"request": request})
  142. @app.post("/login")
  143. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  144. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  145. user = authenticate_user(form_data.username, form_data.password)
  146. if not user:
  147. raise HTTPException(
  148. status_code=status.HTTP_401_UNAUTHORIZED,
  149. detail="Incorrect username or password",
  150. headers={"WWW-Authenticate": "Bearer"},
  151. )
  152. access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  153. access_token = create_access_token(
  154. data={"sub": user.username}, expires_delta=access_token_expires
  155. )
  156. table = db['users']
  157. user.token = access_token
  158. table.update(dict(user), ['username'])
  159. expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  160. access_token = Authorize.create_access_token(subject=user.username, expires_time=expires)
  161. refresh_token = Authorize.create_refresh_token(subject=user.username, expires_time =expires)
  162. Authorize.set_access_cookies(access_token)
  163. Authorize.set_refresh_cookies(refresh_token)
  164. #return templates.TemplateResponse("index.html", {"request": request, "msg": 'Login'})
  165. return {"access_token": access_token, "token_type": "bearer"}
  166. @app.post("/token")
  167. async def access_token(form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  168. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  169. user = authenticate_user(form_data.username, form_data.password)
  170. if not user:
  171. raise HTTPException(
  172. status_code=status.HTTP_401_UNAUTHORIZED,
  173. detail="Incorrect username or password",
  174. headers={"WWW-Authenticate": "Bearer"},
  175. )
  176. access_token_expires = timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS)
  177. access_token = create_access_token(
  178. data={"sub": user.username}, expires_delta=access_token_expires
  179. )
  180. return {"access_token": access_token, "token_type": "bearer"}
  181. #前後端分離完全實現後拔除
  182. @app.post("/register_old")
  183. async def register_old(request: Request):
  184. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  185. user = models.User(**await request.form())
  186. user_obj = first(db.query('SELECT * FROM users where username ="'+str(user.username)+'"'))
  187. if user_obj == None:
  188. user_register(user)
  189. return '註冊成功! 請回到上頁登入帳號'
  190. #return templates.TemplateResponse("make_video.html", {"request": request, "success": True},status_code=status.HTTP_302_FOUND)
  191. #return templates.TemplateResponse("login.html", {'request': request,"success": True}, status_code=status.HTTP_302_FOUND)
  192. else:
  193. return {'msg':user.username+'重複,請更改'}
  194. @app.post("/register")
  195. async def register(request: models.register_req):
  196. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  197. user_obj = first(db.query('SELECT * FROM users where username ="'+str(request.username)+'"'))
  198. if user_obj == None:
  199. if user_register(request):
  200. return {'msg':'ok'}
  201. else:
  202. return {'msg': '內部錯誤'}
  203. else:
  204. return {'msg':request.username+':使用者名稱重複,請更改'}
  205. @app.get('/logout')
  206. def logout(request: Request, Authorize: AuthJWT = Depends()):
  207. Authorize.jwt_required()
  208. Authorize.unset_jwt_cookies()
  209. return {"msg": "ok"}
  210. @app.get("/gen_avatar")
  211. async def avatar():
  212. return FileResponse('static/gen_avatar.html')
  213. @app.post("/swapFace")
  214. async def swapFace(req:models.swap_req):
  215. if 'http' not in req.imgurl:
  216. req.imgurl= 'http://'+req.imgurl
  217. try:
  218. im = Image.open(requests.get(req.imgurl, stream=True).raw)
  219. im= im.convert("RGB")
  220. except:
  221. return {'msg':"無法辨別圖片網址"+req.imgurl}
  222. name_hash = str(time.time()).replace('.','')
  223. x = threading.Thread(target=gen_avatar, args=(name_hash,req.imgurl))
  224. x.start()
  225. return {'msg':'ok'}
  226. @app.post("/uploadfile/")
  227. async def create_upload_file(file: UploadFile = File(...)):
  228. img_name = str(time.time()).replace('.','')
  229. try:
  230. if file.content_type=='video/mp4':
  231. async with aiofiles.open(img_upload_folder+img_name+'.mp4', 'wb') as out_file:
  232. content = await file.read()
  233. await out_file.write(content)
  234. return {"msg": resource_server+tmp_img_sub_folder+img_name+'.mp4'}
  235. else:
  236. contents = await file.read()
  237. image = Image.open(io.BytesIO(contents))
  238. image= image.convert("RGB")
  239. image.save(img_upload_folder+img_name+'.jpg')
  240. return {"msg": resource_server+tmp_img_sub_folder+img_name+'.jpg'}
  241. except Exception as e:
  242. logging.error(traceback.format_exc())
  243. return {'msg':'檔案無法使用'}
  244. @app.post("/upload_pttx/")
  245. async def upload_pttx(file: UploadFile = File(...)):
  246. try:
  247. if "_" in file.filename:
  248. return {'msg':'檔案無法使用檔名不能含有"_"符號'}
  249. else:
  250. pttx_name = file.filename+'_'+str(time.time()).replace('.','')
  251. with open(pttx_dest+pttx_name, "wb+") as file_object:
  252. file_object.write(file.file.read())
  253. return {"msg": resource_server+pttx_sub_folder+pttx_name}
  254. except Exception as e:
  255. logging.error(traceback.format_exc())
  256. return {'msg':'檔案無法使用'}
  257. @app.post("/make_anchor_video_gSlide")
  258. async def make_anchor_video_gSlide(req:models.gSlide_req,token: str = Depends(oauth2_scheme)):
  259. if req.url_type == 0:
  260. name, text_content, image_urls = gSlide.parse_slide_url(req.slide_url,eng=False)
  261. else :
  262. filename = req.slide_url.replace(resource_server+pttx_sub_folder,resource_folder+pttx_sub_folder)
  263. name, text_content, image_urls = gSlide.parse_pttx_url(filename,img_upload_folder,resource_server+tmp_img_sub_folder,eng=False)
  264. if len(image_urls) != len(text_content):
  265. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  266. for idx in range(len(image_urls)):
  267. if 'http' not in image_urls[idx]:
  268. image_urls[idx] = 'http://'+image_urls[idx]
  269. if req.multiLang==0:
  270. for txt in text_content:
  271. if re.search('[a-zA-Z]', txt) !=None:
  272. print('語言錯誤')
  273. return {'msg':'輸入字串不能包含英文字!'}
  274. name_hash = str(time.time()).replace('.','')
  275. for imgu in image_urls:
  276. try:
  277. if get_url_type(imgu) =='video/mp4':
  278. r=requests.get(imgu)
  279. else:
  280. im = Image.open(requests.get(imgu, stream=True).raw)
  281. im= im.convert("RGB")
  282. except:
  283. return {'msg':"無法辨別圖片網址"+imgu}
  284. user_id = get_user_id(token)
  285. proto_req = models.request_normal()
  286. proto_req.text_content = text_content
  287. proto_req.name = name
  288. proto_req.image_urls = image_urls
  289. proto_req.avatar = req.avatar
  290. proto_req.multiLang = req.multiLang
  291. video_id = save_history(proto_req,name_hash,user_id)
  292. x = threading.Thread(target=gen_video_queue, args=(name_hash,name, text_content, image_urls,int(req.avatar),req.multiLang,video_id,user_id))
  293. x.start()
  294. return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"}
  295. @app.post("/make_anchor_video_long")
  296. async def make_anchor_video_long(req:models.request,token: str = Depends(oauth2_scheme)):
  297. left_tag = [m.start() for m in re.finditer('{', req.text_content[0])]
  298. if len(req.image_urls) != len(left_tag):
  299. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  300. for idx in range(len(req.image_urls)):
  301. if 'http' not in req.image_urls[idx]:
  302. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  303. if req.multiLang==0:
  304. for txt in req.text_content:
  305. if re.search('[a-zA-Z]', txt) !=None:
  306. print('語言錯誤')
  307. return {'msg':'輸入字串不能包含英文字!'}
  308. name_hash = str(time.time()).replace('.','')
  309. for imgu in req.image_urls:
  310. try:
  311. if get_url_type(imgu) =='video/mp4':
  312. r=requests.get(imgu)
  313. else:
  314. im = Image.open(requests.get(imgu, stream=True).raw)
  315. im= im.convert("RGB")
  316. except:
  317. return {'msg':"無法辨別圖片網址"+imgu}
  318. user_id = get_user_id(token)
  319. video_id = save_history(req,name_hash,user_id)
  320. 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))
  321. x.start()
  322. return {"msg":"ok"}
  323. @app.post("/make_anchor_video")
  324. async def make_anchor_video(req:models.request,token: str = Depends(oauth2_scheme)):
  325. if len(req.image_urls) != len(req.text_content):
  326. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  327. for idx in range(len(req.image_urls)):
  328. if 'http' not in req.image_urls[idx]:
  329. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  330. if req.multiLang==0:
  331. for txt in req.text_content:
  332. if re.search('[a-zA-Z]', txt) !=None:
  333. print('語言錯誤')
  334. return {'msg':'輸入字串不能包含英文字!'}
  335. name_hash = str(time.time()).replace('.','')
  336. for imgu in req.image_urls:
  337. try:
  338. if get_url_type(imgu) =='video/mp4':
  339. r=requests.get(imgu)
  340. else:
  341. im = Image.open(requests.get(imgu, stream=True).raw)
  342. im= im.convert("RGB")
  343. except:
  344. return {'msg':"無法辨別圖片網址"+imgu}
  345. user_id = get_user_id(token)
  346. video_id = save_history(req,name_hash,user_id)
  347. 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))
  348. x.start()
  349. return {'msg':'ok'}
  350. @app.post("/make_anchor_video_eng")
  351. async def make_anchor_video_eng(req:models.request_eng):
  352. if len(req.image_urls) != len(req.sub_titles) or len(req.sub_titles) != len(req.text_content):
  353. return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
  354. for idx in range(len(req.image_urls)):
  355. if 'http' not in req.image_urls[idx]:
  356. req.image_urls[idx] = 'http://'+req.image_urls[idx]
  357. name_hash = str(time.time()).replace('.','')
  358. for imgu in req.image_urls:
  359. try:
  360. if get_url_type(imgu) =='video/mp4':
  361. r=requests.get(imgu)
  362. else:
  363. im = Image.open(requests.get(imgu, stream=True).raw)
  364. im= im.convert("RGB")
  365. except:
  366. return {'msg':"無法辨別圖片網址"+imgu}
  367. video_id = save_history(req,name_hash)
  368. 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))
  369. x.start()
  370. return {"msg":"ok"}
  371. @app.get("/history_input")
  372. async def history_input(request: Request, Authorize: AuthJWT = Depends()):
  373. Authorize.jwt_required()
  374. current_user = Authorize.get_jwt_subject()
  375. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  376. user_id = first(db.query('SELECT * FROM users where username="' + current_user +'"'))['id']
  377. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  378. logs = []
  379. for row in db.query(statement):
  380. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  381. return logs
  382. @AuthJWT.load_config
  383. def get_config():
  384. return models.Settings()
  385. @app.exception_handler(AuthJWTException)
  386. def authjwt_exception_handler(request: Request, exc: AuthJWTException):
  387. return JSONResponse(
  388. status_code=exc.status_code,
  389. content={"detail": exc.message}
  390. )
  391. def get_user_id(token):
  392. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  393. credentials_exception = HTTPException(
  394. status_code=status.HTTP_401_UNAUTHORIZED,
  395. detail="Could not validate credentials",
  396. headers={"WWW-Authenticate": "Bearer"},
  397. )
  398. try:
  399. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  400. username: str = payload.get("sub")
  401. if username is None:
  402. raise credentials_exception
  403. token_data = models.TokenData(username=username)
  404. except JWTError:
  405. raise credentials_exception
  406. user = get_user(username=token_data.username)
  407. if user is None:
  408. raise credentials_exception
  409. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  410. return user_id
  411. def check_user_exists(username):
  412. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  413. if int(next(iter(db.query('SELECT COUNT(*) FROM AI_anchor.users WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
  414. return True
  415. else:
  416. return False
  417. def get_user(username: str):
  418. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  419. if not check_user_exists(username): # if user don't exist
  420. return False
  421. user_dict = next(
  422. iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  423. user = models.User(**user_dict)
  424. return user
  425. def user_register(user):
  426. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  427. table = db['users']
  428. user.password = get_password_hash(user.password)
  429. table.insert(dict(user))
  430. return True
  431. def get_password_hash(password):
  432. return pwd_context.hash(password)
  433. def verify_password(plain_password, hashed_password):
  434. return pwd_context.verify(plain_password, hashed_password)
  435. def authenticate_user(username: str, password: str):
  436. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  437. if not check_user_exists(username): # if user don't exist
  438. return False
  439. user_dict = next(iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  440. user = models.User(**user_dict)
  441. if not verify_password(password, user.password):
  442. return False
  443. return user
  444. def create_access_token(data: dict, expires_delta):
  445. to_encode = data.copy()
  446. expire = datetime.utcnow() + expires_delta
  447. to_encode.update({"exp": expire})
  448. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  449. return encoded_jwt
  450. def save_history(req,name_hash,user_id):
  451. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  452. log_table = db['history_input']
  453. txt_content_seperate_by_dot = ''
  454. for txt in req.text_content:
  455. txt_content_seperate_by_dot += txt+","
  456. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  457. img_urls_seperate_by_dot = ''
  458. for iurl in req.image_urls:
  459. img_urls_seperate_by_dot += iurl+","
  460. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  461. time_stamp = datetime.fromtimestamp(time.time())
  462. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  463. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  464. ,'user_id':user_id,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','timestamp':time_stamp})
  465. return pk
  466. def get_url_type(url):
  467. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  468. r = urllib.request.urlopen(req)
  469. contentType = r.getheader('Content-Type')
  470. return contentType
  471. def notify_group(msg):
  472. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']
  473. for gid in glist:
  474. headers = {"Authorization": "Bearer " + gid,"Content-Type": "application/x-www-form-urlencoded"}
  475. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params={"message": msg})
  476. def gen_video_long_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  477. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  478. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  479. txt_content_seperate_by_dot = ''
  480. for txt in text_content:
  481. txt_content_seperate_by_dot += txt+","
  482. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  483. img_urls_seperate_by_dot = ''
  484. for iurl in image_urls:
  485. img_urls_seperate_by_dot += iurl+","
  486. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  487. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'multiLang':multiLang,'avatar':avatar,'timestamp':time_stamp})
  488. while True:
  489. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  490. print('another process running, leave loop')#1 means already running
  491. break
  492. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  493. print('all finish, leave loop')
  494. break
  495. top1 = first(db.query('SELECT * FROM video_queue'))
  496. try:
  497. # if True:
  498. db.query('UPDATE video_queue_status SET status = 1;')
  499. c = rpyc.connect("localhost", 8858)
  500. c._config['sync_request_timeout'] = None
  501. remote_svc = c.root
  502. 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
  503. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  504. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  505. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  506. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  507. line_token = user_obj['line_token'] # aa
  508. left_time = user_obj['left_time']
  509. email = user_obj['email']
  510. print('left_time is '+str(left_time))
  511. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  512. if left_time is None:
  513. left_time = 5*60
  514. if left_time < vid_duration:
  515. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  516. print(msg)
  517. msg =msg.encode(encoding='utf-8')
  518. mailer.send_left_not_enough(msg, email)
  519. #notify_line_user(msg, line_token)
  520. notify_group(name+":帳號餘額不足,請至email查看詳細資訊")
  521. else:
  522. left_time = left_time - vid_duration
  523. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  524. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  525. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  526. except Exception as e:
  527. logging.error(traceback.format_exc())
  528. print('video generation error')
  529. notify_group('長影片錯誤-測試')
  530. db['video_queue'].delete(id=top1['id'])
  531. db.query('UPDATE video_queue_status SET status = 0')
  532. def gen_video_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  533. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  534. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  535. txt_content_seperate_by_dot = ''
  536. for txt in text_content:
  537. txt_content_seperate_by_dot += txt+","
  538. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  539. img_urls_seperate_by_dot = ''
  540. for iurl in image_urls:
  541. img_urls_seperate_by_dot += iurl+","
  542. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  543. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'multiLang':multiLang,'avatar':avatar,'timestamp':time_stamp})
  544. while True:
  545. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  546. print('another process running, leave loop')#1 means already running
  547. break
  548. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  549. print('all finish, leave loop')
  550. break
  551. top1 = first(db.query('SELECT * FROM video_queue'))
  552. try:
  553. # if True:
  554. db.query('UPDATE video_queue_status SET status = 1;')
  555. c = rpyc.connect("localhost", 8858)
  556. c._config['sync_request_timeout'] = None
  557. remote_svc = c.root
  558. my_answer = remote_svc.call_video(top1['name_hash'],top1['name'],top1['text_content'].split(','), top1['image_urls'].split(','),top1['multiLang'],top1['avatar']) # method call
  559. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  560. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  561. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  562. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  563. line_token = user_obj['line_token'] # aa
  564. left_time = user_obj['left_time']
  565. email = user_obj['email']
  566. print('left_time is '+str(left_time))
  567. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  568. if left_time is None:
  569. left_time = 5*60
  570. if left_time < vid_duration:
  571. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  572. print(msg)
  573. msg =msg.encode(encoding='utf-8')
  574. mailer.send_left_not_enough(msg, email)
  575. notify_group(msg)
  576. #notify_line_user(msg, line_token)
  577. else:
  578. left_time = left_time - vid_duration
  579. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  580. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  581. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  582. except Exception as e:
  583. logging.error(traceback.format_exc())
  584. print('video generation error')
  585. notify_group('影片錯誤')
  586. db['video_queue'].delete(id=top1['id'])
  587. db.query('UPDATE video_queue_status SET status = 0')
  588. def gen_video_queue_eng(name_hash,name,text_content, image_urls,sub_titles,avatar,video_id):
  589. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  590. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  591. txt_content_seperate_by_dot = ''
  592. for txt in text_content:
  593. txt_content_seperate_by_dot += txt+","
  594. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  595. img_urls_seperate_by_dot = ''
  596. for iurl in image_urls:
  597. img_urls_seperate_by_dot += iurl+","
  598. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  599. subtitles_seperate_by_dot = ''
  600. for sub in sub_titles:
  601. subtitles_seperate_by_dot += sub+","
  602. subtitles_seperate_by_dot = subtitles_seperate_by_dot[:-1]
  603. db['video_queue'].insert({'name_hash':name_hash,'name':name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'subtitles':subtitles_seperate_by_dot,'avatar':avatar,'timestamp':time_stamp})
  604. while True:
  605. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  606. print('another process running, leave loop')
  607. break
  608. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  609. print('all finish, leave loop')
  610. break
  611. top1 = first(db.query('SELECT * FROM video_queue'))
  612. try:
  613. db.query('UPDATE video_queue_status SET status = 1;')
  614. c = rpyc.connect("localhost", 8858)
  615. c._config['sync_request_timeout'] = None
  616. remote_svc = c.root
  617. 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']) # method call
  618. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  619. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  620. notify_group(name+"(ENG)的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  621. except:
  622. print('video generation error')
  623. notify_group('影片錯誤')
  624. db['video_queue'].delete(id=top1['id'])
  625. db.query('UPDATE video_queue_status SET status = 0')
  626. def gen_avatar(name_hash, imgurl):
  627. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  628. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  629. while True:
  630. statement = 'SELECT * FROM avatar_service_status'#only one row in this table, which is the id 1 one
  631. status = -1
  632. for row in db.query(statement):
  633. status = row['status']
  634. if status == 1:
  635. print('leave process loop')
  636. break
  637. statement = 'SELECT * FROM avatar_queue'
  638. works = []
  639. for row in db.query(statement):
  640. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':row['imgurl']})
  641. if len(works)==0:
  642. print('leave process loop')
  643. break
  644. try:
  645. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  646. db.query(statement)
  647. name_hash = works[0]['name_hash']
  648. imgurl = works[0]['imgurl']
  649. c = rpyc.connect("localhost", 8868)
  650. c._config['sync_request_timeout'] = None
  651. remote_svc = c.root
  652. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  653. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  654. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  655. except:
  656. print('gen error')
  657. notify_group('無法辨識人臉')
  658. db['avatar_queue'].delete(id=works[0]['id'])
  659. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;' #only one row in this table, which id 1 one
  660. db.query(statement)
  661. def call_voice(text):
  662. print(text)
  663. print(len(text))
  664. print(type(text))
  665. c = rpyc.connect("localhost", 8858)
  666. c._config['sync_request_timeout'] = None
  667. remote_svc = c.root
  668. my_answer = remote_svc.make_speech(text) # method call
  669. src_path = '/home/ming/AI_Anchor/OpenshotService/speech.mp3'
  670. shutil.copy(src_path,'/home/ming/speech.mp3')
  671. os.remove(src_path)
  672. class text_in(BaseModel):
  673. text: str
  674. @app.post("/make_voice")
  675. async def make_voice(in_text:text_in):
  676. x = threading.Thread(target=call_voice, args=(in_text.text,))
  677. x.start()