mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented foundation of STEM support
This commit is contained in:
1 parent
376569ec75
commit
681add852a
25 files changed
+1816
-17
No files matched your search
@@ -0,0 +1,10 @@
|
||||
"""Konduktor's stem engine: Demucs htdemucs_ft behind a small process protocol.
|
||||
|
||||
A separate program from Konduktor's backend — it carries torch, which the
|
||||
backend deliberately does not — built and released on its own channel
|
||||
(`engine-v*`) and downloaded on first use. It imports nothing from `konduktor`.
|
||||
"""
|
||||
|
||||
#: Bumped whenever the engine's behaviour or protocol changes; the app names the
|
||||
#: engine version it needs.
|
||||
VERSION = "1.0.0"
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Command line: `info` and a one-shot `separate`.
|
||||
|
||||
Audio crosses as RAW planar float32 files — shape (2, n), C order — rather than
|
||||
WAV: nothing to parse, `np.fromfile`/`memmap` either side, and no clamping (a
|
||||
mastered track decodes above 0 dBFS as float, and its stems may too).
|
||||
|
||||
Protocol output is JSON lines on stdout; everything else (torch and demucs
|
||||
print) goes to stderr, so a stray print can never corrupt a message.
|
||||
|
||||
python -m konduktor_engine info
|
||||
python -m konduktor_engine separate --input mix.f32 --samples N \\
|
||||
--output-dir OUT --weights DIR [--device auto|cpu|gpu|mps|cuda] [--seed 0]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from . import VERSION
|
||||
|
||||
|
||||
def _protocol():
|
||||
"""A private copy of stdout for messages; `sys.stdout` becomes stderr."""
|
||||
fd = os.dup(1)
|
||||
os.dup2(2, 1)
|
||||
sys.stdout = sys.stderr
|
||||
return os.fdopen(fd, "w", buffering=1, encoding="utf-8")
|
||||
|
||||
|
||||
def _emit(out, **msg) -> None:
|
||||
out.write(json.dumps(msg) + "\n")
|
||||
out.flush()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="konduktor-engine")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
sub.add_parser("info")
|
||||
sep = sub.add_parser("separate")
|
||||
sep.add_argument("--input", required=True)
|
||||
sep.add_argument("--samples", type=int, required=True)
|
||||
sep.add_argument("--output-dir", required=True)
|
||||
sep.add_argument("--weights", required=True)
|
||||
sep.add_argument("--device", default="auto")
|
||||
sep.add_argument("--seed", type=int, default=0)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
out = _protocol()
|
||||
from . import core
|
||||
|
||||
if args.command == "info":
|
||||
import torch
|
||||
|
||||
_emit(out, event="info", version=VERSION, torch=torch.__version__,
|
||||
devices=core.available_devices(), model=core.MODEL)
|
||||
return 0
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
device = core.pick_device(args.device)
|
||||
pcm = np.fromfile(args.input, dtype=np.float32)
|
||||
if pcm.size != 2 * args.samples:
|
||||
raise ValueError(f"{args.input}: expected {2 * args.samples} floats, found {pcm.size}")
|
||||
pcm = pcm.reshape(2, args.samples)
|
||||
t0 = time.time()
|
||||
model = core.load_model(args.weights)
|
||||
_emit(out, event="loaded", device=device, seconds=round(time.time() - t0, 2))
|
||||
stems = core.separate(model, pcm, device, seed=args.seed,
|
||||
on_progress=lambda f: _emit(out, event="progress", fraction=round(f, 4)))
|
||||
folder = Path(args.output_dir)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for name, x in stems.items():
|
||||
x.tofile(folder / f"{name}.f32")
|
||||
_emit(out, event="done", seconds=round(time.time() - t0, 2), device=device)
|
||||
return 0
|
||||
except Exception as ex: # noqa: BLE001 — reported to the caller, not raised
|
||||
_emit(out, event="error", message=f"{type(ex).__name__}: {ex}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,89 @@
|
||||
"""The separation itself: htdemucs_ft over a stereo 44.1 kHz mix.
|
||||
|
||||
Kept free of I/O and protocol so the CLI (`__main__`), the frozen engine and
|
||||
the golden test all run the same code. Weights are loaded from a LOCAL folder
|
||||
(the four `.safetensors` of `adefossez/HTDemucs-ft` plus `htdemucs_ft.yaml`):
|
||||
the engine never goes online — Konduktor downloads and verifies the weights,
|
||||
since their licence rules out shipping them inside the engine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import numpy as np
|
||||
|
||||
#: Demucs' outputs, in the order the stem file stores them after the mix.
|
||||
SOURCES = ("drums", "bass", "other", "vocals")
|
||||
MODEL = "htdemucs_ft"
|
||||
SAMPLE_RATE = 44100
|
||||
#: As benchmarked (M3 Pro, 2026-09-29): one random shift, 25 % overlap.
|
||||
SHIFTS, OVERLAP = 1, 0.25
|
||||
|
||||
|
||||
def available_devices() -> list[str]:
|
||||
import torch
|
||||
|
||||
devices = ["cpu"]
|
||||
if torch.backends.mps.is_available():
|
||||
devices.insert(0, "mps")
|
||||
if torch.cuda.is_available():
|
||||
devices.insert(0, "cuda")
|
||||
return devices
|
||||
|
||||
|
||||
def pick_device(requested: str = "auto") -> str:
|
||||
"""`auto` = the fastest available; `gpu` = MPS or CUDA, else CPU."""
|
||||
devices = available_devices()
|
||||
if requested in ("auto", "gpu"):
|
||||
return devices[0]
|
||||
if requested not in devices:
|
||||
raise ValueError(f"Device {requested!r} is not available here ({', '.join(devices)})")
|
||||
return requested
|
||||
|
||||
|
||||
def load_model(weights: Path | str):
|
||||
"""The htdemucs_ft bag from a local weights folder."""
|
||||
import yaml
|
||||
from demucs.apply import BagOfModels
|
||||
from demucs.hf import load_safetensors_model
|
||||
|
||||
folder = Path(weights)
|
||||
with open(folder / f"{MODEL}.yaml", encoding="utf-8") as f:
|
||||
bag = yaml.safe_load(f)
|
||||
models = [load_safetensors_model(folder / f"{sig}.safetensors") for sig in bag["models"]]
|
||||
model = BagOfModels(models, bag.get("weights"), bag.get("segment"))
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
|
||||
def separate(model, pcm: np.ndarray, device: str, *, seed: int = 0,
|
||||
on_progress: Callable[[float], None] | None = None) -> dict[str, np.ndarray]:
|
||||
"""Four stems, each shaped like `pcm` (2, n) float32.
|
||||
|
||||
Seeded per call: `shifts=1` applies a RANDOM time shift, so without a seed
|
||||
the same track separates slightly differently each time (measured: Vox 9.2
|
||||
vs 9.6 dB SDR between runs) and a re-conversion would not be reproducible.
|
||||
"""
|
||||
import torch
|
||||
from demucs.apply import apply_model
|
||||
|
||||
if pcm.ndim != 2 or pcm.shape[0] != 2:
|
||||
raise ValueError("Expected a stereo mix shaped (2, n)")
|
||||
n = pcm.shape[1]
|
||||
torch.manual_seed(seed)
|
||||
|
||||
def callback(d: dict) -> None:
|
||||
if on_progress is None or d.get("state") != "end":
|
||||
return
|
||||
models = max(1, int(d.get("models", 1)))
|
||||
done = min(1.0, (int(d.get("segment_offset", 0)) + 1) / max(1, n))
|
||||
on_progress(min(1.0, (int(d.get("model_idx_in_bag", 0)) + done) / models))
|
||||
|
||||
mix = torch.from_numpy(np.ascontiguousarray(pcm, dtype=np.float32))[None]
|
||||
with torch.no_grad():
|
||||
out = apply_model(model, mix, shifts=SHIFTS, split=True, overlap=OVERLAP,
|
||||
progress=False, device=device, callback=callback)[0]
|
||||
out = out.cpu().numpy().astype(np.float32, copy=False)
|
||||
order = [model.sources.index(name) for name in SOURCES]
|
||||
return {name: np.ascontiguousarray(out[i]) for name, i in zip(SOURCES, order)}
|
||||
@@ -0,0 +1,11 @@
|
||||
# Konduktor stem engine — Python 3.12. NOT the backend's requirements: this is a
|
||||
# separate program (it carries torch; the backend deliberately does not).
|
||||
# Pinned to the versions the 2026-09-29 benchmark and the user's listening test
|
||||
# ran on. Hashes are added when the frozen build (engine.yml) lands.
|
||||
torch==2.14.0
|
||||
demucs==4.1.0
|
||||
numpy==2.5.3
|
||||
safetensors==0.8.0
|
||||
pyyaml==6.0.3
|
||||
einops==0.8.2
|
||||
julius==0.2.8
|
||||
Reference in new issue
Block a user