Spaces:
Sleeping
Sleeping
import gradio as gr | |
import yt_dlp | |
import os | |
os.system('yt-dlp -U') | |
def download_media(url, output_format): | |
ydl_opts = {} | |
if output_format == "Audio": | |
ydl_opts = { | |
'format': 'bestaudio/best', | |
'outtmpl': 'downloads/%(title)s.%(ext)s', | |
'postprocessors': [{ | |
'key': 'FFmpegExtractAudio', | |
'preferredcodec': 'mp3', | |
'preferredquality': '192', | |
}], | |
} | |
elif output_format == "Video": | |
ydl_opts = { | |
'format': 'bestvideo+bestaudio/best', | |
'outtmpl': 'downloads/%(title)s.%(ext)s', | |
} | |
try: | |
with yt_dlp.YoutubeDL(ydl_opts) as ydl: | |
info_dict = ydl.extract_info(url, download=True) | |
title = info_dict.get('title', 'Unknown') | |
ext = info_dict.get('ext', 'mp4' if output_format == "Video" else 'mp3') | |
file_path = f'downloads/{title}.{ext}' | |
return file_path, f"Download successful: {title}.{ext}" | |
except Exception as e: | |
return None, f"Error: {str(e)}" | |
# Gradio Blocks UI | |
with gr.Blocks() as demo: | |
gr.Markdown("# Video and Audio Downloader using yt-dlp") | |
with gr.Row(): | |
url_input = gr.Textbox(label="Video/Audio URL") | |
format_dropdown = gr.Dropdown(choices=["Audio", "Video"], label="Output Format") | |
download_button = gr.Button("Download") | |
output_text = gr.Textbox(label="Output Message") | |
# Placeholder for media output | |
audio_output = gr.Audio(label="Audio Output", visible=False) | |
video_output = gr.Video(label="Video Output", visible=False) | |
def handle_download(url, output_format): | |
file_path, message = download_media(url, output_format) | |
if file_path and output_format == "Audio": | |
return file_path, None, audio_output.update(visible=True), video_output.update(visible=False), message | |
elif file_path and output_format == "Video": | |
return None, file_path, audio_output.update(visible=False), video_output.update(visible=True), message | |
else: | |
return None, None, audio_output.update(visible=False), video_output.update(visible=False), message | |
download_button.click(handle_download, | |
inputs=[url_input, format_dropdown], | |
outputs=[audio_output, video_output, audio_output, video_output, output_text]) | |
demo.launch() | |