Hev832's picture
Update run.py
2cb5213 verified
raw
history blame
2.05 kB
import gradio as gr
import yt_dlp
import os
def download_youtube(url, file_format):
ydl_opts = {}
try:
if file_format == "audio":
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': 'downloads/%(title)s.%(ext)s',
}
else:
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'outtmpl': 'downloads/%(title)s.%(ext)s',
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info(url, download=True)
file_path = ydl.prepare_filename(info_dict)
if file_format == "audio":
file_path = os.path.splitext(file_path)[0] + ".mp3"
return file_path, None
except Exception as e:
return None, str(e)
def show_output(file_path, error):
if error:
return error, gr.Audio.update(visible=False), gr.Video.update(visible=False)
if file_path.endswith(".mp3"):
return None, gr.Audio.update(value=file_path, visible=True), gr.Video.update(visible=False)
else:
return None, gr.Audio.update(visible=False), gr.Video.update(value=file_path, visible=True)
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
url_input = gr.Textbox(label="YouTube URL")
format_input = gr.Dropdown(choices=["audio", "video"], label="Format")
download_button = gr.Button("Download")
with gr.Column():
error_output = gr.Textbox(label="Error Output", visible=True)
audio_output = gr.Audio(label="Audio Output", visible=False)
video_output = gr.Video(label="Video Output", visible=False)
download_button.click(download_youtube, inputs=[url_input, format_input], outputs=[error_output, audio_output, video_output])
demo.launch()