main.py 25 KB

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