main.py 28 KB

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