main.py 27 KB

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