openshot_video_generator.py 15 KB

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