"""Model-agnostic separation interface plus the audio-separator implementation. `SeparationEngine.separate(input, step, out_dir, on_progress) -> {model_stem_name: path}` is the only contract the rest of the pipeline uses, so models/libraries can be swapped without touching API or UI. """ from __future__ import annotations import logging import re import threading import time from collections.abc import Callable from pathlib import Path from typing import Protocol import numpy as np from stemdeck.audio_io import read_audio, write_float_wav from stemdeck.settings import ModelStep log = logging.getLogger(__name__) ProgressFn = Callable[[float, str | None], None] # (fraction 0..1, optional message) HEADROOM_PEAK = 0.5 # audio-separator rescales anything above its 0..1 threshold; keep well below it DEVICE_RTF_FACTOR = {"cuda": 1.0, "mps": 2.0, "cpu": 8.0} # config rtf values were measured on CUDA OUTPUT_NAME = re.compile(r"_\(([^)]+)\)") TICK_SEC = 1.0 class SeparationError(RuntimeError): """Friendly, user-facing separation failure.""" class SeparationEngine(Protocol): def separate(self, input_path: Path, step: ModelStep, out_dir: Path, on_progress: ProgressFn) -> dict[str, Path]: ... # ------------------------------------------------------------------ progress capture via tqdm _active_progress: list[Callable[[float, str], None]] = [] def _install_tqdm_hook() -> None: """Route every tqdm bar audio-separator creates to the active progress callback.""" import tqdm as tqdm_module if getattr(tqdm_module.tqdm, "_stemdeck_hook", False): return base = tqdm_module.tqdm class ReportingTqdm(base): # type: ignore[misc, valid-type] _stemdeck_hook = True def __init__(self, *args, **kwargs) -> None: # noqa: ANN002, ANN003 kwargs.setdefault("disable", False) kwargs["file"] = _NullWriter() super().__init__(*args, **kwargs) def update(self, n: float | None = 1) -> bool | None: # noqa: D401 result = super().update(n) if _active_progress and self.total: unit = "download" if self.unit == "iB" else "compute" _active_progress[-1](min(1.0, self.n / self.total), unit) return result tqdm_module.tqdm = ReportingTqdm class _NullWriter: def write(self, _s: str) -> int: return 0 def flush(self) -> None: return None # ------------------------------------------------------------------ audio-separator implementation class AudioSeparatorEngine: def __init__(self, models_dir: Path, device: str, duration_sec: float) -> None: self.models_dir = models_dir self.device = device self.duration_sec = duration_sec _install_tqdm_hook() def _precision(self, step: ModelStep) -> str: if self.device != "cuda" and step.precision != "fp32": return "fp32" # fp16 kernels are only worthwhile (and verified) on CUDA here return step.precision def expected_seconds(self, step: ModelStep) -> float: return max(5.0, step.rtf * self.duration_sec * DEVICE_RTF_FACTOR.get(self.device, 8.0)) def separate(self, input_path: Path, step: ModelStep, out_dir: Path, on_progress: ProgressFn) -> dict[str, Path]: out_dir.mkdir(parents=True, exist_ok=True) audio = read_audio(input_path) peak = float(np.max(np.abs(audio))) if audio.size else 0.0 gain = HEADROOM_PEAK / peak if peak > 1e-9 else 1.0 scaled = out_dir / "_input.wav" write_float_wav(scaled, audio * gain) try: outputs = self._run_with_oom_retry(scaled, step, out_dir, on_progress) finally: scaled.unlink(missing_ok=True) for path in outputs.values(): # undo the headroom gain exactly write_float_wav(path, read_audio(path) / gain) return outputs def _run_with_oom_retry( self, scaled: Path, step: ModelStep, out_dir: Path, on_progress: ProgressFn ) -> dict[str, Path]: try: return self._run(scaled, step, out_dir, on_progress, low_memory=False) except Exception as exc: # noqa: BLE001 - torch raises several OOM types if not _is_oom(exc): raise log.warning("Out of memory on %s, retrying with smaller chunks", step.model) _free_gpu() try: return self._run(scaled, step, out_dir, on_progress, low_memory=True) except Exception as exc2: # noqa: BLE001 if _is_oom(exc2): raise SeparationError( "The GPU ran out of memory on this song even with smaller chunks. " "Try the Fast quality, or close other apps that use the GPU." ) from exc2 raise def _run( self, scaled: Path, step: ModelStep, out_dir: Path, on_progress: ProgressFn, low_memory: bool ) -> dict[str, Path]: from audio_separator.separator import Separator precision = self._precision(step) expected = self.expected_seconds(step) start = time.perf_counter() best = 0.0 def report(bar_fraction: float, unit: str) -> None: nonlocal best if unit == "download": on_progress(best, f"Downloading model {step.model} ({bar_fraction:.0%})") return time_fraction = (time.perf_counter() - start) / expected best = min(0.98, max(best, bar_fraction, time_fraction)) on_progress(best, None) # Model loading / CUDA start-up emit no tqdm updates: tick on elapsed time so the UI never looks frozen. stop_ticker = threading.Event() def tick() -> None: while not stop_ticker.wait(TICK_SEC): report(0.0, "compute") ticker = threading.Thread(target=tick, name="progress-ticker", daemon=True) _active_progress.append(report) ticker.start() try: sep = Separator( log_level=logging.WARNING, model_file_dir=str(self.models_dir), output_dir=str(out_dir), output_format="WAV", normalization_threshold=1.0, use_soundfile=True, use_autocast=precision == "autocast", use_native_fp16=precision == "fp16", demucs_params={"segment_size": "Default", "shifts": step.shifts, "overlap": 0.25, "segments_enabled": True}, mdxc_params={"segment_size": 128 if low_memory else 256, "override_model_segment_size": low_memory, "batch_size": 1, "overlap": step.overlap, "pitch_shift": 0}, mdx_params={"hop_length": 1024, "segment_size": 128 if low_memory else 256, "overlap": 0.25, "batch_size": 1, "enable_denoise": False}, vr_params={"batch_size": 1, "window_size": 512, "aggression": 5, "enable_tta": False, "enable_post_process": False, "post_process_threshold": 0.2, "high_end_process": False}, ) sep.load_model(model_filename=step.model) files = sep.separate(str(scaled)) finally: stop_ticker.set() ticker.join(timeout=2) _active_progress.pop() on_progress(1.0, None) outputs: dict[str, Path] = {} for f in files: path = Path(f) if Path(f).is_absolute() else out_dir / Path(f).name # audio-separator appends "_()_" to the input name; the LAST group is the stem. groups = OUTPUT_NAME.findall(path.stem) outputs[(groups[-1] if groups else path.stem).lower()] = path if not outputs: raise SeparationError(f"The model {step.model} produced no output files.") return outputs def _is_oom(exc: BaseException) -> bool: text = f"{type(exc).__name__}: {exc}".lower() return "out of memory" in text or "outofmemory" in text or "cudnn_status_alloc_failed" in text def _free_gpu() -> None: try: import gc import torch gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() except Exception: # noqa: BLE001 log.debug("could not free GPU memory", exc_info=True) def pick_output(outputs: dict[str, Path], *names: str) -> Path: """Find a model output by (partial) name, e.g. pick_output(o, 'instrumental', 'other').""" for wanted in names: for name, path in outputs.items(): if name == wanted: return path for wanted in names: for name, path in outputs.items(): if wanted in name and not name.startswith("no "): return path raise SeparationError(f"Expected one of {names} from the model, got {sorted(outputs)}")