main.py 25 KB

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