main.py 24 KB

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