File size: 2,726 Bytes
d7bc426
05e0462
5e107b7
 
d7bc426
5e107b7
 
 
d7bc426
5e107b7
 
 
 
 
 
05e0462
 
 
 
 
 
 
 
 
 
5e107b7
05e0462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e107b7
d7bc426
5e107b7
 
 
 
 
 
 
 
d7bc426
5e107b7
 
 
 
 
 
 
 
 
 
 
 
 
 
d7bc426
5e107b7
d7bc426
5e107b7
 
 
 
 
 
 
d7bc426
 
5e107b7
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import gradio as gr
import yt_dlp
import os
import re

def sanitize_filename(title):
    """Remove invalid characters from filename"""
    return re.sub(r'[<>:"/\\|?*]', '', title)

def download_audio(url, output_dir="downloads"):
    try:
        # Create output directory if it doesn't exist
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        
        # Configure yt-dlp options
        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
            'outtmpl': os.path.join(output_dir, '%(title)s.%(ext)s'),
            'verbose': True
        }
        
        # Download with yt-dlp
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            # Get video info first
            info = ydl.extract_info(url, download=False)
            title = info.get('title', 'video')
            duration = info.get('duration', 0)
            author = info.get('uploader', 'Unknown')
            
            # Download the video
            ydl.download([url])
            
            # Construct the output filepath
            safe_title = sanitize_filename(title)
            output_file = os.path.join(output_dir, f"{safe_title}.mp3")
            
            return {
                "status": "success",
                "message": f"Successfully downloaded: {safe_title}",
                "title": title,
                "author": author,
                "duration": f"{duration // 60}:{duration % 60:02d}",
                "file_path": output_file
            }
    
    except Exception as e:
        return {
            "status": "error",
            "message": f"Error: {str(e)}",
            "title": "",
            "author": "",
            "duration": "",
            "file_path": ""
        }

def process_url(url):
    if not url.strip():
        return "Please enter a YouTube URL"
    
    result = download_audio(url)
    
    if result["status"] == "error":
        return result["message"]
    
    return f"""Download successful!
Title: {result['title']}
Author: {result['author']}
Duration: {result['duration']}
Saved to: {result['file_path']}"""

# Create Gradio interface
iface = gr.Interface(
    fn=process_url,
    inputs=gr.Textbox(label="YouTube URL", placeholder="Enter YouTube video URL here..."),
    outputs=gr.Textbox(label="Status"),
    title="YouTube to MP3 Downloader",
    description="Enter a YouTube URL to download the audio as MP3",
    examples=[["https://www.youtube.com/watch?v=dQw4w9WgXcQ"]],
    theme=gr.themes.Base()
)

if __name__ == "__main__":
    iface.launch()