openshot_video_generator.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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. from itertools import groupby
  31. from operator import itemgetter
  32. from util.parser import parser
  33. import pandas as pd
  34. import numpy as np
  35. import jieba
  36. import jieba.posseg as pseg
  37. import urllib.request
  38. import librosa
  39. from pydub import AudioSegment
  40. from pydub.silence import split_on_silence
  41. import itertools
  42. from hakkaUtil import *
  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. tmp_video_dir = 'tmp_video/'
  51. video_sub_folder = 'ai_anchor_video/'
  52. dir_list = [dir_sound,dir_photo,dir_text,dir_video,dir_title,dir_subtitle,dir_anchor,tmp_video_dir]
  53. def notify_group(msg):
  54. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX','HOB1kVNgIb81tTB4Ort1BfhVp9GFo6NlToMQg88vEhh']
  55. for gid in glist:
  56. headers = {
  57. "Authorization": "Bearer " + gid,
  58. "Content-Type": "application/x-www-form-urlencoded"
  59. }
  60. params = {"message": msg}
  61. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  62. def cKey(r,g,b,fuzz):
  63. col=openshot.Color()
  64. col.red=openshot.Keyframe(r)
  65. col.green=openshot.Keyframe(g)
  66. col.blue=openshot.Keyframe(b)
  67. return openshot.ChromaKey(col, openshot.Keyframe(fuzz))
  68. def video_photo_clip(vid=None,layer=None, position=None, end=None
  69. ,scale_x=1,scale_y=1,location_x=0,location_y=0,ck=None,audio=True):
  70. clip = openshot.Clip(vid)
  71. clip.Layer(layer)
  72. clip.Position(position)
  73. clip.End(end)
  74. clip.scale_x=openshot.Keyframe(scale_x)
  75. clip.scale_y=openshot.Keyframe(scale_y)
  76. clip.location_x=openshot.Keyframe(location_x)
  77. clip.location_y=openshot.Keyframe(location_y)
  78. if ck!=None:
  79. clip.AddEffect(ck)
  80. if audio==True:
  81. clip.has_audio=openshot.Keyframe(1)
  82. else:
  83. clip.has_audio=openshot.Keyframe(0)
  84. return clip
  85. def listener_progress(string, percent):
  86. True
  87. def myunichchar(unicode_char):
  88. mb_string = unicode_char.encode('big5')
  89. try:
  90. unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
  91. except NameError:
  92. unicode_char = chr(mb_string[0] << 8 | mb_string[1])
  93. return unicode_char
  94. def get_url_type(url):
  95. print('---------------------------------------------')
  96. print(url)
  97. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  98. r = urllib.request.urlopen(req)
  99. contentType = r.getheader('Content-Type')
  100. print(contentType)
  101. print('-------------------------------------------------')
  102. return contentType
  103. def make_dir(name_hash):
  104. for direct in dir_list:
  105. if not os.path.isdir(direct):
  106. os.mkdir(direct)
  107. try:
  108. os.mkdir(dir_photo+name_hash)
  109. except FileExistsError:
  110. print("~~~~~~Warning~~~~~~~~~Directory " , dir_photo+name_hash , " already exists")
  111. try:
  112. os.mkdir(dir_text+name_hash)
  113. except FileExistsError:
  114. print("~~~~~~Warning~~~~~~~~~Directory " , dir_text+name_hash , " already exists")
  115. try:
  116. os.mkdir(dir_sound+name_hash)
  117. except FileExistsError:
  118. print("~~~~~~Warning~~~~~~~~~Directory " , dir_sound+name_hash , " already exists")
  119. try:
  120. os.mkdir(dir_anchor+name_hash)
  121. except FileExistsError:
  122. print("~~~~~~Warning~~~~~~~~~Directory " , dir_anchor+name_hash , " already exists")
  123. try:
  124. os.mkdir(dir_subtitle+name_hash)
  125. except FileExistsError:
  126. print("~~~~~~Warning~~~~~~~~~Directory " , dir_subtitle+name_hash , " already exists")
  127. def hakkaTTS(mp3_path,ch_sentence):
  128. download = False #如果要下載才需要Ture
  129. hakka_100 = import_hakka_100()
  130. word_data,multi_sound = import_data()
  131. if download:
  132. download_mp3(word_data,multi_sound)
  133. download_hakka_100(hakka_100)
  134. ch_word_list = list(itertools.chain(*word_data['華語詞義集'].tolist())) + hakka_100.chinese_clean.tolist()
  135. import_jieba_userdict(ch_word_list=ch_word_list, userDict_path='userDict.txt')
  136. gen_hakka_tts(word_data,multi_sound,hakka_100,ch_sentence,mp3_path)
  137. def file_prepare(name, name_hash,text_content,image_urls,multiLang,lang='zh'):
  138. make_dir(name_hash)
  139. img_num = 1
  140. for imgu in image_urls:
  141. if get_url_type(imgu) =='video/mp4':
  142. r=requests.get(imgu)
  143. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  144. for chunk in r.iter_content(chunk_size=255):
  145. if chunk:
  146. f.write(chunk)
  147. f.close()
  148. else:
  149. im = Image.open(requests.get(imgu, stream=True).raw)
  150. im= im.convert("RGB")
  151. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  152. img_num+=1
  153. #save text
  154. txt_idx=0
  155. for txt in text_content:
  156. text_file = open(dir_text+name_hash+"/"+str(txt_idx)+".txt", "w")
  157. text_file.write(txt)
  158. text_file.close()
  159. txt_idx+=1
  160. print("text file made")
  161. #make mp3
  162. txt_idx = 0
  163. for txt in text_content:
  164. if multiLang==3:
  165. hakkaTTS(dir_sound+name_hash+"/"+str(txt_idx)+".mp3",txt)
  166. else:
  167. if lang!='zh' or multiLang==1:
  168. if lang!='zh':
  169. tts = gTTS(txt)
  170. tts.save(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  171. else:
  172. tts = gTTS(txt,lang='zh-tw')
  173. tts.save(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  174. #speed up
  175. ff = ffmpy.FFmpeg(inputs={dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3": None}
  176. , outputs={dir_sound+name_hash+"/"+str(txt_idx)+".mp3": ["-filter:a", "atempo=1.2"]})
  177. ff.run()
  178. os.remove(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  179. else:
  180. print('use zhtts')
  181. tts = zhtts.TTS()
  182. tts.text2wav(txt,dir_sound+name_hash+"/"+str(txt_idx)+".mp3")
  183. txt_idx+=1
  184. print("mp3 file made")
  185. #make title as image
  186. txt2image_title(name, dir_title+name_hash+".png",lang)
  187. def file_prepare_long(name, name_hash,text_content,image_urls,multiLang,lang='zh'):
  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. #make mp3
  204. text_parser = parser()
  205. txt_idx = 0
  206. for txt in text_content:
  207. rep_list = text_parser.replace_list(txt)
  208. for reptxt in rep_list:
  209. txt = txt.replace(reptxt,'')
  210. if lang!='zh' or multiLang==1:
  211. if lang!='zh':
  212. tts = gTTS(txt)
  213. tts.save(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  214. else:
  215. tts = gTTS(txt,lang='zh-tw')
  216. tts.save(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  217. #speed up
  218. ff = ffmpy.FFmpeg(inputs={dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3": None}
  219. , outputs={dir_sound+name_hash+"/"+str(txt_idx)+".mp3": ["-filter:a", "atempo=1.2"]})
  220. ff.run()
  221. os.remove(dir_sound+name_hash+"/"+str(txt_idx)+"raw.mp3")
  222. else:
  223. print('use zhtts')
  224. tts = zhtts.TTS()
  225. tts.text2wav(txt,dir_sound+name_hash+"/"+str(txt_idx)+".mp3")
  226. txt_idx+=1
  227. print("mp3 file made")
  228. #make title as image
  229. txt2image_title(name, dir_title+name_hash+".png",lang)
  230. def txt2image(content, save_target,lang='zh'):
  231. unicode_text = trim_punctuation(content)
  232. font = ''
  233. if lang=='zh':
  234. font = ImageFont.truetype(font="font/DFT_B7.ttc", size=38)
  235. else :
  236. font = ImageFont.truetype(font="font/arial.ttf", size=38)
  237. text_width, text_height = font.getsize(unicode_text)
  238. canvas = Image.new('RGBA', (700, 500), (255, 0, 0, 0) )
  239. draw = ImageDraw.Draw(canvas)
  240. text= unicode_text
  241. draw.text((5,5), text, (255, 255, 0), font)
  242. canvas.save(save_target, "PNG")
  243. def txt2image_title(content, save_target, lang='zh'):
  244. unicode_text = trim_punctuation(content)
  245. font = ''
  246. if lang=='zh':
  247. font = ImageFont.truetype(font="font/DFT_B7.ttc", size=22)
  248. else :
  249. font = ImageFont.truetype(font="font/arial.ttf", size=22)
  250. text_width, text_height = font.getsize(unicode_text)
  251. canvas = Image.new('RGBA', (510, 500), (255, 0, 0, 0) )
  252. draw = ImageDraw.Draw(canvas)
  253. text= unicode_text
  254. draw.text((5,5), text, (17, 41, 167), font)
  255. canvas.save(save_target, "PNG")
  256. def call_anchor(fileName,avatar):
  257. conn = rpyc.classic.connect("192.168.1.111",18812)
  258. ros = conn.modules.os
  259. rsys = conn.modules.sys
  260. fr=open(dir_sound+fileName+".mp3",'rb')# voice
  261. #warning!!! file my be replaced by other process
  262. fw=conn.builtins.open('/tmp/output.mp3','wb')
  263. while True:
  264. b=fr.read(1024)
  265. if b:
  266. fw.write(b)
  267. else:
  268. break
  269. fr.close()
  270. fw.close()
  271. val=random.randint(1000000,9999999)
  272. ros.chdir('/home/jared/to_video')
  273. ros.system('./p'+str(avatar)+'.sh '+str(val)+' &')
  274. while True:
  275. print('waiting...')
  276. if ros.path.exists('/tmp/results/'+str(val)):
  277. break
  278. time.sleep(5)
  279. print('waiting...')
  280. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  281. fw=open(dir_anchor+fileName+".mp4",'wb')
  282. while True:
  283. b=fr.read(1024)
  284. if b:
  285. fw.write(b)
  286. else:
  287. break
  288. fr.close()
  289. fw.close()
  290. def syllable_count(word):
  291. word = word.lower()
  292. count = 0
  293. vowels = "aeiouy"
  294. if word[0] in vowels:
  295. count += 1
  296. for index in range(1, len(word)):
  297. if word[index] in vowels and word[index - 1] not in vowels:
  298. count += 1
  299. if word.endswith("e"):
  300. count -= 1
  301. if count == 0:
  302. count += 1
  303. return count
  304. def split_sentence(in_str, maxLen):
  305. re.findall(r'[\u4e00-\u9fff]+', in_str)
  306. zh_idx = []
  307. eng_idx= []
  308. for i in range(len(in_str)):
  309. if in_str[i] > u'\u4e00' and in_str[i] < u'\u9fff':
  310. zh_idx.append(i)
  311. else:
  312. eng_idx.append(i)
  313. space_index = [m.start() for m in re.finditer(' ', in_str)]
  314. for idx in space_index:
  315. eng_idx.remove(idx)
  316. eng_range_list = []
  317. for k, g in groupby(enumerate(eng_idx), lambda ix : ix[0] - ix[1]):
  318. eng_range = list(map(itemgetter(1), g))
  319. eng_range_list.append(eng_range)
  320. total_syllable = 0
  321. for i in range(len(eng_range_list)):
  322. total_syllable += (syllable_count(in_str[eng_range_list[i][0]:eng_range_list[i][-1]+1])+0.5)
  323. for i in range(len(zh_idx)):
  324. total_syllable+=1
  325. #final chchchchchc[en][en][en]
  326. #[en] is a vocabulary dict with occurence of image
  327. zh_eng_idx_list = []
  328. i = 0
  329. while i < len(in_str):
  330. if in_str[i]==' ':
  331. i+=1
  332. if i in zh_idx:
  333. zh_eng_idx_list.append(i)
  334. i+=1
  335. if i in eng_idx:
  336. for ls in eng_range_list:
  337. if i in ls:
  338. zh_eng_idx_list.append(ls)
  339. i = ls[-1]+1
  340. break
  341. zh_eng_dict_list = [{'content':'','time_ratio':0}]
  342. idx = 0
  343. current_len = 0
  344. sen_idx = 0
  345. while idx < len(zh_eng_idx_list):
  346. str_from_idx = ''
  347. sylla_cnt = 1
  348. if type(zh_eng_idx_list[idx])==type([]):
  349. str_from_idx = in_str[zh_eng_idx_list[idx][0]:zh_eng_idx_list[idx][-1]+1]+' '
  350. sylla_cnt = syllable_count(str_from_idx)
  351. else:
  352. str_from_idx = in_str[zh_eng_idx_list[idx]]
  353. if len(zh_eng_dict_list[sen_idx]['content'])+sylla_cnt>=maxLen:
  354. zh_eng_dict_list[sen_idx]['time_ratio'] = current_len/total_syllable
  355. zh_eng_dict_list.append({'content':'','time_ratio':0})
  356. sen_idx+=1
  357. current_len = 0
  358. else:
  359. current_len += sylla_cnt
  360. zh_eng_dict_list[sen_idx]['content'] += str_from_idx
  361. idx+=1
  362. total_ratio = 0
  363. for obj in zh_eng_dict_list:
  364. total_ratio+=obj['time_ratio']
  365. zh_eng_dict_list[-1]['time_ratio'] = 1-total_ratio
  366. return zh_eng_dict_list
  367. def parse_script(file_path,gt_list):
  368. with open(file_path, 'r',encoding="utf-8") as f:
  369. raw_lines = [line.strip() for line in f]
  370. lines = adjustSub_by_text_similarity(gt_list,raw_lines)
  371. text_parser = parser()
  372. #make dict
  373. dict_list = []
  374. for idx in range(len(lines)):
  375. script={}
  376. rep_ls = text_parser.replace_list(lines[idx])
  377. line_content = lines[idx]
  378. for reptxt in rep_ls:
  379. line_content = line_content.replace(reptxt,'')
  380. if len(rep_ls)!=0:
  381. script['image_idx'] = int(rep_ls[0].replace('{','').replace('}',''))
  382. script['content'] = line_content
  383. time_raw = raw_lines[idx * 4 +1 ].split(' --> ')
  384. start = time_raw[0].split(':')
  385. stop = time_raw[1].split(':')
  386. script['start'] = float(start[0])*3600 + float(start[1])*60 + float(start[2].replace(',','.'))
  387. script['stop'] = float(stop[0])*3600 + float(stop[1])*60 + float(stop[2].replace(',','.'))
  388. dict_list.append(script)
  389. #merge duplicated sentences
  390. skip_list = []
  391. script_not_dup_list = []
  392. for idx in range(len(dict_list)):
  393. if idx not in skip_list:
  394. dup_list = []
  395. found = 0
  396. for idx_inner in range(len(dict_list)):
  397. if dict_list[idx_inner]['content'] == dict_list[idx]['content'] and idx <= idx_inner:
  398. dup_list.append(idx_inner)
  399. skip_list.append(idx_inner)
  400. found += 1
  401. if found != 0 and dict_list[idx_inner]['content']!=dict_list[idx]['content'] and idx <= idx_inner:
  402. found = 0
  403. break
  404. for dup_idx in dup_list:
  405. if dup_idx == min(dup_list):
  406. dict_list[dup_idx]['type'] = 'lead_sentence'
  407. else:
  408. dict_list[dup_idx]['type'] = 'duplicated'
  409. dict_list[dup_list[0]]['stop'] = dict_list[dup_list[-1]]['stop']
  410. if dict_list[idx]['type'] == 'lead_sentence':
  411. script_not_dup_list.append(dict_list[idx])
  412. new_idx = 0
  413. splitted_dict = []
  414. for dic in script_not_dup_list:
  415. dic_idx = 0
  416. accumulated_duration = 0
  417. duration = dic['stop']-dic['start']
  418. for sub_dic in split_sentence(dic['content'],13):
  419. new_dic = {}
  420. new_dic['index'] = new_idx
  421. if 'image_idx' in dic:
  422. new_dic['image_obj'] = {'start':dic['start'],'idx':dic['image_idx']}
  423. new_idx+=1
  424. ind_duration = duration * sub_dic['time_ratio']
  425. new_dic['start'] = dic['start'] + accumulated_duration
  426. accumulated_duration += ind_duration
  427. new_dic['content'] = sub_dic['content']
  428. new_dic['duration'] = ind_duration*0.7
  429. splitted_dict.append(new_dic)
  430. return splitted_dict
  431. def adjustSub_by_text_similarity(gts_in,gens_raw):
  432. #call by value only
  433. gts = gts_in[:]
  434. text_parser = parser()
  435. for i in range(len(gts)):
  436. rep_ls = text_parser.replace_list(gts[i])
  437. for reptxt in rep_ls:
  438. gts[i] = gts[i].replace(reptxt,'')
  439. gens = []
  440. for idx in range(int((len(gens_raw)+1)/4)):
  441. gens.append(gens_raw[idx*4+2])
  442. combine2 = [''.join([i,j]) for i,j in zip(gts, gts[1:])]
  443. combine3 = [''.join([i,j,k]) for i,j,k in zip(gts, gts[1:], gts[2:])]
  444. alls = gts #+ combine2 + combine3
  445. adjusted = [None]*len(gens)
  446. duplicated_list = []
  447. for idx in range(len(gens)):
  448. match_text = difflib.get_close_matches(gens[idx], alls, cutoff=0.1)
  449. if len(match_text) != 0:
  450. if match_text[0] not in duplicated_list:
  451. adjusted[idx] = match_text[0]
  452. duplicated_list.append(match_text[0])
  453. else:
  454. if match_text[0] == adjusted[idx-1]:
  455. adjusted[idx] = match_text[0]
  456. else:
  457. found = 0
  458. for mt in match_text:
  459. if mt not in duplicated_list:
  460. adjusted[idx] = mt
  461. found += 1
  462. break
  463. if found ==0:
  464. adjusted[idx] = ' '
  465. else :
  466. adjusted[idx] = ' '
  467. combine2_tag = [''.join([i,j]) for i,j in zip(gts_in, gts_in[1:])]
  468. combine3_tag = [''.join([i,j,k]) for i,j,k in zip(gts_in, gts_in[1:], gts_in[2:])]
  469. alls_tag = gts_in #+ combine2_tag + combine3_tag
  470. for idx in range(len(adjusted)):
  471. match_text = difflib.get_close_matches(adjusted[idx], alls_tag, cutoff=0.1)
  472. adjusted[idx] = match_text[0]
  473. return adjusted
  474. def trim_punctuation(s):
  475. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
  476. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  477. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u" " ,s)
  478. return res
  479. def splitter(s):
  480. for sent in re.findall(u'[^!?,。\!\?]+[!? 。\!\?]?', s, flags=re.U):
  481. yield sent
  482. def split_by_pun(s):
  483. res = list(splitter(s))
  484. return res
  485. def generate_subtitle_image_from_dict(name_hash, sub_dict):
  486. for script in sub_dict:
  487. sv_path = dir_subtitle + name_hash + '/' + str(script['index'])+'.png'
  488. sub = script['content']
  489. txt2image(sub,sv_path)
  490. def generate_subtitle_image(name_hash,text_content):
  491. img_list = [None]*len(text_content)
  492. for idx in range(len(text_content)):
  493. img_list[idx]=[]
  494. senList = split_by_pun(text_content[idx])
  495. for inner_idx in range(len(senList)):
  496. sv_path = dir_subtitle + name_hash +'/'+str(idx)+ str(inner_idx) +'.png'
  497. sub = senList[inner_idx]
  498. txt2image(sub,sv_path)
  499. clean_content = trim_punctuation(sub)
  500. re.findall(r'[\u4e00-\u9fff]+', clean_content)
  501. zh_idx = []
  502. eng_idx= []
  503. for i in range(len(clean_content)):
  504. if clean_content[i] > u'\u4e00' and clean_content[i] < u'\u9fff':
  505. zh_idx.append(i)
  506. else:
  507. eng_idx.append(i)
  508. space_index = [m.start() for m in re.finditer(' ', clean_content)]
  509. for s_idx in space_index:
  510. eng_idx.remove(s_idx)
  511. eng_range_list = []
  512. for k, g in groupby(enumerate(eng_idx), lambda ix : ix[0] - ix[1]):
  513. eng_range = list(map(itemgetter(1), g))
  514. eng_range_list.append(eng_range)
  515. total_syllable = 0
  516. for i in range(len(eng_range_list)):
  517. total_syllable += (syllable_count(clean_content[eng_range_list[i][0]:eng_range_list[i][-1]+1])+0.5)
  518. for i in range(len(zh_idx)):
  519. total_syllable+=1
  520. img_list[idx]+=[{"count":total_syllable,"path":sv_path}]
  521. return img_list
  522. def generate_subtitle_image_ENG(name_hash,text_content):
  523. img_list = [None]*len(text_content)
  524. for idx in range(len(text_content)):
  525. sv_path = dir_subtitle + name_hash +'/'+str(idx)+'.png'
  526. sub = text_content[idx]
  527. txt2image(sub, sv_path,lang='eng')
  528. img_list[idx] = sv_path
  529. return img_list
  530. def video_writer_init(path):
  531. w = openshot.FFmpegWriter(path)
  532. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  533. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  534. openshot.Fraction(1, 1), False, False, 3000000)
  535. return w
  536. def video_gen(name_hash,name,text_content, image_urls,multiLang,avatar):
  537. file_prepare_long(name, name_hash, text_content,image_urls,multiLang)
  538. for fname in range(len(text_content)):
  539. call_anchor(name_hash+"/"+str(fname),avatar)
  540. print('called............................................')
  541. ck=cKey(0,254,0,270)
  542. ck_anchor=cKey(0,255,1,320)
  543. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  544. t.Open()
  545. main_timer = 0
  546. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP_4.mp4")
  547. LOGO_OP.Open() # Open the reader
  548. head_duration = LOGO_OP.info.duration
  549. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=head_duration
  550. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  551. t.AddClip(LOGO_OP_clip)
  552. bg_head = openshot.FFmpegReader(dir_video+"complete_head_aispokesgirl.mp4")
  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 += head_duration
  557. bg_head.Close()
  558. LOGO_OP.Close()
  559. anchor = openshot.FFmpegReader(dir_anchor+name_hash+"/0.mp4")
  560. anchor.Open()
  561. #anchor_clip = video_photo_clip(vid=anchor,layer=4,scale_x=0.65,scale_y=0.65,
  562. # location_x=0.35,location_y=0.25,position=main_timer, end=anchor.info.duration,ck=ck_anchor,audio=False)
  563. #t.AddClip(anchor_clip)
  564. speech = openshot.FFmpegReader(dir_sound+name_hash+"/0.mp3")
  565. speech.Open()
  566. speech_clip = openshot.Clip(speech)
  567. speech_clip.Position(main_timer)
  568. speech_clip.End(anchor.info.duration)
  569. t.AddClip(speech_clip)
  570. main_timer += anchor.info.duration
  571. anchor.Close()
  572. speech.Close()
  573. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  574. LOGO_ED.Open()
  575. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration
  576. ,location_x=0.005,location_y=-0.031, scale_x=0.8,scale_y=0.6825)
  577. t.AddClip(LOGO_ED_clip)
  578. main_timer += LOGO_ED.info.duration
  579. LOGO_ED.Close()
  580. bg = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  581. bg.Open()
  582. bg_times = math.floor(main_timer/bg.info.duration)
  583. left_time = (main_timer) % bg.info.duration
  584. bg_clip_list = [None] * bg_times
  585. bg_list = [None] * bg_times
  586. bg.Close()
  587. bg_timer = head_duration
  588. for idx in range(bg_times):
  589. bg_list[idx] = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  590. bg_list[idx].Open()
  591. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer,end=bg_list[idx].info.duration,ck=ck)
  592. t.AddClip(bg_clip_list[idx])
  593. bg_timer += bg_list[idx].info.duration
  594. bg_list[idx].Close()
  595. bg_left = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  596. bg_left.Open()
  597. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  598. t.AddClip(bg_left_clip)
  599. bg_left.Close()
  600. title = openshot.QtImageReader(dir_title+name_hash+".png")
  601. title.Open() # Open the reader
  602. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  603. t.AddClip(title_clip)
  604. w = video_writer_init(tmp_video_dir+name_hash+"raw.mp4")
  605. w.Open()
  606. frames = int(t.info.fps)*int(main_timer)
  607. for n in range(frames):
  608. f=t.GetFrame(n)
  609. w.WriteFrame(f)
  610. t.Close()
  611. w.Close()
  612. print(name+"RAW DONE : www.choozmo.com:8168/"+tmp_video_dir+name_hash+"raw.mp4")
  613. #start adding sub
  614. #add sub
  615. Ctr_Autosub.init()
  616. 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)
  617. sub_dict = parse_script(tmp_video_dir+name_hash+"script.txt",split_by_pun(text_content[0]))
  618. for subd in sub_dict:
  619. print(subd)
  620. generate_subtitle_image_from_dict(name_hash, sub_dict)
  621. #sv_path = dir_subtitle + name_hash + '/' + str(script['index'])+'.png'
  622. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  623. t.Open()
  624. raw = openshot.FFmpegReader(tmp_video_dir+name_hash+"raw.mp4")
  625. raw.Open()
  626. raw_clip = video_photo_clip(vid=raw,layer=2,position=0, end=raw.info.duration)
  627. t.AddClip(raw_clip)
  628. sub_img_list = [None] * len(sub_dict)
  629. sub_clip_list = [None] * len(sub_dict)
  630. for sub_obj in sub_dict:
  631. idx = int(sub_obj['index'])
  632. sub_img_list[idx] = openshot.QtImageReader(dir_subtitle + name_hash + '/' + str(idx)+'.png')
  633. sub_img_list[idx].Open()
  634. #if sub_obj['duration']>3:
  635. # print('warning')
  636. #print('start:',sub_obj['start'],', duration :', sub_obj['duration'],' content',sub_obj['content'],'idx:',sub_obj['index'])
  637. 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']))
  638. t.AddClip(sub_clip_list[idx])
  639. sub_img_list[idx].Close()
  640. tp = parser()
  641. img_dict_ls = tp.image_clip_info(sub_dict)
  642. img_clip_list = [None]*len(listdir(dir_photo+name_hash))
  643. img_list = [None]*len(img_clip_list)
  644. img_file_ls = listdir(dir_photo+name_hash)
  645. for img_idx in range(len(img_file_ls)):
  646. img_list[img_idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+img_file_ls[img_idx])
  647. img_list[img_idx].Open()
  648. img_clip_list[img_idx] = video_photo_clip(vid=img_list[img_idx],layer=3
  649. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=img_dict_ls[img_idx]['start'],end=img_dict_ls[img_idx]['duration'],audio=False)
  650. t.AddClip(img_clip_list[img_idx])
  651. img_list[img_idx].Close()
  652. anchor = openshot.FFmpegReader(dir_anchor+name_hash+"/0.mp4")
  653. anchor.Open()
  654. anchor_clip = video_photo_clip(vid=anchor,layer=4,scale_x=0.65,scale_y=0.65,
  655. location_x=0.35,location_y=0.25,position=head_duration, end=anchor.info.duration,ck=ck_anchor,audio=False)
  656. t.AddClip(anchor_clip)
  657. w = video_writer_init(tmp_video_dir+name_hash+".mp4")
  658. w.Open()
  659. frames = int(t.info.fps)*int(main_timer)
  660. for n in range(frames):
  661. f=t.GetFrame(n)
  662. w.WriteFrame(f)
  663. t.Close()
  664. w.Close()
  665. os.remove(tmp_video_dir+name_hash+"raw.mp4")
  666. os.remove(tmp_video_dir+name_hash+"script.txt")
  667. print(name+"ALL DONE : www.choozmo.com:8168/"+video_sub_folder+name_hash+"raw.mp4")
  668. def anchor_video_v2(name_hash,name,text_content, image_urls,multiLang,avatar,freeTrial):
  669. print(name)
  670. print(text_content)
  671. print(os.getcwd())
  672. print('sub image made')
  673. print(multiLang)
  674. file_prepare(name, name_hash, text_content,image_urls,multiLang)
  675. sub_list=generate_subtitle_image(name_hash,text_content)
  676. for fname in range(len(text_content)):
  677. call_anchor(name_hash+"/"+str(fname),avatar)
  678. print('step finish')
  679. print('called............................................')
  680. ck=cKey(0,254,0,270)
  681. ck_anchor=cKey(0,255,1,320)
  682. duration = 0
  683. #average layer level is 3
  684. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  685. t.Open()
  686. main_timer = 0
  687. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP_4.mp4")
  688. LOGO_OP.Open() # Open the reader
  689. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  690. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  691. t.AddClip(LOGO_OP_clip)
  692. bg_head = openshot.FFmpegReader(dir_video+"complete_head_aispokesgirl.mp4")
  693. bg_head.Open()
  694. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  695. t.AddClip(bg_head_clip)
  696. main_timer += LOGO_OP.info.duration
  697. head_duration = LOGO_OP.info.duration
  698. bg_head.Close()
  699. LOGO_OP.Close()
  700. clip_duration=0
  701. photo_clip_list = [None]*len(text_content)
  702. img_list = [None]*len(text_content)
  703. anchor_clip_list = [None] * len(text_content)
  704. anchor_list = [None] * len(text_content)
  705. audio_clip_list = [None] * len(text_content)
  706. audio_list = [None] * len(text_content)
  707. sub_clip_list = [None] * len(text_content)
  708. sub_img_list = [None] * len(text_content)
  709. idx = 0
  710. for p in listdir(dir_photo+name_hash):
  711. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  712. clip_duration = anchor_list[idx].info.duration
  713. anchor_list[idx].Open()
  714. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  715. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  716. print('avatar is ', avatar)
  717. t.AddClip(anchor_clip_list[idx])
  718. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  719. img_list[idx].Open()
  720. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  721. ,scale_x=0.8,scale_y=0.6825,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  722. t.AddClip(photo_clip_list[idx])
  723. img_list[idx].Close()
  724. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  725. audio_list[idx].Open()
  726. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  727. audio_clip_list[idx].Position(main_timer)
  728. audio_clip_list[idx].End(clip_duration)
  729. t.AddClip(audio_clip_list[idx])
  730. img_list[idx].Close()
  731. anchor_list[idx].Close()
  732. audio_list[idx].Close()
  733. sub_img_list[idx] = [None] * len(sub_list[idx])
  734. sub_clip_list[idx] = [None] * len(sub_list[idx])
  735. sub_timer = 0
  736. for sub_idx in range(len(sub_list[idx])):
  737. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  738. sub_img_list[idx][sub_idx].Open()
  739. sub_duration = 0.205*sub_list[idx][sub_idx]['count']
  740. 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)
  741. t.AddClip(sub_clip_list[idx][sub_idx])
  742. sub_img_list[idx][sub_idx].Close()
  743. sub_timer += sub_duration
  744. print(sub_list[idx][sub_idx]['path'])
  745. main_timer += clip_duration
  746. idx+=1
  747. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  748. LOGO_ED.Open()
  749. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration+2
  750. ,location_x=0.005,location_y=-0.031
  751. ,scale_x=0.8,scale_y=0.6825)
  752. t.AddClip(LOGO_ED_clip)
  753. ED_duration = LOGO_ED.info.duration
  754. LOGO_ED.Close()
  755. bg = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  756. bg.Open()
  757. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  758. left_time = (main_timer+ED_duration) % bg.info.duration
  759. bg_clip_list = [None] * bg_times
  760. bg_list = [None] * bg_times
  761. bg.Close()
  762. bg_timer = head_duration
  763. for idx in range(bg_times):
  764. bg_list[idx] = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  765. bg_list[idx].Open()
  766. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  767. ,end=bg_list[idx].info.duration,ck=ck)
  768. t.AddClip(bg_clip_list[idx])
  769. bg_timer += bg_list[idx].info.duration
  770. bg_list[idx].Close()
  771. bg_left = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  772. bg_left.Open()
  773. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  774. t.AddClip(bg_left_clip)
  775. bg_left.Close()
  776. title = openshot.QtImageReader(dir_title+name_hash+".png")
  777. title.Open() # Open the reader
  778. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  779. t.AddClip(title_clip)
  780. if freeTrial==1:
  781. print("THIS IS TRIAL")
  782. wm = openshot.QtImageReader(dir_video+"freeTrialWatermark.png")
  783. wm.Open()
  784. wm_clip = video_photo_clip(wm,layer=6,position=0,end=int(head_duration+main_timer+ED_duration))
  785. t.AddClip(wm_clip)
  786. else:
  787. print("THIS IS NOT TRIAL")
  788. print(freeTrial)
  789. ####start building
  790. w = openshot.FFmpegWriter(tmp_video_dir+name_hash+".mp4")
  791. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  792. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  793. openshot.Fraction(1, 1), False, False, 3000000)
  794. w.Open()
  795. #may change duration into t.info.duration
  796. frames = int(t.info.fps)*int(head_duration+main_timer+ED_duration)
  797. for n in range(frames):
  798. f=t.GetFrame(n)
  799. w.WriteFrame(f)
  800. #notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  801. t.Close()
  802. w.Close()
  803. print("video at : www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  804. def anchor_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar,freeTrial):
  805. file_prepare(name, name_hash, text_content,image_urls,1,'eng')
  806. sub_list=generate_subtitle_image_ENG(name_hash,sub_titles)
  807. for fname in range(len(text_content)):
  808. call_anchor(name_hash+"/"+str(fname),avatar)
  809. print('step finish')
  810. print('called............................................')
  811. ck=cKey(0,254,0,270)
  812. ck_anchor=cKey(0,255,1,320)
  813. duration = 0
  814. #average layer level is 3
  815. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  816. t.Open()
  817. main_timer = 0
  818. #add logo
  819. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP_4.mp4")
  820. LOGO_OP.Open() # Open the reader
  821. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  822. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  823. t.AddClip(LOGO_OP_clip)
  824. #add background video (head is different)
  825. bg_head = openshot.FFmpegReader(dir_video+"complete_head_aispokesgirl.mp4")
  826. bg_head.Open()
  827. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  828. t.AddClip(bg_head_clip)
  829. main_timer += LOGO_OP.info.duration
  830. head_duration = LOGO_OP.info.duration
  831. bg_head.Close()
  832. LOGO_OP.Close()
  833. #prepare empty list
  834. clip_duration=0
  835. photo_clip_list = [None]*len(text_content)
  836. img_list = [None]*len(text_content)
  837. anchor_clip_list = [None] * len(text_content)
  838. anchor_list = [None] * len(text_content)
  839. audio_clip_list = [None] * len(text_content)
  840. audio_list = [None] * len(text_content)
  841. sub_clip_list = [None] * len(text_content)
  842. #openshot image holder
  843. sub_img_list = [None] * len(text_content)
  844. idx = 0
  845. for p in listdir(dir_photo+name_hash):
  846. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  847. clip_duration = anchor_list[idx].info.duration
  848. anchor_list[idx].Open()
  849. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  850. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  851. t.AddClip(anchor_clip_list[idx])
  852. #insert image
  853. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  854. img_list[idx].Open()
  855. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  856. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  857. t.AddClip(photo_clip_list[idx])
  858. img_list[idx].Close()
  859. #insert audio (speech)
  860. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  861. audio_list[idx].Open()
  862. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  863. audio_clip_list[idx].Position(main_timer)
  864. audio_clip_list[idx].End(clip_duration)
  865. t.AddClip(audio_clip_list[idx])
  866. #insert subtitle
  867. sub_img_list[idx] = openshot.QtImageReader(sub_list[idx])
  868. sub_img_list[idx].Open()
  869. 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)
  870. t.AddClip(sub_clip_list[idx])
  871. img_list[idx].Close()
  872. anchor_list[idx].Close()
  873. audio_list[idx].Close()
  874. sub_img_list[idx].Close()
  875. main_timer += clip_duration
  876. idx+=1
  877. LOGO_ED = openshot.FFmpegReader(dir_video+"ED_ENG.mp4")
  878. LOGO_ED.Open()
  879. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration+2
  880. ,location_x=0.005,location_y=-0.031
  881. ,scale_x=0.8,scale_y=0.6825)
  882. t.AddClip(LOGO_ED_clip)
  883. ED_duration = LOGO_ED.info.duration
  884. LOGO_ED.Close()
  885. bg = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  886. bg.Open()
  887. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  888. left_time = (main_timer+ED_duration) % bg.info.duration
  889. bg_clip_list = [None] * bg_times
  890. bg_list = [None] * bg_times
  891. bg.Close()
  892. bg_timer = head_duration
  893. for idx in range(bg_times):
  894. bg_list[idx] = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  895. bg_list[idx].Open()
  896. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  897. ,end=bg_list[idx].info.duration,ck=ck)
  898. t.AddClip(bg_clip_list[idx])
  899. bg_timer += bg_list[idx].info.duration
  900. bg_list[idx].Close()
  901. bg_left = openshot.FFmpegReader(dir_video+"complete_double_aispokesgirl.mp4")
  902. bg_left.Open()
  903. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  904. t.AddClip(bg_left_clip)
  905. bg_left.Close()
  906. title = openshot.QtImageReader(dir_title+name_hash+".png")
  907. title.Open() # Open the reader
  908. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  909. t.AddClip(title_clip)
  910. if freeTrial==1:
  911. wm = openshot.QtImageReader(dir_video+"freeTrialWatermark.png")
  912. wm.Open()
  913. wm_clip = video_photo_clip(wm,layer=6,position=0,end=int(head_duration+main_timer+ED_duration))
  914. t.AddClip(wm_clip)
  915. print("THIS IS TRIAL")
  916. else:
  917. print("THIS IS NOT TRIAL")
  918. print(freeTrial)
  919. ####start building
  920. w = openshot.FFmpegWriter(tmp_video_dir+name_hash+".mp4")
  921. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  922. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  923. openshot.Fraction(1, 1), False, False, 3000000)
  924. w.Open()
  925. #may change duration into t.info.duration
  926. frames = int(t.info.fps)*int(head_duration+main_timer+ED_duration)
  927. for n in range(frames):
  928. f=t.GetFrame(n)
  929. w.WriteFrame(f)
  930. #notify_group(name+"(ENG)的影片已經產生完成囉! www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  931. t.Close()
  932. w.Close()
  933. print("video at : www.choozmo.com:8168/"+video_sub_folder+name_hash+".mp4")
  934. #line notifs
  935. import pyttsx3
  936. def make_speech(text):
  937. engine = pyttsx3.init()
  938. #voices = engine.getProperty('voices')
  939. engine.setProperty('voice', 'Mandarin')
  940. engine.save_to_file(text, '/app/speech.mp3')
  941. engine.runAndWait()
  942. class video_service(rpyc.Service):
  943. def exposed_call_video(self,name_hash,name,text_content, image_urls,multiLang,avatar,freeTrial):
  944. print('ML:'+str(multiLang))
  945. anchor_video_v2(name_hash,name,text_content, image_urls,multiLang,avatar,freeTrial)
  946. def exposed_call_video_eng(self,name_hash,name,text_content, image_urls,sub_titles,avatar,freeTrial):
  947. anchor_video_eng(name_hash,name,text_content, image_urls,sub_titles,avatar,freeTrial)
  948. def exposed_call_video_gen(self,name_hash,name,text_content, image_urls,multiLang,avatar):
  949. print('ML:'+str(multiLang))#this is long video version,
  950. video_gen(name_hash,name,text_content, image_urls,multiLang,avatar)
  951. def exposed_make_speech(self,text):
  952. make_speech(text)
  953. from rpyc.utils.server import ThreadedServer
  954. t = ThreadedServer(video_service, port=8858)
  955. print('service started')
  956. t.start()