openshot_video_generator.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. from os import listdir
  2. from os.path import isfile, isdir, join
  3. import threading
  4. import zhtts
  5. import os
  6. import urllib
  7. from typing import List
  8. import requests
  9. from pydantic import BaseModel
  10. from bs4 import BeautifulSoup
  11. from PIL import Image,ImageDraw,ImageFont
  12. import pyttsx3
  13. import rpyc
  14. import random
  15. import re
  16. import time
  17. import math
  18. import dataset
  19. from datetime import datetime
  20. dir_sound = 'mp3_track/'
  21. dir_photo = 'photo/'
  22. dir_text = 'text_file/'
  23. dir_video = 'video_material/'
  24. dir_title = 'title/'
  25. dir_subtitle = 'subtitle/'
  26. dir_anchor = 'anchor_raw/'
  27. tmp_video_dir = 'tmp_video/'
  28. dir_list = [dir_sound,dir_photo,dir_text,dir_video,dir_title,dir_subtitle,dir_anchor,tmp_video_dir]
  29. def notify_group(msg):
  30. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX']
  31. for gid in glist:
  32. headers = {
  33. "Authorization": "Bearer " + gid,
  34. "Content-Type": "application/x-www-form-urlencoded"
  35. }
  36. params = {"message": msg}
  37. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  38. def cKey(r,g,b,fuzz):
  39. col=openshot.Color()
  40. col.red=openshot.Keyframe(r)
  41. col.green=openshot.Keyframe(g)
  42. col.blue=openshot.Keyframe(b)
  43. return openshot.ChromaKey(col, openshot.Keyframe(fuzz))
  44. def video_photo_clip(vid=None,layer=None, position=None, end=None
  45. ,scale_x=1,scale_y=1,location_x=0,location_y=0,ck=None,audio=True):
  46. clip = openshot.Clip(vid)
  47. clip.Layer(layer)
  48. clip.Position(position)
  49. clip.End(end)
  50. clip.scale_x=openshot.Keyframe(scale_x)
  51. clip.scale_y=openshot.Keyframe(scale_y)
  52. clip.location_x=openshot.Keyframe(location_x)
  53. clip.location_y=openshot.Keyframe(location_y)
  54. if ck!=None:
  55. clip.AddEffect(ck)
  56. if audio==True:
  57. clip.has_audio=openshot.Keyframe(1)
  58. else:
  59. clip.has_audio=openshot.Keyframe(0)
  60. return clip
  61. def myunichchar(unicode_char):
  62. mb_string = unicode_char.encode('big5')
  63. try:
  64. unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
  65. except NameError:
  66. unicode_char = chr(mb_string[0] << 8 | mb_string[1])
  67. return unicode_char
  68. def file_prepare(name, name_hash,text_content,image_urls):
  69. #save image
  70. try:
  71. os.mkdir(dir_photo+name_hash)
  72. except FileExistsError:
  73. print("Directory " , dir_photo+name_hash , " already exists")
  74. img_num = 1
  75. for imgu in image_urls:
  76. im = Image.open(requests.get(imgu, stream=True).raw)
  77. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  78. img_num+=1
  79. #save text
  80. text_file = open(dir_text+name_hash+".txt", "w")
  81. text_file.write(text_content)
  82. text_file.close()
  83. print("text file made")
  84. #make mp3
  85. tts = zhtts.TTS()
  86. tts.text2wav(text_content,dir_sound+name_hash+".mp3")
  87. print("mp3 file made")
  88. #make title as image
  89. txt2image(name, dir_title+name_hash+".png")
  90. def get_url_type(url):
  91. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  92. r = urllib.request.urlopen(req)
  93. contentType = r.getheader('Content-Type')
  94. return contentType
  95. def make_dir(name_hash):
  96. for direct in dir_list:
  97. if not os.path.isdir(direct):
  98. os.mkdir(direct)
  99. try:
  100. os.mkdir(dir_photo+name_hash)
  101. except FileExistsError:
  102. print("~~~~~~Warning~~~~~~~~~Directory " , dir_photo+name_hash , " already exists")
  103. try:
  104. os.mkdir(dir_text+name_hash)
  105. except FileExistsError:
  106. print("~~~~~~Warning~~~~~~~~~Directory " , dir_text+name_hash , " already exists")
  107. try:
  108. os.mkdir(dir_sound+name_hash)
  109. except FileExistsError:
  110. print("~~~~~~Warning~~~~~~~~~Directory " , dir_sound+name_hash , " already exists")
  111. try:
  112. os.mkdir(dir_video+name_hash)
  113. except FileExistsError:
  114. print("~~~~~~Warning~~~~~~~~~Directory " , dir_video+name_hash , " already exists")
  115. try:
  116. os.mkdir(dir_anchor+name_hash)
  117. except FileExistsError:
  118. print("~~~~~~Warning~~~~~~~~~Directory " , dir_anchor+name_hash , " already exists")
  119. try:
  120. os.mkdir(dir_subtitle+name_hash)
  121. except FileExistsError:
  122. print("~~~~~~Warning~~~~~~~~~Directory " , dir_subtitle+name_hash , " already exists")
  123. def file_prepare_v2(name, name_hash,text_content,image_urls):
  124. make_dir(name_hash)
  125. img_num = 1
  126. for imgu in image_urls:
  127. if get_url_type(imgu) =='video/mp4':
  128. r=requests.get(imgu)
  129. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  130. for chunk in r.iter_content(chunk_size=255):
  131. if chunk:
  132. f.write(chunk)
  133. f.close()
  134. else:
  135. im = Image.open(requests.get(imgu, stream=True).raw)
  136. im= im.convert("RGB")
  137. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  138. img_num+=1
  139. #save text
  140. txt_idx=0
  141. for txt in text_content:
  142. text_file = open(dir_text+name_hash+"/"+str(txt_idx)+".txt", "w")
  143. text_file.write(txt)
  144. text_file.close()
  145. txt_idx+=1
  146. print("text file made")
  147. #make mp3
  148. language = 'zh-tw'
  149. txt_idx = 0
  150. for txt in text_content:
  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")
  157. def txt2image(content, save_target):
  158. unicode_text = trim_punctuation(content)
  159. font = ImageFont.truetype(font="font/DFT_B7.ttc", size=38)
  160. text_width, text_height = font.getsize(unicode_text)
  161. canvas = Image.new('RGBA', (700, 500), (255, 0, 0, 0) )
  162. draw = ImageDraw.Draw(canvas)
  163. text= unicode_text
  164. draw.text((5,5), text, (255, 255, 0), font)
  165. canvas.save(save_target, "PNG")
  166. def txt2image_title(content, save_target):
  167. unicode_text = trim_punctuation(content)
  168. font = ImageFont.truetype(font="font/DFT_B7.ttc", size=28)
  169. text_width, text_height = font.getsize(unicode_text)
  170. canvas = Image.new('RGBA', (510, 500), (255, 0, 0, 0) )
  171. draw = ImageDraw.Draw(canvas)
  172. text= unicode_text
  173. draw.text((5,5), text, (17, 41, 167), font)
  174. canvas.save(save_target, "PNG")
  175. def call_anchor(fileName,avatar):
  176. conn = rpyc.classic.connect("192.168.1.105",18812)
  177. ros = conn.modules.os
  178. rsys = conn.modules.sys
  179. fr=open(dir_sound+fileName+".mp3",'rb')# voice
  180. #warning!!! file my be replaced by other process
  181. fw=conn.builtins.open('/tmp/output.mp3','wb')
  182. while True:
  183. b=fr.read(1024)
  184. if b:
  185. fw.write(b)
  186. else:
  187. break
  188. fr.close()
  189. fw.close()
  190. val=random.randint(1000000,9999999)
  191. ros.chdir('/home/jared/to_video')
  192. ros.system('./p'+str(avatar)+'.sh '+str(val)+' &')
  193. while True:
  194. print('waiting...')
  195. if ros.path.exists('/tmp/results/'+str(val)):
  196. break
  197. time.sleep(5)
  198. print('waiting...')
  199. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  200. fw=open(dir_anchor+fileName+".mp4",'wb')#peggy1_1
  201. while True:
  202. b=fr.read(1024)
  203. if b:
  204. fw.write(b)
  205. else:
  206. break
  207. fr.close()
  208. fw.close()
  209. def trim_punctuation(s):
  210. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
  211. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  212. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u"" ,s)
  213. return res
  214. def splitter(s):
  215. for sent in re.findall(u'[^!?,。\!\?]+[!?。\!\?]?', s, flags=re.U):
  216. yield sent
  217. def split_by_pun(s):
  218. res = list(splitter(s))
  219. return res
  220. def generate_subtitle_image(name_hash,text_content):
  221. img_list = [None]*len(text_content)
  222. for idx in range(len(text_content)):
  223. img_list[idx]=[]
  224. senList = split_by_pun(text_content[idx])
  225. for inner_idx in range(len(senList)):
  226. sv_path = dir_subtitle + name_hash +'/'+str(idx)+ str(inner_idx) +'.png'
  227. sub = senList[inner_idx]
  228. txt2image(sub,sv_path)
  229. img_list[idx]+=[{"count":len(sub),"path":sv_path}]
  230. return img_list
  231. async def sendProgress(progress,client_id):
  232. ws = create_connection("ws://www.choozmo.com:8888/progress/"+client_id)
  233. ws.send(str(progress))
  234. ws.close()
  235. def anchor_video_v2(name_hash,name,text_content, image_urls,avatar,client_id):
  236. print('sub image made')
  237. file_prepare_v2(name, name_hash, text_content,image_urls)
  238. sub_list=generate_subtitle_image(name_hash,text_content)
  239. progress_per_video = int(40/len(text_content))
  240. for fname in range(len(text_content)):
  241. call_anchor(name_hash+"/"+str(fname),avatar)
  242. print('step finish')
  243. print('called............................................')
  244. ck=cKey(0,254,0,270)
  245. ck_anchor=cKey(0,255,1,320)
  246. duration = 0
  247. #average layer level is 3
  248. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  249. t.Open()
  250. main_timer = 0
  251. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP.mp4")
  252. LOGO_OP.Open() # Open the reader
  253. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  254. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  255. t.AddClip(LOGO_OP_clip)
  256. bg_head = openshot.FFmpegReader(dir_video+"bg_head.avi")
  257. bg_head.Open()
  258. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  259. t.AddClip(bg_head_clip)
  260. main_timer += LOGO_OP.info.duration
  261. head_duration = LOGO_OP.info.duration
  262. bg_head.Close()
  263. LOGO_OP.Close()
  264. progress += 10
  265. clip_duration=0
  266. photo_clip_list = [None]*len(text_content)
  267. img_list = [None]*len(text_content)
  268. anchor_clip_list = [None] * len(text_content)
  269. anchor_list = [None] * len(text_content)
  270. audio_clip_list = [None] * len(text_content)
  271. audio_list = [None] * len(text_content)
  272. sub_clip_list = [None] * len(text_content)
  273. sub_img_list = [None] * len(text_content)
  274. idx = 0
  275. for p in listdir(dir_photo+name_hash):
  276. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  277. clip_duration = anchor_list[idx].info.duration
  278. anchor_list[idx].Open()
  279. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  280. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  281. t.AddClip(anchor_clip_list[idx])
  282. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  283. img_list[idx].Open()
  284. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  285. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  286. t.AddClip(photo_clip_list[idx])
  287. img_list[idx].Close()
  288. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  289. audio_list[idx].Open()
  290. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  291. audio_clip_list[idx].Position(main_timer)
  292. audio_clip_list[idx].End(clip_duration)
  293. t.AddClip(audio_clip_list[idx])
  294. img_list[idx].Close()
  295. anchor_list[idx].Close()
  296. audio_list[idx].Close()
  297. sub_img_list[idx] = [None] * len(sub_list[idx])
  298. sub_clip_list[idx] = [None] * len(sub_list[idx])
  299. sub_timer = 0
  300. for sub_idx in range(len(sub_list[idx])):
  301. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  302. sub_img_list[idx][sub_idx].Open()
  303. sub_duration = 0.205*sub_list[idx][sub_idx]['count']
  304. 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)
  305. t.AddClip(sub_clip_list[idx][sub_idx])
  306. sub_img_list[idx][sub_idx].Close()
  307. sub_timer += sub_duration
  308. print(sub_list[idx][sub_idx]['path'])
  309. main_timer += clip_duration
  310. idx+=1
  311. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  312. LOGO_ED.Open()
  313. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration+2
  314. ,location_x=0.005,location_y=-0.031
  315. ,scale_x=0.8,scale_y=0.6825)
  316. t.AddClip(LOGO_ED_clip)
  317. ED_duration = LOGO_ED.info.duration
  318. LOGO_ED.Close()
  319. bg = openshot.FFmpegReader(dir_video+"bg.mp4")
  320. bg.Open()
  321. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  322. left_time = (main_timer+ED_duration) % bg.info.duration
  323. bg_clip_list = [None] * bg_times
  324. bg_list = [None] * bg_times
  325. bg.Close()
  326. bg_timer = head_duration
  327. for idx in range(bg_times):
  328. bg_list[idx] = openshot.FFmpegReader(dir_video+"bg.mp4")
  329. bg_list[idx].Open()
  330. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  331. ,end=bg_list[idx].info.duration,ck=ck)
  332. t.AddClip(bg_clip_list[idx])
  333. bg_timer += bg_list[idx].info.duration
  334. bg_list[idx].Close()
  335. bg_left = openshot.FFmpegReader(dir_video+"bg.mp4")
  336. bg_left.Open()
  337. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  338. t.AddClip(bg_left_clip)
  339. bg_left.Close()
  340. title = openshot.QtImageReader(dir_title+name_hash+".png")
  341. title.Open() # Open the reader
  342. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  343. t.AddClip(title_clip)
  344. ####start building
  345. w = openshot.FFmpegWriter(tmp_video_dir+name_hash+".mp4")
  346. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  347. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  348. openshot.Fraction(1, 1), False, False, 3000000)
  349. w.Open()
  350. #may change duration into t.info.duration
  351. frames = int(t.info.fps)*int(head_duration+main_timer+ED_duration)
  352. for n in range(frames):
  353. f=t.GetFrame(n)
  354. w.WriteFrame(f)
  355. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+name_hash+".mp4")
  356. t.Close()
  357. w.Close()
  358. print("video at : www.choozmo.com:8168/"+name_hash+".mp4")
  359. #line notifs
  360. class video_service(rpyc.Service):
  361. def exposed_call_video(self,name_hash,name,text_content, image_urls,avatar,client_id):
  362. anchor_video_v2(name_hash,name,text_content, image_urls,avatar,client_id)
  363. from rpyc.utils.server import ThreadedServer
  364. t = ThreadedServer(video_service, port=8878)
  365. print('service started')
  366. t.start()