main.py 32 KB

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