main.py 17 KB

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