File size: 1,727 Bytes
f7b3397
051b0bd
da8f353
087c136
051b0bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80cfb0f
 
 
 
 
 
051b0bd
80cfb0f
1f810c1
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
from yt_dlp import YoutubeDL
import os

def download_youtube(url, output_format):
    ydl_opts = {}
    file_path = ""
    
    if output_format == "audio":
        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
            'outtmpl': 'downloads/%(title)s.%(ext)s',
        }
    elif output_format == "video":
        ydl_opts = {
            'format': 'bestvideo+bestaudio/best',
            'outtmpl': 'downloads/%(title)s.%(ext)s',
        }

    with YoutubeDL(ydl_opts) as ydl:
        result = ydl.extract_info(url, download=True)
        file_path = ydl.prepare_filename(result)

        if output_format == "audio":
            file_path = file_path.replace(result['ext'], 'mp3')

    return file_path

def show_media(file_path, output_format):
    if output_format == "audio":
        return gr.Audio.update(value=file_path)
    elif output_format == "video":
        return gr.Video.update(value=file_path)

def yt_download(url, output_format):
    file_path = download_youtube(url, output_format)
    return show_media(file_path, output_format)

with gr.Blocks() as demo:
    gr.Markdown("## YouTube Downloader")
    url_input = gr.Textbox(label="YouTube URL")
    format_input = gr.Radio(choices=["audio", "video"], label="Format")
    download_btn = gr.Button("Download")
    download_btn.click(yt_download, inputs=[url_input, format_input], outputs=[audio_output, video_output])

    audio_output = gr.Audio(label="Audio Output")
    
    video_output = gr.Video(label="Video Output")
        
demo.launch()