Spaces:
Paused
Paused
File size: 11,525 Bytes
3ece626 552d4af 3ece626 e9a1734 3ece626 e9a1734 3ece626 fc1edf2 3ece626 e9a1734 3ece626 fc1edf2 3ece626 fc1edf2 3ece626 e9a1734 3ece626 a199468 e9a1734 a199468 fc1edf2 3ece626 e9a1734 3ece626 fc1edf2 3ece626 e9a1734 3ece626 552d4af 3ece626 fc1edf2 3ece626 e9a1734 fc1edf2 e9a1734 552d4af 3ece626 e9a1734 fc1edf2 e9a1734 552d4af 3ece626 e9a1734 3ece626 e9a1734 fc1edf2 e9a1734 fc1edf2 e9a1734 fc1edf2 e9a1734 fc1edf2 e9a1734 552d4af e9a1734 fc1edf2 e9a1734 fc1edf2 e9a1734 fc1edf2 e9a1734 fc1edf2 e9a1734 fc1edf2 e9a1734 552d4af e9a1734 fc1edf2 e9a1734 3ece626 e9a1734 3ece626 e9a1734 fc1edf2 3ece626 552d4af e9a1734 3ece626 e9a1734 3ece626 552d4af 3ece626 e9a1734 a199468 e9a1734 2eadd2b 552d4af 3ece626 |
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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
import gradio as gr
from yt_dlp import YoutubeDL
import os
from pydub import AudioSegment
DOWNLOADS_FOLDER = "downloads"
os.makedirs(DOWNLOADS_FOLDER, exist_ok=True)
def download_youtube_audio(url, file_format, duration_sec):
"""Download and process audio from YouTube"""
try:
# Download best audio available
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),
'quiet': False,
'no_warnings': False,
'extract_flat': False,
'noplaylist': True,
}
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")
# Clean filename
safe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip()
safe_title = safe_title[:100]
original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")
if original_file != original_file_safe:
if os.path.exists(original_file_safe):
os.remove(original_file_safe)
os.rename(original_file, original_file_safe)
original_file = original_file_safe
# Load audio
audio = AudioSegment.from_file(original_file)
# Handle duration
if duration_sec > 0:
duration_ms = min(len(audio), int(duration_sec * 1000))
trimmed_audio = audio[:duration_ms]
else:
trimmed_audio = audio
# Determine output file
base_name = os.path.splitext(original_file)[0]
if file_format.lower() == "mp3":
output_file = base_name + ".mp3"
trimmed_audio.export(output_file, format="mp3", bitrate="192k")
elif file_format.lower() == "opus":
output_file = base_name + ".opus"
trimmed_audio.export(output_file, format="opus", bitrate="128k")
elif file_format.lower() == "wav":
output_file = base_name + ".wav"
trimmed_audio.export(output_file, format="wav")
elif file_format.lower() == "m4a":
output_file = base_name + ".m4a"
trimmed_audio.export(output_file, format="ipod", codec="aac")
else:
output_file = original_file
# Clean up original if converted
if output_file != original_file and os.path.exists(original_file):
os.remove(original_file)
return output_file, f"✅ Downloaded: {os.path.basename(output_file)}"
except Exception as e:
return None, f"❌ Error: {str(e)}"
def download_soundcloud_audio(url, file_format, duration_sec):
"""Download and process audio from SoundCloud"""
try:
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s'),
'quiet': False,
'no_warnings': False,
'extract_flat': False,
}
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")
# Clean filename
safe_title = "".join(c for c in info['title'] if c.isalnum() or c in (' ', '-', '_')).rstrip()
safe_title = safe_title[:100]
original_file_safe = os.path.join(DOWNLOADS_FOLDER, f"{safe_title}.{info['ext']}")
if original_file != original_file_safe:
if os.path.exists(original_file_safe):
os.remove(original_file_safe)
os.rename(original_file, original_file_safe)
original_file = original_file_safe
# Load and process audio
audio = AudioSegment.from_file(original_file)
if duration_sec > 0:
duration_ms = min(len(audio), int(duration_sec * 1000))
trimmed_audio = audio[:duration_ms]
else:
trimmed_audio = audio
# Convert to desired format
base_name = os.path.splitext(original_file)[0]
if file_format.lower() == "mp3":
output_file = base_name + ".mp3"
trimmed_audio.export(output_file, format="mp3", bitrate="192k")
elif file_format.lower() == "opus":
output_file = base_name + ".opus"
trimmed_audio.export(output_file, format="opus", bitrate="128k")
elif file_format.lower() == "wav":
output_file = base_name + ".wav"
trimmed_audio.export(output_file, format="wav")
elif file_format.lower() == "m4a":
output_file = base_name + ".m4a"
trimmed_audio.export(output_file, format="ipod", codec="aac")
else:
output_file = original_file
# Clean up
if output_file != original_file and os.path.exists(original_file):
os.remove(original_file)
return output_file, f"✅ Downloaded: {os.path.basename(output_file)}"
except Exception as e:
return None, f"❌ Error: {str(e)}"
# Create Gradio interface - REMOVE theme parameter from here
with gr.Blocks(title="Audio Downloader") as iface:
gr.Markdown("# 🎵 Audio Downloader")
gr.Markdown("Download audio from YouTube or SoundCloud")
with gr.Tabs():
# YouTube Tab
with gr.Tab("YouTube"):
with gr.Row():
with gr.Column():
youtube_url = gr.Textbox(
label="YouTube URL",
placeholder="https://www.youtube.com/watch?v=...",
lines=1
)
with gr.Row():
youtube_format = gr.Dropdown(
choices=["mp3", "m4a", "opus", "wav"],
value="mp3",
label="Output Format"
)
youtube_duration = gr.Slider(
minimum=0,
maximum=1800,
value=60,
step=5,
label="Duration (seconds)",
info="0 = full video"
)
youtube_btn = gr.Button(
"Download from YouTube",
variant="primary",
size="lg"
)
youtube_status = gr.Textbox(
label="Status",
interactive=False
)
youtube_output = gr.File(
label="Downloaded File",
interactive=False
)
# YouTube examples
with gr.Accordion("YouTube Examples", open=False):
gr.Examples(
examples=[
["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],
["https://www.youtube.com/watch?v=JGwWNGJdvx8"],
["https://www.youtube.com/watch?v=9bZkp7q19f0"],
["https://youtu.be/kJQP7kiw5Fk"]
],
inputs=youtube_url,
label="Try these URLs:"
)
# SoundCloud Tab
with gr.Tab("SoundCloud"):
with gr.Row():
with gr.Column():
soundcloud_url = gr.Textbox(
label="SoundCloud URL",
placeholder="https://soundcloud.com/...",
lines=1
)
with gr.Row():
soundcloud_format = gr.Dropdown(
choices=["mp3", "m4a", "opus", "wav"],
value="mp3",
label="Output Format"
)
soundcloud_duration = gr.Slider(
minimum=0,
maximum=600,
value=60,
step=5,
label="Duration (seconds)",
info="0 = full track"
)
soundcloud_btn = gr.Button(
"Download from SoundCloud",
variant="primary",
size="lg"
)
soundcloud_status = gr.Textbox(
label="Status",
interactive=False
)
soundcloud_output = gr.File(
label="Downloaded File",
interactive=False
)
# SoundCloud examples
with gr.Accordion("SoundCloud Examples", open=False):
gr.Examples(
examples=[
["https://soundcloud.com/antonio-antetomaso/mutiny-on-the-bounty-closing-titles-cover"],
["https://soundcloud.com/officialnikkig/kill-bill-sza-kill-bill-remix"],
["https://soundcloud.com/lofi-girl"],
["https://soundcloud.com/monstercat/pegboard-nerds-disconnected"]
],
inputs=soundcloud_url,
label="Try these URLs:"
)
# Instructions
with gr.Accordion("📖 Instructions & Info", open=False):
gr.Markdown("""
### How to Use:
1. **Select the platform tab** (YouTube or SoundCloud)
2. **Paste a URL** from the selected platform
3. **Choose output format** (MP3, M4A, Opus, or WAV)
4. **Set duration** (0 for full track, or specify seconds)
5. **Click Download** button
### Supported Formats:
- **MP3**: Most compatible, good quality
- **M4A**: Apple format, smaller file size
- **Opus**: Best quality at low bitrates
- **WAV**: Lossless, large file size
### Notes:
- Files are saved in the 'downloads' folder
- Some content may have download restrictions
- Long videos may take time to process
""")
# Connect button events
youtube_btn.click(
fn=download_youtube_audio,
inputs=[youtube_url, youtube_format, youtube_duration],
outputs=[youtube_output, youtube_status]
)
soundcloud_btn.click(
fn=download_soundcloud_audio,
inputs=[soundcloud_url, soundcloud_format, soundcloud_duration],
outputs=[soundcloud_output, soundcloud_status]
)
# Launch the app - MOVE theme parameter to here
if __name__ == "__main__":
iface.launch(
server_name="127.0.0.1",
server_port=7860,
show_error=True,
share=False,
theme=gr.themes.Soft(),
ssr_mode=False # Disable SSR to avoid warning
) |