deepsync's picture
Update app.py
1a92ad7 verified
raw
history blame
1.85 kB
import os
import yt_dlp
import gradio as gr
import subprocess
from uuid import uuid4
from time import sleep
from tempfile import TemporaryDirectory
cachedir = ".cache"
def clip(yt_url, start_timestamp, duration):
start_timestamp = round(float(start_timestamp), 3)
duration = round(float(duration), 3)
with TemporaryDirectory() as tmpdir:
video_output_path = os.path.join(tmpdir, "video.mp4")
ydl_opts = {
"quiet": True,
"outtmpl": video_output_path,
"postprocessors": [{"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}],
"cachedir": cachedir
}
if not os.path.exists(video_output_path):
try:
ydl_opts["format"] = "22"
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([yt_url])
except Exception as e:
print(e)
ydl_opts["format"] = "bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480[ext=mp4]/best"
sleep(5)
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([yt_url])
clip_path = os.path.join(tmpdir, f"{uuid4()}.mp3")
print(f'ffmpeg -ss {start_timestamp} -t {duration} -i "{video_output_path}" "{clip_path}"')
subprocess.run(f'ffmpeg -ss {start_timestamp} -t {duration} -i "{video_output_path}" "{clip_path}"', shell=True)
print(os.listdir(tmpdir))
sleep(3)
return clip_path
url_link = gr.Textbox(label="YouTube URL")
start_timestamp = gr.Textbox(label="Clip start timestamp (in seconds)")
clip_length = gr.Textbox(label="Clip length (in seconds)")
interface = gr.Interface(clip, [url_link, start_timestamp, clip_length], "audio", title="YouTube Clipper")
if __name__=="__main__":
interface.queue().launch()