main.py 27 KB

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