vid-url-dl-mod / app.py
Omnibus's picture
Update app.py
b81a2d5
raw
history blame
8.39 kB
import gradio as gr
import yt_dlp
import os
import json
from rembg import remove as rm
import cv2
import uuid
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
import moviepy.video.io.ImageSequenceClip
uid=uuid.uuid4()
if not os.path.exists(f'{uid}'): os.makedirs(f'{uid}')
if not os.path.exists(f'{uid}-frames'): os.makedirs(f'{uid}-frames')
if not os.path.exists(f'{uid}-rembg'): os.makedirs(f'{uid}-rembg')
load_js = """
function(text_input, url_params) {
console.log(text_input, url_params);
const params = new URLSearchParams(window.location.search);
url_params = Object.fromEntries(params);
return [text_input, url_params]
}
"""
def rem_cv(inp):
cap = cv2.VideoCapture(f'{inp}')
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
fgbg = cv2.bgsegm.createBackgroundSubtractorGMG()
while True:
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
yield (fgmask)
def load_video(vid):
new_video_in = str(vid)
capture = cv2.VideoCapture(new_video_in)
fps = capture.get(cv2.CAP_PROP_FPS)
msc = capture.get(cv2.CAP_PROP_POS_MSEC)
frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
print (msc)
msc = float(frame_count/fps)
print (msc)
capture.release()
vid_t = round(msc)
#if vid_t <=59:
# seconds = vid_t
# minutes = "00"
# hours = "00"
#if vid_t >59 and vid_t <=359:
# if vid_t >59 and vid_t<=360:minutes = (vid_t/60)
hours = int(vid_t/360)
minutes = int(vid_t/60)-(hours*360)
seconds = vid_t-(minutes*60)-(hours*360)
vid_len = f'{hours}:{minutes}:{seconds}'
#vid_len_up = gr.update(label = "End", value = f"{vid_len}", placeholder = "0:00:54")
return frame_count, fps, vid_len
def capture_function(vid):
new_video_in = str(f"{uid}-clip.mp4")
capture = cv2.VideoCapture(new_video_in)
frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
fbox=[]
cnt=0
frame_count1= int(frame_count)
for i in range(int(frame_count1)-1):
capture.set(cv2.CAP_PROP_POS_FRAMES, i)
ret, frame_f = capture.read(i)
#frame_ff = cv2.cvtColor(frame_f, cv2.COLOR_BGR2RGB)
cv2.imwrite(f'{uid}-frames/{i}.png',frame_f)
fbox.append(f'{uid}-frames/{i}.png')
frame_num=f'Working on {i+1} of {frame_count1}'
yield fbox,fbox,frame_num
#return fbox,fbox,frame_num
yield (fbox,fbox,frame_num)
def im_2_vid(images,fps):
#width, height = Image.open(images[0]).size
this_im=cv2.imread(images[0])
height=this_im.shape[0]
width= this_im.shape[1]
print (width,height)
size = (width, height)
movie_clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(images, fps)
movie_clip.write_videofile(f'{uid}-rembg/bg_removed-{uid}.mp4')
#codec = cv2.VideoWriter_fourcc(*'mp4v') #DIVX, DIVD
#video = cv2.VideoWriter("tmp_vid.mp4", codec, fps, size)
#for img in images:
# video.write(img)
return (f'{uid}-rembg/bg_removed-{uid}.mp4', f'{uid}-rembg/bg_removed-{uid}.mp4')
def rem_bg(vid):
new_video_in = str(vid)
capture = cv2.VideoCapture(new_video_in)
frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
fps = capture.get(cv2.CAP_PROP_FPS)
fbox2=[]
cnt=0
frame_count1= int(frame_count)
for i in range(int(frame_count1)-1):
capture.set(cv2.CAP_PROP_POS_FRAMES, i)
ret, frame_f = capture.read(i)
#frame_ff = cv2.cvtColor(frame_f, cv2.COLOR_BGR2RGB)
out = rm(frame_f)
print (i)
cv2.imwrite(f'{uid}-rembg/{i}.png',out)
fbox2.append(f'{uid}-rembg/{i}.png')
frame_num=f'Working on {i+1} of {frame_count1-1}'
yield fbox2,frame_num,None
frame_num=f'Done: {i+1} of {frame_count1}'
out_vid,_file = im_2_vid(fbox2, fps)
yield (fbox2,frame_num,out_vid)
def predict(text, url_params):
mod_url=""
mod=gr.HTML("")
out = None
valid=gr.update(visible=False)
mod_url = url_params.get('url')
print (mod_url)
return ["" + text + "", mod_url]
def dl(inp):
out = None
out_file=[]
try:
inp_out=inp.replace("https://","")
inp_out=inp_out.replace("/","_").replace(".","_")
os.system(f'yt-dlp "{inp}" --trim-filenames 100 -o "{uid}/{inp_out}.mp4"')
out = f"{uid}/{inp_out}.mp4"
except Exception as e:
print (e)
out = None
return out,out,out,out,out
def trim_vid(vid,start_time,end_time):
print (vid)
start_hr=int(start_time.split(":",2)[0])*360
start_min=int(start_time.split(":",2)[1])*60
start_sec=int(start_time.split(":",2)[2])
end_hr=int(end_time.split(":",2)[0])*360
end_min=int(end_time.split(":",2)[1])*60
end_sec=int(end_time.split(":",2)[2])
start=start_hr+start_min+start_sec
end=end_hr+end_min+end_sec
#vid = f"{inp_out}.mp4"
ffmpeg_extract_subclip(vid, start, end, targetname=f"{uid}-clip.mp4")
out= f"{uid}-clip.mp4"
capture = cv2.VideoCapture(out)
frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
capture.release()
return out,out,frame_count
def other():
new_video_in = str(vid)
capture = cv2.VideoCapture(new_video_in)
frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
fps = capture.get(cv2.CAP_PROP_FPS)
fbox3=[]
frame_count1= int(frame_count)
start = (int(fps*int(start_f)))
capture.set(cv2.CAP_PROP_POS_FRAMES, i-1)
for i in range(int(frame_count1)):
capture.set(cv2.CAP_PROP_POS_FRAMES, i)
ret, frame_f = capture.read(i)
#frame_ff = cv2.cvtColor(frame_f, cv2.COLOR_BGR2RGB)
out = rm(frame_f)
print (i)
cv2.imwrite(f'{uid}-rembg/{i}.png',out)
fbox3.append(f'{uid}-rembg/{i}.png')
frame_num=f'Working on {i+1} of {frame_count}'
yield fbox2,frame_num,None
with gr.Blocks() as app:
with gr.Tab("Load"):
with gr.Row():
with gr.Column():
inp_url = gr.Textbox()
go_btn = gr.Button("Run")
outp_vid=gr.Video(format="mp4")
with gr.Column():
with gr.Row():
frame_count=gr.Textbox(label="Frame Count",interactive = False)
fps=gr.Textbox(label="FPS",interactive = False)
outp_file=gr.Files()
with gr.Row():
start_f = gr.Textbox(label = "Start", value = "0:00:00", placeholder = "0:00:23",interactive = True)
end_f = gr.Textbox(label = "End", value = "0:00:05", placeholder = "0:00:54",interactive = True)
trim_count = gr.Textbox(label="Trimmed Frames")
trim_btn=gr.Button("Trim")
out_trim=gr.Video(format="mp4")
hid_box = gr.Textbox(visible=False)
with gr.Tab("Frames"):
with gr.Row():
frame_btn = gr.Button("Get Frames")
frame_stat=gr.Textbox("Status")
with gr.Row():
with gr.Column():
frame_gal = gr.Gallery(columns=6)
with gr.Column():
frame_file = gr.Files()
with gr.Tab("Rem BG"):
with gr.Row():
with gr.Column():
rem_btn=gr.Button()
in_vid=gr.Video(format="mp4")
with gr.Column():
#rem_vid=gr.Video()
frame_num=gr.Textbox(label="Progress")
rem_vid=gr.Gallery(columns=6)
rem_bg_vid=gr.Video()
with gr.Row(visible=False):
text_input=gr.Textbox()
text_output=gr.Textbox()
url_params=gr.JSON()
def echo_fn(inp):
return inp
#outp_vid.change(echo_fn,outp_vid,[out_trim])
trim_btn.click(trim_vid,[hid_box,start_f,end_f],[out_trim,in_vid,trim_count])
outp_vid.change(load_video,outp_vid,[frame_count,fps,end_f]).then(echo_fn,outp_vid,[out_trim])
frame_btn.click(capture_function,[out_trim],[frame_gal,frame_file,frame_stat])
rem_btn.click(rem_bg,[out_trim],[rem_vid,frame_num,rem_bg_vid])
go_btn.click(dl,inp_url,[outp_vid,outp_file,out_trim,hid_box])
app.load(fn=predict, inputs=[text_input,url_params], outputs=[text_output,text_input],_js=load_js)
app.launch()