main.py 27 KB

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