main.py 21 KB

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