main.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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. from websocket import create_connection
  25. from fastapi.middleware.cors import CORSMiddleware
  26. #service nginx restart
  27. #uvicorn main:app --host="0.0.0.0" --reload --port 8888
  28. app = FastAPI()
  29. origins = [
  30. "https://hhh.com.tw"
  31. "http://172.105.205.52",
  32. "http://172.105.205.52:8001",
  33. "http://172.104.93.163",
  34. ]
  35. app.add_middleware(
  36. CORSMiddleware,
  37. # allow_origins=origins,
  38. allow_origins=["*"],
  39. allow_credentials=True,
  40. allow_methods=["*"],
  41. allow_headers=["*"],
  42. )
  43. dir_sound = 'mp3_track/'
  44. dir_photo = 'photo/'
  45. dir_text = 'text_file/'
  46. dir_video = 'video_material/'
  47. dir_title = 'title/'
  48. dir_subtitle = 'subtitle/'
  49. dir_anchor = 'anchor_raw/'
  50. class request(BaseModel):
  51. name: str
  52. text_content: str
  53. image_urls: List[str]
  54. class QQ(BaseModel):
  55. n1: str
  56. n2: str
  57. class request2(BaseModel):
  58. name: str
  59. text_content: List[str]
  60. image_urls: List[str]
  61. class anchor_request(BaseModel):
  62. name: str
  63. text_content: str
  64. image_urls: List[str]
  65. class ConnectionManager:
  66. def __init__(self):
  67. self.active_connections: List[WebSocket] = []
  68. async def connect(self, websocket: WebSocket):
  69. await websocket.accept()
  70. self.active_connections.append(websocket)
  71. def disconnect(self, websocket: WebSocket):
  72. self.active_connections.remove(websocket)
  73. async def send_personal_message(self, message: str, websocket: WebSocket):
  74. await websocket.send_text(message)
  75. async def broadcast(self, message: str):
  76. for connection in self.active_connections:
  77. await connection.send_text(message)
  78. manager = ConnectionManager()
  79. @app.get("/")
  80. async def root():
  81. return {"message": "Hello, this is index"}
  82. @app.get("/index2")
  83. async def index2():
  84. return FileResponse('index2.html')
  85. @app.get("/script_msg.js")
  86. async def index2():
  87. return FileResponse('script_msg.js')
  88. @app.get("/style.css")
  89. async def index2():
  90. return FileResponse('style.css')
  91. @app.get("/progress_page")
  92. async def progress_page():
  93. return FileResponse('progress.html')
  94. @app.post("/make_anchor_video_v2")
  95. async def make_anchor_video_v2(req:request2):
  96. x = threading.Thread(target=anchor_video_v2, args=(req.name, req.text_content, req.image_urls))
  97. x.start()
  98. #return RedirectResponse("https://www.choozmo.com/progress_page")
  99. #return {"https://www.choozmo.com:8888/progress_page"}
  100. return {"msg":"製作影片需要時間,請您耐心等候 稍後可以在www.choozmo.com:8168/"+req.name+".mp4 中觀看"}
  101. @app.websocket("/ws/{client_id}")
  102. async def websocket_endpoint(websocket: WebSocket, client_id: int):
  103. await manager.connect(websocket)
  104. try:
  105. while True:
  106. data = await websocket.receive_text()
  107. await manager.send_personal_message(f"You wrote: {data}", websocket)
  108. await manager.broadcast(data)
  109. except WebSocketDisconnect:
  110. manager.disconnect(websocket)
  111. await manager.broadcast(f"Client #{client_id} left the chat")
  112. def notify_group(msg):
  113. headers = {
  114. "Authorization": "Bearer " + "WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD",
  115. "Content-Type": "application/x-www-form-urlencoded"
  116. }
  117. params = {"message": msg}
  118. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  119. #print(r)
  120. def cKey(r,g,b,fuzz):
  121. col=openshot.Color()
  122. col.red=openshot.Keyframe(r)
  123. col.green=openshot.Keyframe(g)
  124. col.blue=openshot.Keyframe(b)
  125. return openshot.ChromaKey(col, openshot.Keyframe(fuzz))
  126. def video_photo_clip(vid=None,layer=None, position=None, end=None
  127. ,scale_x=1,scale_y=1,location_x=0,location_y=0,ck=None,audio=True):
  128. clip = openshot.Clip(vid)
  129. clip.Layer(layer)
  130. clip.Position(position)
  131. clip.End(end)
  132. clip.scale_x=openshot.Keyframe(scale_x)
  133. clip.scale_y=openshot.Keyframe(scale_y)
  134. clip.location_x=openshot.Keyframe(location_x)
  135. clip.location_y=openshot.Keyframe(location_y)
  136. if ck!=None:
  137. clip.AddEffect(ck)
  138. if audio==True:
  139. clip.has_audio=openshot.Keyframe(1)
  140. else:
  141. clip.has_audio=openshot.Keyframe(0)
  142. return clip
  143. def myunichchar(unicode_char):
  144. mb_string = unicode_char.encode('big5')
  145. try:
  146. unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
  147. except NameError:
  148. unicode_char = chr(mb_string[0] << 8 | mb_string[1])
  149. return unicode_char
  150. def file_prepare(name, name_hash,text_content,image_urls):
  151. #save image
  152. try:
  153. os.mkdir(dir_photo+name_hash)
  154. except FileExistsError:
  155. print("Directory " , dir_photo+name_hash , " already exists")
  156. img_num = 1
  157. for imgu in image_urls:
  158. im = Image.open(requests.get(imgu, stream=True).raw)
  159. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  160. img_num+=1
  161. #save text
  162. text_file = open(dir_text+name_hash+".txt", "w")
  163. text_file.write(text_content)
  164. text_file.close()
  165. print("text file made")
  166. #make mp3
  167. tts = zhtts.TTS()
  168. tts.text2wav(text_content,dir_sound+name_hash+".mp3")
  169. print("mp3 file made")
  170. #make title as image
  171. txt2image(name, dir_title+name_hash+".png")
  172. def get_url_type(url):
  173. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  174. r = urllib.request.urlopen(req)
  175. contentType = r.getheader('Content-Type')
  176. return contentType
  177. def downloadfile(name,url):
  178. name=name+".mp4"
  179. def make_dir(name_hash):
  180. #save image
  181. try:
  182. os.mkdir(dir_photo+name_hash)
  183. except FileExistsError:
  184. print("~~~~~~Warning~~~~~~~~~Directory " , dir_photo+name_hash , " already exists")
  185. try:
  186. os.mkdir(dir_text+name_hash)
  187. except FileExistsError:
  188. print("~~~~~~Warning~~~~~~~~~Directory " , dir_text+name_hash , " already exists")
  189. try:
  190. os.mkdir(dir_sound+name_hash)
  191. except FileExistsError:
  192. print("~~~~~~Warning~~~~~~~~~Directory " , dir_sound+name_hash , " already exists")
  193. try:
  194. os.mkdir(dir_video+name_hash)
  195. except FileExistsError:
  196. print("~~~~~~Warning~~~~~~~~~Directory " , dir_video+name_hash , " already exists")
  197. try:
  198. os.mkdir(dir_anchor+name_hash)
  199. except FileExistsError:
  200. print("~~~~~~Warning~~~~~~~~~Directory " , dir_anchor+name_hash , " already exists")
  201. try:
  202. os.mkdir(dir_subtitle+name_hash)
  203. except FileExistsError:
  204. print("~~~~~~Warning~~~~~~~~~Directory " , dir_subtitle+name_hash , " already exists")
  205. def file_prepare_v2(name, name_hash,text_content,image_urls):
  206. make_dir(name_hash)
  207. img_num = 1
  208. for imgu in image_urls:
  209. if get_url_type(imgu) =='video/mp4':
  210. r=requests.get(imgu)
  211. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  212. for chunk in r.iter_content(chunk_size=255):
  213. if chunk:
  214. f.write(chunk)
  215. f.close()
  216. else:
  217. im = Image.open(requests.get(imgu, stream=True).raw)
  218. im= im.convert("RGB")
  219. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  220. img_num+=1
  221. #save text
  222. txt_idx=0
  223. for txt in text_content:
  224. text_file = open(dir_text+name_hash+"/"+str(txt_idx)+".txt", "w")
  225. text_file.write(txt)
  226. text_file.close()
  227. txt_idx+=1
  228. print("text file made")
  229. #make mp3
  230. language = 'zh-tw'
  231. txt_idx = 0
  232. for txt in text_content:
  233. tts = zhtts.TTS()
  234. tts.text2wav(txt,dir_sound+name_hash+"/"+str(txt_idx)+".mp3")
  235. txt_idx+=1
  236. print("mp3 file made")
  237. #make title as image
  238. txt2image_title(name, dir_title+name_hash+".png")
  239. def txt2image(content, save_target):
  240. unicode_text = trim_punctuation(content)
  241. font = ImageFont.truetype(font="DFT_B7.ttc", size=38)
  242. text_width, text_height = font.getsize(unicode_text)
  243. canvas = Image.new('RGBA', (700, 500), (255, 0, 0, 0) )
  244. draw = ImageDraw.Draw(canvas)
  245. text= unicode_text
  246. draw.text((5,5), text, (255, 255, 0), font)
  247. canvas.save(save_target, "PNG")
  248. def txt2image_title(content, save_target):
  249. unicode_text = trim_punctuation(content)
  250. font = ImageFont.truetype(font="DFT_B7.ttc", size=28)
  251. text_width, text_height = font.getsize(unicode_text)
  252. canvas = Image.new('RGBA', (510, 500), (255, 0, 0, 0) )
  253. draw = ImageDraw.Draw(canvas)
  254. text= unicode_text
  255. draw.text((5,5), text, (17, 41, 167), font)
  256. canvas.save(save_target, "PNG")
  257. '''
  258. def txt2image_title(content, save_target):
  259. unicode_text =content
  260. font = ImageFont.truetype("font.ttf", 23,encoding='big5')
  261. text_width, text_height = font.getsize(unicode_text)
  262. canvas = Image.new('RGBA', (500, 500), (255, 0, 0, 0) )
  263. draw = ImageDraw.Draw(canvas)
  264. text=''
  265. for c in unicode_text:
  266. if len(re.findall(r'[\u4e00-\u9fff]+', c))>0:
  267. text+=myunichchar(c)
  268. else:
  269. text+=c
  270. draw.text((5,5), text, (17, 41, 167), font)
  271. canvas.save(save_target, "PNG")
  272. '''
  273. def call_achor_video_v2(fileName):
  274. conn = rpyc.classic.connect("192.168.1.105",18812)
  275. ros = conn.modules.os
  276. rsys = conn.modules.sys
  277. fr=open(dir_sound+fileName+".mp3",'rb')# voice
  278. #warning!!! file my be replaced by other process
  279. fw=conn.builtins.open('/tmp/output.mp3','wb')
  280. while True:
  281. b=fr.read(1024)
  282. if b:
  283. fw.write(b)
  284. else:
  285. break
  286. fr.close()
  287. fw.close()
  288. val=random.randint(1000000,9999999)
  289. ros.chdir('/home/jared/to_video')
  290. ros.system('./p6.sh '+str(val)+' &')
  291. while True:
  292. print('waiting...')
  293. if ros.path.exists('/tmp/results/'+str(val)):
  294. break
  295. time.sleep(5)
  296. print('waiting...')
  297. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  298. fw=open(dir_anchor+fileName+".mp4",'wb')#peggy1_1
  299. while True:
  300. b=fr.read(1024)
  301. if b:
  302. fw.write(b)
  303. else:
  304. break
  305. fr.close()
  306. fw.close()
  307. def call_achor_video(name):
  308. conn = rpyc.classic.connect("192.168.1.105",18812)
  309. ros = conn.modules.os
  310. rsys = conn.modules.sys
  311. fr=open(dir_sound+name+".mp3",'rb')# voice
  312. #warning!!! file my be replaced by other process
  313. fw=conn.builtins.open('/tmp/output.mp3','wb')
  314. while True:
  315. b=fr.read(1024)
  316. if b:
  317. fw.write(b)
  318. else:
  319. break
  320. fr.close()
  321. fw.close()
  322. val=random.randint(1000000,9999999)
  323. ros.chdir('/home/jared/to_video')
  324. ros.system('./p6.sh '+str(val)+' &')
  325. while True:
  326. print('waiting...')
  327. if ros.path.exists('/tmp/results/'+str(val)):
  328. break
  329. time.sleep(15)
  330. print('waiting...')
  331. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  332. fw=open(dir_anchor+name+'.mp4','wb')#peggy1_1
  333. while True:
  334. b=fr.read(1024)
  335. if b:
  336. fw.write(b)
  337. else:
  338. break
  339. fr.close()
  340. fw.close()
  341. print('called..............................................')
  342. def trim_punctuation(s):
  343. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
  344. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  345. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u"" ,s)
  346. return res
  347. def splitter(s):
  348. for sent in re.findall(u'[^!?,。\!\?]+[!?。\!\?]?', s, flags=re.U):
  349. yield sent
  350. def split_by_pun(s):
  351. res = list(splitter(s))
  352. return res
  353. def generate_subtitle_image(name_hash,text_content):
  354. img_list = [None]*len(text_content)
  355. for idx in range(len(text_content)):
  356. img_list[idx]=[]
  357. senList = split_by_pun(text_content[idx])
  358. for inner_idx in range(len(senList)):
  359. sv_path = dir_subtitle + name_hash +'/'+str(idx)+ str(inner_idx) +'.png'
  360. sub = senList[inner_idx]
  361. txt2image(sub,sv_path)
  362. img_list[idx]+=[{"count":len(sub),"path":sv_path}]
  363. return img_list
  364. def anchor_video_v2(name,text_content, image_urls):
  365. #ws = create_connection("ws://www.choozmo.com/progress")
  366. progress = 0
  367. m = hashlib.md5()
  368. m.update(name.encode("utf-8"))
  369. name_hash = m.hexdigest()
  370. print('sub image made')
  371. file_prepare_v2(name, name_hash, text_content,image_urls)
  372. progress = 10
  373. #ws.send(str(progress))
  374. sub_list=generate_subtitle_image(name_hash,text_content)
  375. progress = 20
  376. #ws.send(str(progress))
  377. progress_per_video = int(40/len(text_content))
  378. for fname in range(len(text_content)):
  379. call_achor_video_v2(name_hash+"/"+str(fname))
  380. progress += progress_per_video
  381. #ws.send(str(progress))
  382. print('step finish')
  383. print('called............................................')
  384. ck=cKey(0,254,0,150)
  385. ck_anchor=cKey(0,255,1,320)
  386. duration = 0
  387. #average layer level is 3
  388. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  389. t.Open()
  390. main_timer = 0
  391. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP.mp4")
  392. LOGO_OP.Open() # Open the reader
  393. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  394. ,location_y=-0.03,scale_x=0.8,scale_y=0.71)
  395. t.AddClip(LOGO_OP_clip)
  396. bg_head = openshot.FFmpegReader(dir_video+"bg_head.avi")
  397. bg_head.Open()
  398. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  399. t.AddClip(bg_head_clip)
  400. main_timer += LOGO_OP.info.duration
  401. head_duration = LOGO_OP.info.duration
  402. bg_head.Close()
  403. LOGO_OP.Close()
  404. progress += 10
  405. clip_duration=0
  406. photo_clip_list = [None]*len(text_content)
  407. img_list = [None]*len(text_content)
  408. anchor_clip_list = [None] * len(text_content)
  409. anchor_list = [None] * len(text_content)
  410. audio_clip_list = [None] * len(text_content)
  411. audio_list = [None] * len(text_content)
  412. sub_clip_list = [None] * len(text_content)
  413. sub_img_list = [None] * len(text_content)
  414. idx = 0
  415. for p in listdir(dir_photo+name_hash):
  416. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  417. clip_duration = anchor_list[idx].info.duration
  418. anchor_list[idx].Open()
  419. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  420. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  421. t.AddClip(anchor_clip_list[idx])
  422. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  423. img_list[idx].Open()
  424. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  425. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  426. t.AddClip(photo_clip_list[idx])
  427. img_list[idx].Close()
  428. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  429. audio_list[idx].Open()
  430. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  431. audio_clip_list[idx].Position(main_timer)
  432. audio_clip_list[idx].End(clip_duration)
  433. t.AddClip(audio_clip_list[idx])
  434. img_list[idx].Close()
  435. anchor_list[idx].Close()
  436. audio_list[idx].Close()
  437. sub_img_list[idx] = [None] * len(sub_list[idx])
  438. sub_clip_list[idx] = [None] * len(sub_list[idx])
  439. sub_timer = 0
  440. for sub_idx in range(len(sub_list[idx])):
  441. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  442. sub_img_list[idx][sub_idx].Open()
  443. sub_duration = 0.205*sub_list[idx][sub_idx]['count']
  444. 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)
  445. t.AddClip(sub_clip_list[idx][sub_idx])
  446. sub_img_list[idx][sub_idx].Close()
  447. sub_timer += sub_duration
  448. print(sub_list[idx][sub_idx]['path'])
  449. main_timer += clip_duration
  450. idx+=1
  451. progress+=10
  452. #ws.send(str(progress))
  453. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  454. LOGO_ED.Open()
  455. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration
  456. ,location_y=-0.03,scale_x=0.8,scale_y=0.71)
  457. t.AddClip(LOGO_ED_clip)
  458. ED_duration = LOGO_ED.info.duration
  459. LOGO_ED.Close()
  460. bg = openshot.FFmpegReader(dir_video+"bg.mp4")
  461. bg.Open()
  462. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  463. left_time = (main_timer+ED_duration) % bg.info.duration
  464. bg_clip_list = [None] * bg_times
  465. bg_list = [None] * bg_times
  466. bg.Close()
  467. bg_timer = head_duration
  468. for idx in range(bg_times):
  469. bg_list[idx] = openshot.FFmpegReader(dir_video+"bg.mp4")
  470. bg_list[idx].Open()
  471. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  472. ,end=bg_list[idx].info.duration,ck=ck)
  473. t.AddClip(bg_clip_list[idx])
  474. bg_timer += bg_list[idx].info.duration
  475. bg_list[idx].Close()
  476. bg_left = openshot.FFmpegReader(dir_video+"bg.mp4")
  477. bg_left.Open()
  478. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  479. t.AddClip(bg_left_clip)
  480. bg_left.Close()
  481. title = openshot.QtImageReader(dir_title+name_hash+".png")
  482. title.Open() # Open the reader
  483. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  484. t.AddClip(title_clip)
  485. ####start building
  486. w = openshot.FFmpegWriter("../html/"+name_hash+".mp4")
  487. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  488. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  489. openshot.Fraction(1, 1), False, False, 3000000)
  490. w.Open()
  491. #may change duration into t.info.duration
  492. for n in range(int(t.info.fps)*int(head_duration+main_timer+ED_duration)):
  493. f=t.GetFrame(n)
  494. w.WriteFrame(f)
  495. t.Close()
  496. w.Close()
  497. print("Raw Video done")
  498. print("video at : www.choozmo.com:8168/"+name_hash+".mp4")
  499. progress = 100
  500. #ws.send(str(progress))
  501. #line notifs
  502. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+name_hash+".mp4")
  503. def anchor_video_v3(name,text_content, image_urls):
  504. ws = create_connection("ws://www.choozmo.com:8888/progress")
  505. progress = 0
  506. m = hashlib.md5()
  507. m.update(name.encode("utf-8"))
  508. name_hash = m.hexdigest()
  509. print('sub image made')
  510. file_prepare_v2(name, name_hash, text_content,image_urls)
  511. progress = 10
  512. ws.send(str(progress))
  513. sub_list=generate_subtitle_image(name_hash,text_content)
  514. progress = 20
  515. ws.send(str(progress))
  516. progress_per_video = int(40/len(text_content))
  517. for fname in range(len(text_content)):
  518. call_achor_video_v2(name_hash+"/"+str(fname))
  519. progress += progress_per_video
  520. ws.send(str(progress))
  521. print('step finish')
  522. print('called............................................')
  523. ck=cKey(0,254,0,150)
  524. ck_anchor=cKey(0,255,1,320)
  525. duration = 0
  526. #average layer level is 3
  527. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  528. t.Open()
  529. main_timer = 0
  530. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP.mp4")
  531. LOGO_OP.Open() # Open the reader
  532. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  533. ,location_y=-0.03,scale_x=0.8,scale_y=0.71)
  534. t.AddClip(LOGO_OP_clip)
  535. bg_head = openshot.FFmpegReader(dir_video+"bg_head.avi")
  536. bg_head.Open()
  537. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  538. t.AddClip(bg_head_clip)
  539. main_timer += LOGO_OP.info.duration
  540. head_duration = LOGO_OP.info.duration
  541. bg_head.Close()
  542. LOGO_OP.Close()
  543. progress += 10
  544. clip_duration=0
  545. photo_clip_list = [None]*len(text_content)
  546. img_list = [None]*len(text_content)
  547. anchor_clip_list = [None] * len(text_content)
  548. anchor_list = [None] * len(text_content)
  549. audio_clip_list = [None] * len(text_content)
  550. audio_list = [None] * len(text_content)
  551. sub_clip_list = [None] * len(text_content)
  552. sub_img_list = [None] * len(text_content)
  553. idx = 0
  554. for p in listdir(dir_photo+name_hash):
  555. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  556. clip_duration = anchor_list[idx].info.duration
  557. anchor_list[idx].Open()
  558. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  559. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  560. t.AddClip(anchor_clip_list[idx])
  561. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  562. img_list[idx].Open()
  563. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  564. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  565. t.AddClip(photo_clip_list[idx])
  566. img_list[idx].Close()
  567. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  568. audio_list[idx].Open()
  569. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  570. audio_clip_list[idx].Position(main_timer)
  571. audio_clip_list[idx].End(clip_duration)
  572. t.AddClip(audio_clip_list[idx])
  573. img_list[idx].Close()
  574. anchor_list[idx].Close()
  575. audio_list[idx].Close()
  576. sub_img_list[idx] = [None] * len(sub_list[idx])
  577. sub_clip_list[idx] = [None] * len(sub_list[idx])
  578. sub_timer = 0
  579. for sub_idx in range(len(sub_list[idx])):
  580. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  581. sub_img_list[idx][sub_idx].Open()
  582. sub_duration = 0.205*sub_list[idx][sub_idx]['count']
  583. 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)
  584. t.AddClip(sub_clip_list[idx][sub_idx])
  585. sub_img_list[idx][sub_idx].Close()
  586. sub_timer += sub_duration
  587. print(sub_list[idx][sub_idx]['path'])
  588. main_timer += clip_duration
  589. idx+=1
  590. progress+=10
  591. ws.send(str(progress))
  592. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  593. LOGO_ED.Open()
  594. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration
  595. ,location_y=-0.03,scale_x=0.8,scale_y=0.71)
  596. t.AddClip(LOGO_ED_clip)
  597. ED_duration = LOGO_ED.info.duration
  598. LOGO_ED.Close()
  599. bg = openshot.FFmpegReader(dir_video+"bg.mp4")
  600. bg.Open()
  601. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  602. left_time = (main_timer+ED_duration) % bg.info.duration
  603. bg_clip_list = [None] * bg_times
  604. bg_list = [None] * bg_times
  605. bg.Close()
  606. bg_timer = head_duration
  607. for idx in range(bg_times):
  608. bg_list[idx] = openshot.FFmpegReader(dir_video+"bg.mp4")
  609. bg_list[idx].Open()
  610. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  611. ,end=bg_list[idx].info.duration,ck=ck)
  612. t.AddClip(bg_clip_list[idx])
  613. bg_timer += bg_list[idx].info.duration
  614. bg_list[idx].Close()
  615. bg_left = openshot.FFmpegReader(dir_video+"bg.mp4")
  616. bg_left.Open()
  617. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  618. t.AddClip(bg_left_clip)
  619. bg_left.Close()
  620. title = openshot.QtImageReader(dir_title+name_hash+".png")
  621. title.Open() # Open the reader
  622. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  623. t.AddClip(title_clip)
  624. ####start building
  625. w = openshot.FFmpegWriter("../html/"+name_hash+".mp4")
  626. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  627. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  628. openshot.Fraction(1, 1), False, False, 3000000)
  629. w.Open()
  630. #may change duration into t.info.duration
  631. for n in range(int(t.info.fps)*int(head_duration+main_timer+ED_duration)):
  632. f=t.GetFrame(n)
  633. w.WriteFrame(f)
  634. t.Close()
  635. w.Close()
  636. print("Raw Video done")
  637. print("video at : www.choozmo.com:8168/"+name_hash+".mp4")
  638. progress = 100
  639. ws.send(str(progress))
  640. ws.close()
  641. #line notifs
  642. #notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+name_hash+".mp4")