File size: 2,219 Bytes
7614bef
1b0ff1c
6e10c3a
7614bef
 
 
 
6e10c3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7614bef
 
 
 
6e10c3a
7614bef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
import gradio as gr
from moviepy.audio.io.AudioFileClip import AudioFileClip
import yt_dlp
import os

def download_youtube(url, output_format, resolution, audio_bitrate):
    try:
        output_dir = "downloads"
        os.makedirs(output_dir, exist_ok=True)
        output_template = f"{output_dir}/%(title)s.%(ext)s"

        ydl_opts = {
            "format": "bestaudio/best" if output_format in ["MP3", "WAV"] else f"bestvideo[height<={resolution[:-1]}]+bestaudio/best",
            "outtmpl": output_template,
            "postprocessors": [],
        }

        if output_format == "MP3":
            ydl_opts["postprocessors"].append({
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': audio_bitrate.replace("k", ""),
            })
        elif output_format == "WAV":
            ydl_opts["postprocessors"].append({
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'wav',
            })

        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(url, download=True)
            filename = ydl.prepare_filename(info_dict)
            if output_format in ["MP3", "WAV"]:
                filename = os.path.splitext(filename)[0] + f".{output_format.lower()}"
            return "Download complete", filename

    except Exception as e:
        return f"Error: {str(e)}", None


formats = ["MP3", "WAV", "MP4"]
resolutions = ["360p", "480p", "720p", "1080p"]
bitrates = ["64k", "128k", "192k", "256k", "320k"]

interface = gr.Interface(
    fn=download_youtube,
    inputs=[
        gr.Text(label="YouTube Video URL"),
        gr.Radio(formats, label="Select Format"),
        gr.Dropdown(resolutions, label="Video Resolution (for MP4)", value="720p"),
        gr.Dropdown(bitrates, label="Audio Bitrate (for MP3)", value="128k"),
    ],
    outputs=[
        gr.Text(label="Status"),
        gr.File(label="Download File"),
    ],
    title="🎵 YouTube Downloader",
    description="Download YouTube videos as MP3, WAV, or MP4 with quality selection. Built with Pytube + Gradio."
)

if __name__ == "__main__":
    os.makedirs("downloads", exist_ok=True)
    interface.launch()