File size: 2,034 Bytes
f7b3397
91243d9
da8f353
087c136
91243d9
051b0bd
62bd18f
91243d9
62bd18f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051b0bd
62bd18f
 
 
051b0bd
91243d9
62bd18f
 
91243d9
62bd18f
91243d9
62bd18f
051b0bd
 
91243d9
 
 
 
 
 
62bd18f
91243d9
 
 
 
62bd18f
91243d9
80cfb0f
051b0bd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
    except Exception as e:
        return str(e)

def show_output(file_path):
    if not file_path or not os.path.exists(file_path):
        return "Error downloading file.", None, None
    if file_path.endswith(".mp3"):
        return None, gr.Audio(file_path, label="Audio Output"), None
    else:
        return None, None, gr.Video(file_path, label="Video Output")

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=False)
            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=None).then(
        show_output, inputs=None, outputs=[error_output, audio_output, video_output]
    )

demo.launch()