openshot_video_generator.py 14 KB

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