File size: 1,683 Bytes
f7b3397
91243d9
da8f353
087c136
91243d9
051b0bd
91243d9
051b0bd
 
 
 
 
 
 
 
 
91243d9
051b0bd
 
 
 
 
91243d9
 
 
 
 
051b0bd
 
 
91243d9
 
 
 
 
051b0bd
 
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
import gradio as gr
import yt_dlp
import os

def download_youtube(url, file_format):
    ydl_opts = {}
    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

def show_output(file_path):
    if file_path.endswith(".mp3"):
        return gr.Audio(file_path, label="Audio Output"), None
    else:
        return 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():
            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=[audio_output, video_output]
    )

demo.launch()