main.py 22 KB

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