Nymbo's picture
Modernize: Gradio 6.29, safe yt-dlp invocation, ffmpeg
69339e7 verified
Raw History Blame Contribute Delete
1.78 kB
import os
import re
import subprocess
import tempfile
import gradio as gr
FORMAT_OPTS = {
"mp3": ["-f", "ba/b", "-x", "--audio-format", "mp3"], # MP3 format
"mp4": ["-f", "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best", "--merge-output-format", "mp4"], # MP4 video + audio
"flac": ["-f", "ba/b", "-x", "--audio-format", "flac"], # FLAC lossless audio
"aac": ["-f", "ba/b", "-x", "--audio-format", "aac"], # AAC lossy high-quality audio
}
def fetch(url, name, ext):
url = (url or "").strip()
if not url.startswith(("http://", "https://")):
raise gr.Error("Please enter a valid http(s) link.")
name = re.sub(r"[^\w\-. ]", "_", (name or "").strip()) or "download"
out_dir = tempfile.mkdtemp()
filename = os.path.join(out_dir, f"{name}.{ext}")
# Argument list (no shell) so the URL can't inject commands
cmd = ["yt-dlp", "--no-playlist", *FORMAT_OPTS[ext], "-o", filename, url]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0 or not os.path.exists(filename):
err = (result.stderr or result.stdout or "").strip().splitlines()
raise gr.Error("Download failed: " + (err[-1] if err else "unknown error"))
return filename
# Create the Gradio interface
interface = gr.Interface(
fn=fetch,
inputs=[
gr.Textbox(label="Link Address", placeholder="Enter the URL here ..."),
gr.Textbox(label="File Name", placeholder="Example: file_name"),
gr.Dropdown(["mp3", "mp4", "flac", "aac"], value="mp3", label="File Type"),
],
outputs=gr.File(label="Download!"),
description="Download from X, Youtube, Reddit, etc..",
flagging_mode="never",
)
# Launch the interface
interface.launch(theme="Nymbo/Nymbo_Theme")