import gradio as gr import os import subprocess import random import time DOWNLOAD_DIR = os.path.join(os.getcwd(), "downloads") os.makedirs(DOWNLOAD_DIR, exist_ok=True) USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" ] def get_random_user_agent(): return random.choice(USER_AGENTS) def run_command(command): try: result = subprocess.run( command, capture_output=True, text=True, timeout=600, encoding='utf-8', errors='ignore' ) if result.returncode == 0: return True, result.stdout else: return False, result.stderr except subprocess.TimeoutExpired: return False, "⏰ Timeout: demorou muito." except Exception as e: return False, f"Erro: {str(e)}" def download_media(url, tipo="audio", qualidade="best", formato="mp3"): if not url.strip(): return "❌ URL inválida!", None filepath = os.path.join(DOWNLOAD_DIR, "%(title)s.%(ext)s") if tipo == "audio": cmd = [ "yt-dlp", "--user-agent", get_random_user_agent(), "--extract-audio", "-x", "--audio-format", formato, "--audio-quality", qualidade, "-o", filepath, url ] else: format_string = 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' if qualidade != "best": format_string = f'bestvideo[height<=?{qualidade}][ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' cmd = [ "yt-dlp", "--user-agent", get_random_user_agent(), "-f", format_string, "--merge-output-format", "mp4", "-o", filepath, url ] ok, log = run_command(cmd) if ok: files = sorted(os.listdir(DOWNLOAD_DIR), key=lambda x: os.path.getctime(os.path.join(DOWNLOAD_DIR, x))) last_file = os.path.join(DOWNLOAD_DIR, files[-1]) if files else None return f"✅ Download concluído!\n{log}", last_file else: return f"❌ Erro:\n{log}", None def app_fn(url, tipo, qualidade, formato): msg, arquivo = download_media(url, tipo, qualidade, formato) return msg, arquivo with gr.Blocks() as demo: gr.Markdown("# 🚀 YouTube Downloader (Vídeo & Áudio)") url = gr.Textbox(label="Cole o link do YouTube", placeholder="https://youtube.com/...") tipo = gr.Radio(["audio", "video"], value="audio", label="Tipo de Download") formato = gr.Dropdown(["mp3", "m4a", "wav", "flac"], value="mp3", label="Formato de Áudio") qualidade = gr.Dropdown(["best", "0", "5", "9", "1080", "720", "480"], value="best", label="Qualidade") btn = gr.Button("📥 Baixar") log = gr.Textbox(label="Log", lines=10) file_out = gr.File(label="Arquivo Gerado") btn.click(app_fn, inputs=[url, tipo, qualidade, formato], outputs=[log, file_out]) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)