main.py 24 KB

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