import gradio as gr from yt_dlp import YoutubeDL import os def download_youtube(url, output_format): ydl_opts = {} file_path = "" if output_format == "audio": ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'outtmpl': 'downloads/%(title)s.%(ext)s', } elif output_format == "video": ydl_opts = { 'format': 'bestvideo+bestaudio/best', 'outtmpl': 'downloads/%(title)s.%(ext)s', } with YoutubeDL(ydl_opts) as ydl: result = ydl.extract_info(url, download=True) file_path = ydl.prepare_filename(result) if output_format == "audio": file_path = file_path.replace(result['ext'], 'mp3') return file_path def show_media(file_path, output_format): if output_format == "audio": return gr.Audio.update(value=file_path) elif output_format == "video": return gr.Video.update(value=file_path) def yt_download(url, output_format): file_path = download_youtube(url, output_format) return show_media(file_path, output_format) with gr.Blocks() as demo: gr.Markdown("## YouTube Downloader") url_input = gr.Textbox(label="YouTube URL") format_input = gr.Radio(choices=["audio", "video"], label="Format") download_btn = gr.Button("Download") download_btn.click(yt_download, inputs=[url_input, format_input], outputs=[audio_output, video_output]) audio_output = gr.Audio(label="Audio Output") video_output = gr.Video(label="Video Output") demo.launch()