main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. from fastapi import FastAPI
  2. import openshot
  3. from os import listdir
  4. from os.path import isfile, isdir, join
  5. import threading
  6. import zhtts
  7. import os
  8. import urllib
  9. from typing import List
  10. import requests
  11. from pydantic import BaseModel
  12. from bs4 import BeautifulSoup
  13. import time
  14. from PIL import Image,ImageDraw,ImageFont
  15. import pyttsx3
  16. import rpyc
  17. import random
  18. import time
  19. import math
  20. import hashlib
  21. import re
  22. import urllib.request
  23. from fastapi.responses import FileResponse
  24. #service nginx restart
  25. #uvicorn main:app --host="0.0.0.0" --reload --port 8888
  26. app = FastAPI()
  27. dir_sound = 'mp3_track/'
  28. dir_photo = 'photo/'
  29. dir_text = 'text_file/'
  30. dir_video = 'video_material/'
  31. dir_title = 'title/'
  32. dir_subtitle = 'subtitle/'
  33. dir_anchor = 'anchor_raw/'
  34. class request(BaseModel):
  35. name: str
  36. text_content: str
  37. image_urls: List[str]
  38. class QQ(BaseModel):
  39. n1: str
  40. n2: str
  41. class request2(BaseModel):
  42. name: str
  43. text_content: List[str]
  44. image_urls: List[str]
  45. class anchor_request(BaseModel):
  46. name: str
  47. text_content: str
  48. image_urls: List[str]
  49. @app.get("/")
  50. async def root():
  51. return {"message": "Hello, this is index"}
  52. @app.get("/index2")
  53. async def index2():
  54. return FileResponse('index2.html')
  55. @app.get("/script_msg.js")
  56. async def index2():
  57. return FileResponse('script_msg.js')
  58. @app.get("/style.css")
  59. async def index2():
  60. return FileResponse('style.css')
  61. @app.post("/qqreq")
  62. async def qqreq(qq:QQ):
  63. print(qq.n1)
  64. print(qq.n2)
  65. return {"msg":"製作影片需要時間,請您耐心等候"}
  66. @app.post("/make_anchor_video_v2")
  67. async def make_anchor_video_v2(req:request2):
  68. x = threading.Thread(target=anchor_video_v2, args=(req.name, req.text_content, req.image_urls))
  69. x.start()
  70. return {"msg":"製作影片需要時間,請您耐心等候 稍後可以在www.choozmo.com:8168/"+req.name+".mp4 中觀看"}
  71. def notify_group(msg):
  72. headers = {
  73. "Authorization": "Bearer " + "WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD",
  74. "Content-Type": "application/x-www-form-urlencoded"
  75. }
  76. params = {"message": msg}
  77. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  78. #print(r)
  79. def cKey(r,g,b,fuzz):
  80. col=openshot.Color()
  81. col.red=openshot.Keyframe(r)
  82. col.green=openshot.Keyframe(g)
  83. col.blue=openshot.Keyframe(b)
  84. return openshot.ChromaKey(col, openshot.Keyframe(fuzz))
  85. def video_photo_clip(vid=None,layer=None, position=None, end=None
  86. ,scale_x=1,scale_y=1,location_x=0,location_y=0,ck=None,audio=True):
  87. clip = openshot.Clip(vid)
  88. clip.Layer(layer)
  89. clip.Position(position)
  90. clip.End(end)
  91. clip.scale_x=openshot.Keyframe(scale_x)
  92. clip.scale_y=openshot.Keyframe(scale_y)
  93. clip.location_x=openshot.Keyframe(location_x)
  94. clip.location_y=openshot.Keyframe(location_y)
  95. if ck!=None:
  96. clip.AddEffect(ck)
  97. if audio==True:
  98. clip.has_audio=openshot.Keyframe(1)
  99. else:
  100. clip.has_audio=openshot.Keyframe(0)
  101. return clip
  102. def myunichchar(unicode_char):
  103. mb_string = unicode_char.encode('big5')
  104. try:
  105. unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
  106. except NameError:
  107. unicode_char = chr(mb_string[0] << 8 | mb_string[1])
  108. return unicode_char
  109. def file_prepare(name, name_hash,text_content,image_urls):
  110. #save image
  111. try:
  112. os.mkdir(dir_photo+name_hash)
  113. except FileExistsError:
  114. print("Directory " , dir_photo+name_hash , " already exists")
  115. img_num = 1
  116. for imgu in image_urls:
  117. im = Image.open(requests.get(imgu, stream=True).raw)
  118. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  119. img_num+=1
  120. #save text
  121. text_file = open(dir_text+name_hash+".txt", "w")
  122. text_file.write(text_content)
  123. text_file.close()
  124. print("text file made")
  125. #make mp3
  126. tts = zhtts.TTS()
  127. tts.text2wav(text_content,dir_sound+name_hash+".mp3")
  128. print("mp3 file made")
  129. #make title as image
  130. txt2image(name, dir_title+name_hash+".png")
  131. def get_url_type(url):
  132. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  133. r = urllib.request.urlopen(req)
  134. contentType = r.getheader('Content-Type')
  135. return contentType
  136. def downloadfile(name,url):
  137. name=name+".mp4"
  138. def make_dir(name_hash):
  139. #save image
  140. try:
  141. os.mkdir(dir_photo+name_hash)
  142. except FileExistsError:
  143. print("~~~~~~Warning~~~~~~~~~Directory " , dir_photo+name_hash , " already exists")
  144. try:
  145. os.mkdir(dir_text+name_hash)
  146. except FileExistsError:
  147. print("~~~~~~Warning~~~~~~~~~Directory " , dir_text+name_hash , " already exists")
  148. try:
  149. os.mkdir(dir_sound+name_hash)
  150. except FileExistsError:
  151. print("~~~~~~Warning~~~~~~~~~Directory " , dir_sound+name_hash , " already exists")
  152. try:
  153. os.mkdir(dir_video+name_hash)
  154. except FileExistsError:
  155. print("~~~~~~Warning~~~~~~~~~Directory " , dir_video+name_hash , " already exists")
  156. try:
  157. os.mkdir(dir_anchor+name_hash)
  158. except FileExistsError:
  159. print("~~~~~~Warning~~~~~~~~~Directory " , dir_anchor+name_hash , " already exists")
  160. try:
  161. os.mkdir(dir_subtitle+name_hash)
  162. except FileExistsError:
  163. print("~~~~~~Warning~~~~~~~~~Directory " , dir_subtitle+name_hash , " already exists")
  164. def file_prepare_v2(name, name_hash,text_content,image_urls):
  165. make_dir(name_hash)
  166. img_num = 1
  167. for imgu in image_urls:
  168. if get_url_type(imgu) =='video/mp4':
  169. r=requests.get(imgu)
  170. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  171. for chunk in r.iter_content(chunk_size=255):
  172. if chunk:
  173. f.write(chunk)
  174. f.close()
  175. else:
  176. im = Image.open(requests.get(imgu, stream=True).raw)
  177. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  178. img_num+=1
  179. #save text
  180. txt_idx=0
  181. for txt in text_content:
  182. text_file = open(dir_text+name_hash+"/"+str(txt_idx)+".txt", "w")
  183. text_file.write(txt)
  184. text_file.close()
  185. txt_idx+=1
  186. print("text file made")
  187. #make mp3
  188. language = 'zh-tw'
  189. txt_idx = 0
  190. for txt in text_content:
  191. tts = zhtts.TTS()
  192. tts.text2wav(txt,dir_sound+name_hash+"/"+str(txt_idx)+".mp3")
  193. txt_idx+=1
  194. print("mp3 file made")
  195. #make title as image
  196. txt2image_title(name, dir_title+name_hash+".png")
  197. def txt2image(content, save_target):
  198. unicode_text = trim_punctuation(content)
  199. font = ImageFont.truetype(font="DFT_B7.ttc", size=38)
  200. text_width, text_height = font.getsize(unicode_text)
  201. canvas = Image.new('RGBA', (700, 500), (255, 0, 0, 0) )
  202. draw = ImageDraw.Draw(canvas)
  203. text= unicode_text
  204. draw.text((5,5), text, (255, 255, 0), font)
  205. canvas.save(save_target, "PNG")
  206. def txt2image_title(content, save_target):
  207. unicode_text = trim_punctuation(content)
  208. font = ImageFont.truetype(font="DFT_B7.ttc", size=28)
  209. text_width, text_height = font.getsize(unicode_text)
  210. canvas = Image.new('RGBA', (500, 500), (255, 0, 0, 0) )
  211. draw = ImageDraw.Draw(canvas)
  212. text= unicode_text
  213. draw.text((5,5), text, (17, 41, 167), font)
  214. canvas.save(save_target, "PNG")
  215. '''
  216. def txt2image_title(content, save_target):
  217. unicode_text =content
  218. font = ImageFont.truetype("font.ttf", 23,encoding='big5')
  219. text_width, text_height = font.getsize(unicode_text)
  220. canvas = Image.new('RGBA', (500, 500), (255, 0, 0, 0) )
  221. draw = ImageDraw.Draw(canvas)
  222. text=''
  223. for c in unicode_text:
  224. if len(re.findall(r'[\u4e00-\u9fff]+', c))>0:
  225. text+=myunichchar(c)
  226. else:
  227. text+=c
  228. draw.text((5,5), text, (17, 41, 167), font)
  229. canvas.save(save_target, "PNG")
  230. '''
  231. def call_achor_video_v2(fileName):
  232. conn = rpyc.classic.connect("192.168.1.105",18812)
  233. ros = conn.modules.os
  234. rsys = conn.modules.sys
  235. fr=open(dir_sound+fileName+".mp3",'rb')# voice
  236. #warning!!! file my be replaced by other process
  237. fw=conn.builtins.open('/tmp/output.mp3','wb')
  238. while True:
  239. b=fr.read(1024)
  240. if b:
  241. fw.write(b)
  242. else:
  243. break
  244. fr.close()
  245. fw.close()
  246. val=random.randint(1000000,9999999)
  247. ros.chdir('/home/jared/to_video')
  248. ros.system('./p6.sh '+str(val)+' &')
  249. while True:
  250. print('waiting...')
  251. if ros.path.exists('/tmp/results/'+str(val)):
  252. break
  253. time.sleep(5)
  254. print('waiting...')
  255. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  256. fw=open(dir_anchor+fileName+".mp4",'wb')#peggy1_1
  257. while True:
  258. b=fr.read(1024)
  259. if b:
  260. fw.write(b)
  261. else:
  262. break
  263. fr.close()
  264. fw.close()
  265. def call_achor_video(name):
  266. conn = rpyc.classic.connect("192.168.1.105",18812)
  267. ros = conn.modules.os
  268. rsys = conn.modules.sys
  269. fr=open(dir_sound+name+".mp3",'rb')# voice
  270. #warning!!! file my be replaced by other process
  271. fw=conn.builtins.open('/tmp/output.mp3','wb')
  272. while True:
  273. b=fr.read(1024)
  274. if b:
  275. fw.write(b)
  276. else:
  277. break
  278. fr.close()
  279. fw.close()
  280. val=random.randint(1000000,9999999)
  281. ros.chdir('/home/jared/to_video')
  282. ros.system('./p6.sh '+str(val)+' &')
  283. while True:
  284. print('waiting...')
  285. if ros.path.exists('/tmp/results/'+str(val)):
  286. break
  287. time.sleep(15)
  288. print('waiting...')
  289. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  290. fw=open(dir_anchor+name+'.mp4','wb')#peggy1_1
  291. while True:
  292. b=fr.read(1024)
  293. if b:
  294. fw.write(b)
  295. else:
  296. break
  297. fr.close()
  298. fw.close()
  299. print('called............................................')
  300. def trim_punctuation(s):
  301. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
  302. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  303. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u"" ,s)
  304. return res
  305. def splitter(s):
  306. for sent in re.findall(u'[^!?,。\.\!\?]+[!?。\.\!\?]?', s, flags=re.U):
  307. yield sent
  308. def split_by_pun(s):
  309. res = list(splitter(s))
  310. return res
  311. def generate_subtitle_image(name_hash,text_content):
  312. img_list = [None]*len(text_content)
  313. for idx in range(len(text_content)):
  314. img_list[idx]=[]
  315. senList = split_by_pun(text_content[idx])
  316. for inner_idx in range(len(senList)):
  317. sv_path = dir_subtitle + name_hash +'/'+str(idx)+ str(inner_idx) +'.png'
  318. sub = senList[inner_idx]
  319. txt2image(sub,sv_path)
  320. img_list[idx]+=[{"count":len(sub),"path":sv_path}]
  321. return img_list
  322. def anchor_video_v2(name,text_content, image_urls):
  323. m = hashlib.md5()
  324. m.update(name.encode("utf-8"))
  325. name_hash = m.hexdigest()
  326. print('sub image made')
  327. file_prepare_v2(name, name_hash, text_content,image_urls)
  328. sub_list=generate_subtitle_image(name_hash,text_content)
  329. for fname in range(len(text_content)):
  330. call_achor_video_v2(name_hash+"/"+str(fname))
  331. print('step finish')
  332. print('called............................................')
  333. ck=cKey(0,254,0,150)
  334. ck_anchor=cKey(0,255,1,320)
  335. duration = 0
  336. #average layer level is 3
  337. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  338. t.Open()
  339. main_timer = 0
  340. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP.mp4")
  341. LOGO_OP.Open() # Open the reader
  342. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  343. ,location_y=-0.03,scale_x=0.8,scale_y=0.71)
  344. t.AddClip(LOGO_OP_clip)
  345. bg_head = openshot.FFmpegReader(dir_video+"bg_head.avi")
  346. bg_head.Open()
  347. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  348. t.AddClip(bg_head_clip)
  349. main_timer += LOGO_OP.info.duration
  350. head_duration = LOGO_OP.info.duration
  351. bg_head.Close()
  352. LOGO_OP.Close()
  353. clip_duration=0
  354. photo_clip_list = [None]*len(text_content)
  355. img_list = [None]*len(text_content)
  356. anchor_clip_list = [None] * len(text_content)
  357. anchor_list = [None] * len(text_content)
  358. audio_clip_list = [None] * len(text_content)
  359. audio_list = [None] * len(text_content)
  360. sub_clip_list = [None] * len(text_content)
  361. sub_img_list = [None] * len(text_content)
  362. idx = 0
  363. for p in listdir(dir_photo+name_hash):
  364. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  365. clip_duration = anchor_list[idx].info.duration
  366. anchor_list[idx].Open()
  367. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  368. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  369. t.AddClip(anchor_clip_list[idx])
  370. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  371. img_list[idx].Open()
  372. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  373. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  374. t.AddClip(photo_clip_list[idx])
  375. img_list[idx].Close()
  376. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  377. audio_list[idx].Open()
  378. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  379. audio_clip_list[idx].Position(main_timer)
  380. audio_clip_list[idx].End(clip_duration)
  381. t.AddClip(audio_clip_list[idx])
  382. img_list[idx].Close()
  383. anchor_list[idx].Close()
  384. audio_list[idx].Close()
  385. sub_img_list[idx] = [None] * len(sub_list[idx])
  386. sub_clip_list[idx] = [None] * len(sub_list[idx])
  387. sub_timer = 0
  388. for sub_idx in range(len(sub_list[idx])):
  389. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  390. sub_img_list[idx][sub_idx].Open()
  391. sub_duration = 0.21*sub_list[idx][sub_idx]['count']
  392. 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)
  393. t.AddClip(sub_clip_list[idx][sub_idx])
  394. sub_img_list[idx][sub_idx].Close()
  395. sub_timer += sub_duration
  396. print(sub_list[idx][sub_idx]['path'])
  397. main_timer += clip_duration
  398. idx+=1
  399. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  400. LOGO_ED.Open()
  401. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration
  402. ,location_y=-0.03,scale_x=0.8,scale_y=0.71)
  403. t.AddClip(LOGO_ED_clip)
  404. ED_duration = LOGO_ED.info.duration
  405. LOGO_ED.Close()
  406. bg = openshot.FFmpegReader(dir_video+"bg.mp4")
  407. bg.Open()
  408. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  409. left_time = (main_timer+ED_duration) % bg.info.duration
  410. bg_clip_list = [None] * bg_times
  411. bg_list = [None] * bg_times
  412. bg.Close()
  413. bg_timer = head_duration
  414. for idx in range(bg_times):
  415. bg_list[idx] = openshot.FFmpegReader(dir_video+"bg.mp4")
  416. bg_list[idx].Open()
  417. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  418. ,end=bg_list[idx].info.duration,ck=ck)
  419. t.AddClip(bg_clip_list[idx])
  420. bg_timer += bg_list[idx].info.duration
  421. bg_list[idx].Close()
  422. bg_left = openshot.FFmpegReader(dir_video+"bg.mp4")
  423. bg_left.Open()
  424. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  425. t.AddClip(bg_left_clip)
  426. bg_left.Close()
  427. title = openshot.QtImageReader(dir_title+name_hash+".png")
  428. title.Open() # Open the reader
  429. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.05, location_y=0.801,position=0,end=head_duration+main_timer)
  430. t.AddClip(title_clip)
  431. ####start building
  432. w = openshot.FFmpegWriter("../html/"+name_hash+".mp4")
  433. w.SetAudioOptions(True, "libmp3lame", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  434. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  435. openshot.Fraction(1, 1), False, False, 3000000)
  436. w.Open()
  437. #may change duration into t.info.duration
  438. for n in range(int(t.info.fps)*int(head_duration+main_timer+ED_duration)):
  439. f=t.GetFrame(n)
  440. w.WriteFrame(f)
  441. t.Close()
  442. w.Close()
  443. print("Raw Video done")
  444. print("video at : www.choozmo.com:8168/"+name_hash+".mp4")
  445. #line notifs
  446. #notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+name_hash+".mp4")