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