main.py 27 KB

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