File size: 970 Bytes
4074cdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import tempfile
import hashlib
import gradio as gr
import yt_dlp


def download(url: str) -> str:
    if not url:
        raise gr.Error("Please input a YouTube URL")

    hash = hashlib.md5(url.encode()).hexdigest()
    tmp_file = os.path.join(tempfile.gettempdir(), f"{hash}")

    ydl_opts = {
        "format": "bestaudio/best",
        "outtmpl": tmp_file,
        "postprocessors": [
            {
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "192",
            }
        ],
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

    return tmp_file + ".mp3"


with gr.Blocks() as app:
    url = gr.Textbox(lines=1, label="Enter URL")
    btn = gr.Button("Download", variant="primary")
    audio = gr.Audio(type="filepath", label="Downloaded Audio", format="mp3")

    btn.click(fn=download, inputs=[url], outputs=[audio])

app.launch(show_error=True)