openshot_video_generator.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. from os import listdir
  2. from os.path import isfile, isdir, join
  3. import openshot
  4. import threading
  5. import zhtts
  6. import os
  7. import urllib
  8. from typing import List
  9. import requests
  10. from pydantic import BaseModel
  11. from bs4 import BeautifulSoup
  12. from PIL import Image,ImageDraw,ImageFont
  13. import pyttsx3
  14. import rpyc
  15. import random
  16. import re
  17. import time
  18. import math
  19. import dataset
  20. from datetime import datetime
  21. from gtts import gTTS
  22. import ffmpy
  23. from difflib import SequenceMatcher
  24. import difflib
  25. from autosub import DEFAULT_CONCURRENCY
  26. from autosub import DEFAULT_SUBTITLE_FORMAT
  27. from pytranscriber.control.ctr_main import Ctr_Main
  28. from pytranscriber.control.ctr_autosub import Ctr_Autosub
  29. import multiprocessing
  30. dir_sound = 'mp3_track/'
  31. dir_photo = 'photo/'
  32. dir_text = 'text_file/'
  33. dir_video = 'video_material/'
  34. dir_title = 'title/'
  35. dir_subtitle = 'subtitle/'
  36. dir_anchor = 'anchor_raw/'
  37. tmp_video_dir = 'tmp_video/'
  38. video_sub_folder = 'ai_anchor_video/'
  39. dir_list = [dir_sound,dir_photo,dir_text,dir_video,dir_title,dir_subtitle,dir_anchor,tmp_video_dir]
  40. def notify_group(msg):
  41. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']
  42. for gid in glist:
  43. headers = {
  44. "Authorization": "Bearer " + gid,
  45. "Content-Type": "application/x-www-form-urlencoded"
  46. }
  47. params = {"message": msg}
  48. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  49. def cKey(r,g,b,fuzz):
  50. col=openshot.Color()
  51. col.red=openshot.Keyframe(r)
  52. col.green=openshot.Keyframe(g)
  53. col.blue=openshot.Keyframe(b)
  54. return openshot.ChromaKey(col, openshot.Keyframe(fuzz))
  55. def video_photo_clip(vid=None,layer=None, position=None, end=None
  56. ,scale_x=1,scale_y=1,location_x=0,location_y=0,ck=None,audio=True):
  57. clip = openshot.Clip(vid)
  58. clip.Layer(layer)
  59. clip.Position(position)
  60. clip.End(end)
  61. clip.scale_x=openshot.Keyframe(scale_x)
  62. clip.scale_y=openshot.Keyframe(scale_y)
  63. clip.location_x=openshot.Keyframe(location_x)
  64. clip.location_y=openshot.Keyframe(location_y)
  65. if ck!=None:
  66. clip.AddEffect(ck)
  67. if audio==True:
  68. clip.has_audio=openshot.Keyframe(1)
  69. else:
  70. clip.has_audio=openshot.Keyframe(0)
  71. return clip
  72. def listener_progress(string, percent):
  73. True
  74. def myunichchar(unicode_char):
  75. mb_string = unicode_char.encode('big5')
  76. try:
  77. unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
  78. except NameError:
  79. unicode_char = chr(mb_string[0] << 8 | mb_string[1])
  80. return unicode_char
  81. def get_url_type(url):
  82. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  83. r = urllib.request.urlopen(req)
  84. contentType = r.getheader('Content-Type')
  85. return contentType
  86. def make_dir(name_hash):
  87. for direct in dir_list:
  88. if not os.path.isdir(direct):
  89. os.mkdir(direct)
  90. try:
  91. os.mkdir(dir_photo+name_hash)
  92. except FileExistsError:
  93. print("~~~~~~Warning~~~~~~~~~Directory " , dir_photo+name_hash , " already exists")
  94. try:
  95. os.mkdir(dir_text+name_hash)
  96. except FileExistsError:
  97. print("~~~~~~Warning~~~~~~~~~Directory " , dir_text+name_hash , " already exists")
  98. try:
  99. os.mkdir(dir_sound+name_hash)
  100. except FileExistsError:
  101. print("~~~~~~Warning~~~~~~~~~Directory " , dir_sound+name_hash , " already exists")
  102. try:
  103. os.mkdir(dir_anchor+name_hash)
  104. except FileExistsError:
  105. print("~~~~~~Warning~~~~~~~~~Directory " , dir_anchor+name_hash , " already exists")
  106. try:
  107. os.mkdir(dir_subtitle+name_hash)
  108. except FileExistsError:
  109. print("~~~~~~Warning~~~~~~~~~Directory " , dir_subtitle+name_hash , " already exists")
  110. def file_prepare(name, name_hash,text_content,image_urls,multiLang,lang='zh'):
  111. make_dir(name_hash)
  112. img_num = 1
  113. for imgu in image_urls:
  114. if get_url_type(imgu) =='video/mp4':
  115. r=requests.get(imgu)
  116. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  117. for chunk in r.iter_content(chunk_size=255):
  118. if chunk:
  119. f.write(chunk)
  120. f.close()
  121. else:
  122. im = Image.open(requests.get(imgu, stream=True).raw)
  123. im= im.convert("RGB")
  124. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  125. img_num+=1
  126. #save text
  127. txt_idx=0
  128. for txt in text_content:
  129. text_file = open(dir_text+name_hash+"/"+str(txt_idx)+".txt", "w")
  130. text_file.write(txt)
  131. text_file.close()
  132. txt_idx+=1
  133. print("text file made")
  134. #make mp3
  135. txt_idx = 0
  136. for txt in text_content:
  137. if lang!='zh' or multiLang==1:
  138. if lang!='zh':
  139. tts = gTTS(txt)
  140. tts.save(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  141. else:
  142. tts = gTTS(txt,lang='zh-tw')
  143. tts.save(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  144. #speed up
  145. ff = ffmpy.FFmpeg(inputs={dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3": None}
  146. , outputs={dir_sound+name_hash+"/"+str(txt_idx)+".mp3": ["-filter:a", "atempo=1.2"]})
  147. ff.run()
  148. os.remove(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  149. else:
  150. print('use zhtts')
  151. tts = zhtts.TTS()
  152. tts.text2wav(txt,dir_sound+name_hash+"/"+str(txt_idx)+".mp3")
  153. txt_idx+=1
  154. print("mp3 file made")
  155. #make title as image
  156. txt2image_title(name, dir_title+name_hash+".png",lang)
  157. def txt2image(content, save_target,lang='zh'):
  158. unicode_text = trim_punctuation(content)
  159. font = ''
  160. if lang=='zh':
  161. font = ImageFont.truetype(font="font/DFT_B7.ttc", size=38)
  162. else :
  163. font = ImageFont.truetype(font="font/arial.ttf", size=38)
  164. text_width, text_height = font.getsize(unicode_text)
  165. canvas = Image.new('RGBA', (700, 500), (255, 0, 0, 0) )
  166. draw = ImageDraw.Draw(canvas)
  167. text= unicode_text
  168. draw.text((5,5), text, (255, 255, 0), font)
  169. canvas.save(save_target, "PNG")
  170. def txt2image_title(content, save_target, lang='zh'):
  171. unicode_text = trim_punctuation(content)
  172. font = ''
  173. if lang=='zh':
  174. font = ImageFont.truetype(font="font/DFT_B7.ttc", size=22)
  175. else :
  176. font = ImageFont.truetype(font="font/arial.ttf", size=22)
  177. text_width, text_height = font.getsize(unicode_text)
  178. canvas = Image.new('RGBA', (510, 500), (255, 0, 0, 0) )
  179. draw = ImageDraw.Draw(canvas)
  180. text= unicode_text
  181. draw.text((5,5), text, (17, 41, 167), font)
  182. canvas.save(save_target, "PNG")
  183. def call_anchor(fileName,avatar):
  184. conn = rpyc.classic.connect("192.168.1.105",18812)
  185. ros = conn.modules.os
  186. rsys = conn.modules.sys
  187. fr=open(dir_sound+fileName+".mp3",'rb')# voice
  188. #warning!!! file my be replaced by other process
  189. fw=conn.builtins.open('/tmp/output.mp3','wb')
  190. while True:
  191. b=fr.read(1024)
  192. if b:
  193. fw.write(b)
  194. else:
  195. break
  196. fr.close()
  197. fw.close()
  198. val=random.randint(1000000,9999999)
  199. ros.chdir('/home/jared/to_video')
  200. ros.system('./p'+str(avatar)+'.sh '+str(val)+' &')
  201. while True:
  202. print('waiting...')
  203. if ros.path.exists('/tmp/results/'+str(val)):
  204. break
  205. time.sleep(5)
  206. print('waiting...')
  207. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  208. fw=open(dir_anchor+fileName+".mp4",'wb')
  209. while True:
  210. b=fr.read(1024)
  211. if b:
  212. fw.write(b)
  213. else:
  214. break
  215. fr.close()
  216. fw.close()
  217. def parse_script(file_path):
  218. with open(file_path, 'r') as f:
  219. lines = [line.strip() for line in f]
  220. lines = adjustSub_by_text_similarity(gt_list,lines)
  221. dict_list = []
  222. for idx in range(int((len(lines)+1)/4)):
  223. script={}
  224. script['index'] = idx
  225. time_raw = lines[idx * 4]
  226. script['content'] = lines[idx * 4 + 2]
  227. start = time_raw.split(' --> ')[0].split(':')
  228. stop = time_raw.split(' --> ')[1].split(':')
  229. start[2] = start[2].replace(',','.')
  230. stop[2] = stop[2].replace(',','.')
  231. start_sec = float(start[0])*3600 + float(start[1])*60 + float(start[2])
  232. stop_sec = float(stop[0])*3600 + float(stop[1])*60 + float(stop[2])
  233. duration = start_sec-stop_sec
  234. script['start'] = start_sec
  235. script['stop'] = stop_sec
  236. script['duration'] = abs(duration)
  237. dict_list.append(script)
  238. new_idx = 0
  239. splitted_dict = []
  240. for dic in dict_list:
  241. #螢幕寬度只能容納13個字
  242. if dic['content']>13:
  243. times = math.ceil(len(dic['content'])/13)
  244. time_ratio = []
  245. for t in range(times):
  246. time_ratio[t] = len(dic['content'][t*13:t*13+13])/13 * dic['duration']
  247. for t in range(times):
  248. if time_ratio[t]>0.22:#about less than 3 words
  249. new_dic = {}
  250. new_dic['index'] = new_idx
  251. new_dic['content'] = dic['content'][t*13:t*13+13]
  252. start_plus = 0
  253. for t2 in range(t):
  254. start_plus += time_ratio[t2]
  255. new_dic['start'] = dic['start'] + start_plus
  256. new_dic['stop'] = new_dic['start']+time_ratio[t]
  257. new_dic['duration'] = time_ratio[t]
  258. splitted_dict.append(new_dic)
  259. new_idx+=1
  260. else:
  261. splitted_dict[new_idx-1]['content']+=dic['content']
  262. else:
  263. dic['index'] = new_idx
  264. new_idx+=1
  265. splitted_dict.append(dic)
  266. return splitted_dict
  267. def adjustSub_by_text_similarity(gts,gens):
  268. combine2 = [''.join([i,j]) for i,j in zip(gts, gts[1:])]
  269. combine3 = [''.join([i,j,k]) for i,j,k in zip(gts, gts[1:], gts[2:])]
  270. alls = gts+combine2+combine3
  271. for idx in range(len(gens)):
  272. match_text = difflib.get_close_matches(gens[idx], alls, cutoff=0.1)
  273. if len(match_text) != 0:
  274. print('{ '+gens[idx]+' }校正後: '+match_text[0])
  275. gens[idx] = match_text[0]
  276. else:
  277. print('無校正:'+gens[idx])
  278. return gens
  279. def trim_punctuation(s):
  280. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
  281. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  282. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u" " ,s)
  283. return res
  284. def splitter(s):
  285. for sent in re.findall(u'[^!?,。\!\?]+[!?。\!\?]?', s, flags=re.U):
  286. yield sent
  287. def split_by_pun(s):
  288. res = list(splitter(s))
  289. return res
  290. def generate_subtitle_image_from_dict(name_hash, sub_dict):
  291. for script in sub_dict:
  292. sv_path = dir_subtitle + name_hash + '/' + str(script['index'])+'.png'
  293. sub = script['content']
  294. txt2image(sub,sv_path)
  295. def generate_subtitle_image(name_hash,text_content):
  296. img_list = [None]*len(text_content)
  297. for idx in range(len(text_content)):
  298. img_list[idx]=[]
  299. senList = split_by_pun(text_content[idx])
  300. for inner_idx in range(len(senList)):
  301. sv_path = dir_subtitle + name_hash +'/'+str(idx)+ str(inner_idx) +'.png'
  302. sub = senList[inner_idx]
  303. txt2image(sub,sv_path)
  304. img_list[idx]+=[{"count":len(sub),"path":sv_path}]
  305. return img_list
  306. def generate_subtitle_image_ENG(name_hash,text_content):
  307. img_list = [None]*len(text_content)
  308. for idx in range(len(text_content)):
  309. sv_path = dir_subtitle + name_hash +'/'+str(idx)+'.png'
  310. sub = text_content[idx]
  311. txt2image(sub, sv_path,lang='eng')
  312. img_list[idx] = sv_path
  313. return img_list
  314. def video_writer_init(path):
  315. w = openshot.FFmpegWriter(path)
  316. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  317. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  318. openshot.Fraction(1, 1), False, False, 3000000)
  319. return w
  320. def video_gen(name_hash,name,text_content, image_urls,multiLang,avatar):
  321. file_prepare(name, name_hash, text_content,image_urls,multiLang)
  322. for fname in range(len(text_content)):
  323. call_anchor(name_hash+"/"+str(fname),avatar)
  324. print('called............................................')
  325. ck=cKey(0,254,0,270)
  326. ck_anchor=cKey(0,255,1,320)
  327. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  328. t.Open()
  329. main_timer = 0
  330. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP_4.mp4")
  331. LOGO_OP.Open() # Open the reader
  332. head_duration = LOGO_OP.info.duration
  333. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=head_duration
  334. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  335. t.AddClip(LOGO_OP_clip)
  336. bg_head = openshot.FFmpegReader(dir_video+"complete_head_aispokesgirl.mp4")
  337. bg_head.Open()
  338. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  339. t.AddClip(bg_head_clip)
  340. main_timer += head_duration
  341. bg_head.Close()
  342. LOGO_OP.Close()
  343. anchor = openshot.FFmpegReader(dir_anchor+name_hash+"/0.mp4")
  344. anchor.Open()
  345. #anchor_clip = video_photo_clip(vid=anchor,layer=4,scale_x=0.65,scale_y=0.65,
  346. # location_x=0.35,location_y=0.25,position=main_timer, end=anchor.info.duration,ck=ck_anchor,audio=False)
  347. #t.AddClip(anchor_clip)
  348. speech = openshot.FFmpegReader(dir_sound+name_hash+"/0.mp3")
  349. speech.Open()
  350. speech_clip = openshot.Clip(speech)
  351. speech_clip.Position(main_timer)
  352. speech_clip.End(anchor.info.duration)
  353. t.AddClip(speech_clip)
  354. main_timer += anchor.info.duration
  355. anchor.Close()
  356. speech.Close()
  357. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  358. LOGO_ED.Open()
  359. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration
  360. ,location_x=0.005,location_y=-0.031, scale_x=0.8,scale_y=0.6825)
  361. t.AddClip(LOGO_ED_clip)
  362. main_timer += LOGO_ED.info.duration
  363. LOGO_ED.Close()
  364. bg = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  365. bg.Open()
  366. bg_times = math.floor(main_timer/bg.info.duration)
  367. left_time = (main_timer) % bg.info.duration
  368. bg_clip_list = [None] * bg_times
  369. bg_list = [None] * bg_times
  370. bg.Close()
  371. bg_timer = head_duration
  372. for idx in range(bg_times):
  373. bg_list[idx] = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  374. bg_list[idx].Open()
  375. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer,end=bg_list[idx].info.duration,ck=ck)
  376. t.AddClip(bg_clip_list[idx])
  377. bg_timer += bg_list[idx].info.duration
  378. bg_list[idx].Close()
  379. bg_left = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  380. bg_left.Open()
  381. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  382. t.AddClip(bg_left_clip)
  383. bg_left.Close()
  384. title = openshot.QtImageReader(dir_title+name_hash+".png")
  385. title.Open() # Open the reader
  386. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  387. t.AddClip(title_clip)
  388. w = video_writer_init(tmp_video_dir+name_hash+"raw.mp4")
  389. w.Open()
  390. frames = int(t.info.fps)*int(main_timer)
  391. for n in range(frames):
  392. f=t.GetFrame(n)
  393. w.WriteFrame(f)
  394. t.Close()
  395. w.Close()
  396. print(name+"RAW DONE : www.choozmo.com:8168/"+tmp_video_dir+name_hash+"raw.mp4")
  397. #start adding sub
  398. #add sub
  399. Ctr_Autosub.init()
  400. Ctr_Autosub.generate_subtitles(tmp_video_dir+name_hash+"raw.mp4",'zh',listener_progress,output=tmp_video_dir+name_hash+"script.txt",concurrency=DEFAULT_CONCURRENCY,subtitle_file_format=DEFAULT_SUBTITLE_FORMAT)
  401. sub_dict = parse_script(tmp_video_dir+name_hash+"script.txt")
  402. generate_subtitle_image_from_dict(name_hash, sub_dict)
  403. #sv_path = dir_subtitle + name_hash + '/' + str(script['index'])+'.png'
  404. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  405. t.Open()
  406. raw = openshot.FFmpegReader(tmp_video_dir+name_hash+"raw.mp4")
  407. raw.Open()
  408. raw_clip = video_photo_clip(vid=raw,layer=2,position=0, end=raw.info.duration)
  409. t.AddClip(raw_clip)
  410. sub_img_list = [None] * len(sub_dict)
  411. sub_clip_list = [None] * len(sub_dict)
  412. for sub_obj in sub_dict:
  413. idx = int(sub_obj['index'])
  414. sub_img_list[idx] = openshot.QtImageReader(dir_subtitle + name_hash + '/' + str(idx)+'.png')
  415. sub_img_list[idx].Open()
  416. sub_clip_list[idx] = video_photo_clip(vid=sub_img_list[idx], layer=6,location_x=0.069, location_y=0.89,position=sub_obj['start'],end=math.ceil(sub_obj['duration']))
  417. t.AddClip(sub_clip_list[idx])
  418. sub_img_list[idx].Close()
  419. anchor = openshot.FFmpegReader(dir_anchor+name_hash+"/0.mp4")
  420. anchor.Open()
  421. anchor_clip = video_photo_clip(vid=anchor,layer=4,scale_x=0.65,scale_y=0.65,
  422. location_x=0.35,location_y=0.25,position=head_duration, end=anchor.info.duration,ck=ck_anchor,audio=False)
  423. t.AddClip(anchor_clip)
  424. w = video_writer_init(tmp_video_dir+name_hash+".mp4")
  425. w.Open()
  426. frames = int(t.info.fps)*int(main_timer)
  427. for n in range(frames):
  428. f=t.GetFrame(n)
  429. w.WriteFrame(f)
  430. t.Close()
  431. w.Close()
  432. os.remove(tmp_video_dir+name_hash+"raw.mp4")
  433. os.remove(tmp_video_dir+name_hash+"script.txt")
  434. print(name+"ALL DONE : www.choozmo.com:8168/"+video_sub_folder+name_hash+"raw.mp4")
  435. def anchor_video_v2(name_hash,name,text_content, image_urls,multiLang,avatar):
  436. print(os.getcwd())
  437. print('sub image made')
  438. print(multiLang)
  439. file_prepare(name, name_hash, text_content,image_urls,multiLang)
  440. sub_list=generate_subtitle_image(name_hash,text_content)
  441. for fname in range(len(text_content)):
  442. call_anchor(name_hash+"/"+str(fname),avatar)
  443. print('step finish')
  444. print('called............................................')
  445. ck=cKey(0,254,0,270)
  446. ck_anchor=cKey(0,255,1,320)
  447. duration = 0
  448. #average layer level is 3
  449. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  450. t.Open()
  451. main_timer = 0
  452. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP_4.mp4")
  453. LOGO_OP.Open() # Open the reader
  454. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  455. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  456. t.AddClip(LOGO_OP_clip)
  457. bg_head = openshot.FFmpegReader(dir_video+"complete_head_aispokesgirl.mp4")
  458. bg_head.Open()
  459. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  460. t.AddClip(bg_head_clip)
  461. main_timer += LOGO_OP.info.duration
  462. head_duration = LOGO_OP.info.duration
  463. bg_head.Close()
  464. LOGO_OP.Close()
  465. clip_duration=0
  466. photo_clip_list = [None]*len(text_content)
  467. img_list = [None]*len(text_content)
  468. anchor_clip_list = [None] * len(text_content)
  469. anchor_list = [None] * len(text_content)
  470. audio_clip_list = [None] * len(text_content)
  471. audio_list = [None] * len(text_content)
  472. sub_clip_list = [None] * len(text_content)
  473. sub_img_list = [None] * len(text_content)
  474. idx = 0
  475. for p in listdir(dir_photo+name_hash):
  476. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  477. clip_duration = anchor_list[idx].info.duration
  478. anchor_list[idx].Open()
  479. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  480. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  481. t.AddClip(anchor_clip_list[idx])
  482. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  483. img_list[idx].Open()
  484. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  485. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  486. t.AddClip(photo_clip_list[idx])
  487. img_list[idx].Close()
  488. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  489. audio_list[idx].Open()
  490. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  491. audio_clip_list[idx].Position(main_timer)
  492. audio_clip_list[idx].End(clip_duration)
  493. t.AddClip(audio_clip_list[idx])
  494. img_list[idx].Close()
  495. anchor_list[idx].Close()
  496. audio_list[idx].Close()
  497. sub_img_list[idx] = [None] * len(sub_list[idx])
  498. sub_clip_list[idx] = [None] * len(sub_list[idx])
  499. sub_timer = 0
  500. for sub_idx in range(len(sub_list[idx])):
  501. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  502. sub_img_list[idx][sub_idx].Open()
  503. sub_duration = 0.205*sub_list[idx][sub_idx]['count']
  504. 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)
  505. t.AddClip(sub_clip_list[idx][sub_idx])
  506. sub_img_list[idx][sub_idx].Close()
  507. sub_timer += sub_duration
  508. print(sub_list[idx][sub_idx]['path'])
  509. main_timer += clip_duration
  510. idx+=1
  511. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  512. LOGO_ED.Open()
  513. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration+2
  514. ,location_x=0.005,location_y=-0.031
  515. ,scale_x=0.8,scale_y=0.6825)
  516. t.AddClip(LOGO_ED_clip)
  517. ED_duration = LOGO_ED.info.duration
  518. LOGO_ED.Close()
  519. bg = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  520. bg.Open()
  521. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  522. left_time = (main_timer+ED_duration) % bg.info.duration
  523. bg_clip_list = [None] * bg_times
  524. bg_list = [None] * bg_times
  525. bg.Close()
  526. bg_timer = head_duration
  527. for idx in range(bg_times):
  528. bg_list[idx] = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  529. bg_list[idx].Open()
  530. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  531. ,end=bg_list[idx].info.duration,ck=ck)
  532. t.AddClip(bg_clip_list[idx])
  533. bg_timer += bg_list[idx].info.duration
  534. bg_list[idx].Close()
  535. bg_left = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  536. bg_left.Open()
  537. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  538. t.AddClip(bg_left_clip)
  539. bg_left.Close()
  540. title = openshot.QtImageReader(dir_title+name_hash+".png")
  541. title.Open() # Open the reader
  542. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  543. t.AddClip(title_clip)
  544. ####start building
  545. w = openshot.FFmpegWriter(tmp_video_dir+name_hash+".mp4")
  546. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  547. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  548. openshot.Fraction(1, 1), False, False, 3000000)
  549. w.Open()
  550. #may change duration into t.info.duration
  551. frames = int(t.info.fps)*int(head_duration+main_timer+ED_duration)
  552. for n in range(frames):
  553. f=t.GetFrame(n)
  554. w.WriteFrame(f)
  555. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  556. t.Close()
  557. w.Close()
  558. print("video at : www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  559. def anchor_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar):
  560. file_prepare(name, name_hash, text_content,image_urls,'eng')
  561. sub_list=generate_subtitle_image_ENG(name_hash,sub_titles)
  562. for fname in range(len(text_content)):
  563. call_anchor(name_hash+"/"+str(fname),avatar)
  564. print('step finish')
  565. print('called............................................')
  566. ck=cKey(0,254,0,270)
  567. ck_anchor=cKey(0,255,1,320)
  568. duration = 0
  569. #average layer level is 3
  570. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  571. t.Open()
  572. main_timer = 0
  573. #add logo
  574. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP_4.mp4")
  575. LOGO_OP.Open() # Open the reader
  576. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  577. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  578. t.AddClip(LOGO_OP_clip)
  579. #add background video (head is different)
  580. bg_head = openshot.FFmpegReader(dir_video+"complete_head_aispokesgirl.mp4")
  581. bg_head.Open()
  582. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  583. t.AddClip(bg_head_clip)
  584. main_timer += LOGO_OP.info.duration
  585. head_duration = LOGO_OP.info.duration
  586. bg_head.Close()
  587. LOGO_OP.Close()
  588. #prepare empty list
  589. clip_duration=0
  590. photo_clip_list = [None]*len(text_content)
  591. img_list = [None]*len(text_content)
  592. anchor_clip_list = [None] * len(text_content)
  593. anchor_list = [None] * len(text_content)
  594. audio_clip_list = [None] * len(text_content)
  595. audio_list = [None] * len(text_content)
  596. sub_clip_list = [None] * len(text_content)
  597. #openshot image holder
  598. sub_img_list = [None] * len(text_content)
  599. idx = 0
  600. for p in listdir(dir_photo+name_hash):
  601. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  602. clip_duration = anchor_list[idx].info.duration
  603. anchor_list[idx].Open()
  604. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  605. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  606. t.AddClip(anchor_clip_list[idx])
  607. #insert image
  608. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  609. img_list[idx].Open()
  610. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  611. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  612. t.AddClip(photo_clip_list[idx])
  613. img_list[idx].Close()
  614. #insert audio (speech)
  615. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  616. audio_list[idx].Open()
  617. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  618. audio_clip_list[idx].Position(main_timer)
  619. audio_clip_list[idx].End(clip_duration)
  620. t.AddClip(audio_clip_list[idx])
  621. #insert subtitle
  622. sub_img_list[idx] = openshot.QtImageReader(sub_list[idx])
  623. sub_img_list[idx].Open()
  624. sub_clip_list[idx] = video_photo_clip(vid=sub_img_list[idx], layer=6,location_x=0.069, location_y=0.89,position=main_timer,end=clip_duration)
  625. t.AddClip(sub_clip_list[idx])
  626. img_list[idx].Close()
  627. anchor_list[idx].Close()
  628. audio_list[idx].Close()
  629. sub_img_list[idx].Close()
  630. main_timer += clip_duration
  631. idx+=1
  632. LOGO_ED = openshot.FFmpegReader(dir_video+"ED_ENG.mp4")
  633. LOGO_ED.Open()
  634. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration+2
  635. ,location_x=0.005,location_y=-0.031
  636. ,scale_x=0.8,scale_y=0.6825)
  637. t.AddClip(LOGO_ED_clip)
  638. ED_duration = LOGO_ED.info.duration
  639. LOGO_ED.Close()
  640. bg = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  641. bg.Open()
  642. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  643. left_time = (main_timer+ED_duration) % bg.info.duration
  644. bg_clip_list = [None] * bg_times
  645. bg_list = [None] * bg_times
  646. bg.Close()
  647. bg_timer = head_duration
  648. for idx in range(bg_times):
  649. bg_list[idx] = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  650. bg_list[idx].Open()
  651. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  652. ,end=bg_list[idx].info.duration,ck=ck)
  653. t.AddClip(bg_clip_list[idx])
  654. bg_timer += bg_list[idx].info.duration
  655. bg_list[idx].Close()
  656. bg_left = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  657. bg_left.Open()
  658. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  659. t.AddClip(bg_left_clip)
  660. bg_left.Close()
  661. title = openshot.QtImageReader(dir_title+name_hash+".png")
  662. title.Open() # Open the reader
  663. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  664. t.AddClip(title_clip)
  665. ####start building
  666. w = openshot.FFmpegWriter(tmp_video_dir+name_hash+".mp4")
  667. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  668. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  669. openshot.Fraction(1, 1), False, False, 3000000)
  670. w.Open()
  671. #may change duration into t.info.duration
  672. frames = int(t.info.fps)*int(head_duration+main_timer+ED_duration)
  673. for n in range(frames):
  674. f=t.GetFrame(n)
  675. w.WriteFrame(f)
  676. notify_group(name+"(ENG)的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  677. t.Close()
  678. w.Close()
  679. print("video at : www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  680. #line notifs
  681. class video_service(rpyc.Service):
  682. def exposed_call_video(self,name_hash,name,text_content, image_urls,multiLang,avatar):
  683. print('ML:'+str(multiLang))
  684. anchor_video_v2(name_hash,name,text_content, image_urls,multiLang,avatar)
  685. def exposed_call_video_eng(self,name_hash,name,text_content, image_urls,sub_titles,avatar):
  686. anchor_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar)
  687. def exposed_call_video_gen(self,name_hash,name,text_content, image_urls,multiLang,avatar):
  688. print('ML:'+str(multiLang))#this is long video version,
  689. video_gen(name_hash,name,text_content, image_urls,multiLang,avatar)
  690. from rpyc.utils.server import ThreadedServer
  691. t = ThreadedServer(video_service, port=8858)
  692. print('service started')
  693. t.start()