main.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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. avatar: str
  56. class ConnectionManager:
  57. def __init__(self):
  58. self.active_connections: List[WebSocket] = []
  59. async def connect(self, websocket: WebSocket):
  60. await websocket.accept()
  61. self.active_connections.append(websocket)
  62. def disconnect(self, websocket: WebSocket):
  63. self.active_connections.remove(websocket)
  64. async def send_personal_message(self, message: str, websocket: WebSocket):
  65. await websocket.send_text(message)
  66. async def broadcast(self, message: str):
  67. for connection in self.active_connections:
  68. await connection.send_text(message)
  69. manager = ConnectionManager()
  70. @app.get("/")
  71. async def root():
  72. return {"message": "Hello, this is index"}
  73. @app.get("/index2")
  74. async def index2():
  75. return FileResponse('index2.html')
  76. @app.get("/index3")
  77. async def index2():
  78. return FileResponse('index3.html')
  79. @app.get("/script_msg.js")
  80. async def index2():
  81. return FileResponse('script_msg.js')
  82. @app.get("/script_msg2.js")
  83. async def index2():
  84. return FileResponse('script_msg2.js')
  85. @app.get("/style.css")
  86. async def index2():
  87. return FileResponse('style.css')
  88. @app.get("/progress_page")
  89. async def progress_page():
  90. return FileResponse('progress.html')
  91. @app.post("/make_anchor_video_v2")
  92. async def make_anchor_video_v2(req:request):
  93. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/AI_anchor?charset=utf8mb4')
  94. log_table = db['history_input']
  95. txt_content_seperate_by_dot = ''
  96. for txt in req.text_content:
  97. txt_content_seperate_by_dot += txt+","
  98. txt_content_seperate_by_dot = txt_content_seperate_by_dot[:-1]
  99. img_urls_seperate_by_dot = ''
  100. for iurl in req.image_urls:
  101. img_urls_seperate_by_dot += iurl+","
  102. img_urls_seperate_by_dot = img_urls_seperate_by_dot[:-1]
  103. time_stamp = datetime.fromtimestamp(time.time())
  104. time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
  105. pk = log_table.insert({'name':req.name,'text_content':txt_content_seperate_by_dot,'image_urls':img_urls_seperate_by_dot,'timestamp':time_stamp})
  106. x = threading.Thread(target=anchor_video_v2, args=(req.name, req.text_content, req.image_urls,int(req.avatar)))
  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,avatar):
  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. ros.system('./p'+str(avatar)+'.sh '+str(val)+' &')
  323. while True:
  324. print('waiting...')
  325. if ros.path.exists('/tmp/results/'+str(val)):
  326. break
  327. time.sleep(5)
  328. print('waiting...')
  329. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  330. fw=open(dir_anchor+fileName+".mp4",'wb')#peggy1_1
  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. def call_achor_video(name):
  340. conn = rpyc.classic.connect("192.168.1.105",18812)
  341. ros = conn.modules.os
  342. rsys = conn.modules.sys
  343. fr=open(dir_sound+name+".mp3",'rb')# voice
  344. #warning!!! file my be replaced by other process
  345. fw=conn.builtins.open('/tmp/output.mp3','wb')
  346. while True:
  347. b=fr.read(1024)
  348. if b:
  349. fw.write(b)
  350. else:
  351. break
  352. fr.close()
  353. fw.close()
  354. val=random.randint(1000000,9999999)
  355. ros.chdir('/home/jared/to_video')
  356. ros.system('./p6.sh '+str(val)+' &')
  357. while True:
  358. print('waiting...')
  359. if ros.path.exists('/tmp/results/'+str(val)):
  360. break
  361. time.sleep(15)
  362. print('waiting...')
  363. fr=conn.builtins.open('/tmp/results/'+str(val)+'.mp4','rb')
  364. fw=open(dir_anchor+name+'.mp4','wb')#peggy1_1
  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. print('called..............................................')
  374. def trim_punctuation(s):
  375. pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
  376. pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
  377. res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u"" ,s)
  378. return res
  379. def splitter(s):
  380. for sent in re.findall(u'[^!?,。\!\?]+[!?。\!\?]?', s, flags=re.U):
  381. yield sent
  382. def split_by_pun(s):
  383. res = list(splitter(s))
  384. return res
  385. def generate_subtitle_image(name_hash,text_content):
  386. img_list = [None]*len(text_content)
  387. for idx in range(len(text_content)):
  388. img_list[idx]=[]
  389. senList = split_by_pun(text_content[idx])
  390. for inner_idx in range(len(senList)):
  391. sv_path = dir_subtitle + name_hash +'/'+str(idx)+ str(inner_idx) +'.png'
  392. sub = senList[inner_idx]
  393. txt2image(sub,sv_path)
  394. img_list[idx]+=[{"count":len(sub),"path":sv_path}]
  395. return img_list
  396. def anchor_video_v2(name,text_content, image_urls,avatar):
  397. #ws = create_connection("ws://www.choozmo.com:8888/progress")
  398. progress = 0
  399. name_hash = str(time.time()).replace('.','')
  400. print('sub image made')
  401. file_prepare_v2(name, name_hash, text_content,image_urls)
  402. progress = 10
  403. #ws.send(str(progress))
  404. sub_list=generate_subtitle_image(name_hash,text_content)
  405. progress = 20
  406. #ws.send(str(progress))
  407. progress_per_video = int(40/len(text_content))
  408. for fname in range(len(text_content)):
  409. call_achor_video_v2(name_hash+"/"+str(fname),avatar)
  410. progress += progress_per_video
  411. #ws.send(str(progress))
  412. print('step finish')
  413. print('called............................................')
  414. ck=cKey(0,254,0,270)
  415. ck_anchor=cKey(0,255,1,320)
  416. duration = 0
  417. #average layer level is 3
  418. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  419. t.Open()
  420. main_timer = 0
  421. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP.mp4")
  422. LOGO_OP.Open() # Open the reader
  423. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  424. ,location_y=-0.03,scale_x=0.8,scale_y=0.704)
  425. t.AddClip(LOGO_OP_clip)
  426. bg_head = openshot.FFmpegReader(dir_video+"bg_head.avi")
  427. bg_head.Open()
  428. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  429. t.AddClip(bg_head_clip)
  430. main_timer += LOGO_OP.info.duration
  431. head_duration = LOGO_OP.info.duration
  432. bg_head.Close()
  433. LOGO_OP.Close()
  434. progress += 10
  435. clip_duration=0
  436. photo_clip_list = [None]*len(text_content)
  437. img_list = [None]*len(text_content)
  438. anchor_clip_list = [None] * len(text_content)
  439. anchor_list = [None] * len(text_content)
  440. audio_clip_list = [None] * len(text_content)
  441. audio_list = [None] * len(text_content)
  442. sub_clip_list = [None] * len(text_content)
  443. sub_img_list = [None] * len(text_content)
  444. idx = 0
  445. for p in listdir(dir_photo+name_hash):
  446. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  447. clip_duration = anchor_list[idx].info.duration
  448. anchor_list[idx].Open()
  449. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  450. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  451. t.AddClip(anchor_clip_list[idx])
  452. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  453. img_list[idx].Open()
  454. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  455. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  456. t.AddClip(photo_clip_list[idx])
  457. img_list[idx].Close()
  458. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  459. audio_list[idx].Open()
  460. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  461. audio_clip_list[idx].Position(main_timer)
  462. audio_clip_list[idx].End(clip_duration)
  463. t.AddClip(audio_clip_list[idx])
  464. img_list[idx].Close()
  465. anchor_list[idx].Close()
  466. audio_list[idx].Close()
  467. sub_img_list[idx] = [None] * len(sub_list[idx])
  468. sub_clip_list[idx] = [None] * len(sub_list[idx])
  469. sub_timer = 0
  470. for sub_idx in range(len(sub_list[idx])):
  471. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  472. sub_img_list[idx][sub_idx].Open()
  473. sub_duration = 0.205*sub_list[idx][sub_idx]['count']
  474. 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)
  475. t.AddClip(sub_clip_list[idx][sub_idx])
  476. sub_img_list[idx][sub_idx].Close()
  477. sub_timer += sub_duration
  478. print(sub_list[idx][sub_idx]['path'])
  479. main_timer += clip_duration
  480. idx+=1
  481. progress+=10
  482. #ws.send(str(progress))
  483. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  484. LOGO_ED.Open()
  485. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration+2
  486. ,location_x=0.005,location_y=-0.031
  487. ,scale_x=0.8,scale_y=0.6825)
  488. t.AddClip(LOGO_ED_clip)
  489. ED_duration = LOGO_ED.info.duration
  490. LOGO_ED.Close()
  491. bg = openshot.FFmpegReader(dir_video+"bg.mp4")
  492. bg.Open()
  493. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  494. left_time = (main_timer+ED_duration) % bg.info.duration
  495. bg_clip_list = [None] * bg_times
  496. bg_list = [None] * bg_times
  497. bg.Close()
  498. bg_timer = head_duration
  499. for idx in range(bg_times):
  500. bg_list[idx] = openshot.FFmpegReader(dir_video+"bg.mp4")
  501. bg_list[idx].Open()
  502. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  503. ,end=bg_list[idx].info.duration,ck=ck)
  504. t.AddClip(bg_clip_list[idx])
  505. bg_timer += bg_list[idx].info.duration
  506. bg_list[idx].Close()
  507. bg_left = openshot.FFmpegReader(dir_video+"bg.mp4")
  508. bg_left.Open()
  509. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  510. t.AddClip(bg_left_clip)
  511. bg_left.Close()
  512. title = openshot.QtImageReader(dir_title+name_hash+".png")
  513. title.Open() # Open the reader
  514. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  515. t.AddClip(title_clip)
  516. ####start building
  517. w = openshot.FFmpegWriter("../html/"+name_hash+".mp4")
  518. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  519. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  520. openshot.Fraction(1, 1), False, False, 3000000)
  521. w.Open()
  522. progress = 100
  523. #ws.send(str(progress))
  524. #may change duration into t.info.duration
  525. for n in range(int(t.info.fps)*int(head_duration+main_timer+ED_duration)):
  526. f=t.GetFrame(n)
  527. w.WriteFrame(f)
  528. notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+name_hash+".mp4")
  529. t.Close()
  530. w.Close()
  531. print("Raw Video done")
  532. print("video at : www.choozmo.com:8168/"+name_hash+".mp4")
  533. #line notifs
  534. def anchor_video_v3333(name,text_content, image_urls,avatar):
  535. ws = create_connection("ws://www.choozmo.com:8888/progress")
  536. progress = 0
  537. name_hash = str(time.time()).replace('.','')
  538. print('sub image made')
  539. file_prepare_v2(name, name_hash, text_content,image_urls)
  540. progress = 10
  541. ws.send(str(progress))
  542. sub_list=generate_subtitle_image(name_hash,text_content)
  543. progress = 20
  544. ws.send(str(progress))
  545. progress_per_video = int(40/len(text_content))
  546. for fname in range(len(text_content)):
  547. call_achor_video_v2(name_hash+"/"+str(fname))
  548. progress += progress_per_video
  549. ws.send(str(progress))
  550. print('step finish')
  551. print('called............................................')
  552. ck=cKey(0,254,0,270)
  553. ck_anchor=cKey(0,255,1,320)
  554. duration = 0
  555. #average layer level is 3
  556. t = openshot.Timeline(1280, 720, openshot.Fraction(30000, 1000), 44100, 2, openshot.LAYOUT_STEREO)
  557. t.Open()
  558. main_timer = 0
  559. LOGO_OP = openshot.FFmpegReader(dir_video+"LOGO_OP.mp4")
  560. LOGO_OP.Open() # Open the reader
  561. LOGO_OP_clip = video_photo_clip(vid=LOGO_OP,layer=4,position=0,end=LOGO_OP.info.duration
  562. ,location_y=-0.03,scale_x=0.8,scale_y=0.71)
  563. t.AddClip(LOGO_OP_clip)
  564. bg_head = openshot.FFmpegReader(dir_video+"bg_head.avi")
  565. bg_head.Open()
  566. bg_head_clip = video_photo_clip(vid=bg_head,layer=2,position=0,end=LOGO_OP.info.duration,ck=ck)
  567. t.AddClip(bg_head_clip)
  568. main_timer += LOGO_OP.info.duration
  569. head_duration = LOGO_OP.info.duration
  570. bg_head.Close()
  571. LOGO_OP.Close()
  572. progress += 10
  573. clip_duration=0
  574. photo_clip_list = [None]*len(text_content)
  575. img_list = [None]*len(text_content)
  576. anchor_clip_list = [None] * len(text_content)
  577. anchor_list = [None] * len(text_content)
  578. audio_clip_list = [None] * len(text_content)
  579. audio_list = [None] * len(text_content)
  580. sub_clip_list = [None] * len(text_content)
  581. sub_img_list = [None] * len(text_content)
  582. idx = 0
  583. for p in listdir(dir_photo+name_hash):
  584. anchor_list[idx] = openshot.FFmpegReader(dir_anchor+name_hash+"/"+str(idx)+".mp4")
  585. clip_duration = anchor_list[idx].info.duration
  586. anchor_list[idx].Open()
  587. anchor_clip_list[idx] = video_photo_clip(vid=anchor_list[idx],layer=4,scale_x=0.65,scale_y=0.65,
  588. location_x=0.35,location_y=0.25,position=main_timer, end=clip_duration,ck=ck_anchor,audio=False)
  589. t.AddClip(anchor_clip_list[idx])
  590. img_list[idx] = openshot.FFmpegReader(dir_photo+name_hash+'/'+p)
  591. img_list[idx].Open()
  592. photo_clip_list[idx] = video_photo_clip(vid=img_list[idx],layer=3
  593. ,scale_x=0.81,scale_y=0.68,location_y=-0.03,position=main_timer,end=clip_duration,audio=False)
  594. t.AddClip(photo_clip_list[idx])
  595. img_list[idx].Close()
  596. audio_list[idx] = openshot.FFmpegReader(dir_sound+name_hash+"/"+str(idx)+".mp3")
  597. audio_list[idx].Open()
  598. audio_clip_list[idx] = openshot.Clip(audio_list[idx])
  599. audio_clip_list[idx].Position(main_timer)
  600. audio_clip_list[idx].End(clip_duration)
  601. t.AddClip(audio_clip_list[idx])
  602. img_list[idx].Close()
  603. anchor_list[idx].Close()
  604. audio_list[idx].Close()
  605. sub_img_list[idx] = [None] * len(sub_list[idx])
  606. sub_clip_list[idx] = [None] * len(sub_list[idx])
  607. sub_timer = 0
  608. for sub_idx in range(len(sub_list[idx])):
  609. sub_img_list[idx][sub_idx] = openshot.QtImageReader(sub_list[idx][sub_idx]['path'])
  610. sub_img_list[idx][sub_idx].Open()
  611. sub_duration = 0.205*sub_list[idx][sub_idx]['count']
  612. 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)
  613. t.AddClip(sub_clip_list[idx][sub_idx])
  614. sub_img_list[idx][sub_idx].Close()
  615. sub_timer += sub_duration
  616. print(sub_list[idx][sub_idx]['path'])
  617. main_timer += clip_duration
  618. idx+=1
  619. progress+=10
  620. ws.send(str(progress))
  621. LOGO_ED = openshot.FFmpegReader(dir_video+"LOGO_ED.avi")
  622. LOGO_ED.Open()
  623. LOGO_ED_clip = video_photo_clip(vid=LOGO_ED,layer=4,position=main_timer,end=LOGO_ED.info.duration+2
  624. ,location_x=0,location_y=-0.02
  625. ,scale_x=0.79,scale_y=0.685)
  626. t.AddClip(LOGO_ED_clip)
  627. ED_duration = LOGO_ED.info.duration
  628. LOGO_ED.Close()
  629. bg = openshot.FFmpegReader(dir_video+"bg.mp4")
  630. bg.Open()
  631. bg_times = math.floor(main_timer+ED_duration/bg.info.duration)
  632. left_time = (main_timer+ED_duration) % bg.info.duration
  633. bg_clip_list = [None] * bg_times
  634. bg_list = [None] * bg_times
  635. bg.Close()
  636. bg_timer = head_duration
  637. for idx in range(bg_times):
  638. bg_list[idx] = openshot.FFmpegReader(dir_video+"bg.mp4")
  639. bg_list[idx].Open()
  640. bg_clip_list[idx] = video_photo_clip(bg_list[idx],layer=2,position=bg_timer
  641. ,end=bg_list[idx].info.duration,ck=ck)
  642. t.AddClip(bg_clip_list[idx])
  643. bg_timer += bg_list[idx].info.duration
  644. bg_list[idx].Close()
  645. bg_left = openshot.FFmpegReader(dir_video+"bg.mp4")
  646. bg_left.Open()
  647. bg_left_clip = video_photo_clip(bg_left,layer=2,position=bg_timer,end=left_time,ck=ck)
  648. t.AddClip(bg_left_clip)
  649. bg_left.Close()
  650. title = openshot.QtImageReader(dir_title+name_hash+".png")
  651. title.Open() # Open the reader
  652. title_clip = video_photo_clip(vid=title, layer=4,location_x=-0.047, location_y=0.801,position=0,end=head_duration+main_timer)
  653. t.AddClip(title_clip)
  654. ####start building
  655. w = openshot.FFmpegWriter("../html/"+name_hash+".mp4")
  656. w.SetAudioOptions(True, "aac", 44100, 2, openshot.LAYOUT_STEREO, 3000000)
  657. w.SetVideoOptions(True, "libx264", openshot.Fraction(30000, 1000), 1280, 720,
  658. openshot.Fraction(1, 1), False, False, 3000000)
  659. w.Open()
  660. progress = 100
  661. ws.send(str(progress))
  662. #may change duration into t.info.duration
  663. for n in range(int(t.info.fps)*int(head_duration+main_timer+ED_duration)):
  664. f=t.GetFrame(n)
  665. w.WriteFrame(f)
  666. #notify_group(name+"的影片已經產生完成囉! www.choozmo.com:8168/"+name_hash+".mp4")
  667. t.Close()
  668. w.Close()
  669. print("Video done")
  670. print("video at : www.choozmo.com:8168/"+name_hash+".mp4")
  671. #line notifs