main.py 39 KB

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