main.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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_old")
  372. async def history_input_old(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. @app.post("/history_input")
  383. async def history_input(token: str = Depends(oauth2_scheme)):
  384. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  385. user_id = get_user_id(token)
  386. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  387. statement = 'SELECT * FROM history_input WHERE user_id="'+str(user_id)+'" ORDER BY timestamp DESC LIMIT 50'
  388. logs = []
  389. for row in db.query(statement):
  390. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  391. return logs
  392. @AuthJWT.load_config
  393. def get_config():
  394. return models.Settings()
  395. @app.exception_handler(AuthJWTException)
  396. def authjwt_exception_handler(request: Request, exc: AuthJWTException):
  397. return JSONResponse(
  398. status_code=exc.status_code,
  399. content={"detail": exc.message}
  400. )
  401. def get_user_id(token):
  402. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  403. credentials_exception = HTTPException(
  404. status_code=status.HTTP_401_UNAUTHORIZED,
  405. detail="Could not validate credentials",
  406. headers={"WWW-Authenticate": "Bearer"},
  407. )
  408. try:
  409. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  410. username: str = payload.get("sub")
  411. if username is None:
  412. raise credentials_exception
  413. token_data = models.TokenData(username=username)
  414. except JWTError:
  415. raise credentials_exception
  416. user = get_user(username=token_data.username)
  417. if user is None:
  418. raise credentials_exception
  419. user_id = first(db.query('SELECT * FROM users where username="' + user.username+'"'))['id']
  420. return user_id
  421. def check_user_exists(username):
  422. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  423. if int(next(iter(db.query('SELECT COUNT(*) FROM AI_anchor.users WHERE username = "'+username+'"')))['COUNT(*)']) > 0:
  424. return True
  425. else:
  426. return False
  427. def get_user(username: str):
  428. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  429. if not check_user_exists(username): # if user don't exist
  430. return False
  431. user_dict = next(
  432. iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  433. user = models.User(**user_dict)
  434. return user
  435. def user_register(user):
  436. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  437. table = db['users']
  438. user.password = get_password_hash(user.password)
  439. table.insert(dict(user))
  440. return True
  441. def get_password_hash(password):
  442. return pwd_context.hash(password)
  443. def verify_password(plain_password, hashed_password):
  444. return pwd_context.verify(plain_password, hashed_password)
  445. def authenticate_user(username: str, password: str):
  446. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  447. if not check_user_exists(username): # if user don't exist
  448. return False
  449. user_dict = next(iter(db.query('SELECT * FROM AI_anchor.users where username ="'+username+'"')))
  450. user = models.User(**user_dict)
  451. if not verify_password(password, user.password):
  452. return False
  453. return user
  454. def create_access_token(data: dict, expires_delta):
  455. to_encode = data.copy()
  456. expire = datetime.utcnow() + expires_delta
  457. to_encode.update({"exp": expire})
  458. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  459. return encoded_jwt
  460. def save_history(req,name_hash,user_id):
  461. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  462. log_table = db['history_input']
  463. txt_content_seperate_by_dot = ''
  464. for txt in req.text_content:
  465. txt_content_seperate_by_dot += txt+","
  466. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  467. img_urls_seperate_by_dot = ''
  468. for iurl in req.image_urls:
  469. img_urls_seperate_by_dot += iurl+","
  470. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  471. time_stamp = datetime.fromtimestamp(time.time())
  472. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  473. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot
  474. ,'user_id':user_id,'link':'www.choozmo.com:8168/'+video_sub_folder+name_hash+'.mp4','timestamp':time_stamp})
  475. return pk
  476. def get_url_type(url):
  477. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  478. r = urllib.request.urlopen(req)
  479. contentType = r.getheader('Content-Type')
  480. return contentType
  481. def notify_group(msg):
  482. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']
  483. for gid in glist:
  484. headers = {"Authorization": "Bearer " + gid,"Content-Type": "application/x-www-form-urlencoded"}
  485. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params={"message": msg})
  486. def gen_video_long_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  487. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  488. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  489. txt_content_seperate_by_dot = ''
  490. for txt in text_content:
  491. txt_content_seperate_by_dot += txt+","
  492. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  493. img_urls_seperate_by_dot = ''
  494. for iurl in image_urls:
  495. img_urls_seperate_by_dot += iurl+","
  496. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  497. 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})
  498. while True:
  499. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  500. print('another process running, leave loop')#1 means already running
  501. break
  502. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  503. print('all finish, leave loop')
  504. break
  505. top1 = first(db.query('SELECT * FROM video_queue'))
  506. try:
  507. # if True:
  508. db.query('UPDATE video_queue_status SET status = 1;')
  509. c = rpyc.connect("localhost", 8858)
  510. c._config['sync_request_timeout'] = None
  511. remote_svc = c.root
  512. 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
  513. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  514. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  515. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  516. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  517. line_token = user_obj['line_token'] # aa
  518. left_time = user_obj['left_time']
  519. email = user_obj['email']
  520. print('left_time is '+str(left_time))
  521. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  522. if left_time is None:
  523. left_time = 5*60
  524. if left_time < vid_duration:
  525. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  526. print(msg)
  527. msg =msg.encode(encoding='utf-8')
  528. mailer.send_left_not_enough(msg, email)
  529. #notify_line_user(msg, line_token)
  530. notify_group(name+":帳號餘額不足,請至email查看詳細資訊")
  531. else:
  532. left_time = left_time - vid_duration
  533. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  534. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  535. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  536. except Exception as e:
  537. logging.error(traceback.format_exc())
  538. print('video generation error')
  539. notify_group('長影片錯誤-測試')
  540. db['video_queue'].delete(id=top1['id'])
  541. db.query('UPDATE video_queue_status SET status = 0')
  542. def gen_video_queue(name_hash,name,text_content, image_urls,avatar,multiLang,video_id,user_id):
  543. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  544. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  545. txt_content_seperate_by_dot = ''
  546. for txt in text_content:
  547. txt_content_seperate_by_dot += txt+","
  548. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  549. img_urls_seperate_by_dot = ''
  550. for iurl in image_urls:
  551. img_urls_seperate_by_dot += iurl+","
  552. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  553. 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})
  554. while True:
  555. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  556. print('another process running, leave loop')#1 means already running
  557. break
  558. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  559. print('all finish, leave loop')
  560. break
  561. top1 = first(db.query('SELECT * FROM video_queue'))
  562. try:
  563. # if True:
  564. db.query('UPDATE video_queue_status SET status = 1;')
  565. c = rpyc.connect("localhost", 8858)
  566. c._config['sync_request_timeout'] = None
  567. remote_svc = c.root
  568. 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
  569. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  570. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  571. vid_duration = VideoFileClip(video_dest+top1['name_hash']+'.mp4').duration
  572. user_obj = first(db.query('SELECT * FROM users where id ="'+str(user_id)+'"'))
  573. line_token = user_obj['line_token'] # aa
  574. left_time = user_obj['left_time']
  575. email = user_obj['email']
  576. print('left_time is '+str(left_time))
  577. db.query('UPDATE history_input SET duration ='+str(vid_duration)+' WHERE id='+str(video_id)+';')
  578. if left_time is None:
  579. left_time = 5*60
  580. if left_time < vid_duration:
  581. msg = '您本月額度剩下'+str(left_time)+'秒,此部影片有'+str(vid_duration)+'秒, 若要繼續產生影片請至 192.168.1.106:8887/confirm_add_value?name_hash='+name_hash+' 加值'
  582. print(msg)
  583. msg =msg.encode(encoding='utf-8')
  584. mailer.send_left_not_enough(msg, email)
  585. notify_group(msg)
  586. #notify_line_user(msg, line_token)
  587. else:
  588. left_time = left_time - vid_duration
  589. db.query('UPDATE users SET left_time ='+str(left_time)+' WHERE id='+str(user_id)+';')
  590. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  591. #notify_line_user(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4", line_token)
  592. except Exception as e:
  593. logging.error(traceback.format_exc())
  594. print('video generation error')
  595. notify_group('影片錯誤')
  596. db['video_queue'].delete(id=top1['id'])
  597. db.query('UPDATE video_queue_status SET status = 0')
  598. def gen_video_queue_eng(name_hash,name,text_content, image_urls,sub_titles,avatar,video_id):
  599. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  600. time_stamp = datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
  601. txt_content_seperate_by_dot = ''
  602. for txt in text_content:
  603. txt_content_seperate_by_dot += txt+","
  604. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  605. img_urls_seperate_by_dot = ''
  606. for iurl in image_urls:
  607. img_urls_seperate_by_dot += iurl+","
  608. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  609. subtitles_seperate_by_dot = ''
  610. for sub in sub_titles:
  611. subtitles_seperate_by_dot += sub+","
  612. subtitles_seperate_by_dot = subtitles_seperate_by_dot[:-1]
  613. 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})
  614. while True:
  615. if first(db.query('SELECT * FROM video_queue_status'))['status'] == 1:#only one row in this table, which is the id 1 one
  616. print('another process running, leave loop')
  617. break
  618. if first(db.query('SELECT COUNT(1) FROM video_queue'))['COUNT(1)'] == 0:
  619. print('all finish, leave loop')
  620. break
  621. top1 = first(db.query('SELECT * FROM video_queue'))
  622. try:
  623. db.query('UPDATE video_queue_status SET status = 1;')
  624. c = rpyc.connect("localhost", 8858)
  625. c._config['sync_request_timeout'] = None
  626. remote_svc = c.root
  627. 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
  628. shutil.copy(tmp_video_dir+top1['name_hash']+'.mp4',video_dest+top1['name_hash']+'.mp4')
  629. os.remove(tmp_video_dir+top1['name_hash']+'.mp4')
  630. notify_group(name+"(ENG)的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  631. except:
  632. print('video generation error')
  633. notify_group('影片錯誤')
  634. db['video_queue'].delete(id=top1['id'])
  635. db.query('UPDATE video_queue_status SET status = 0')
  636. def gen_avatar(name_hash, imgurl):
  637. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  638. db['avatar_queue'].insert({'name_hash':name_hash,'imgurl':imgurl})
  639. while True:
  640. statement = 'SELECT * FROM avatar_service_status'#only one row in this table, which is the id 1 one
  641. status = -1
  642. for row in db.query(statement):
  643. status = row['status']
  644. if status == 1:
  645. print('leave process loop')
  646. break
  647. statement = 'SELECT * FROM avatar_queue'
  648. works = []
  649. for row in db.query(statement):
  650. works.append({'id':row['id'],'name_hash':row['name_hash'],'imgurl':row['imgurl']})
  651. if len(works)==0:
  652. print('leave process loop')
  653. break
  654. try:
  655. statement = 'UPDATE avatar_service_status SET status = 1 WHERE id=1;'
  656. db.query(statement)
  657. name_hash = works[0]['name_hash']
  658. imgurl = works[0]['imgurl']
  659. c = rpyc.connect("localhost", 8868)
  660. c._config['sync_request_timeout'] = None
  661. remote_svc = c.root
  662. my_answer = remote_svc.call_avatar(name_hash,imgurl) # method call
  663. shutil.copy(tmp_avatar_dir+name_hash+'.mp4',avatar_dest+name_hash+'.mp4')
  664. os.remove(tmp_avatar_dir+name_hash+'.mp4')
  665. except:
  666. print('gen error')
  667. notify_group('無法辨識人臉')
  668. db['avatar_queue'].delete(id=works[0]['id'])
  669. statement = 'UPDATE avatar_service_status SET status = 0 WHERE id=1;' #only one row in this table, which id 1 one
  670. db.query(statement)
  671. def call_voice(text):
  672. print(text)
  673. print(len(text))
  674. print(type(text))
  675. c = rpyc.connect("localhost", 8858)
  676. c._config['sync_request_timeout'] = None
  677. remote_svc = c.root
  678. my_answer = remote_svc.make_speech(text) # method call
  679. src_path = '/home/ming/AI_Anchor/OpenshotService/speech.mp3'
  680. shutil.copy(src_path,'/home/ming/speech.mp3')
  681. os.remove(src_path)
  682. class text_in(BaseModel):
  683. text: str
  684. @app.post("/make_voice")
  685. async def make_voice(in_text:text_in):
  686. x = threading.Thread(target=call_voice, args=(in_text.text,))
  687. x.start()