main.py 24 KB

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