stemdeck-gpu / stemdeck /pipeline /sam_engine.py
AnjaneyaTurai's picture
Deploy the StemDeck GPU service
25e4412 verified
Raw History Blame Contribute Delete
4.84 kB
"""SAM Audio engine: runs `stemdeck.sam_runner` in the separate SAM venv and returns a 44.1 kHz stereo target.
SAM Audio works on a mono 48 kHz signal. To keep the extracted instrument's stereo placement, the mono result is
turned into a time-frequency mask and applied to each channel of the input stem.
"""
from __future__ import annotations
import logging
import subprocess
import threading
import time
from pathlib import Path
import numpy as np
from stemdeck.audio_io import SAMPLE_RATE, fit_length, read_audio, write_float_wav
from stemdeck.pipeline.separator import ProgressFn, SeparationError
from stemdeck.settings import PROJECT_ROOT, SamAudioConfig, Settings
log = logging.getLogger(__name__)
# Measured on a GTX 1650 Ti / 16 GB RAM: importing the SAM stack + loading the 5 GB checkpoint takes ~5-8 min
# (Windows Defender scans the venv's files; RAM is tight). Only drives the progress/ETA estimate.
SAM_STARTUP_SEC = 360.0
N_FFT, HOP = 2048, 512
class SamAudioEngine:
def __init__(self, settings: Settings, cfg: SamAudioConfig, duration_sec: float) -> None:
self.python = settings.resolve(cfg.python)
self.cfg = cfg
self.cache_dir = settings.models_dir / "sam-audio"
self.duration_sec = duration_sec
def expected_seconds(self) -> float:
return SAM_STARTUP_SEC + self.cfg.rtf * self.duration_sec
def extract(self, input_path: Path, prompt: str, out_dir: Path, on_progress: ProgressFn) -> np.ndarray:
if not self.python.exists():
raise SeparationError("SAM Audio is not installed. See the README section 'Isolate anything'.")
out_dir.mkdir(parents=True, exist_ok=True)
mix = read_audio(input_path)
mono_in = out_dir / "sam_input.wav"
write_float_wav(mono_in, np.repeat(mix.mean(axis=1, keepdims=True), 2, axis=1))
target_path = out_dir / "sam_target.wav"
self._run(mono_in, prompt, target_path, on_progress)
target_mono = _load_resampled_mono(target_path, len(mix))
return apply_mono_mask(mix, target_mono)
def _run(self, input_path: Path, prompt: str, target_path: Path, on_progress: ProgressFn) -> None:
cmd = [str(self.python), "-m", "stemdeck.sam_runner", str(input_path), prompt, str(target_path),
"--size", self.cfg.model_size, "--dtype", self.cfg.dtype, "--chunk", str(self.cfg.chunk_sec),
"--cache-dir", str(self.cache_dir), "--ode-step", str(self.cfg.ode_step_size)]
proc = subprocess.Popen(cmd, cwd=str(PROJECT_ROOT / "backend"), stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")
stderr_tail: list[str] = []
threading.Thread(target=_drain, args=(proc.stderr, stderr_tail), daemon=True).start()
start, reported, error = time.perf_counter(), 0.0, None
assert proc.stdout is not None
for line in proc.stdout:
line = line.strip()
if line.startswith("PROGRESS "):
reported = max(reported, float(line.split()[1]))
elif line.startswith("ERROR "):
error = line[6:]
elapsed_frac = (time.perf_counter() - start) / self.expected_seconds()
on_progress(min(0.97, max(reported, elapsed_frac)), None)
code = proc.wait()
if code != 0 or error:
log.error("sam_runner failed (%s): %s", code, "".join(stderr_tail[-40:]))
raise SeparationError(error or "SAM Audio stopped unexpectedly. See data/logs/worker.log.")
on_progress(1.0, None)
def _drain(stream, sink: list[str]) -> None: # noqa: ANN001
for line in stream:
sink.append(line)
if len(sink) > 200:
del sink[:100]
def _load_resampled_mono(path: Path, n_frames: int) -> np.ndarray:
import soundfile as sf
import soxr
data, sr = sf.read(str(path), dtype="float32", always_2d=True)
mono = data.mean(axis=1)
if sr != SAMPLE_RATE:
mono = soxr.resample(mono, sr, SAMPLE_RATE, quality="HQ").astype(np.float32)
return fit_length(mono[:, None], n_frames)[:, 0]
def apply_mono_mask(mix: np.ndarray, target_mono: np.ndarray) -> np.ndarray:
"""Soft ratio mask |T| / |M| from the mono estimate, applied to each channel of the stereo input."""
import librosa
mix_mono = mix.mean(axis=1)
spec_mix = librosa.stft(mix_mono, n_fft=N_FFT, hop_length=HOP)
spec_tgt = librosa.stft(target_mono, n_fft=N_FFT, hop_length=HOP)
mask = np.clip(np.abs(spec_tgt) / (np.abs(spec_mix) + 1e-8), 0.0, 1.0)
channels = []
for c in range(mix.shape[1]):
spec = librosa.stft(mix[:, c], n_fft=N_FFT, hop_length=HOP)
channels.append(librosa.istft(spec * mask, hop_length=HOP, length=len(mix)))
return np.stack(channels, axis=1).astype(np.float32)