File size: 15,431 Bytes
763d88e 36badcc b80e728 f994150 f18255f 36badcc 763d88e 36badcc b911552 f18255f b911552 f18255f f994150 0b49997 1e940c9 0b49997 1e940c9 0b49997 1e940c9 0b49997 b911552 0b49997 1e940c9 0b49997 1e940c9 0b49997 1e940c9 0b49997 36badcc 763d88e 36badcc 763d88e 36badcc b80e728 75dedd6 763d88e 36badcc 763d88e 36badcc 763d88e f18255f 763d88e f18255f 763d88e 10d4684 763d88e f18255f 763d88e 10d4684 36badcc 763d88e 36badcc 763d88e 36badcc b911552 36badcc b911552 f18255f e33058f 36badcc f18255f 36badcc f18255f b911552 f994150 b911552 f994150 b911552 e33058f b911552 f18255f b911552 f994150 1e940c9 e33058f f994150 b911552 36badcc f994150 36badcc f994150 36badcc f994150 36badcc f994150 36badcc f994150 763d88e 8814906 763d88e a6fda81 36badcc b229ffd 36badcc 7736d9a 36badcc 763d88e 36badcc 0b49997 b229ffd f994150 0b49997 f18255f 0b49997 f18255f f994150 36badcc 75d8a47 36badcc 763d88e 36badcc 763d88e f18255f 36badcc e33058f f18255f 36badcc f994150 36badcc f18255f 36badcc f18255f 36badcc f18255f f994150 36badcc 763d88e 36badcc 763d88e 36badcc f18255f 36badcc 763d88e 36badcc be15f31 |
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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
# app.py
import gradio as gr
import torch
import torchaudio
from demucs.pretrained import get_model
from demucs.apply import apply_model
import os
import tempfile
import numpy as np
import warnings
import soundfile as sf
import librosa
import time
warnings.filterwarnings("ignore")
# --- Setup the models ---
print("Setting up models...")
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Using device: {device}")
# Load HT-Demucs model
print("Loading HT-Demucs model...")
htdemucs_model = get_model(name="htdemucs")
htdemucs_model = htdemucs_model.to(device)
htdemucs_model.eval()
print("HT-Demucs model loaded successfully.")
# Setup Spleeter with Python API approach
print("Setting up Spleeter...")
spleeter_separator = None
spleeter_audio_adapter = None
spleeter_available = False
def patch_spleeter_redirects():
"""Patch Spleeter to handle GitHub redirects properly"""
try:
import httpx
from spleeter.model.provider.github import GithubModelProvider
# Store the original download method
original_download = GithubModelProvider.download
def patched_download(self, name, model_directory):
"""Patched download method that handles redirects"""
import os
import tarfile
import tempfile
from urllib.parse import urlparse
print(f"Downloading {name} model with redirect handling...")
# Model URLs - only 5stems
model_urls = {
'5stems': 'https://github.com/deezer/spleeter/releases/download/v1.4.0/5stems.tar.gz'
}
if name not in model_urls:
return original_download(self, name, model_directory)
url = model_urls[name]
try:
# Create a session that follows redirects
with httpx.Client(follow_redirects=True, timeout=300) as client:
print(f"Downloading from: {url}")
response = client.get(url)
response.raise_for_status()
# Save to temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix='.tar.gz') as tmp_file:
tmp_file.write(response.content)
tmp_file_path = tmp_file.name
print(f"Downloaded {len(response.content)} bytes")
# Extract the model
os.makedirs(model_directory, exist_ok=True)
with tarfile.open(tmp_file_path, 'r:gz') as tar:
tar.extractall(model_directory)
# Clean up
os.unlink(tmp_file_path)
print(f"β
Successfully downloaded and extracted {name} model")
except Exception as e:
print(f"β Failed to download {name} model: {e}")
# Fallback to original method
return original_download(self, name, model_directory)
# Apply the patch
GithubModelProvider.download = patched_download
print("β
Patched Spleeter to handle GitHub redirects")
return True
except Exception as e:
print(f"β οΈ Could not patch Spleeter redirects: {e}")
return False
def setup_spleeter_with_retry():
"""Setup Spleeter 5stems model only"""
global spleeter_separator, spleeter_audio_adapter, spleeter_available
try:
from spleeter.separator import Separator
from spleeter.audio.adapter import AudioAdapter
import os
# Patch Spleeter to handle redirects
patch_spleeter_redirects()
# Set environment variables to help with model download
os.environ['SPLEETER_MODEL_PATH'] = '/tmp/spleeter_models'
# Create the 5stems separator
print("Creating Spleeter 5stems separator...")
spleeter_separator = Separator('spleeter:5stems')
spleeter_audio_adapter = AudioAdapter.default()
spleeter_available = True
print("β
Spleeter 5stems model loaded successfully!")
return True
except Exception as e:
print(f"β Failed to load Spleeter 5stems: {e}")
spleeter_separator = None
spleeter_audio_adapter = None
spleeter_available = False
return False
# Try to setup Spleeter
setup_spleeter_with_retry()
# --- HT-Demucs separation function ---
def separate_with_htdemucs(audio_path):
"""
Separates an audio file using HT-Demucs into drums, bass, other, and vocals.
Returns FILE PATHS.
"""
if audio_path is None:
return None, None, None, None, "Please upload an audio file."
try:
print(f"HT-Demucs: Loading audio from: {audio_path}")
# Load audio with torchaudio
wav, sr = torchaudio.load(audio_path)
if wav.shape[0] == 1:
print("Audio is mono, converting to stereo.")
wav = wav.repeat(2, 1)
wav = wav.to(device)
print("HT-Demucs: Applying the separation model...")
with torch.no_grad():
sources = apply_model(htdemucs_model, wav[None], device=device, progress=True)[0]
print("HT-Demucs: Separation complete.")
# Save stems with timestamp to ensure uniqueness
timestamp = int(time.time() * 1000) # millisecond timestamp
output_dir = f"htdemucs_stems_{timestamp}"
os.makedirs(output_dir, exist_ok=True)
stem_names = ["drums", "bass", "other", "vocals"]
output_paths = []
for i, name in enumerate(stem_names):
out_path = os.path.join(output_dir, f"{name}_{timestamp}.wav")
torchaudio.save(out_path, sources[i].cpu(), sr)
output_paths.append(out_path)
print(f"β
HT-Demucs saved {name} to {out_path}")
return output_paths[0], output_paths[1], output_paths[2], output_paths[3], "β
HT-Demucs separation successful!"
except Exception as e:
print(f"HT-Demucs Error: {e}")
return None, None, None, None, f"β HT-Demucs Error: {str(e)}"
# --- Spleeter separation function ---
def separate_with_spleeter(audio_path):
"""
Separates an audio file using Spleeter into vocals, drums, bass, other, and piano.
Uses Python API approach from stem_separation_spleeter.py
Returns FILE PATHS.
"""
if audio_path is None:
return None, None, None, None, None, "Please upload an audio file."
if not spleeter_available or spleeter_separator is None or spleeter_audio_adapter is None:
return None, None, None, None, None, "β Spleeter not available. Please install Spleeter."
try:
print(f"Spleeter: Processing audio from: {audio_path}")
# Create output directory with timestamp
timestamp = int(time.time() * 1000)
output_dir = f"spleeter_stems_{timestamp}"
os.makedirs(output_dir, exist_ok=True)
# Load audio using Spleeter's audio adapter (from stem_separation_spleeter.py)
print("Spleeter: Loading audio...")
waveform, sample_rate = spleeter_audio_adapter.load(audio_path, sample_rate=44100)
print(f"Spleeter: Loaded audio - shape: {waveform.shape}, sr: {sample_rate}")
# Perform the separation (from stem_separation_spleeter.py)
print("Spleeter: Separating audio sources...")
prediction = spleeter_separator.separate(waveform)
print("Spleeter: Separation complete.")
print(f"Spleeter: Prediction keys: {list(prediction.keys())}")
# Save stems with timestamp
output_paths = []
stem_names = ["vocals", "drums", "bass", "other", "piano"]
for stem_name in stem_names:
if stem_name in prediction:
out_path = os.path.join(output_dir, f"{stem_name}_{timestamp}.wav")
stem_audio = prediction[stem_name]
print(f"Spleeter: {stem_name} audio shape: {stem_audio.shape}, dtype: {stem_audio.dtype}")
# Save using soundfile for better compatibility
sf.write(out_path, stem_audio, sample_rate)
output_paths.append(out_path)
print(f"β
Spleeter saved {stem_name} to {out_path}")
else:
print(f"β οΈ Warning: {stem_name} not found in prediction")
output_paths.append(None)
# Ensure we have 5 outputs
while len(output_paths) < 5:
output_paths.append(None)
return output_paths[0], output_paths[1], output_paths[2], output_paths[3], output_paths[4], "β
Spleeter separation successful!"
except Exception as e:
print(f"Spleeter Error: {e}")
import traceback
traceback.print_exc()
return None, None, None, None, None, f"β Spleeter Error: {str(e)}"
# --- Combined separation function ---
def separate_selected_models(audio_path, run_htdemucs, run_spleeter):
"""
Separates an audio file using selected models (HT-Demucs, Spleeter, or both).
Returns stems from selected models.
"""
if audio_path is None:
return [None] * 11, "Please upload an audio file."
if not run_htdemucs and not run_spleeter:
return [None] * 11, "β Please select at least one model to run."
try:
htdemucs_results = [None] * 5 # 4 stems + 1 status
spleeter_results = [None] * 6 # 5 stems + 1 status
status_messages = []
# Run HT-Demucs if selected
if run_htdemucs:
print("Running HT-Demucs...")
htdemucs_results = separate_with_htdemucs(audio_path)
status_messages.append(htdemucs_results[-1])
# Run Spleeter if selected
if run_spleeter:
print("Running Spleeter...")
spleeter_results = separate_with_spleeter(audio_path)
status_messages.append(spleeter_results[-1])
# Combine results: HT-Demucs (4 stems) + Spleeter (5 stems)
all_results = list(htdemucs_results[:-1]) + list(spleeter_results[:-1])
# Create combined status message
models_used = []
if run_htdemucs:
models_used.append("HT-Demucs")
if run_spleeter:
models_used.append("Spleeter")
combined_status = f"π΅ {' + '.join(models_used)} completed!\n\n" + "\n".join(status_messages)
return all_results + [combined_status]
except Exception as e:
print(f"Combined Error: {e}")
import traceback
traceback.print_exc()
return [None] * 11, f"β Error: {str(e)}"
# --- Gradio UI ---
print("Creating Gradio interface...")
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# π΅ Spleeter & Demucs - Now Both Work!
**Follow me on:** [ Hugging Face @ahk-d](https://huggingface.co/ahk-d) | [ GitHub @ahk-d](https://github.com/ahk-d)
""")
with gr.Row():
with gr.Column(scale=1):
audio_input = gr.Audio(type="filepath", label="π΅ Upload Your Song")
# Model selection toggles
gr.Markdown("### ποΈ Select Models to Run")
with gr.Row():
htdemucs_toggle = gr.Checkbox(label="π― HT-Demucs", value=True, info="Drums, Bass, Other, Vocals")
spleeter_label = "π΅ Spleeter 2025 (5stems)" if spleeter_available else "π΅ Spleeter 2025"
spleeter_info = "Vocals, Drums, Bass, Other, Piano" if spleeter_available else "5stems model not available"
spleeter_toggle = gr.Checkbox(
label=spleeter_label,
value=spleeter_available,
info=spleeter_info,
interactive=spleeter_available
)
separate_button = gr.Button("π Separate Music", variant="primary", size="lg")
status_output = gr.Textbox(label="π Status", interactive=False, lines=4)
gr.Markdown("---")
with gr.Row():
# HT-Demucs Results
with gr.Column():
gr.Markdown("### π― HT-Demucs Results")
with gr.Row():
htdemucs_drums = gr.Audio(label="π₯ Drums", type="filepath")
htdemucs_bass = gr.Audio(label="πΈ Bass", type="filepath")
with gr.Row():
htdemucs_other = gr.Audio(label="πΌ Other", type="filepath")
htdemucs_vocals = gr.Audio(label="π€ Vocals", type="filepath")
# Spleeter Results
with gr.Column():
gr.Markdown("### π΅ Spleeter 2025 Results")
with gr.Row():
spleeter_vocals = gr.Audio(label="π€ Vocals", type="filepath")
spleeter_drums = gr.Audio(label="π₯ Drums", type="filepath")
with gr.Row():
spleeter_bass = gr.Audio(label="πΈ Bass", type="filepath")
spleeter_other = gr.Audio(label="πΌ Other", type="filepath")
with gr.Row():
spleeter_piano = gr.Audio(label="πΉ Piano", type="filepath")
if spleeter_available:
gr.Markdown("*5stems model: Vocals, Drums, Bass, Other, Piano*")
else:
gr.Markdown("*Note: Spleeter 5stems model not available*")
gr.Markdown("---")
with gr.Row():
comparison_text = f"""
### π Model Comparison
| Feature | HT-Demucs | Spleeter 2025 (5stems) |
|---------|-----------|----------|
| **Vocals** | β
High Quality | {'β
Available' if spleeter_available else 'β N/A'} |
| **Drums** | β
High Quality | {'β
Available' if spleeter_available else 'β N/A'} |
| **Bass** | β
High Quality | {'β
Available' if spleeter_available else 'β N/A'} |
| **Other** | β
High Quality | {'β
Available' if spleeter_available else 'β N/A'} |
| **Piano** | β Not Available | {'β
**Available**' if spleeter_available else 'β N/A'} |
| **Speed** | β‘ Fast | {'β‘ Fast' if spleeter_available else 'β N/A'} |
| **Quality** | π Excellent | {'π Good' if spleeter_available else 'β N/A'} |
**π‘ Tip:** Use Spleeter 2025 for piano separation, HT-Demucs for other instruments!
"""
gr.Markdown(comparison_text)
# Connect the button to the combined function
separate_button.click(
fn=separate_selected_models,
inputs=[audio_input, htdemucs_toggle, spleeter_toggle],
outputs=[
htdemucs_drums, htdemucs_bass, htdemucs_other, htdemucs_vocals, # HT-Demucs outputs
spleeter_vocals, spleeter_drums, spleeter_bass, spleeter_other, spleeter_piano, # Spleeter outputs
status_output # Status output
]
)
gr.Markdown("""
---
<p style='text-align: center; font-size: small;'>
π Powered by <strong>HT-Demucs</strong> & <strong>Spleeter 2025</strong> |
π΅ Compare and choose your best stems!
</p>
""")
if __name__ == "__main__":
demo.launch(share=True) |