main.py 28 KB

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