main.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. from fastapi.staticfiles import StaticFiles
  30. #service nginx restart
  31. #uvicorn main:app --host="0.0.0.0" --reload --port 8888
  32. app = FastAPI()
  33. origins = [
  34. "https://hhh.com.tw"
  35. "http://172.105.205.52",
  36. "http://172.105.205.52:8001",
  37. "http://172.104.93.163",
  38. ]
  39. app.add_middleware(
  40. CORSMiddleware,
  41. # allow_origins=origins,
  42. allow_origins=["*"],
  43. allow_credentials=True,
  44. allow_methods=["*"],
  45. allow_headers=["*"],
  46. )
  47. app.mount("/static", StaticFiles(directory="static"), name="static")
  48. app.mount("/static/img", StaticFiles(directory="static/img"), name="static/img")
  49. dir_sound = 'mp3_track/'
  50. dir_photo = 'photo/'
  51. dir_text = 'text_file/'
  52. dir_video = 'video_material/'
  53. dir_title = 'title/'
  54. dir_subtitle = 'subtitle/'
  55. dir_anchor = 'anchor_raw/'
  56. class swap_req(BaseModel):
  57. imgurl: str
  58. class request(BaseModel):
  59. name: str
  60. text_content: List[str]
  61. image_urls: List[str]
  62. avatar: str
  63. client_id :str
  64. class ConnectionManager:
  65. def __init__(self):
  66. self.active_connections: List[WebSocket] = []
  67. async def connect(self, websocket: WebSocket):
  68. await websocket.accept()
  69. self.active_connections.append(websocket)
  70. def disconnect(self, websocket: WebSocket):
  71. self.active_connections.remove(websocket)
  72. async def send_personal_message(self, message: str, websocket: WebSocket):
  73. await websocket.send_text(message)
  74. async def broadcast(self, message: str):
  75. for connection in self.active_connections:
  76. await connection.send_text(message)
  77. @app.get("/")
  78. async def root():
  79. return {"message": "Hello, this is index"}
  80. @app.get("/index2")
  81. async def index2():
  82. return FileResponse('static/index2.html')
  83. @app.get("/gen_avatar")
  84. async def index2():
  85. return FileResponse('gen_avatar.html')
  86. @app.post("/swapFace")
  87. async def swapFace(req:swap_req):
  88. sf = swap_face(req.imgurl)
  89. result = sf.run()
  90. #notify_group(result)hi
  91. return result
  92. @app.post("/make_anchor_video_v2")
  93. async def make_anchor_video_v2(req:request):
  94. for txt in req.text_content:
  95. if re.search('[a-zA-Z]', txt) !=None:
  96. return {'msg':'輸入字串不能包含英文字!'}
  97. name_hash = str(time.time()).replace('.','')
  98. for imgu in req.image_urls:
  99. try:
  100. if get_url_type(imgu) =='video/mp4':
  101. r=requests.get(imgu)
  102. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  103. else:
  104. im = Image.open(requests.get(imgu, stream=True).raw)
  105. im= im.convert("RGB")
  106. except:
  107. return {'msg':"無法辨別圖片網址"+imgu}
  108. save_history(req,name_hash)
  109. x = threading.Thread(target=anchor_video_v2, args=(name_hash,req.name, req.text_content, req.image_urls,int(req.avatar),req.client_id))
  110. x.start()
  111. return {"msg":"製作影片需要時間,請您耐心等候 稍後可以在www.choozmo.com:8168/"+name_hash+".mp4 中觀看"}
  112. manager = ConnectionManager()
  113. @app.websocket("/progress/{client_id}")
  114. async def websocket_endpoint(websocket: WebSocket, client_id: int):
  115. await manager.connect(websocket)
  116. try:
  117. while True:
  118. data = await websocket.receive_text()
  119. await manager.send_personal_message(data, websocket)
  120. await manager.broadcast(data)
  121. except WebSocketDisconnect:
  122. manager.disconnect(websocket)
  123. @app.get("/history_input")
  124. async def history_input():
  125. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  126. statement = 'SELECT * FROM history_input ORDER BY timestamp DESC LIMIT 50'
  127. logs = []
  128. for row in db.query(statement):
  129. logs.append({'id':row['id'],'name':row['name'],'text_content':row['text_content'].split(','),'link':row['link'],'image_urls':row['image_urls'].split(',')})
  130. return logs
  131. def notify_group(msg):
  132. glist=['7vilzohcyQMPLfAMRloUawiTV4vtusZhxv8Czo7AJX8','WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD','1dbtJHbWVbrooXmQqc4r8OyRWDryjD4TMJ6DiDsdgsX']
  133. for gid in glist:
  134. headers = {
  135. "Authorization": "Bearer " + gid,
  136. "Content-Type": "application/x-www-form-urlencoded"
  137. }
  138. params = {"message": msg}
  139. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  140. def save_history(req,name_hash):
  141. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  142. log_table = db['history_input']
  143. txt_content_seperate_by_dot = ''
  144. for txt in req.text_content:
  145. txt_content_seperate_by_dot += txt+","
  146. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  147. img_urls_seperate_by_dot = ''
  148. for iurl in req.image_urls:
  149. img_urls_seperate_by_dot += iurl+","
  150. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  151. time_stamp = datetime.fromtimestamp(time.time())
  152. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  153. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'link':'www.choozmo.com:8168/'+name_hash+'.mp4','timestamp':time_stamp})
  154. def cKey(r,g,b,fuzz):
  155. col=openshot.Color()
  156. col.red=openshot.Keyframe(r)
  157. col.green=openshot.Keyframe(g)
  158. col.blue=openshot.Keyframe(b)
  159. return openshot.ChromaKey(col, openshot.Keyframe(fuzz))
  160. def video_photo_clip(vid=None,layer=None, position=None, end=None
  161. ,scale_x=1,scale_y=1,location_x=0,location_y=0,ck=None,audio=True):
  162. clip = openshot.Clip(vid)
  163. clip.Layer(layer)
  164. clip.Position(position)
  165. clip.End(end)
  166. clip.scale_x=openshot.Keyframe(scale_x)
  167. clip.scale_y=openshot.Keyframe(scale_y)
  168. clip.location_x=openshot.Keyframe(location_x)
  169. clip.location_y=openshot.Keyframe(location_y)
  170. if ck!=None:
  171. clip.AddEffect(ck)
  172. if audio==True:
  173. clip.has_audio=openshot.Keyframe(1)
  174. else:
  175. clip.has_audio=openshot.Keyframe(0)
  176. return clip
  177. def myunichchar(unicode_char):
  178. mb_string = unicode_char.encode('big5')
  179. try:
  180. unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
  181. except NameError:
  182. unicode_char = chr(mb_string[0] << 8 | mb_string[1])
  183. return unicode_char
  184. def file_prepare(name, name_hash,text_content,image_urls):
  185. #save image
  186. try:
  187. os.mkdir(dir_photo+name_hash)
  188. except FileExistsError:
  189. print("Directory " , dir_photo+name_hash , " already exists")
  190. img_num = 1
  191. for imgu in image_urls:
  192. im = Image.open(requests.get(imgu, stream=True).raw)
  193. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  194. img_num+=1
  195. #save text
  196. text_file = open(dir_text+name_hash+".txt", "w")
  197. text_file.write(text_content)
  198. text_file.close()
  199. print("text file made")
  200. #make mp3
  201. tts = zhtts.TTS()
  202. tts.text2wav(text_content,dir_sound+name_hash+".mp3")
  203. print("mp3 file made")
  204. #make title as image
  205. txt2image(name, dir_title+name_hash+".png")
  206. def get_url_type(url):
  207. req = urllib.request.Request(url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'})
  208. r = urllib.request.urlopen(req)
  209. contentType = r.getheader('Content-Type')
  210. return contentType
  211. def downloadfile(name,url):
  212. name=name+".mp4"
  213. def make_dir(name_hash):
  214. #save image
  215. try:
  216. os.mkdir(dir_photo+name_hash)
  217. except FileExistsError:
  218. print("~~~~~~Warning~~~~~~~~~Directory " , dir_photo+name_hash , " already exists")
  219. try:
  220. os.mkdir(dir_text+name_hash)
  221. except FileExistsError:
  222. print("~~~~~~Warning~~~~~~~~~Directory " , dir_text+name_hash , " already exists")
  223. try:
  224. os.mkdir(dir_sound+name_hash)
  225. except FileExistsError:
  226. print("~~~~~~Warning~~~~~~~~~Directory " , dir_sound+name_hash , " already exists")
  227. try:
  228. os.mkdir(dir_video+name_hash)
  229. except FileExistsError:
  230. print("~~~~~~Warning~~~~~~~~~Directory " , dir_video+name_hash , " already exists")
  231. try:
  232. os.mkdir(dir_anchor+name_hash)
  233. except FileExistsError:
  234. print("~~~~~~Warning~~~~~~~~~Directory " , dir_anchor+name_hash , " already exists")
  235. try:
  236. os.mkdir(dir_subtitle+name_hash)
  237. except FileExistsError:
  238. print("~~~~~~Warning~~~~~~~~~Directory " , dir_subtitle+name_hash , " already exists")
  239. def file_prepare_v2(name, name_hash,text_content,image_urls):
  240. make_dir(name_hash)
  241. img_num = 1
  242. for imgu in image_urls:
  243. if get_url_type(imgu) =='video/mp4':
  244. r=requests.get(imgu)
  245. f=open(dir_photo+name_hash+"/"+str(img_num)+".mp4",'wb')
  246. for chunk in r.iter_content(chunk_size=255):
  247. if chunk:
  248. f.write(chunk)
  249. f.close()
  250. else:
  251. im = Image.open(requests.get(imgu, stream=True).raw)
  252. im= im.convert("RGB")
  253. im.save(dir_photo+name_hash+"/"+str(img_num)+".jpg")
  254. img_num+=1
  255. #save text
  256. txt_idx=0
  257. for txt in text_content:
  258. text_file = open(dir_text+name_hash+"/"+str(txt_idx)+".txt", "w")
  259. text_file.write(txt)
  260. text_file.close()
  261. txt_idx+=1
  262. print("text file made")
  263. #make mp3
  264. language = 'zh-tw'
  265. txt_idx = 0
  266. for txt in text_content:
  267. tts = zhtts.TTS()
  268. tts.text2wav(txt,dir_sound+name_hash+"/"+str(txt_idx)+".mp3")
  269. txt_idx+=1
  270. print("mp3 file made")
  271. #make title as image
  272. txt2image_title(name, dir_title+name_hash+".png")
  273. def txt2image(content, save_target):
  274. unicode_text = trim_punctuation(content)
  275. font = ImageFont.truetype(font="DFT_B7.ttc", size=38)
  276. text_width, text_height = font.getsize(unicode_text)
  277. canvas = Image.new('RGBA', (700, 500), (255, 0, 0, 0) )
  278. draw = ImageDraw.Draw(canvas)
  279. text= unicode_text
  280. draw.text((5,5), text, (255, 255, 0), font)
  281. canvas.save(save_target, "PNG")
  282. def txt2image_title(content, save_target):
  283. unicode_text = trim_punctuation(content)
  284. font = ImageFont.truetype(font="DFT_B7.ttc", size=28)
  285. text_width, text_height = font.getsize(unicode_text)
  286. canvas = Image.new('RGBA', (510, 500), (255, 0, 0, 0) )
  287. draw = ImageDraw.Draw(canvas)
  288. text= unicode_text
  289. draw.text((5,5), text, (17, 41, 167), font)
  290. canvas.save(save_target, "PNG")
  291. '''
  292. def txt2image_title(content, save_target):
  293. unicode_text =content
  294. font = ImageFont.truetype("font.ttf", 23,encoding='big5')
  295. text_width, text_height = font.getsize(unicode_text)
  296. canvas = Image.new('RGBA', (500, 500), (255, 0, 0, 0) )
  297. draw = ImageDraw.Draw(canvas)
  298. text=''
  299. for c in unicode_text:
  300. if len(re.findall(r'[\u4e00-\u9fff]+', c))>0:
  301. text+=myunichchar(c)
  302. else:
  303. text+=c
  304. draw.text((5,5), text, (17, 41, 167), font)
  305. canvas.save(save_target, "PNG")
  306. '''
  307. def call_anchor(fileName,avatar):
  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+fileName+".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('./p'+str(avatar)+'.sh '+str(val)+' &')
  325. while True:
  326. print('waiting...')
  327. if ros.path.exists('/tmp/results/'+str(val)):
  328. break
  329. time.sleep(5)
  330. print('waiting...')
  331. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  332. fw=open(dir_anchor+fileName+".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. def trim_punctuation(s):
  342. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
  343. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  344. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u"" ,s)
  345. return res
  346. def splitter(s):
  347. for sent in re.findall(u'[^!?,。\!\?]+[!?。\!\?]?', s, flags=re.U):
  348. yield sent
  349. def split_by_pun(s):
  350. res = list(splitter(s))
  351. return res
  352. def generate_subtitle_image(name_hash,text_content):
  353. img_list = [None]*len(text_content)
  354. for idx in range(len(text_content)):
  355. img_list[idx]=[]
  356. senList = split_by_pun(text_content[idx])
  357. for inner_idx in range(len(senList)):
  358. sv_path = dir_subtitle + name_hash +'/'+str(idx)+ str(inner_idx) +'.png'
  359. sub = senList[inner_idx]
  360. txt2image(sub,sv_path)
  361. img_list[idx]+=[{"count":len(sub),"path":sv_path}]
  362. return img_list
  363. async def sendProgress(progress,client_id):
  364. ws = create_connection("ws://www.choozmo.com:8888/progress/"+client_id)
  365. ws.send(str(progress))
  366. ws.close()
  367. def anchor_video_v2(name_hash,name,text_content, image_urls,avatar,client_id):
  368. progress = 0
  369. asyncio.run(sendProgress(progress,client_id))
  370. print('sub image made')
  371. file_prepare_v2(name, name_hash, text_content,image_urls)
  372. progress = 20
  373. asyncio.run(sendProgress(progress,client_id))
  374. sub_list=generate_subtitle_image(name_hash,text_content)
  375. progress = 30
  376. asyncio.run(sendProgress(progress,client_id))
  377. progress_per_video = int(40/len(text_content))
  378. for fname in range(len(text_content)):
  379. call_anchor(name_hash+"/"+str(fname),avatar)
  380. progress += progress_per_video
  381. print('step finish')
  382. asyncio.run(sendProgress(progress,client_id))
  383. print('called............................................')
  384. ck=cKey(0,254,0,270)
  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.704)
  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. asyncio.run(sendProgress(progress,client_id))
  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+2
  456. ,location_x=0.005,location_y=-0.031
  457. ,scale_x=0.8,scale_y=0.6825)
  458. t.AddClip(LOGO_ED_clip)
  459. ED_duration = LOGO_ED.info.duration
  460. LOGO_ED.Close()
  461. bg = openshot.FFmpegReader(dir_video+"bg.mp4")
  462. bg.Open()
  463. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  464. left_time = (main_timer+ED_duration) % bg.info.duration
  465. bg_clip_list = [None] * bg_times
  466. bg_list = [None] * bg_times
  467. bg.Close()
  468. bg_timer = head_duration
  469. for idx in range(bg_times):
  470. bg_list[idx] = openshot.FFmpegReader(dir_video+"bg.mp4")
  471. bg_list[idx].Open()
  472. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  473. ,end=bg_list[idx].info.duration,ck=ck)
  474. t.AddClip(bg_clip_list[idx])
  475. bg_timer += bg_list[idx].info.duration
  476. bg_list[idx].Close()
  477. bg_left = openshot.FFmpegReader(dir_video+"bg.mp4")
  478. bg_left.Open()
  479. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  480. t.AddClip(bg_left_clip)
  481. bg_left.Close()
  482. title = openshot.QtImageReader(dir_title+name_hash+".png")
  483. title.Open() # Open the reader
  484. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  485. t.AddClip(title_clip)
  486. ####start building
  487. w = openshot.FFmpegWriter("../html/"+name_hash+".mp4")
  488. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  489. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  490. openshot.Fraction(1, 1), False, False, 3000000)
  491. w.Open()
  492. #may change duration into t.info.duration
  493. frames = int(t.info.fps)*int(head_duration+main_timer+ED_duration)
  494. for n in range(frames):
  495. f=t.GetFrame(n)
  496. w.WriteFrame(f)
  497. progress = 100
  498. asyncio.run(sendProgress(progress,client_id))
  499. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+name_hash+".mp4")
  500. t.Close()
  501. w.Close()
  502. progress = 100
  503. asyncio.run(sendProgress(progress,client_id))
  504. print("Raw Video done")
  505. print("video at : www.choozmo.com:8168/"+name_hash+".mp4")
  506. #line notifs