main.py 27 KB

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