main.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. from fastapi import FastAPI,Cookie, Depends, FastAPI, Query, WebSocket, status, WebSocketDisconnect
  2. import openshot
  3. from os import listdir
  4. from os.path import isfile, isdir, join
  5. import threading
  6. import zhtts
  7. import os
  8. import urllib
  9. from typing import List
  10. import requests
  11. from pydantic import BaseModel
  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 websocket import create_connection
  25. from fastapi.middleware.cors import CORSMiddleware
  26. import dataset
  27. from datetime import datetime
  28. from util.swap_face import swap_face
  29. from fastapi.staticfiles import StaticFiles
  30. #service nginx restart
  31. #uvicorn main:app --host="0.0.0.0" --reload --port 8888
  32. app = FastAPI()
  33. origins = [
  34. "https://hhh.com.tw"
  35. "http://172.105.205.52",
  36. "http://172.105.205.52:8001",
  37. "http://172.104.93.163",
  38. ]
  39. app.add_middleware(
  40. CORSMiddleware,
  41. # allow_origins=origins,
  42. allow_origins=["*"],
  43. allow_credentials=True,
  44. allow_methods=["*"],
  45. allow_headers=["*"],
  46. )
  47. app.mount("/static", StaticFiles(directory="static"), name="static")
  48. app.mount("/static/img", StaticFiles(directory="static/img"), name="static/img")
  49. dir_sound = 'mp3_track/'
  50. dir_photo = 'photo/'
  51. dir_text = 'text_file/'
  52. dir_video = 'video_material/'
  53. dir_title = 'title/'
  54. dir_subtitle = 'subtitle/'
  55. dir_anchor = 'anchor_raw/'
  56. class swap_req(BaseModel):
  57. imgurl: str
  58. class request(BaseModel):
  59. name: str
  60. text_content: List[str]
  61. image_urls: List[str]
  62. avatar: str
  63. client_id :str
  64. class ConnectionManager:
  65. def __init__(self):
  66. self.active_connections: List[WebSocket] = []
  67. async def connect(self, websocket: WebSocket):
  68. await websocket.accept()
  69. self.active_connections.append(websocket)
  70. def disconnect(self, websocket: WebSocket):
  71. self.active_connections.remove(websocket)
  72. async def send_personal_message(self, message: str, websocket: WebSocket):
  73. await websocket.send_text(message)
  74. async def broadcast(self, message: str):
  75. for connection in self.active_connections:
  76. await connection.send_text(message)
  77. @app.get("/")
  78. async def root():
  79. return {"message": "Hello, this is index"}
  80. @app.get("/index2")
  81. async def index2():
  82. return FileResponse('static/index2.html')
  83. @app.get("/gen_avatar")
  84. async def index2():
  85. return FileResponse('gen_avatar.html')
  86. @app.post("/swapFace")
  87. async def swapFace(req:swap_req):
  88. sf = swap_face(req.imgurl)
  89. result = sf.run()
  90. #notify_group(result)
  91. return result
  92. @app.post("/make_anchor_video_v2")
  93. async def make_anchor_video_v2(req:request):
  94. for txt in req.text_content:
  95. if re.search('[a-zA-Z]', txt) !=None:
  96. return {'msg':'輸入字串不能包含英文字!'}
  97. name_hash = str(time.time()).replace('.','')
  98. for imgu in req.image_urls:
  99. try:
  100. if get_url_type(imgu) =='video/mp4':
  101. r=requests.get(imgu)
  102. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  103. else:
  104. im = Image.open(requests.get(imgu, stream=True).raw)
  105. im= im.convert("RGB")
  106. except:
  107. return {'msg':"無法辨別圖片網址"+imgu}
  108. save_history(req,name_hash)
  109. x = threading.Thread(target=anchor_video_v2, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.client_id))
  110. x.start()
  111. return {"msg":"製作影片需要時間,請您耐心等候 稍後可以在www.choozmo.com:8168/"+name_hash+".mp4 中觀看"}
  112. manager = ConnectionManager()
  113. @app.websocket("/progress/{client_id}")
  114. async def websocket_endpoint(websocket: WebSocket, client_id: int):
  115. await manager.connect(websocket)
  116. try:
  117. while True:
  118. data = await websocket.receive_text()
  119. await manager.send_personal_message(data, websocket)
  120. await manager.broadcast(data)
  121. except WebSocketDisconnect:
  122. manager.disconnect(websocket)
  123. @app.get("/history_input")
  124. async def history_input():
  125. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  126. statement = 'SELECT * FROM history_input ORDER BY timestamp DESC LIMIT 50'
  127. logs = []
  128. for row in db.query(statement):
  129. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  130. return logs
  131. def notify_group(msg):
  132. '''
  133. headers = {
  134. "Authorization": "Bearer " + "WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD",
  135. "Content-Type": "application/x-www-form-urlencoded"
  136. }
  137. params = {"message": msg}
  138. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  139. '''
  140. headers = {
  141. "Authorization": "Bearer " + "7a0JnlE9TrbtwSJyL8dYjkiwedFZ4ZPmIhQbgaFPA1b",
  142. "Content-Type": "application/x-www-form-urlencoded"
  143. }
  144. params = {"message": msg}
  145. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  146. print(r)
  147. def save_history(req,name_hash):
  148. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  149. log_table = db['history_input']
  150. txt_content_seperate_by_dot = ''
  151. for txt in req.text_content:
  152. txt_content_seperate_by_dot += txt+","
  153. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  154. img_urls_seperate_by_dot = ''
  155. for iurl in req.image_urls:
  156. img_urls_seperate_by_dot += iurl+","
  157. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  158. time_stamp = datetime.fromtimestamp(time.time())
  159. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  160. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'link':'www.choozmo.com:8168/'+name_hash+'.mp4','timestamp':time_stamp})
  161. def cKey(r,g,b,fuzz):
  162. col=openshot.Color()
  163. col.red=openshot.Keyframe(r)
  164. col.green=openshot.Keyframe(g)
  165. col.blue=openshot.Keyframe(b)
  166. return openshot.ChromaKey(col, openshot.Keyframe(fuzz))
  167. def video_photo_clip(vid=None,layer=None, position=None, end=None
  168. ,scale_x=1,scale_y=1,location_x=0,location_y=0,ck=None,audio=True):
  169. clip = openshot.Clip(vid)
  170. clip.Layer(layer)
  171. clip.Position(position)
  172. clip.End(end)
  173. clip.scale_x=openshot.Keyframe(scale_x)
  174. clip.scale_y=openshot.Keyframe(scale_y)
  175. clip.location_x=openshot.Keyframe(location_x)
  176. clip.location_y=openshot.Keyframe(location_y)
  177. if ck!=None:
  178. clip.AddEffect(ck)
  179. if audio==True:
  180. clip.has_audio=openshot.Keyframe(1)
  181. else:
  182. clip.has_audio=openshot.Keyframe(0)
  183. return clip
  184. def myunichchar(unicode_char):
  185. mb_string = unicode_char.encode('big5')
  186. try:
  187. unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
  188. except NameError:
  189. unicode_char = chr(mb_string[0] << 8 | mb_string[1])
  190. return unicode_char
  191. def file_prepare(name, name_hash,text_content,image_urls):
  192. #save image
  193. try:
  194. os.mkdir(dir_photo+name_hash)
  195. except FileExistsError:
  196. print("Directory " , dir_photo+name_hash , " already exists")
  197. img_num = 1
  198. for imgu in image_urls:
  199. im = Image.open(requests.get(imgu, stream=True).raw)
  200. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  201. img_num+=1
  202. #save text
  203. text_file = open(dir_text+name_hash+".txt", "w")
  204. text_file.write(text_content)
  205. text_file.close()
  206. print("text file made")
  207. #make mp3
  208. tts = zhtts.TTS()
  209. tts.text2wav(text_content,dir_sound+name_hash+".mp3")
  210. print("mp3 file made")
  211. #make title as image
  212. txt2image(name, dir_title+name_hash+".png")
  213. def get_url_type(url):
  214. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  215. r = urllib.request.urlopen(req)
  216. contentType = r.getheader('Content-Type')
  217. return contentType
  218. def downloadfile(name,url):
  219. name=name+".mp4"
  220. def make_dir(name_hash):
  221. #save image
  222. try:
  223. os.mkdir(dir_photo+name_hash)
  224. except FileExistsError:
  225. print("~~~~~~Warning~~~~~~~~~Directory " , dir_photo+name_hash , " already exists")
  226. try:
  227. os.mkdir(dir_text+name_hash)
  228. except FileExistsError:
  229. print("~~~~~~Warning~~~~~~~~~Directory " , dir_text+name_hash , " already exists")
  230. try:
  231. os.mkdir(dir_sound+name_hash)
  232. except FileExistsError:
  233. print("~~~~~~Warning~~~~~~~~~Directory " , dir_sound+name_hash , " already exists")
  234. try:
  235. os.mkdir(dir_video+name_hash)
  236. except FileExistsError:
  237. print("~~~~~~Warning~~~~~~~~~Directory " , dir_video+name_hash , " already exists")
  238. try:
  239. os.mkdir(dir_anchor+name_hash)
  240. except FileExistsError:
  241. print("~~~~~~Warning~~~~~~~~~Directory " , dir_anchor+name_hash , " already exists")
  242. try:
  243. os.mkdir(dir_subtitle+name_hash)
  244. except FileExistsError:
  245. print("~~~~~~Warning~~~~~~~~~Directory " , dir_subtitle+name_hash , " already exists")
  246. def file_prepare_v2(name, name_hash,text_content,image_urls):
  247. make_dir(name_hash)
  248. img_num = 1
  249. for imgu in image_urls:
  250. if get_url_type(imgu) =='video/mp4':
  251. r=requests.get(imgu)
  252. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  253. for chunk in r.iter_content(chunk_size=255):
  254. if chunk:
  255. f.write(chunk)
  256. f.close()
  257. else:
  258. im = Image.open(requests.get(imgu, stream=True).raw)
  259. im= im.convert("RGB")
  260. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  261. img_num+=1
  262. #save text
  263. txt_idx=0
  264. for txt in text_content:
  265. text_file = open(dir_text+name_hash+"/"+str(txt_idx)+".txt", "w")
  266. text_file.write(txt)
  267. text_file.close()
  268. txt_idx+=1
  269. print("text file made")
  270. #make mp3
  271. language = 'zh-tw'
  272. txt_idx = 0
  273. for txt in text_content:
  274. tts = zhtts.TTS()
  275. tts.text2wav(txt,dir_sound+name_hash+"/"+str(txt_idx)+".mp3")
  276. txt_idx+=1
  277. print("mp3 file made")
  278. #make title as image
  279. txt2image_title(name, dir_title+name_hash+".png")
  280. def txt2image(content, save_target):
  281. unicode_text = trim_punctuation(content)
  282. font = ImageFont.truetype(font="DFT_B7.ttc", size=38)
  283. text_width, text_height = font.getsize(unicode_text)
  284. canvas = Image.new('RGBA', (700, 500), (255, 0, 0, 0) )
  285. draw = ImageDraw.Draw(canvas)
  286. text= unicode_text
  287. draw.text((5,5), text, (255, 255, 0), font)
  288. canvas.save(save_target, "PNG")
  289. def txt2image_title(content, save_target):
  290. unicode_text = trim_punctuation(content)
  291. font = ImageFont.truetype(font="DFT_B7.ttc", size=28)
  292. text_width, text_height = font.getsize(unicode_text)
  293. canvas = Image.new('RGBA', (510, 500), (255, 0, 0, 0) )
  294. draw = ImageDraw.Draw(canvas)
  295. text= unicode_text
  296. draw.text((5,5), text, (17, 41, 167), font)
  297. canvas.save(save_target, "PNG")
  298. '''
  299. def txt2image_title(content, save_target):
  300. unicode_text =content
  301. font = ImageFont.truetype("font.ttf", 23,encoding='big5')
  302. text_width, text_height = font.getsize(unicode_text)
  303. canvas = Image.new('RGBA', (500, 500), (255, 0, 0, 0) )
  304. draw = ImageDraw.Draw(canvas)
  305. text=''
  306. for c in unicode_text:
  307. if len(re.findall(r'[\u4e00-\u9fff]+', c))>0:
  308. text+=myunichchar(c)
  309. else:
  310. text+=c
  311. draw.text((5,5), text, (17, 41, 167), font)
  312. canvas.save(save_target, "PNG")
  313. '''
  314. def call_anchor(fileName,avatar):
  315. conn = rpyc.classic.connect("192.168.1.105",18812)
  316. ros = conn.modules.os
  317. rsys = conn.modules.sys
  318. fr=open(dir_sound+fileName+".mp3",'rb')# voice
  319. #warning!!! file my be replaced by other process
  320. fw=conn.builtins.open('/tmp/output.mp3','wb')
  321. while True:
  322. b=fr.read(1024)
  323. if b:
  324. fw.write(b)
  325. else:
  326. break
  327. fr.close()
  328. fw.close()
  329. val=random.randint(1000000,9999999)
  330. ros.chdir('/home/jared/to_video')
  331. ros.system('./p'+str(avatar)+'.sh '+str(val)+' &')
  332. while True:
  333. print('waiting...')
  334. if ros.path.exists('/tmp/results/'+str(val)):
  335. break
  336. time.sleep(5)
  337. print('waiting...')
  338. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  339. fw=open(dir_anchor+fileName+".mp4",'wb')#peggy1_1
  340. while True:
  341. b=fr.read(1024)
  342. if b:
  343. fw.write(b)
  344. else:
  345. break
  346. fr.close()
  347. fw.close()
  348. def trim_punctuation(s):
  349. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
  350. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  351. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u"" ,s)
  352. return res
  353. def splitter(s):
  354. for sent in re.findall(u'[^!?,。\!\?]+[!?。\!\?]?', s, flags=re.U):
  355. yield sent
  356. def split_by_pun(s):
  357. res = list(splitter(s))
  358. return res
  359. def generate_subtitle_image(name_hash,text_content):
  360. img_list = [None]*len(text_content)
  361. for idx in range(len(text_content)):
  362. img_list[idx]=[]
  363. senList = split_by_pun(text_content[idx])
  364. for inner_idx in range(len(senList)):
  365. sv_path = dir_subtitle + name_hash +'/'+str(idx)+ str(inner_idx) +'.png'
  366. sub = senList[inner_idx]
  367. txt2image(sub,sv_path)
  368. img_list[idx]+=[{"count":len(sub),"path":sv_path}]
  369. return img_list
  370. async def sendProgress(progress,client_id):
  371. ws = create_connection("ws://www.choozmo.com:8888/progress/"+client_id)
  372. ws.send(str(progress))
  373. ws.close()
  374. def anchor_video_v2(name_hash,name,text_content, image_urls,avatar,client_id):
  375. progress = 0
  376. asyncio.run(sendProgress(progress,client_id))
  377. print('sub image made')
  378. file_prepare_v2(name, name_hash, text_content,image_urls)
  379. progress = 20
  380. asyncio.run(sendProgress(progress,client_id))
  381. sub_list=generate_subtitle_image(name_hash,text_content)
  382. progress = 30
  383. asyncio.run(sendProgress(progress,client_id))
  384. progress_per_video = int(40/len(text_content))
  385. for fname in range(len(text_content)):
  386. call_anchor(name_hash+"/"+str(fname),avatar)
  387. progress += progress_per_video
  388. print('step finish')
  389. asyncio.run(sendProgress(progress,client_id))
  390. print('called............................................')
  391. ck=cKey(0,254,0,270)
  392. ck_anchor=cKey(0,255,1,320)
  393. duration = 0
  394. #average layer level is 3
  395. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  396. t.Open()
  397. main_timer = 0
  398. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP.mp4")
  399. LOGO_OP.Open() # Open the reader
  400. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  401. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  402. t.AddClip(LOGO_OP_clip)
  403. bg_head = openshot.FFmpegReader(dir_video+"bg_head.avi")
  404. bg_head.Open()
  405. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  406. t.AddClip(bg_head_clip)
  407. main_timer += LOGO_OP.info.duration
  408. head_duration = LOGO_OP.info.duration
  409. bg_head.Close()
  410. LOGO_OP.Close()
  411. progress += 10
  412. clip_duration=0
  413. photo_clip_list = [None]*len(text_content)
  414. img_list = [None]*len(text_content)
  415. anchor_clip_list = [None] * len(text_content)
  416. anchor_list = [None] * len(text_content)
  417. audio_clip_list = [None] * len(text_content)
  418. audio_list = [None] * len(text_content)
  419. sub_clip_list = [None] * len(text_content)
  420. sub_img_list = [None] * len(text_content)
  421. idx = 0
  422. for p in listdir(dir_photo+name_hash):
  423. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  424. clip_duration = anchor_list[idx].info.duration
  425. anchor_list[idx].Open()
  426. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  427. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  428. t.AddClip(anchor_clip_list[idx])
  429. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  430. img_list[idx].Open()
  431. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  432. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  433. t.AddClip(photo_clip_list[idx])
  434. img_list[idx].Close()
  435. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  436. audio_list[idx].Open()
  437. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  438. audio_clip_list[idx].Position(main_timer)
  439. audio_clip_list[idx].End(clip_duration)
  440. t.AddClip(audio_clip_list[idx])
  441. img_list[idx].Close()
  442. anchor_list[idx].Close()
  443. audio_list[idx].Close()
  444. sub_img_list[idx] = [None] * len(sub_list[idx])
  445. sub_clip_list[idx] = [None] * len(sub_list[idx])
  446. sub_timer = 0
  447. for sub_idx in range(len(sub_list[idx])):
  448. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  449. sub_img_list[idx][sub_idx].Open()
  450. sub_duration = 0.205*sub_list[idx][sub_idx]['count']
  451. sub_clip_list[idx][sub_idx] = video_photo_clip(vid=sub_img_list[idx][sub_idx], layer=6,location_x=0.069, location_y=0.89,position=main_timer+sub_timer,end=sub_duration)
  452. t.AddClip(sub_clip_list[idx][sub_idx])
  453. sub_img_list[idx][sub_idx].Close()
  454. sub_timer += sub_duration
  455. print(sub_list[idx][sub_idx]['path'])
  456. main_timer += clip_duration
  457. idx+=1
  458. progress+=10
  459. asyncio.run(sendProgress(progress,client_id))
  460. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  461. LOGO_ED.Open()
  462. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration+2
  463. ,location_x=0.005,location_y=-0.031
  464. ,scale_x=0.8,scale_y=0.6825)
  465. t.AddClip(LOGO_ED_clip)
  466. ED_duration = LOGO_ED.info.duration
  467. LOGO_ED.Close()
  468. bg = openshot.FFmpegReader(dir_video+"bg.mp4")
  469. bg.Open()
  470. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  471. left_time = (main_timer+ED_duration) % bg.info.duration
  472. bg_clip_list = [None] * bg_times
  473. bg_list = [None] * bg_times
  474. bg.Close()
  475. bg_timer = head_duration
  476. for idx in range(bg_times):
  477. bg_list[idx] = openshot.FFmpegReader(dir_video+"bg.mp4")
  478. bg_list[idx].Open()
  479. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  480. ,end=bg_list[idx].info.duration,ck=ck)
  481. t.AddClip(bg_clip_list[idx])
  482. bg_timer += bg_list[idx].info.duration
  483. bg_list[idx].Close()
  484. bg_left = openshot.FFmpegReader(dir_video+"bg.mp4")
  485. bg_left.Open()
  486. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  487. t.AddClip(bg_left_clip)
  488. bg_left.Close()
  489. title = openshot.QtImageReader(dir_title+name_hash+".png")
  490. title.Open() # Open the reader
  491. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  492. t.AddClip(title_clip)
  493. ####start building
  494. w = openshot.FFmpegWriter("../html/"+name_hash+".mp4")
  495. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  496. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  497. openshot.Fraction(1, 1), False, False, 3000000)
  498. w.Open()
  499. #may change duration into t.info.duration
  500. frames = int(t.info.fps)*int(head_duration+main_timer+ED_duration)
  501. for n in range(frames):
  502. f=t.GetFrame(n)
  503. w.WriteFrame(f)
  504. progress = 100
  505. asyncio.run(sendProgress(progress,client_id))
  506. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+name_hash+".mp4")
  507. t.Close()
  508. w.Close()
  509. progress = 100
  510. asyncio.run(sendProgress(progress,client_id))
  511. print("Raw Video done")
  512. print("video at : www.choozmo.com:8168/"+name_hash+".mp4")
  513. #line notifs