main.py 28 KB

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