main.py 20 KB

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