MySafeCode commited on
Commit
4f02f65
·
verified ·
1 Parent(s): eb9dc67

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -0
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from yt_dlp import YoutubeDL
3
+ import os
4
+ from pydub import AudioSegment
5
+ import re
6
+
7
+ DOWNLOADS_FOLDER = "downloads"
8
+ os.makedirs(DOWNLOADS_FOLDER, exist_ok=True)
9
+
10
+ def sanitize_filename(filename):
11
+ """Remove invalid characters from filename"""
12
+ # Remove characters that are invalid in filenames
13
+ return re.sub(r'[<>:"/\\|?*]', '', filename)
14
+
15
+ def download_audio(url, file_format, platform):
16
+ try:
17
+ # Set download options
18
+ ydl_opts = {
19
+ 'format': 'bestaudio/best',
20
+ 'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),
21
+ 'quiet': True,
22
+ 'no_warnings': True
23
+ }
24
+
25
+ # Platform-specific handling if needed
26
+ if platform == "youtube":
27
+ # You could add YouTube-specific options here
28
+ pass
29
+ elif platform == "soundcloud":
30
+ # You could add SoundCloud-specific options here
31
+ pass
32
+
33
+ with YoutubeDL(ydl_opts) as ydl:
34
+ info = ydl.extract_info(url, download=True)
35
+ original_filename = ydl.prepare_filename(info)
36
+
37
+ # Get the actual downloaded filename
38
+ if os.path.exists(original_filename):
39
+ downloaded_file = original_filename
40
+ else:
41
+ # Sometimes the extension might be different
42
+ base_name = os.path.splitext(original_filename)[0]
43
+ for ext in ['.m4a', '.webm', '.mp3', '.opus']:
44
+ possible_file = base_name + ext
45
+ if os.path.exists(possible_file):
46
+ downloaded_file = possible_file
47
+ break
48
+ else:
49
+ downloaded_file = original_filename
50
+
51
+ # If user wants specific format, convert if needed
52
+ if file_format.lower() != "original":
53
+ target_ext = f".{file_format.lower()}"
54
+ current_ext = os.path.splitext(downloaded_file)[1].lower()
55
+
56
+ if current_ext != target_ext:
57
+ # Create sanitized output filename
58
+ base_name = os.path.splitext(downloaded_file)[0]
59
+ sanitized_base = sanitize_filename(os.path.basename(base_name))
60
+ output_file = os.path.join(DOWNLOADS_FOLDER, sanitized_base + target_ext)
61
+
62
+ try:
63
+ # Convert audio format
64
+ audio = AudioSegment.from_file(downloaded_file)
65
+ audio.export(output_file, format=file_format.lower())
66
+ downloaded_file = output_file
67
+ except Exception as e:
68
+ print(f"Conversion failed: {e}")
69
+ # Return original file if conversion fails
70
+ pass
71
+
72
+ return downloaded_file
73
+
74
+ except Exception as e:
75
+ return f"Error: {str(e)}"
76
+
77
+ # Gradio interface
78
+ with gr.Blocks(title="Audio Downloader", theme=gr.themes.Soft()) as iface:
79
+ gr.Markdown("# 🎵 Audio Downloader")
80
+ gr.Markdown("Download audio from YouTube or SoundCloud")
81
+
82
+ with gr.Row():
83
+ platform_choice = gr.Dropdown(
84
+ choices=["youtube", "soundcloud"],
85
+ value="youtube",
86
+ label="Select Platform"
87
+ )
88
+
89
+ with gr.Row():
90
+ url_input = gr.Textbox(
91
+ label="URL",
92
+ placeholder="Enter YouTube or SoundCloud URL here...",
93
+ scale=4
94
+ )
95
+
96
+ with gr.Row():
97
+ format_choice = gr.Dropdown(
98
+ choices=["original", "mp3", "m4a", "wav", "opus"],
99
+ value="mp3",
100
+ label="Select Output Format"
101
+ )
102
+
103
+ with gr.Row():
104
+ download_button = gr.Button("Download Audio", variant="primary", size="lg")
105
+
106
+ with gr.Row():
107
+ download_file = gr.File(label="Download Your Audio")
108
+
109
+ with gr.Row():
110
+ status_output = gr.Textbox(label="Status", visible=False)
111
+
112
+ def download_wrapper(url, file_format, platform):
113
+ result = download_audio(url, file_format, platform)
114
+ if isinstance(result, str) and result.startswith("Error:"):
115
+ return gr.update(value=None, visible=True), gr.update(value=result, visible=True)
116
+ else:
117
+ return gr.update(value=result, visible=True), gr.update(value="Download complete!", visible=True)
118
+
119
+ download_button.click(
120
+ fn=download_wrapper,
121
+ inputs=[url_input, format_choice, platform_choice],
122
+ outputs=[download_file, status_output]
123
+ )
124
+
125
+ # Examples
126
+ gr.Examples(
127
+ examples=[
128
+ ["https://www.youtube.com/watch?v=dQw4w9WgXcQ", "mp3", "youtube"],
129
+ ["https://soundcloud.com/artist/track", "mp3", "soundcloud"],
130
+ ],
131
+ inputs=[url_input, format_choice, platform_choice],
132
+ label="Try these examples:"
133
+ )
134
+
135
+ iface.launch(share=False, show_error=True)