steambench / backend /engine.py
Priyansu4002's picture
Deploy StemBench UI + FastAPI ONNX backend
714d0ee verified
Raw History Blame Contribute Delete
11.4 kB
"""GPU-accelerated (DirectML/CUDA) + CPU fallback ONNX separation engine with real chunk progress."""
from __future__ import annotations
import shutil
import subprocess
import threading
import time
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import onnxruntime as ort
import soundfile as sf
import torch
from huggingface_hub import hf_hub_download
if shutil.which("ffmpeg") is None:
try:
import static_ffmpeg
static_ffmpeg.add_paths()
except ImportError:
pass
ProgressFn = Callable[[int, str, float | None], None]
@dataclass(frozen=True)
class OnnxModelSpec:
id: str
label: str
description: str
repo: str
filename: str
n_fft: int
hop: int
window: str # "hann" | "ones"
normalized: bool
segment: int
frames: int
step: float
fade: float
standardize: bool
vocals_idx: int
prefer_gpu: bool
PROFILES: dict[str, OnnxModelSpec] = {
"studio": OnnxModelSpec(
id="studio",
label="Studio Quality",
description="Highest vocal and instrumental clarity.",
repo="audiojs/mel-roformer",
filename="mel-roformer.fp16.onnx",
n_fft=2048,
hop=441,
window="hann",
normalized=False,
segment=352800, # 8s @ 44.1 kHz
frames=801,
step=0.5,
fade=0.1,
standardize=False,
vocals_idx=0,
prefer_gpu=True,
),
"fast": OnnxModelSpec(
id="fast",
label="Fast Mode",
description="Quick separation for long tracks and mixes.",
repo="audiojs/scnet",
filename="scnet.int8.onnx",
n_fft=4096,
hop=1024,
window="ones",
normalized=True,
segment=485100, # 11s @ 44.1 kHz
frames=476,
step=0.5,
fade=0.1,
standardize=True,
vocals_idx=3, # drums=0, bass=1, other=2, vocals=3
prefer_gpu=False, # SCNet LSTM graph is faster on CPU and avoids DirectML fusion errors
),
}
SAMPLE_RATE = 44100
_lock = threading.Lock()
_sessions: dict[str, ort.InferenceSession] = {}
_warmed: set[str] = set()
def _create_session(spec: OnnxModelSpec) -> ort.InferenceSession:
model_path = hf_hub_download(spec.repo, spec.filename)
opts = ort.SessionOptions()
opts.enable_cpu_mem_arena = False
opts.enable_mem_pattern = False
if spec.prefer_gpu:
avail = ort.get_available_providers()
gpu_providers = [p for p in ("CUDAExecutionProvider", "DmlExecutionProvider") if p in avail]
if gpu_providers:
try:
return ort.InferenceSession(
model_path,
sess_options=opts,
providers=[*gpu_providers, "CPUExecutionProvider"],
)
except Exception:
pass # Fall back cleanly to CPU if GPU driver rejects graph
return ort.InferenceSession(model_path, sess_options=opts, providers=["CPUExecutionProvider"])
def _get_session(spec: OnnxModelSpec) -> ort.InferenceSession:
if spec.id not in _sessions:
_sessions[spec.id] = _create_session(spec)
return _sessions[spec.id]
def warmup_models() -> None:
"""Pre-load and compile GPU shaders in the background at server startup so first user job starts immediately."""
for profile_id in ("studio", "fast"):
spec = PROFILES[profile_id]
try:
with _lock:
sess = _get_session(spec)
if spec.id not in _warmed:
# Run one silent dummy tensor to compile DirectML/CUDA shaders ahead of time
inp = sess.get_inputs()[0]
shape = [int(d) if isinstance(d, int) and d > 0 else 1 for d in inp.shape]
sess.run(None, {inp.name: np.zeros(shape, dtype=np.float32)})
_warmed.add(spec.id)
except Exception:
pass
def is_warmed(profile_id: str = "studio") -> bool:
return profile_id in _warmed
def _decode_to_stereo_44k(input_path: Path) -> np.ndarray:
"""Decode any audio format to (N, 2) float32 at 44.1 kHz via ffmpeg."""
cmd = [
"ffmpeg",
"-v",
"error",
"-i",
str(input_path),
"-f",
"f32le",
"-acodec",
"pcm_f32le",
"-ac",
"2",
"-ar",
str(SAMPLE_RATE),
"pipe:1",
]
proc = subprocess.run(cmd, capture_output=True, check=False)
if proc.returncode != 0 or not proc.stdout:
raise RuntimeError(f"Could not decode audio file: {proc.stderr.decode(errors='ignore')}")
return np.frombuffer(proc.stdout, dtype=np.float32).reshape(-1, 2).copy()
def _demix_complex_onnx(
sess: ort.InferenceSession,
mix: np.ndarray,
spec: OnnxModelSpec,
on_progress: ProgressFn | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""Run overlap-add complex-spectrogram separation with real per-chunk progress and ETA."""
x = mix.T.astype(np.float32) # (2, N)
N = x.shape[1]
if spec.standardize:
mono = x.mean(axis=0, dtype=np.float64)
mean = float(mono.mean())
std = float(np.sqrt(np.mean((mono - mean) ** 2)) + 1e-8)
x_norm = (x - mean) / std
else:
std = 1.0
x_norm = x
n_fft, hop, T_frames, L = spec.n_fft, spec.hop, spec.frames, spec.segment
win = torch.ones(n_fft) if spec.window == "ones" else torch.hann_window(n_fft)
step_samples = max(1, int(L * spec.step))
border = L - step_samples
wide = border > 0 and N > 2 * border
if wide:
x_pad = np.stack([np.pad(x_norm[c], (border, border), mode="reflect") for c in range(2)], axis=0)
else:
x_pad = x_norm
M = x_pad.shape[1]
fade = int(L * spec.fade)
starts: list[int] = []
s = 0
while True:
starts.append(s)
if s + L >= M:
break
s += step_samples
total_chunks = len(starts)
acc = np.zeros((2, M), dtype=np.float64)
wsum = np.zeros(M, dtype=np.float64)
in_name = sess.get_inputs()[0].name
b = 4 * spec.vocals_idx
chunk_times: list[float] = []
for k, start in enumerate(starts):
t_chunk = time.perf_counter()
length = min(L, M - start)
seg = np.zeros((2, L), dtype=np.float32)
if length == L:
seg[:] = x_pad[:, start : start + L]
else:
mode = "reflect" if length > L // 2 else "constant"
for c in range(2):
seg[c] = np.pad(x_pad[c, start : start + length], (0, L - length), mode=mode)
pad_stft = max(L, (T_frames - 1) * hop)
if pad_stft > L:
seg_in = torch.zeros((2, pad_stft), dtype=torch.float32)
seg_in[:, :L] = torch.from_numpy(seg)
else:
seg_in = torch.from_numpy(seg)
stft = torch.stft(
seg_in,
n_fft=n_fft,
hop_length=hop,
win_length=n_fft,
window=win,
center=True,
normalized=spec.normalized,
return_complex=True,
)[:, :, :T_frames]
inp = np.empty((1, 4, stft.shape[1], T_frames), dtype=np.float32)
inp[0, 0] = stft[0].real.numpy()
inp[0, 1] = stft[0].imag.numpy()
inp[0, 2] = stft[1].real.numpy()
inp[0, 3] = stft[1].imag.numpy()
out = sess.run(None, {in_name: inp})[0]
v_spec = torch.complex(
torch.from_numpy(np.stack([out[0, b], out[0, b + 2]], axis=0)),
torch.from_numpy(np.stack([out[0, b + 1], out[0, b + 3]], axis=0)),
)
voc_seg = torch.istft(
v_spec,
n_fft=n_fft,
hop_length=hop,
win_length=n_fft,
window=win,
center=True,
normalized=spec.normalized,
length=L,
).numpy()
w = np.ones(length, dtype=np.float64)
if k > 0 and fade > 1:
w[:fade] = np.arange(fade) / (fade - 1)
if k < total_chunks - 1 and fade > 1:
tail = np.arange(fade - 1, -1, -1) / (fade - 1)
span = max(0, length - (L - fade))
if span > 0:
w[L - fade : length] = np.minimum(w[L - fade : length], tail[:span])
acc[:, start : start + length] += voc_seg[:, :length] * w
wsum[start : start + length] += w
chunk_times.append(time.perf_counter() - t_chunk)
if on_progress is not None:
done = k + 1
pct = min(94, max(8, int(8 + (done / total_chunks) * 86)))
# Use recent rolling average so ETA reflects steady-state GPU speed
recent = chunk_times[-5:]
avg_per_chunk = sum(recent) / len(recent)
eta = max(0.0, avg_per_chunk * (total_chunks - done))
on_progress(pct, "Separating vocals & music...", round(eta, 1))
off = border if wide else 0
voc = (acc[:, off : off + N] / np.maximum(wsum[off : off + N], 1e-8) * std).T.astype(np.float32)
inst = (mix - voc).astype(np.float32)
return voc, inst
def _write_stem(audio: np.ndarray, out_path: Path, fmt: str) -> Path:
peak = float(np.max(np.abs(audio)))
if peak > 0.99:
audio = audio * (0.99 / peak)
if fmt in ("WAV", "FLAC"):
sf.write(out_path, audio, SAMPLE_RATE, subtype="PCM_16" if fmt == "WAV" else None)
return out_path
tmp_wav = out_path.with_suffix(".tmp.wav")
sf.write(tmp_wav, audio, SAMPLE_RATE, subtype="PCM_16")
proc = subprocess.run(
["ffmpeg", "-v", "error", "-y", "-i", str(tmp_wav), "-b:a", "320k", str(out_path)],
capture_output=True,
check=False,
)
tmp_wav.unlink(missing_ok=True)
if proc.returncode != 0:
raise RuntimeError(f"Could not encode {fmt}: {proc.stderr.decode(errors='ignore')}")
return out_path
def separate_file(
input_path: Path,
output_dir: Path,
profile_id: str = "studio",
output_format: str = "WAV",
on_progress: ProgressFn | None = None,
) -> dict:
"""Run stem separation for a single audio file and return stem paths + timing."""
spec = PROFILES.get(profile_id)
if spec is None:
raise ValueError(f"Unknown profile '{profile_id}'. Valid: {list(PROFILES.keys())}")
fmt = output_format.upper()
if fmt not in ("WAV", "MP3", "FLAC"):
raise ValueError("output_format must be WAV, MP3, or FLAC")
output_dir.mkdir(parents=True, exist_ok=True)
t0 = time.perf_counter()
if on_progress:
on_progress(4, "Preparing audio track...", None)
mix = _decode_to_stereo_44k(input_path)
if on_progress:
on_progress(7, "Separating vocals & music...", None)
with _lock:
sess = _get_session(spec)
voc, inst = _demix_complex_onnx(sess, mix, spec, on_progress=on_progress)
if on_progress:
on_progress(96, "Finalizing audio tracks...", 1.0)
ext = fmt.lower()
voc_path = _write_stem(voc, output_dir / f"vocals.{ext}", fmt)
inst_path = _write_stem(inst, output_dir / f"instrumental.{ext}", fmt)
elapsed = round(time.perf_counter() - t0, 2)
if on_progress:
on_progress(100, "Complete", 0.0)
return {
"vocals_path": voc_path,
"instrumental_path": inst_path,
"model": spec.label,
"profile": spec.id,
"elapsed_sec": elapsed,
}