main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import openshot
  2. import re
  3. from PIL import Image,ImageDraw,ImageFont
  4. import pandas as pd
  5. import os
  6. import cv2
  7. import numpy as np
  8. # import moviepy.editor as mp
  9. import time
  10. import pysrt
  11. import shutil
  12. import rpyc
  13. import random
  14. import string
  15. import requests
  16. from bs4 import BeautifulSoup
  17. import zipfile
  18. def cKey(r,g,b,fuzz):
  19. col=openshot.Color()
  20. col.red=openshot.Keyframe(r)
  21. col.green=openshot.Keyframe(g)
  22. col.blue=openshot.Keyframe(b)
  23. return openshot.ChromaKey(col, openshot.Keyframe(fuzz))
  24. def video_writer_init(path):
  25. w = openshot.FFmpegWriter(path)
  26. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  27. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  28. openshot.Fraction(1, 1), False, False, 3000000)
  29. return w
  30. def video_photo_clip(video=None,layer=None, position=None, end=None
  31. ,scale_x=1,scale_y=1,location_x=0,location_y=0,ck=None,audio=True):
  32. clip = openshot.Clip(video)
  33. clip.Layer(layer)
  34. clip.Position(position)
  35. clip.End(end)
  36. clip.scale_x=openshot.Keyframe(scale_x)
  37. clip.scale_y=openshot.Keyframe(scale_y)
  38. clip.location_x=openshot.Keyframe(location_x)
  39. clip.location_y=openshot.Keyframe(location_y)
  40. if ck!=None:
  41. clip.AddEffect(ck)
  42. if audio==True:
  43. clip.has_audio=openshot.Keyframe(1)
  44. else:
  45. clip.has_audio=openshot.Keyframe(0)
  46. return clip
  47. def trim_punctuation(s):
  48. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+'
  49. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  50. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u" " ,s)
  51. return res
  52. def randomString(stringLength=10):
  53. letters = string.ascii_lowercase
  54. return ''.join(random.choice(letters) for i in range(stringLength))
  55. def mp3_to_anchor(fname):
  56. conn = rpyc.classic.connect("192.168.192.221",18812)
  57. fr=open(fname,'rb')
  58. ropen = conn.builtins.open
  59. randname=randomString(10)
  60. finalname=randomString(10)
  61. fw=ropen('/tmp/'+randname+'.mp4','wb')
  62. fw.write(fr.read())
  63. fw.close()
  64. ros = conn.modules.os
  65. ros.system('/root/to_video/p9.sh '+randname+".mp4 "+finalname+".mp4")
  66. return 'http://192.168.192.221/video/'+finalname+'.mp4'
  67. # conn.execute('import os')
  68. def download_mp4(url,name):
  69. headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'}
  70. with open('input_self/AI_girl/ai_spokesgirl_%s.mp4'%(name),'wb') as f:
  71. r = requests.get(url, headers=headers, stream=True)
  72. if r.status_code == 404:
  73. return False
  74. for chunk in r.iter_content(chunk_size=1024):
  75. if chunk:
  76. f.write(chunk)
  77. return True
  78. def text_to_short_vedio_create(read_csv_use="導盲犬協會.csv",pwd_use="導盲犬協會影片素材2/",op="input_self/LOGO_OP_4.mp4",ed="input_self/LOGO_ED.mp4",bg="input_self/串場樣板1_long.mp4",input_zip="input/input_data.zip"):
  79. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  80. t.Open()
  81. files=os.listdir("input/")
  82. print(files)
  83. for i in files:
  84. if i[-4:]==".zip":
  85. input_zip="input/"+i
  86. break
  87. # try:
  88. # os.remove("./templates/index.html")
  89. # except:
  90. # pass
  91. with zipfile.ZipFile(input_zip, 'r') as zf:
  92. for fn in zf.namelist():
  93. right_fn = fn.encode('cp437').decode('big5') # 將檔名正確編碼
  94. check_p=right_fn.split("/")
  95. if right_fn[-1]=="/" :
  96. os.mkdir("input/"+right_fn[:-1])
  97. pwd_use=right_fn
  98. break
  99. if len(check_p)==2:
  100. os.mkdir("input/"+check_p[0])
  101. pwd_use=check_p[0]+"/"
  102. break
  103. with zipfile.ZipFile(input_zip, 'r') as zf:
  104. for fn in zf.namelist():
  105. right_fn = fn.encode('cp437').decode('big5') # 將檔名正確編碼
  106. check_p=right_fn.split("/")
  107. if right_fn[-1]=="/" :
  108. continue
  109. if right_fn[-4:]==".csv":
  110. read_csv_use = right_fn
  111. with open("input/"+right_fn, 'wb') as output_file: # 建立並開啟新檔案
  112. with zf.open(fn, 'r') as origin_file: # 開啟原檔案
  113. shutil.copyfileobj(origin_file, output_file) # 將原檔案內容複製到新檔案
  114. # 去背參數
  115. # ck=cKey(0,254,0,270)
  116. ck=cKey(0,255,0,320)
  117. ck_anchor=None
  118. #時間
  119. time_= 0
  120. csv_use=pd.read_csv("input/"+read_csv_use)
  121. csv_use=csv_use.dropna(how='all')
  122. csv_use.reset_index(inplace=True)
  123. anchor_op = openshot.FFmpegReader(op)
  124. anchor_op.Open()
  125. anchor_clip_op = video_photo_clip(video=anchor_op,layer=2,scale_x=1,scale_y=1,
  126. location_x=0,location_y=0,position=time_, end=anchor_op.info.duration,ck=ck_anchor,audio=True)
  127. t.AddClip(anchor_clip_op)
  128. anchor_op.Close()
  129. time_+=anchor_op.info.duration
  130. for i in range(len(csv_use)):
  131. # for i in range(3):
  132. pwd_=str(csv_use.loc[i,['音檔']].values[0])
  133. locals()['anchor_music'+str(i)] = openshot.FFmpegReader("input/"+pwd_use+pwd_)
  134. locals()['anchor_music'+str(i)].Open()
  135. locals()['anchor_music'+str(i)+'clip'] = video_photo_clip(video=locals()['anchor_music'+str(i)],layer=3,scale_x=0,scale_y=0,
  136. location_x=0,location_y=0,position=time_, end=locals()['anchor_music'+str(i)].info.duration,ck=ck_anchor,audio=True)
  137. t.AddClip(locals()['anchor_music'+str(i)+'clip'])
  138. locals()['anchor_music'+str(i)].Close()
  139. if str(csv_use.loc[i,['是否要場景']].values[0])=="是":
  140. scale_x_use = 0.59
  141. scale_y_use = 0.59
  142. t1 = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  143. t1.Open()
  144. pwd_=str(csv_use.loc[i,['音檔']].values[0])
  145. locals()['anchor_music_t'+str(i)] = openshot.FFmpegReader("input/"+pwd_use+pwd_)
  146. locals()['anchor_music_t'+str(i)].Open()
  147. locals()['anchor_music_t'+str(i)+'clip'] = video_photo_clip(video=locals()['anchor_music_t'+str(i)],layer=3,scale_x=0,scale_y=0,
  148. location_x=0,location_y=0,position=0, end=locals()['anchor_music_t'+str(i)].info.duration,ck=ck_anchor,audio=True)
  149. t1.AddClip(locals()['anchor_music_t'+str(i)+'clip'])
  150. locals()['anchor_music_t'+str(i)].Close()
  151. w = video_writer_init("input_self/tmp1/%s.mp4"%('anchor_music'+str(i)))
  152. w.Open()
  153. frames = int(t1.info.fps)*int(locals()['anchor_music_t'+str(i)].info.duration)
  154. for n in range(frames):
  155. f=t1.GetFrame(n)
  156. w.WriteFrame(f)
  157. w.Close()
  158. t1.Close()
  159. fname=mp3_to_anchor("input_self/tmp1/%s.mp4"%('anchor_music'+str(i)))
  160. # print(fname)
  161. time.sleep(180)
  162. while True:
  163. result = download_mp4(fname,str(i))
  164. if result:
  165. break
  166. print('等待...')
  167. time.sleep(60)
  168. else:
  169. scale_x_use = 1
  170. scale_y_use = 1
  171. choose=str(csv_use.loc[i,['素材']].values[0]).split(".")[-1]
  172. pwd_p1=str(csv_use.loc[i,['素材']].values[0])
  173. if choose == 'mp4':
  174. locals()['anchor'+str(i)] = openshot.FFmpegReader("input/"+pwd_use+pwd_p1)
  175. locals()['anchor'+str(i)].Open()
  176. locals()['anchor'+str(i)+'clip'] = video_photo_clip(video=locals()['anchor'+str(i)],layer=4,scale_x=scale_x_use,scale_y=scale_y_use,
  177. location_x=-0.04,location_y=-0.04,position=time_, end=locals()['anchor_music'+str(i)].info.duration,ck=ck_anchor,audio=False)
  178. t.AddClip(locals()['anchor'+str(i)+'clip'])
  179. locals()['anchor'+str(i)].Close()
  180. if str(csv_use.loc[i,['是否要場景']].values[0])=="是":
  181. locals()['anchor_ad'+str(i)] = openshot.FFmpegReader('input_self/AI_girl/ai_spokesgirl_%s.mp4'%(str(i)))
  182. locals()['anchor_ad'+str(i)].Open()
  183. locals()['anchor_clip_ad'+str(i)] = video_photo_clip(video=locals()['anchor_ad'+str(i)],layer=6,scale_x=0.8,scale_y=0.8,
  184. location_x=0.38,location_y=0.35,position=time_, end=locals()['anchor_music'+str(i)].info.duration,ck=ck,audio=False)
  185. t.AddClip(locals()['anchor_clip_ad'+str(i)])
  186. locals()['anchor_ad'+str(i)].Close()
  187. locals()['anchor_bg'+str(i)] = openshot.FFmpegReader(bg)
  188. locals()['anchor_bg'+str(i)].Open()
  189. locals()['anchor_clip_bg'+str(i)] = video_photo_clip(video=locals()['anchor_bg'+str(i)],layer=2,scale_x=1,scale_y=1,
  190. location_x=0,location_y=0,position=time_, end=locals()['anchor_music'+str(i)].info.duration,ck=ck_anchor,audio=False)
  191. t.AddClip(locals()['anchor_clip_bg'+str(i)])
  192. locals()['anchor_bg'+str(i)].Close()
  193. elif choose == 'jpg' or choose == 'png':
  194. locals()['anchor'+str(i)] = openshot.QtImageReader("input/"+pwd_use+pwd_p1)
  195. locals()['anchor'+str(i)].Open()
  196. locals()['anchor'+str(i)+'clip'] = video_photo_clip(video=locals()['anchor'+str(i)],layer=4,scale_x=scale_x_use,scale_y=scale_y_use,
  197. location_x=-0.04,location_y=-0.04,position=time_, end=locals()['anchor_music'+str(i)].info.duration,ck=ck_anchor,audio=False)
  198. t.AddClip(locals()['anchor'+str(i)+'clip'])
  199. locals()['anchor'+str(i)].Close()
  200. if str(csv_use.loc[i,['是否要場景']].values[0])=="是":
  201. locals()['anchor_ad'+str(i)] = openshot.FFmpegReader("input_self/AI_girl/ai_spokesgirl_%s.mp4"%(str(i)))
  202. locals()['anchor_ad'+str(i)].Open()
  203. locals()['anchor_clip_ad'+str(i)] = video_photo_clip(video=locals()['anchor_ad'+str(i)],layer=6,scale_x=0.8,scale_y=0.8,
  204. location_x=0.38,location_y=0.35,position=time_, end=locals()['anchor_music'+str(i)].info.duration,ck=ck,audio=False)
  205. t.AddClip(locals()['anchor_clip_ad'+str(i)])
  206. locals()['anchor_ad'+str(i)].Close()
  207. locals()['anchor_bg'+str(i)] = openshot.FFmpegReader(bg)
  208. locals()['anchor_bg'+str(i)].Open()
  209. locals()['anchor_clip_bg'+str(i)] = video_photo_clip(video=locals()['anchor_bg'+str(i)],layer=2,scale_x=1,scale_y=1,
  210. location_x=0,location_y=0,position=time_, end=locals()['anchor_music'+str(i)].info.duration,ck=ck_anchor,audio=False)
  211. t.AddClip(locals()['anchor_clip_bg'+str(i)])
  212. locals()['anchor_bg'+str(i)].Close()
  213. time_+=locals()['anchor_music'+str(i)].info.duration
  214. anchor_ed = openshot.FFmpegReader(ed)
  215. anchor_ed.Open()
  216. anchor_clip_ed = video_photo_clip(video=anchor_ed,layer=2,scale_x=1,scale_y=1,
  217. location_x=0,location_y=0,position=time_, end=anchor_ed.info.duration,ck=ck_anchor,audio=True)
  218. time_+=anchor_ed.info.duration
  219. t.AddClip(anchor_clip_ed)
  220. anchor_ed.Close()
  221. w = video_writer_init("input_self/tmp1/test.mp4")
  222. w.Open()
  223. frames = int(t.info.fps)*int(time_)
  224. for n in range(frames):
  225. f=t.GetFrame(n)
  226. w.WriteFrame(f)
  227. t.Close()
  228. w.Close()
  229. shutil.rmtree('input')
  230. os.mkdir('input')
  231. shutil.rmtree('input_self/AI_girl')
  232. os.mkdir('input_self/AI_girl')
  233. #文字轉圖片
  234. def txt2image(content, save_target,lang='zh',size=26,fon="input_self/font/DFT_B7.ttc"):
  235. unicode_text = trim_punctuation(content)
  236. font = ''
  237. if lang=='zh':
  238. font = ImageFont.truetype(font=fon, size=size)
  239. else :
  240. font = ImageFont.truetype(font="input_self/font/arial.ttf", size=size)
  241. W, H = (1280,500)
  242. canvas = Image.new('RGB', (W, H), "#00FF00")
  243. draw = ImageDraw.Draw(canvas)
  244. text= content
  245. if "\n" in text:
  246. w, h = draw.textsize(text.split("\n")[0],font = font)
  247. #draw.text(((W-w)/2,0), text[0:18],'black', font)
  248. text_border(draw,(W-w)/2,0,text.split("\n")[0],font,'black','white')
  249. w, h = draw.textsize(text.split("\n")[1],font = font)
  250. #draw.text(((W-w)/2,h+2), text[18:],'black', font)
  251. text_border(draw,(W-w)/2,h+2,text.split("\n")[1],font,'black','white')
  252. else:
  253. w, h = draw.textsize(content,font = font)
  254. #draw.text(((W-w)/2,0), text,'black', font)
  255. text_border(draw,(W-w)/2,0,text,font,'black','white')
  256. canvas.save(save_target, "PNG")
  257. def text_border(draw,x,y,text,font,shadowcolor,fillcolor):
  258. draw.text((x-1, y), text, font=font, fill=shadowcolor)
  259. draw.text((x+1, y), text, font=font, fill=shadowcolor)
  260. draw.text((x, y-1), text, font=font, fill=shadowcolor)
  261. draw.text((x, y+1), text, font=font, fill=shadowcolor)
  262. draw.text((x-1, y+1), text, font=font, fill=shadowcolor)
  263. draw.text((x+1, y-1), text, font=font, fill=shadowcolor)
  264. draw.text((x-1, y-1), text, font=font, fill=shadowcolor)
  265. draw.text((x+1, y+1), text, font=font, fill=shadowcolor)
  266. # thicker border
  267. draw.text((x-2, y-2), text, font=font, fill=shadowcolor)
  268. draw.text((x+2, y-2), text, font=font, fill=shadowcolor)
  269. draw.text((x-2, y+2), text, font=font, fill=shadowcolor)
  270. draw.text((x+2, y+2), text, font=font, fill=shadowcolor)
  271. # now draw the text over it
  272. draw.text((x, y), text, font=font, fill=fillcolor)
  273. def srt_to_csv(srt_file):
  274. subs = pysrt.open(srt_file)
  275. csv_file = srt_file.split('.')[0] + ".csv"
  276. with open(csv_file, 'w', newline='') as csvfile:
  277. # 建立 CSV 檔寫入器
  278. writer = csv.writer(csvfile)
  279. for context in subs:
  280. writer.writerow([context.index, context.start,context.end, context.text])
  281. return csv_file
  282. def csv_to_text(csv_file,text_font):
  283. text_form = []
  284. with open(csv_file, newline='') as csvfile:
  285. # 讀取 CSV 檔案內容
  286. rows = csv.reader(csvfile)
  287. # 以迴圈輸出每一列
  288. for row in rows:
  289. start = datetime.strptime(row[1], "%H:%M:%S,%f")
  290. end = datetime.strptime(row[2], "%H:%M:%S,%f") - datetime.strptime(row[1], "%H:%M:%S,%f")
  291. end_timeStamp=end.seconds+0.000001*end.microseconds
  292. start_timeStamp=start.minute*60+start.second+ 0.000001*start.microsecond
  293. text_form.append({'text':row[3],'start':start_timeStamp,'end':end_timeStamp,'size':36,'font':text_font})
  294. return text_form
  295. def text_to_short_vedio(mp4_file ,sound_file,output_filename,text_font):
  296. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  297. t.Open()
  298. # 去背參數
  299. ck = cKey(0, 254, 0, 270)
  300. ck_anchor = cKey(0, 255, 0, 320)
  301. anchor = openshot.FFmpegReader(mp4_file)
  302. anchor.Open()
  303. anchor_clip = video_photo_clip(video=anchor,layer=2,scale_x=1,scale_y=1,
  304. location_x=0,location_y=0,position=0, end=anchor.info.duration,audio=True)
  305. t.AddClip(anchor_clip)
  306. anchor.Close()
  307. number = 0
  308. sound_srt_file = ""
  309. #音檔自動產生srt(逐字稿)
  310. if ".srt" in sound_file:
  311. sound_srt_file = sound_file
  312. elif not sound_file is None:
  313. cmd = "autosub -S zh-TW -D zh-TW " + sound_file
  314. os.system(cmd)
  315. sound_srt_file = sound_file.split('.')[0] + ".srt"
  316. csv_file = srt_to_csv(sound_srt_file)
  317. text_form = csv_to_text(csv_file,text_font)
  318. print(sound_srt_file)
  319. #開啟srt檔
  320. try:
  321. # subs = pysrt.open(sound_srt_file)
  322. # text_form = []
  323. # for context in subs:
  324. # #print(context.start.minutes*60+context.start.seconds+ 0.001*context.start.milliseconds)
  325. # end = context.end-context.start
  326. # end_timeStamp=(end.minutes*60+end.seconds+ 0.001*end.milliseconds)
  327. # start_timeStamp=(context.start.minutes*60+context.start.seconds+ 0.001*context.start.milliseconds)
  328. # text_form.append({'text':context.text,'start':start_timeStamp,'end':end_timeStamp,'size':36,'font':text_font})
  329. number = 0
  330. for text_tmp in text_form:
  331. file_name = "input_self/tmp/save_target_" + str(number) + ".png"
  332. txt2image(text_tmp['text'], file_name,lang='zh',size = text_tmp['size'],fon = text_tmp['font'])
  333. exec('text_anchor_{} = openshot.QtImageReader("input_self/tmp/save_target_{}.png")'.format(number,number))
  334. exec('text_anchor_{}.Open()'.format(number))
  335. exec('text_anchor_{}.Open()'.format(number))
  336. exec('text_anchor_clip_{} = video_photo_clip(video=text_anchor_{},layer=4,scale_x=1,scale_y=1,\
  337. location_x=0,location_y=0.67,position=text_tmp["start"], end=text_tmp["end"],ck=ck_anchor,audio=True)'.format(number,number))
  338. exec('t.AddClip(text_anchor_clip_{})'.format(number))
  339. exec('text_anchor_{}.Close()'.format(number))
  340. number = number+1
  341. except:
  342. print("無法開啟srt檔案(字幕產生失敗)")
  343. w = video_writer_init(output_filename)
  344. w.Open()
  345. frames = int(t.info.fps)*int(anchor.info.duration)
  346. for n in range(frames):
  347. f=t.GetFrame(n)
  348. w.WriteFrame(f)
  349. t.Close()
  350. w.Close()
  351. #刪除暫存檔案
  352. shutil.rmtree('input_self/tmp')
  353. os.mkdir('input_self/tmp')
  354. shutil.rmtree('input_self/tmp1')
  355. os.mkdir('input_self/tmp1')
  356. if __name__ == '__main__':
  357. text_to_short_vedio_create()
  358. text_to_short_vedio(mp4_file = "input_self/tmp1/test.mp4",sound_file ='input_self/tmp1/test.mp4',
  359. output_filename="output/demo.mp4",text_font ="input_self/font/DFT_R7.ttc")