main.py 25 KB

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