"""Egystormy Split - free stem separation for DJs (Demucs, MIT), on ZeroGPU. One Gradio app serving three modes: split -> vocals.wav + accompaniment.wav (derived from htdemucs 4-stem) 4 -> vocals / drums / bass / other (htdemucs) 6 -> vocals / drums / bass / guitar / piano / other (htdemucs_6s) The separation function is decorated with @spaces.GPU so HuggingFace allocates a ZeroGPU (A10G) for each call. Weights are the official public Demucs checkpoints (MIT); they are fetched once into the local torch hub cache from dl.fbaipublicfiles.com and verified by Demucs' own hash check. """ import subprocess import tempfile import urllib.request import zipfile from pathlib import Path import gradio as gr import soundfile as sf import spaces import torch WEIGHT_URLS = { "955717e8-8726e21a.th": ( "https://dl.fbaipublicfiles.com/demucs/hybrid_transformer/955717e8-8726e21a.th" ), "5c90dfd2-34c22ccb.th": ( "https://dl.fbaipublicfiles.com/demucs/hybrid_transformer/5c90dfd2-34c22ccb.th" ), } MODEL_FOR_MODE = {"split": "htdemucs", "4": "htdemucs", "6": "htdemucs_6s"} STEMS_FOR_MODE = { "split": ["vocals", "accompaniment"], "4": ["vocals", "drums", "bass", "other"], "6": ["vocals", "drums", "bass", "guitar", "piano", "other"], } # This Space is a free online mirror: ZeroGPU caps each GPU booking at the # visitor's allowance (60 s for free visitors), and very long tracks belong # to the local Egystormy Tools app, which has no length limit. MAX_TRACK_SECONDS = 8 * 60 _models = {} def _audio_seconds(path): """Best-effort duration probe (header/ffprobe only, no full decode).""" try: info = sf.info(path) if info.samplerate: return info.frames / float(info.samplerate) except Exception: pass try: out = subprocess.run( [ "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path), ], capture_output=True, text=True, timeout=30, ) return float(out.stdout.strip()) except Exception: return None def _estimate_duration(audio_path=None, *args, **kwargs): """ZeroGPU booking size: ~1 s of GPU per 6 s of audio at shifts=0 on an A10G, clamped to [20, 60] so it always fits the free-visitor ceiling.""" secs = _audio_seconds(audio_path) if audio_path else None if not secs: return 60 return max(20, min(60, int(secs / 6))) def _ensure_weights(): """Download the official Demucs checkpoints into the torch hub cache.""" ckpt_dir = Path(torch.hub.get_dir()) / "checkpoints" ckpt_dir.mkdir(parents=True, exist_ok=True) for name, url in WEIGHT_URLS.items(): target = ckpt_dir / name if target.exists() and target.stat().st_size > 1_000_000: continue tmp = target.with_suffix(".part") with urllib.request.urlopen(url, timeout=120) as resp, open(tmp, "wb") as fh: while True: chunk = resp.read(1024 * 1024) if not chunk: break fh.write(chunk) tmp.rename(target) def _get_model(name): if name not in _models: _ensure_weights() from demucs.pretrained import get_model model = get_model(name) model.eval() _models[name] = model return _models[name] def _load_mix(audio_path: str) -> torch.Tensor: """Decode any input to a [channels, samples] float tensor at 44.1 kHz stereo.""" tmp_wav = None try: fd, tmp_wav = tempfile.mkstemp(suffix=".wav") Path(tmp_wav).unlink(missing_ok=True) proc = subprocess.run( [ "ffmpeg", "-y", "-v", "error", "-i", audio_path, "-ar", "44100", "-ac", "2", "-f", "wav", "-acodec", "pcm_f32le", tmp_wav, ], capture_output=True, text=True, timeout=600, ) if proc.returncode != 0: raise RuntimeError(proc.stderr[-400:]) data, _sr = sf.read(tmp_wav, always_2d=True, dtype="float32") except FileNotFoundError: # ffmpeg missing: fall back to libsndfile decoding + tensor resample. data, sr = sf.read(audio_path, always_2d=True, dtype="float32") tensor = torch.from_numpy(data.T) if tensor.shape[0] == 1: tensor = tensor.repeat(2, 1) if sr != 44100: import torch.nn.functional as F tensor = F.interpolate( tensor[None], size=int(tensor.shape[1] * 44100 / sr), mode="linear", align_corners=False, )[0] return tensor finally: if tmp_wav: Path(tmp_wav).unlink(missing_ok=True) mix = torch.from_numpy(data.T) if mix.shape[0] == 1: mix = mix.repeat(2, 1) return mix @spaces.GPU(duration=_estimate_duration) def _separate_gpu(audio_path, mode, progress=gr.Progress(track_tqdm=False)): mode = str(mode) if mode not in MODEL_FOR_MODE: raise ValueError("Unknown mode.") progress(0.05, desc="Loading model") model = _get_model(MODEL_FOR_MODE[mode]) device = "cuda" if torch.cuda.is_available() else "cpu" progress(0.15, desc="Preparing audio") mix = _load_mix(audio_path) # Match demucs CLI reference normalisation. ref = mix.mean(0) mix = (mix - ref.mean()) / (ref.std() + 1e-8) progress(0.3, desc=f"Separating on {device.upper()} - please wait") from demucs.apply import apply_model model.to(device) try: with torch.no_grad(): out = apply_model( model, mix[None].to(device), device=device, shifts=0, split=True, overlap=0.25, progress=False, )[0] finally: model.to("cpu") if device == "cuda": torch.cuda.empty_cache() out = out.float().cpu() # Undo the reference normalisation so stems are at listening level. out = out * ref.std() + ref.mean() sources = list(model.sources) stems = {name: out[i] for i, name in enumerate(sources)} if mode == "split": acc = stems["drums"] + stems["bass"] + stems["other"] stems = {"vocals": stems["vocals"], "accompaniment": acc} progress(0.9, desc="Writing stem files") out_dir = Path(tempfile.mkdtemp(prefix="egystormy_split_")) files = [] for name in STEMS_FOR_MODE[mode]: path = out_dir / f"{name}.wav" sf.write(str(path), stems[name].clamp(-1.0, 1.0).T.numpy(), 44100, subtype="PCM_16") files.append(str(path)) zip_path = out_dir / "egystormy-stems.zip" with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: for f in files: zf.write(f, arcname=Path(f).name) progress(1.0, desc="Done") summary = ( f"Done - mode {mode}: {', '.join(STEMS_FOR_MODE[mode])}. " "Download the individual stems or the zip." ) return [str(zip_path)] + files, summary def separate(audio_path, mode, progress=gr.Progress(track_tqdm=False)): """CPU-side entry point: length guard first, then the GPU call. Every failure is reported as readable Status text - never as Gradio's raw "Error" boxes. """ if not audio_path: return None, "Please upload an audio file first." secs = _audio_seconds(audio_path) if secs is not None and secs > MAX_TRACK_SECONDS: mins, rem = divmod(int(round(secs)), 60) return None, ( f"This free mirror takes tracks up to 8 minutes - yours is " f"{mins}:{rem:02d}. Longer tracks belong to the local " "Egystormy Tools app: same Demucs engine, on your own PC, " "free and with no length limit." ) try: return _separate_gpu(audio_path, mode, progress) except Exception as exc: # ZeroGPU quota, decode errors, OOM, ... msg = str(getattr(exc, "message", exc) or exc).strip() if "duration" in msg.lower() and "maximum" in msg.lower(): msg = ( "The free GPU time for this call was too small for that " "track. Try a shorter track, or use the local Egystormy " "Tools app - free, on your own PC, no limits." ) return None, f"Separation did not finish: {msg}" with gr.Blocks(title="Egystormy Split") as demo: gr.Markdown( "# Egystormy Split\n" "Free stem separation for DJs, powered by Demucs (MIT). " "Pick a mode, upload a track, get the stems back.\n\n" "- **split** - vocals + accompaniment\n" "- **4** - vocals / drums / bass / other\n" "- **6** - vocals / drums / bass / guitar / piano / other\n\n" "Free mirror limit: tracks up to **8 minutes**. Longer tracks: " "use the free local Egystormy Tools app - no length limit." ) with gr.Row(): audio_in = gr.Audio(label="Audio track", type="filepath") mode_in = gr.Radio( choices=["split", "4", "6"], value="split", label="Mode", ) go = gr.Button("Separate", variant="primary") files_out = gr.File(label="Stems", file_count="multiple") summary_out = gr.Textbox(label="Status", interactive=False) go.click(fn=separate, inputs=[audio_in, mode_in], outputs=[files_out, summary_out]) if __name__ == "__main__": demo.queue(default_concurrency_limit=1) demo.launch()