main.py 21 KB

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