File size: 2,046 Bytes
f7b3397
91243d9
da8f353
087c136
91243d9
051b0bd
62bd18f
91243d9
62bd18f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
051b0bd
ee31586
62bd18f
ee31586
051b0bd
ee31586
 
2cb5213
91243d9
ee31586
91243d9
ee31586
051b0bd
 
91243d9
 
 
 
 
 
2cb5213
91243d9
 
 
2cb5213
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
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()