Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Evaluation: separation metrics (SI-SDR, SDR, stems vs input, bed level and stereo, noise, speed) and WER with Whisper

Claudee05ad55d7b83
diff --git a/scripts/eval/eval.mjs b/scripts/eval/eval.mjs
index b099a406..a63fad76 100644
--- a/scripts/eval/eval.mjs
+++ b/scripts/eval/eval.mjs
@@ -100,7 +100,7 @@ pnpm eval:covers --versions [--dry-run] [--public-dir public] [--manifest …]
history: "pnpm eval:history [--suite soul] [--case soul/v1-general] [--limit 20]",
validate: "pnpm eval:validate [suite files…] checks every case file and that the generated suites match the research",
trash: "pnpm eval:trash <runId> [--dry-run] moves the run's generations to that Fuobe's Trash (its results here stay)",
- setup: "pnpm eval:setup [--identity] [--download [--dinov2] [--scrfd]] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv)",
+ setup: "pnpm eval:setup [--identity] [--asr] [--download [--dinov2] [--scrfd]] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv); --asr adds Whisper for the separation suite's word error rate",
};
function usage() {
@@ -557,7 +557,7 @@ function coversFromMastersCmd(v, ctx) {
}
async function setup(args, ctx) {
- const { values: v } = parse(args, { identity: { type: "boolean" }, dinov2: { type: "boolean" }, scrfd: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });
+ const { values: v } = parse(args, { identity: { type: "boolean" }, asr: { type: "boolean" }, dinov2: { type: "boolean" }, scrfd: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });
if (v.help) return ctx.print(HELP.setup), 0;
const step = (cmd, a, opts = {}) => {
ctx.note(`$ ${cmd} ${a.join(" ")}`);
@@ -569,7 +569,8 @@ async function setup(args, ctx) {
if (!fs.existsSync(path.join(METRICS_DIR, py))) step("uv", ["venv", ".venv", "--python", ">=3.11"]);
step("uv", ["pip", "install", "--python", py, "-r", "requirements.txt", "--torch-backend", v["torch-backend"] ?? "cpu"]);
if (v.identity) step("uv", ["pip", "install", "--python", py, "-r", "requirements-identity.txt"]);
- if (v.download) step(py, ["-m", "fuobe_metrics.download", ...(v.identity ? ["--identity"] : []), ...(v.dinov2 ? ["--dinov2"] : []), ...(v.scrfd ? ["--scrfd"] : [])]);
+ if (v.asr) step("uv", ["pip", "install", "--python", py, "-r", "requirements-asr.txt", "--torch-backend", v["torch-backend"] ?? "cpu"]);
+ if (v.download) step(py, ["-m", "fuobe_metrics.download", ...(v.identity ? ["--identity"] : []), ...(v.asr ? ["--asr"] : []), ...(v.dinov2 ? ["--dinov2"] : []), ...(v.scrfd ? ["--scrfd"] : [])]);
ctx.print(`Metrics ready in ${path.join(METRICS_DIR, ".venv")}${v.download ? "" : " (weights download on first use, or run pnpm eval:setup --download)"}.`);
return 0;
}
diff --git a/scripts/eval/lib/metric-info.mjs b/scripts/eval/lib/metric-info.mjs
index dfa2b320..9681b4ec 100644
--- a/scripts/eval/lib/metric-info.mjs
+++ b/scripts/eval/lib/metric-info.mjs
@@ -18,6 +18,21 @@ export const METRIC_INFO = {
continuity: { label: "Shot continuity", better: "higher", unit: "cosine", tie: 0.005, digits: 3 },
paletteFit: { label: "Palette distance", better: "lower", unit: "mean ΔE76", tie: 0.5, digits: 1 },
paletteCover: { label: "Palette used", better: "higher", unit: "0–1", tie: 0.05, digits: 2 },
+ voiceSiSdr: { label: "Dialogue SI-SDR", better: "higher", unit: "dB", tie: 0.3, digits: 1 },
+ musicSiSdr: { label: "Music SI-SDR", better: "higher", unit: "dB", tie: 0.3, digits: 1 },
+ effectsSiSdr: { label: "Effects SI-SDR", better: "higher", unit: "dB", tie: 0.3, digits: 1 },
+ backgroundSiSdr: { label: "Music & effects SI-SDR", better: "higher", unit: "dB", tie: 0.3, digits: 1 },
+ voiceSdr: { label: "Dialogue SDR", better: "higher", unit: "dB", tie: 0.3, digits: 1 },
+ backgroundSdr: { label: "Music & effects SDR", better: "higher", unit: "dB", tie: 0.3, digits: 1 },
+ mixError: { label: "Stems vs input", better: "lower", unit: "dB under the input", tie: 3, digits: 1 },
+ bedLevel: { label: "Bed level vs reference", better: "none", unit: "dB", tie: 0, digits: 2 },
+ bedPeak: { label: "Bed peak", better: "none", unit: "dBFS", tie: 0, digits: 2 },
+ stereoCorrGap: { label: "Bed stereo gap", better: "lower", unit: "|Δ L/R correlation|", tie: 0.02, digits: 3 },
+ noiseInVoice: { label: "Noise left in the dialogue", better: "lower", unit: "share of the known noise", tie: 0.03, digits: 2 },
+ speedX: { label: "Speed", better: "higher", unit: "x real time", tie: 0.02, digits: 2 },
+ wer: { label: "WER, dialogue stem", better: "lower", unit: "0–1", tie: 0.02, digits: 3 },
+ werInput: { label: "WER, input as is", better: "lower", unit: "0–1", tie: 0.02, digits: 3 },
+ werTranscript: { label: "WER, the job's transcript", better: "lower", unit: "0–1", tie: 0.02, digits: 3 },
seconds: { label: "Time", better: "lower", unit: "s (wall clock)", tie: 0.5, digits: 1 },
costUsd: { label: "Cost", better: "lower", unit: "US$", tie: 0.0005, digits: 4 },
vramGb: { label: "Peak memory", better: "lower", unit: "GB", tie: 0.1, digits: 2 },
diff --git a/scripts/eval/lib/run.mjs b/scripts/eval/lib/run.mjs
index 9a91020f..42edba18 100644
--- a/scripts/eval/lib/run.mjs
+++ b/scripts/eval/lib/run.mjs
@@ -641,13 +641,13 @@ async function download(client, gens, folder, runFolder) {
const dest = path.join(folder, `${n}${role}.txt`);
fs.mkdirSync(folder, { recursive: true });
fs.writeFileSync(dest, o.text);
- files.push({ file: path.relative(runFolder, dest), kind: "text", generationId: g.id, bytes: Buffer.byteLength(o.text) });
+ files.push({ file: path.relative(runFolder, dest), kind: "text", generationId: g.id, bytes: Buffer.byteLength(o.text), ...(o.meta?.role && { role: o.meta.role }) });
continue;
}
const ext = /^\.[a-z\d]{1,10}$/i.exec(path.extname(new URL(o.url, "http://x").pathname))?.[0] ?? ".bin";
const dest = path.join(folder, `${n}${role}${ext}`);
const bytes = await client.download(o.url, dest);
- files.push({ file: path.relative(runFolder, dest), url: o.url, kind: o.kind, contentType: o.contentType ?? null, generationId: g.id, bytes, ...(o.meta?.role && { role: o.meta.role }), ...(o.meta?.demo && { demo: true }) });
+ files.push({ file: path.relative(runFolder, dest), url: o.url, kind: o.kind, contentType: o.contentType ?? null, generationId: g.id, bytes, ...(o.meta?.role && { role: o.meta.role }), ...(o.meta?.stem && { stem: o.meta.stem }), ...(o.meta?.demo && { demo: true }) });
}
}
return files;
diff --git a/scripts/eval/lib/schema.mjs b/scripts/eval/lib/schema.mjs
index 57fa0ff8..c9c15627 100644
--- a/scripts/eval/lib/schema.mjs
+++ b/scripts/eval/lib/schema.mjs
@@ -5,7 +5,7 @@
import { z } from "zod";
export const ENGINES = /** @type {const} */ (["demo", "open", "cloud"]);
-export const METRICS = /** @type {const} */ (["clip", "aesthetic", "style", "identity", "temporal", "lipsync", "continuity", "palette"]);
+export const METRICS = /** @type {const} */ (["clip", "aesthetic", "style", "identity", "temporal", "lipsync", "continuity", "palette", "separation", "wer"]);
const Slug = z.string().regex(/^[a-z0-9][a-z0-9-]*$/, "lower-case letters, digits and dashes");
const CaseId = z.string().max(120).regex(/^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*)*$/, "lower-case words joined by - . _ and /");
diff --git a/scripts/eval/metrics/fuobe_metrics/media.py b/scripts/eval/metrics/fuobe_metrics/media.py
index dc91cea1..9c145acf 100644
--- a/scripts/eval/metrics/fuobe_metrics/media.py
+++ b/scripts/eval/metrics/fuobe_metrics/media.py
@@ -106,3 +106,21 @@ def images_of(path: str | pathlib.Path, frames: int = 4) -> list[Image.Image]:
arr = arr[np.linspace(0, len(arr) - 1, frames).astype(int)]
return [Image.fromarray(a) for a in arr]
return []
+
+
+def audio_channels(path: str | pathlib.Path, sr: int = 44100) -> np.ndarray | None:
+ """The sound with its channels kept (channels × samples, float32) at `sr` Hz, or None when there is none. Files with
+ more than 2 channels come back as they are; the separation metrics compare mono stems with their mono mean."""
+ r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=channels", "-of", "csv=p=0", str(path)], capture_output=True, text=True)
+ try:
+ channels = int((r.stdout or "").strip().splitlines()[0])
+ except (ValueError, IndexError):
+ channels = 0
+ if not channels:
+ return None
+ r = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vn", "-ac", str(channels), "-ar", str(sr), "-f", "f32le", "-"], capture_output=True)
+ if r.returncode != 0 or not r.stdout:
+ return None
+ a = np.frombuffer(r.stdout, dtype="<f4")
+ n = len(a) // channels
+ return a[: n * channels].reshape(n, channels).T.copy()
diff --git a/scripts/eval/metrics/fuobe_metrics/models.py b/scripts/eval/metrics/fuobe_metrics/models.py
index c19d3738..e65c0614 100644
--- a/scripts/eval/metrics/fuobe_metrics/models.py
+++ b/scripts/eval/metrics/fuobe_metrics/models.py
@@ -205,3 +205,35 @@ class Faces:
return None
f = max(faces, key=lambda x: float((x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1])))
return {"embedding": np.asarray(f.normed_embedding, dtype=np.float64), "box": [float(v) for v in f.bbox]}
+
+
+class Asr:
+ """Whisper base.en (transformers) on 16 kHz mono audio → text. Optional: pnpm eval:setup --asr."""
+
+ def __init__(self, device: str = "cpu"):
+ try:
+ from transformers import WhisperForConditionalGeneration, WhisperProcessor # noqa: PLC0415
+ except ImportError as e:
+ raise Missing("speech recognition needs transformers: run pnpm eval:setup --asr") from e
+ torch = _torch()
+ m = MODELS["whisper-base-en"]
+ folder = None
+ for f in m["files"]:
+ folder = pathlib.Path(_download("whisper-base-en", f)).parent
+ self.processor = WhisperProcessor.from_pretrained(str(folder))
+ self.model = WhisperForConditionalGeneration.from_pretrained(str(folder)).to(device).eval()
+ self.device = device
+ self.torch = torch
+
+ def text(self, audio: np.ndarray, sr: int = 16000) -> str:
+ """The words in up to the first 30 s of each 30 s window, joined (the suite's clips are 10–30 s)."""
+ out = []
+ for i in range(0, max(1, len(audio)), 30 * sr):
+ chunk = np.asarray(audio[i : i + 30 * sr], dtype=np.float32)
+ if len(chunk) < sr // 10:
+ continue
+ feats = self.processor(chunk, sampling_rate=sr, return_tensors="pt").input_features.to(self.device)
+ with self.torch.no_grad():
+ ids = self.model.generate(feats, max_new_tokens=220)
+ out.append(self.processor.batch_decode(ids, skip_special_tokens=True)[0].strip())
+ return " ".join(t for t in out if t)
diff --git a/scripts/eval/metrics/fuobe_metrics/registry.py b/scripts/eval/metrics/fuobe_metrics/registry.py
index 2e84cb6b..749bba42 100644
--- a/scripts/eval/metrics/fuobe_metrics/registry.py
+++ b/scripts/eval/metrics/fuobe_metrics/registry.py
@@ -11,6 +11,14 @@ FAMILIES = {
"lipsync": ["lipsync", "lipsyncOffset"],
"continuity": ["continuity"],
"palette": ["paletteFit", "paletteCover"],
+ # Soundtrack separation against the case's known stems (scripts/eval/fixtures/make-separation.py).
+ "separation": [
+ "voiceSiSdr", "musicSiSdr", "effectsSiSdr", "backgroundSiSdr", "voiceSdr", "backgroundSdr",
+ "mixError", "bedLevel", "bedPeak", "stereoCorrGap", "noiseInVoice", "speedX",
+ ],
+ # Word error rate of the voice stem (Whisper), of the input as it is (the same ASR without separating first), and of
+ # the job's own transcript when its graph transcribes (Qwen3-ASR in the dub's first step).
+ "wer": ["wer", "werInput", "werTranscript"],
}
METRICS = {
@@ -29,6 +37,21 @@ METRICS = {
"continuity": {"label": "Shot continuity", "better": "higher", "unit": "cosine between consecutive shots"},
"paletteFit": {"label": "Palette distance", "better": "lower", "unit": "mean ΔE76 to the nearest palette colour"},
"paletteCover": {"label": "Palette used", "better": "higher", "unit": "share of the palette's colours"},
+ "voiceSiSdr": {"label": "Dialogue SI-SDR", "better": "higher", "unit": "dB against the known speech"},
+ "musicSiSdr": {"label": "Music SI-SDR", "better": "higher", "unit": "dB against the known music"},
+ "effectsSiSdr": {"label": "Effects SI-SDR", "better": "higher", "unit": "dB against the known effects"},
+ "backgroundSiSdr": {"label": "Music & effects SI-SDR", "better": "higher", "unit": "dB against the known bed"},
+ "voiceSdr": {"label": "Dialogue SDR", "better": "higher", "unit": "dB (level counts)"},
+ "backgroundSdr": {"label": "Music & effects SDR", "better": "higher", "unit": "dB (level counts)"},
+ "mixError": {"label": "Stems vs input", "better": "lower", "unit": "dB under the input (voice + bed)"},
+ "bedLevel": {"label": "Bed level vs reference", "better": "none", "unit": "dB (0 = same; AudioMerge's peak scaling shows negative)"},
+ "bedPeak": {"label": "Bed peak", "better": "none", "unit": "dBFS"},
+ "stereoCorrGap": {"label": "Bed stereo gap", "better": "lower", "unit": "|L/R correlation − the reference bed's|"},
+ "noiseInVoice": {"label": "Noise left in the dialogue", "better": "lower", "unit": "share of the known hum or hiss"},
+ "speedX": {"label": "Speed", "better": "higher", "unit": "x real time (all passes)"},
+ "wer": {"label": "WER, dialogue stem", "better": "lower", "unit": "word error rate 0–1"},
+ "werInput": {"label": "WER, input as is", "better": "lower", "unit": "word error rate 0–1"},
+ "werTranscript": {"label": "WER, the job's transcript", "better": "lower", "unit": "word error rate 0–1"},
}
# Weights, each pinned to a Hugging Face revision. "commercial" says whether the model itself may be used
@@ -88,6 +111,14 @@ MODELS = {
"licence": "non-commercial research only (insightface model packs)",
"commercial": False,
},
+ # Speech recognition for the separation suite's word error rate (pnpm eval:setup --asr).
+ "whisper-base-en": {
+ "repo": "openai/whisper-base.en",
+ "files": ["config.json", "generation_config.json", "model.safetensors", "preprocessor_config.json", "tokenizer.json", "tokenizer_config.json", "vocab.json", "merges.txt", "normalizer.json", "added_tokens.json", "special_tokens_map.json"],
+ "revision": "911407f4214e0e1d82085af863093ec0b66f9cd6",
+ "licence": "MIT (OpenAI Whisper code and weights; the Hugging Face card says Apache-2.0)",
+ "commercial": True,
+ },
# Style similarity on image features alone (--style-model dinov2): DINOv2 ViT-S/14 as timm packs it.
"dinov2-small": {
"arch": "vit_small_patch14_dinov2.lvd142m",
diff --git a/scripts/eval/metrics/fuobe_metrics/score.py b/scripts/eval/metrics/fuobe_metrics/score.py
index e335930e..8275b8d3 100644
--- a/scripts/eval/metrics/fuobe_metrics/score.py
+++ b/scripts/eval/metrics/fuobe_metrics/score.py
@@ -18,8 +18,9 @@ import time
import numpy as np
from . import maths
-from .media import audio_track, have_ffmpeg, images_of, kind_of, video_frames
-from .models import MODELS, Aesthetic, Clip, Dino, Faces, Missing, device_of
+from . import separation as sep
+from .media import audio_channels, audio_track, have_ffmpeg, images_of, kind_of, video_frames
+from .models import MODELS, Aesthetic, Asr, Clip, Dino, Faces, Missing, device_of
from .registry import FAMILIES
VERSION = 1
@@ -65,9 +66,65 @@ def media_outputs(run_dir: pathlib.Path, job: dict) -> list[pathlib.Path]:
return out
+# Stem names as the providers write them (src/server/generations.ts STEM_ALIASES), folded to the suite's four.
+STEMS = {
+ "voice": "voice", "vocals": "voice", "speech": "voice", "target": "voice", "dialogue": "voice",
+ "background": "background", "accompaniment": "background", "instrumental": "background", "residual": "background", "no_vocals": "background",
+ "music": "music", "effects": "effects", "sfx": "effects",
+}
+
+
+def audio_outputs(run_dir: pathlib.Path, job: dict) -> dict[str, pathlib.Path]:
+ """The job's audio stems by name (voice, music, effects, background; other stems such as Demucs's drums keep
+ their own names). An unnamed first audio output is the voice (a chain without a stem takes the dialogue)."""
+ out: dict[str, pathlib.Path] = {}
+ for o in job.get("outputs", []):
+ p = run_dir / o["file"]
+ if o.get("kind") != "audio" and kind_of(p) != "audio":
+ continue
+ if not p.exists():
+ continue
+ name = str(o.get("stem") or o.get("role") or "").lower()
+ key = STEMS.get(name, name) or ("voice" if "voice" not in out else f"audio{len(out)}")
+ out.setdefault(key, p)
+ return out
+
+
+def text_output(run_dir: pathlib.Path, job: dict, role: str) -> str | None:
+ """A text output by role (its file name ends in -<role>.txt)."""
+ for o in job.get("outputs", []):
+ if o.get("kind") == "text" and (o.get("role") == role or o["file"].endswith(f"-{role}.txt")):
+ p = run_dir / o["file"]
+ if p.exists():
+ return p.read_text(encoding="utf8", errors="replace")
+ return None
+
+
+def references_of(job: dict) -> tuple[dict[str, pathlib.Path], dict]:
+ """A separation case's known parts (voice, music, effects, background, noise, mix .flac/.wav) and its meta.json
+ (the words spoken, levels and licences), from the folder its references name."""
+ files = [pathlib.Path(r) for r in job.get("references", []) if kind_of(r) == "audio" and pathlib.Path(r).exists()]
+ stems = {f.stem.lower(): f for f in files}
+ meta = {}
+ if files:
+ m = files[0].parent / "meta.json"
+ if m.exists():
+ meta = json.loads(m.read_text(encoding="utf8"))
+ return stems, meta
+
+
+def input_file(job: dict) -> pathlib.Path | None:
+ ins = job.get("inputs") or {}
+ for k in ("audio", "video"):
+ v = ins.get(k)
+ if isinstance(v, str) and pathlib.Path(v).exists():
+ return pathlib.Path(v)
+ return None
+
+
def fingerprint(run_dir: pathlib.Path, job: dict, config: dict) -> str:
h = hashlib.sha256(json.dumps(config, sort_keys=True).encode())
- for p in media_outputs(run_dir, job) + [pathlib.Path(r) for r in job.get("references", [])]:
+ for p in media_outputs(run_dir, job) + list(audio_outputs(run_dir, job).values()) + [pathlib.Path(r) for r in job.get("references", [])]:
try:
st = p.stat()
h.update(f"{p}|{st.st_size}|{int(st.st_mtime)}".encode())
@@ -86,6 +143,8 @@ class Scorer:
self._aesthetic = None
self._faces = None
self._dino = None
+ self._asr = None
+ self.run_dir: pathlib.Path | None = None
self.used: dict[str, dict] = {}
self.skipped: dict[str, str] = {}
@@ -127,6 +186,12 @@ class Scorer:
self.used["identity"] = {**MODELS[name], "key": name, **found}
return self._faces
+ def asr(self):
+ if self._asr is None:
+ self._asr = Asr(self.device)
+ self.used["wer"] = {**{k: v for k, v in MODELS["whisper-base-en"].items() if k != "files"}, "key": "whisper-base-en"}
+ return self._asr
+
# Metric families: each returns a dict of keys from registry.FAMILIES plus notes.
def family(self, name: str, job: dict, outs: list[pathlib.Path]) -> dict:
return getattr(self, f"m_{name}")(job, outs)
@@ -273,6 +338,96 @@ class Scorer:
return res
+ def m_separation(self, job, outs):
+ stems = audio_outputs(self.run_dir, job)
+ if not stems:
+ return {"_note": "no audio stems in the result"}
+ refs, meta = references_of(job)
+ sr = int(meta.get("sampleRate") or 44100)
+ res: dict = {}
+ notes = []
+ got = {k: audio_channels(p, sr) for k, p in stems.items()}
+ got = {k: v for k, v in got.items() if v is not None}
+ # A model without a bed stem (Demucs: drums, bass, other) gets one from every stem that isn't the voice.
+ if "background" not in got:
+ rest = [v for k, v in got.items() if k != "voice"]
+ if rest:
+ got["background"] = sum(sep.crop(*rest)) if len(rest) > 1 else rest[0]
+ src = input_file(job)
+ mix = audio_channels(src, sr) if src else None
+ # Stems from a decoded AAC or a hosted model can sit a few hundred samples off: line each one up with the input.
+ anchor = mix if mix is not None else (audio_channels(refs["mix"], sr) if "mix" in refs else None)
+ if anchor is not None:
+ probe = sum(sep.crop(got["voice"], got["background"])) if "voice" in got and "background" in got else next(iter(got.values()))
+ lag = sep.best_offset(probe, anchor, max_lag=4096)
+ if lag:
+ got = {k: sep.shift(v, lag) for k, v in got.items()}
+ notes.append(f"stems shifted {lag} samples to line up with the input")
+ if mix is not None and "voice" in got and "background" in got:
+ res["mixError"] = sep.mixture_error([got["voice"], got["background"]], mix)["db"]
+ for name in ("voice", "music", "effects", "background"):
+ if name in got and name in refs:
+ ref = audio_channels(refs[name], sr)
+ if ref is None:
+ continue
+ res[f"{name}SiSdr"] = round(sep.si_sdr(got[name], ref), 2)
+ if name in ("voice", "background"):
+ res[f"{name}Sdr"] = round(sep.sdr(got[name], ref), 2)
+ if "background" in got and "background" in refs:
+ ref = audio_channels(refs["background"], sr)
+ lv = sep.bed_level(got["background"], ref)
+ res["bedLevel"], res["bedPeak"] = lv["delta"], lv["peak"]
+ st = sep.stereo_check(got["background"], ref)
+ res["stereoCorrGap"] = st["corrGap"]
+ res["_stereo"] = st
+ if "noise" in refs:
+ share = sep.noise_share({k: v for k, v in got.items() if k in ("voice", "music", "effects")}, audio_channels(refs["noise"], sr))
+ if "voice" in share:
+ res["noiseInVoice"] = share["voice"]
+ res["_noise"] = share
+ report = text_output(self.run_dir, job, "report")
+ speed = None
+ if report:
+ try:
+ speed = sep.report_speed(json.loads(report))
+ except ValueError:
+ speed = None
+ if speed is None and mix is not None and (job.get("comfy") or {}).get("execMs"):
+ speed = (mix.shape[1] / sr) / (job["comfy"]["execMs"] / 1000.0)
+ notes.append("speed from ComfyUI's time for the whole graph")
+ if speed:
+ res["speedX"] = round(speed, 3)
+ if not refs:
+ notes.append("no known stems for this input (a real clip: listen on the blind review page)")
+ if notes:
+ res["_note"] = "; ".join(notes)
+ return res
+
+ def m_wer(self, job, outs):
+ _, meta = references_of(job)
+ text = meta.get("text")
+ if not text:
+ return {"_note": "no known words for this input"}
+ res: dict = {}
+ transcript = text_output(self.run_dir, job, "transcript")
+ if transcript:
+ res["werTranscript"] = round(sep.wer(text, transcript)["wer"], 4)
+ stems = audio_outputs(self.run_dir, job)
+ asr = self.asr()
+ if "voice" in stems:
+ a = audio_track(stems["voice"])
+ if a is not None:
+ hyp = asr.text(a)
+ res["wer"] = round(sep.wer(text, hyp)["wer"], 4)
+ res["_heard"] = hyp
+ src = input_file(job)
+ if src is not None:
+ a = audio_track(src)
+ if a is not None:
+ res["werInput"] = round(sep.wer(text, asr.text(a))["wer"], 4)
+ return res
+
+
def group_continuity(scorer: Scorer, run_dir: pathlib.Path, jobs: list[dict]) -> dict:
"""Shot lists: the middle frame of each shot, CLIP-embedded, against the next shot's."""
groups: dict[str, list[dict]] = {}
@@ -326,6 +481,7 @@ def main(argv=None) -> int:
previous = json.loads(out_file.read_text(encoding="utf8")) if out_file.exists() and not args.force else {}
config = {"v": VERSION, "clip": args.clip_model, "style": args.style_model, "identity": args.identity_model, "faceDetector": args.face_detector if args.identity_model == "auraface" else "buffalo_l", "frames": args.frames, "fps": args.fps}
scorer = Scorer(args)
+ scorer.run_dir = run_dir
jobs = read_jobs(run_dir)
results: dict[str, dict] = {}
started = time.time()
@@ -356,6 +512,8 @@ def main(argv=None) -> int:
continue
note = got.pop("_note", None)
refs = got.pop("_refs", None)
+ for k in [k for k in got if k.startswith("_")]:
+ row[f"_{fam}{k[1:].capitalize()}"] = got.pop(k)
if note:
notes.append(f"{fam}: {note}")
if refs is not None:
diff --git a/scripts/eval/metrics/fuobe_metrics/separation.py b/scripts/eval/metrics/fuobe_metrics/separation.py
new file mode 100644
index 00000000..24973695
--- /dev/null
+++ b/scripts/eval/metrics/fuobe_metrics/separation.py
@@ -0,0 +1,234 @@
+"""Source-separation maths on plain numpy arrays (channels × samples, float), so it is tested without a model or a file:
+SI-SDR and SDR of a stem against its known reference, whether the stems add back up to the input, the level and peak
+of a bed against the reference bed (AudioMerge scales a bed down when it peaks over full scale), a stereo check
+(left/right correlation and width), where a known noise ends up, and the word error rate of a transcript."""
+
+from __future__ import annotations
+
+import math
+import re
+import unicodedata
+
+import numpy as np
+
+EPS = 1e-12
+
+
+def as_channels(x) -> np.ndarray:
+ """A signal as channels × samples (float64): a 1-D array is one channel."""
+ a = np.asarray(x, dtype=np.float64)
+ return a[None, :] if a.ndim == 1 else a
+
+
+def mono(x) -> np.ndarray:
+ """The mean of the channels."""
+ return as_channels(x).mean(axis=0)
+
+
+def match_channels(est, ref) -> tuple[np.ndarray, np.ndarray]:
+ """Both signals with the same channel count: a mono one is compared with the other's mean (a mono stem against a
+ stereo reference is scored against the reference's mono mean, never copied to two channels)."""
+ e, r = as_channels(est), as_channels(ref)
+ if e.shape[0] == r.shape[0]:
+ return e, r
+ if e.shape[0] == 1:
+ return e, r.mean(axis=0, keepdims=True)
+ if r.shape[0] == 1:
+ return e.mean(axis=0, keepdims=True), r
+ c = min(e.shape[0], r.shape[0])
+ return e[:c], r[:c]
+
+
+def crop(*xs) -> list[np.ndarray]:
+ """Every signal cut to the shortest one's length."""
+ xs = [as_channels(x) for x in xs]
+ n = min(x.shape[1] for x in xs)
+ return [x[:, :n] for x in xs]
+
+
+def best_offset(est, ref, max_lag: int) -> int:
+ """The shift (in samples, |lag| ≤ max_lag) that lines `est` up with `ref` best: est[t + lag] ≈ ref[t]. A decoder's
+ priming samples (AAC) or a hosted model's padding can move a stem by a few hundred samples."""
+ a, b = mono(est), mono(ref)
+ n = min(len(a), len(b))
+ if n < 2 or max_lag <= 0:
+ return 0
+ a, b = a[:n], b[:n]
+ size = 1 << int(math.ceil(math.log2(2 * n)))
+ corr = np.fft.irfft(np.fft.rfft(a, size) * np.conj(np.fft.rfft(b, size)), size)
+ lags = np.concatenate([corr[: max_lag + 1], corr[-max_lag:]])
+ idx = np.concatenate([np.arange(0, max_lag + 1), np.arange(-max_lag, 0)])
+ return int(idx[int(np.argmax(lags))])
+
+
+def shift(x, lag: int) -> np.ndarray:
+ """x moved left by `lag` samples (x[t + lag]), the end padded with silence; a negative lag moves it right."""
+ x = as_channels(x)
+ if lag == 0:
+ return x
+ out = np.zeros_like(x)
+ if lag > 0:
+ out[:, : x.shape[1] - lag] = x[:, lag:]
+ else:
+ out[:, -lag:] = x[:, : x.shape[1] + lag]
+ return out
+
+
+def _db(num: float, den: float) -> float:
+ return float(10.0 * math.log10((num + EPS) / (den + EPS)))
+
+
+def si_sdr(est, ref) -> float:
+ """Scale-invariant SDR in dB (Le Roux et al. 2019), the mean over channels; both signals zero-mean. Higher is
+ better; a stem's level doesn't change it."""
+ e, r = crop(*match_channels(est, ref))
+ vals = []
+ for ec, rc in zip(e, r):
+ ec = ec - ec.mean()
+ rc = rc - rc.mean()
+ alpha = float(ec @ rc) / (float(rc @ rc) + EPS)
+ target = alpha * rc
+ vals.append(_db(float(target @ target), float((ec - target) @ (ec - target))))
+ return float(np.mean(vals))
+
+
+def sdr(est, ref) -> float:
+ """SDR in dB as MUSDB's newer scoring defines it (signal over error, no projection): the level counts, so a stem
+ that comes out quieter than its reference scores lower. The mean over channels."""
+ e, r = crop(*match_channels(est, ref))
+ return float(np.mean([_db(float(rc @ rc), float((rc - ec) @ (rc - ec))) for ec, rc in zip(e, r)]))
+
+
+def rms_db(x) -> float:
+ """RMS level in dBFS over every channel (−inf for silence is clipped to −200)."""
+ a = as_channels(x)
+ v = float(np.sqrt(np.mean(a**2))) if a.size else 0.0
+ return max(-200.0, 20.0 * math.log10(v + EPS))
+
+
+def peak_db(x) -> float:
+ """Sample peak in dBFS (0 = full scale)."""
+ a = as_channels(x)
+ v = float(np.max(np.abs(a))) if a.size else 0.0
+ return max(-200.0, 20.0 * math.log10(v + EPS))
+
+
+def mixture_error(stems: list, mix) -> dict:
+ """Do the stems add up to the input? The error of their sum against the mix, as dB under the mix's level (−60 dB
+ or lower: the same sound; 16-bit FLAC stems land around −90 dB) and the largest sample difference."""
+ total = None
+ for s in stems:
+ s = as_channels(s)
+ total = s if total is None else crop(total, s)[0] + crop(total, s)[1]
+ if total is None:
+ return {"db": None, "maxAbs": None}
+ t, m = crop(*match_channels(total, mix))
+ err = t - m
+ return {"db": round(rms_db(err) - rms_db(m), 2), "maxAbs": float(np.max(np.abs(err))) if err.size else 0.0}
+
+
+def bed_level(est, ref) -> dict:
+ """The bed's level and peak against the reference bed's: delta in dB (0 = same level; a bed that AudioMerge scaled
+ down under full scale comes out negative) and its own peak in dBFS."""
+ e, r = crop(*match_channels(est, ref))
+ return {"delta": round(rms_db(e) - rms_db(r), 2), "peak": round(peak_db(e), 2), "peakRef": round(peak_db(r), 2)}
+
+
+def stereo(x) -> dict:
+ """Left/right correlation (1 = mono, 0 = unrelated, −1 = out of phase) and width (side over mid energy, dB) of a
+ 2-channel signal; a mono one says so."""
+ a = as_channels(x)
+ if a.shape[0] < 2:
+ return {"channels": int(a.shape[0]), "corr": 1.0, "width": None}
+ left, right = a[0] - a[0].mean(), a[1] - a[1].mean()
+ corr = float(left @ right) / (math.sqrt(float(left @ left) * float(right @ right)) + EPS)
+ mid, side = (a[0] + a[1]) / 2, (a[0] - a[1]) / 2
+ return {"channels": int(a.shape[0]), "corr": round(corr, 4), "width": round(_db(float(side @ side), float(mid @ mid)), 2)}
+
+
+def stereo_check(est, ref) -> dict:
+ """The bed's stereo image against the reference bed's: both correlations, the gap between them, the width gap
+ (dB), and each channel's level against the reference's (dB). A mono bed against a stereo reference shows as a
+ correlation of 1 and no width."""
+ e, r = as_channels(est), as_channels(ref)
+ se, sr = stereo(e), stereo(r)
+ out = {"corr": se["corr"], "corrRef": sr["corr"], "corrGap": round(abs(se["corr"] - sr["corr"]), 4), "channels": se["channels"]}
+ if se["width"] is not None and sr["width"] is not None:
+ out["widthGap"] = round(se["width"] - sr["width"], 2)
+ if e.shape[0] >= 2 and r.shape[0] >= 2:
+ ec, rc = crop(e[:2], r[:2])
+ out["levelLeft"] = round(rms_db(ec[0]) - rms_db(rc[0]), 2)
+ out["levelRight"] = round(rms_db(ec[1]) - rms_db(rc[1]), 2)
+ return out
+
+
+def noise_share(stems: dict, noise) -> dict:
+ """Where a known steady noise (hum, hiss) ended up: each stem's projection onto the noise, as a share of it
+ (<stem, noise> / <noise, noise>, on the mono mean). The other sources are uncorrelated with the noise and the
+ stems add up to the mix, so the shares add up to about 1."""
+ n = mono(noise)
+ n = n - n.mean()
+ den = float(n @ n) + EPS
+ out = {}
+ for name, s in stems.items():
+ sm = mono(s)
+ k = min(len(sm), len(n))
+ out[name] = round(float((sm[:k] - sm[:k].mean()) @ n[:k]) / den, 3)
+ return out
+
+
+_NUMBERS = {"0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine", "10": "ten"}
+
+
+def words(text: str) -> list[str]:
+ """A transcript as words for WER: lower case, accents kept, punctuation dropped (an apostrophe inside a word stays),
+ hyphens split words, single digits spelt out (Whisper writes "3", the script says "three")."""
+ t = unicodedata.normalize("NFKC", text or "").lower().replace("’", "'").replace("-", " ")
+ t = re.sub(r"[^\w\s']", " ", t)
+ out = []
+ for w in t.split():
+ w = w.strip("'")
+ if w:
+ out.append(_NUMBERS.get(w, w))
+ return out
+
+
+def wer(reference: str, hypothesis: str) -> dict:
+ """Word error rate: (substitutions + deletions + insertions) / reference words, by Levenshtein alignment on
+ words(). 0 is perfect; it can exceed 1 when the hypothesis adds many words."""
+ ref, hyp = words(reference), words(hypothesis)
+ n, m = len(ref), len(hyp)
+ # d[i][j]: (cost, subs, dels, ins) to turn ref[:i] into hyp[:j]
+ prev = [(j, 0, 0, j) for j in range(m + 1)]
+ for i in range(1, n + 1):
+ cur = [(i, 0, i, 0)]
+ for j in range(1, m + 1):
+ same = ref[i - 1] == hyp[j - 1]
+ c_sub = prev[j - 1]
+ c_del = prev[j]
+ c_ins = cur[j - 1]
+ options = [
+ (c_sub[0] + (0 if same else 1), c_sub[1] + (0 if same else 1), c_sub[2], c_sub[3]),
+ (c_del[0] + 1, c_del[1], c_del[2] + 1, c_del[3]),
+ (c_ins[0] + 1, c_ins[1], c_ins[2], c_ins[3] + 1),
+ ]
+ cur.append(min(options))
+ prev = cur
+ cost, subs, dels, ins = prev[m]
+ return {"wer": (cost / n) if n else (0.0 if m == 0 else 1.0), "words": n, "substitutions": subs, "deletions": dels, "insertions": ins}
+
+
+def report_speed(report: dict) -> float | None:
+ """Times real time from ComfyUI-DBS's JSON report (audio seconds per second of work, all channels' passes
+ included), or None when the report doesn't say."""
+ if not isinstance(report, dict):
+ return None
+ for key in ("realtime_factor", "x_realtime", "times_realtime", "speed_x_realtime", "realtime_x", "rtf_x"):
+ v = report.get(key)
+ if isinstance(v, (int, float)) and v > 0:
+ return float(v)
+ audio = report.get("audio_seconds") or report.get("audio_sec") or report.get("duration_seconds")
+ run = report.get("run_seconds") or report.get("elapsed_seconds") or report.get("seconds")
+ if isinstance(audio, (int, float)) and isinstance(run, (int, float)) and run > 0:
+ return float(audio) / float(run)
+ return None
diff --git a/scripts/eval/metrics/requirements-asr.in b/scripts/eval/metrics/requirements-asr.in
new file mode 100644
index 00000000..c3d6bdf8
--- /dev/null
+++ b/scripts/eval/metrics/requirements-asr.in
@@ -0,0 +1,7 @@
+# Optional: speech recognition for the separation suite's word error rate (WER of the voice stem against the known
+# words). pnpm eval:setup --asr installs it; without it the separation metrics run and WER says it was skipped.
+# The model is OpenAI Whisper base.en at a pinned revision (registry.py "whisper-base-en"; OpenAI's Whisper code and
+# weights are MIT, the Hugging Face card says Apache-2.0).
+# Compiled against the main set, so torch and huggingface_hub stay the pinned ones:
+# uv pip compile requirements-asr.in -c requirements.txt --torch-backend cpu --python-version 3.12 -o requirements-asr.txt
+transformers==5.22.1 # Apache-2.0
diff --git a/scripts/eval/metrics/requirements-asr.txt b/scripts/eval/metrics/requirements-asr.txt
new file mode 100644
index 00000000..5e299e36
--- /dev/null
+++ b/scripts/eval/metrics/requirements-asr.txt
@@ -0,0 +1,102 @@
+# This file was autogenerated by uv via the following command:
+# uv pip compile requirements-asr.in -c requirements.txt --torch-backend cpu --python-version 3.12 -o requirements-asr.txt
+annotated-doc==0.0.5
+ # via typer
+anyio==4.15.1
+ # via
+ # -c requirements.txt
+ # httpx2
+click==8.5.0
+ # via
+ # -c requirements.txt
+ # huggingface-hub
+filelock==4.2.4
+ # via
+ # -c requirements.txt
+ # huggingface-hub
+fsspec==2026.9.0
+ # via
+ # -c requirements.txt
+ # huggingface-hub
+h11==0.16.0
+ # via
+ # -c requirements.txt
+ # httpcore2
+hf-xet==1.7.0
+ # via
+ # -c requirements.txt
+ # huggingface-hub
+httpcore2==2.16.0
+ # via
+ # -c requirements.txt
+ # httpx2
+httpx2==2.16.0
+ # via
+ # -c requirements.txt
+ # huggingface-hub
+huggingface-hub==2.3.0
+ # via
+ # -c requirements.txt
+ # tokenizers
+ # transformers
+idna==3.20
+ # via
+ # -c requirements.txt
+ # anyio
+ # httpx2
+markdown-it-py==4.2.0
+ # via rich
+mdurl==0.1.2
+ # via markdown-it-py
+numpy==2.5.4
+ # via
+ # -c requirements.txt
+ # transformers
+packaging==26.3
+ # via
+ # -c requirements.txt
+ # huggingface-hub
+ # transformers
+pygments==2.21.0
+ # via
+ # -c requirements.txt
+ # rich
+pyyaml==6.0.3
+ # via
+ # -c requirements.txt
+ # huggingface-hub
+ # transformers
+regex==2026.9.29
+ # via
+ # -c requirements.txt
+ # transformers
+rich==15.0.0
+ # via typer
+safetensors==0.8.0
+ # via
+ # -c requirements.txt
+ # transformers
+shellingham==1.5.4
+ # via typer
+tokenizers==0.23.3
+ # via transformers
+tqdm==4.70.1
+ # via
+ # -c requirements.txt
+ # huggingface-hub
+ # transformers
+transformers==5.22.1
+ # via -r requirements-asr.in
+truststore==0.10.5
+ # via
+ # -c requirements.txt
+ # httpcore2
+ # httpx2
+typer==0.27.3
+ # via transformers
+typing-extensions==4.16.0
+ # via
+ # -c requirements.txt
+ # anyio
+ # httpx2
+ # huggingface-hub
diff --git a/scripts/eval/metrics/tests/test_separation.py b/scripts/eval/metrics/tests/test_separation.py
new file mode 100644
index 00000000..8d376aeb
--- /dev/null
+++ b/scripts/eval/metrics/tests/test_separation.py
@@ -0,0 +1,121 @@
+"""The separation maths on constructed signals (numpy only, no model, no file)."""
+
+import math
+
+import numpy as np
+import pytest
+
+from fuobe_metrics import separation as sep
+
+RNG = np.random.default_rng(7)
+SR = 8000
+
+
+def tone(freq, seconds=1.0, amp=0.5):
+ t = np.arange(int(SR * seconds)) / SR
+ return amp * np.sin(2 * np.pi * freq * t)
+
+
+def test_si_sdr_known_values():
+ ref = tone(220)
+ # A perfect copy at any level is perfect: SI-SDR ignores the scale.
+ assert sep.si_sdr(ref, ref) > 100
+ assert sep.si_sdr(0.25 * ref, ref) > 100
+ # Orthogonal noise at the reference's power: 0 dB.
+ noise = tone(331)
+ noise = noise - (noise @ ref) / (ref @ ref) * ref
+ noise *= np.linalg.norm(ref) / np.linalg.norm(noise)
+ assert sep.si_sdr(ref + noise, ref) == pytest.approx(0.0, abs=0.01)
+ # Noise at a tenth of the amplitude: 20 dB.
+ assert sep.si_sdr(ref + 0.1 * noise, ref) == pytest.approx(20.0, abs=0.01)
+
+
+def test_sdr_counts_the_level_and_si_sdr_does_not():
+ ref = tone(220)
+ half = 0.5 * ref
+ assert sep.si_sdr(half, ref) > 100
+ # error = 0.5·ref, so SDR = 20·log10(1 / 0.5) = 6.02 dB
+ assert sep.sdr(half, ref) == pytest.approx(20 * math.log10(2), abs=0.01)
+
+
+def test_stereo_against_mono_reference_uses_the_mean():
+ ref = tone(220)
+ stereo = np.stack([ref, ref])
+ assert sep.si_sdr(stereo, ref) > 100
+ # A mono stem against a stereo reference: compared with the reference's mean.
+ assert sep.si_sdr(ref, np.stack([ref * 0.9, ref * 1.1])) > 100
+
+
+def test_mixture_error_and_lengths():
+ v, b = tone(220), tone(440)
+ mix = v + b
+ assert sep.mixture_error([v, b], mix)["db"] < -100
+ off = sep.mixture_error([v, 0.9 * b], mix)
+ # error 0.1·b against mix (v and b same power, uncorrelated): 20·log10(0.1/√2) ≈ −23 dB
+ assert off["db"] == pytest.approx(20 * math.log10(0.1 / math.sqrt(2)), abs=0.1)
+ # Stems a few samples longer than the mix are cut to it.
+ assert sep.mixture_error([np.append(v, [0, 0]), b], mix)["db"] < -100
+
+
+def test_bed_level_catches_peak_scaling():
+ bed = tone(110, amp=0.9)
+ # AudioMerge divides a result that peaks over 1.0 by its peak: a bed peaking at 1.25 comes back 1.94 dB down.
+ scaled = (bed * 1.25) / 1.25 / 1.25
+ lv = sep.bed_level(scaled, bed)
+ assert lv["delta"] == pytest.approx(-20 * math.log10(1.25), abs=0.01)
+ assert lv["peak"] == pytest.approx(20 * math.log10(0.9 / 1.25), abs=0.01)
+
+
+def test_stereo_check():
+ left, right = tone(220), RNG.standard_normal(SR) * 0.3
+ ref = np.stack([left, right])
+ same = sep.stereo_check(ref, ref)
+ assert same["corrGap"] == pytest.approx(0.0, abs=1e-9)
+ assert same["levelLeft"] == pytest.approx(0.0) and same["levelRight"] == pytest.approx(0.0)
+ # A mono bed has correlation 1 and no width.
+ m = sep.stereo_check(sep.mono(ref), ref)
+ assert m["corr"] == 1.0 and m["channels"] == 1 and "widthGap" not in m
+ assert m["corrGap"] > 0.5
+ # A 6 dB quieter right channel shows on that side only.
+ q = sep.stereo_check(np.stack([left, right * 0.5]), ref)
+ assert q["levelLeft"] == pytest.approx(0.0) and q["levelRight"] == pytest.approx(-6.02, abs=0.01)
+ assert sep.stereo(np.stack([left, left]))["corr"] == pytest.approx(1.0)
+ assert sep.stereo(np.stack([left, -left]))["corr"] == pytest.approx(-1.0)
+
+
+def test_noise_share():
+ noise = RNG.standard_normal(SR * 8) * 0.3
+ voice, music = tone(220, 8), tone(330, 8)
+ stems = {"voice": voice + 0.25 * noise, "music": music + 0.75 * noise}
+ share = sep.noise_share(stems, noise)
+ assert share["voice"] == pytest.approx(0.25, abs=0.03)
+ assert share["music"] == pytest.approx(0.75, abs=0.03)
+
+
+def test_best_offset_and_shift():
+ x = RNG.standard_normal(4000)
+ late = np.concatenate([np.zeros(37), x])[:4000]
+ lag = sep.best_offset(late, x, max_lag=200)
+ assert lag == 37
+ assert sep.si_sdr(sep.shift(late, lag)[0][:3900], x[:3900]) > 100
+ assert sep.best_offset(x, late, max_lag=200) == -37
+
+
+def test_wer_on_fixed_strings():
+ ref = "The quick brown fox jumps over the lazy dog."
+ assert sep.wer(ref, "the quick brown fox jumps over the lazy dog")["wer"] == 0.0
+ # Punctuation, case, hyphens and single digits don't count.
+ assert sep.wer("It's a well-known fact: 3 cats.", "its a well known fact three cats")["wer"] == pytest.approx(1 / 7)
+ assert sep.wer("it's a well-known fact: 3 cats.", "it's a well known fact, three cats")["wer"] == 0.0
+ w = sep.wer(ref, "the quick brown fox jumped over lazy dog today")
+ assert (w["substitutions"], w["deletions"], w["insertions"], w["words"]) == (1, 1, 1, 9)
+ assert w["wer"] == pytest.approx(3 / 9)
+ assert sep.wer(ref, "")["wer"] == 1.0
+ assert sep.wer("", "")["wer"] == 0.0
+
+
+def test_report_speed():
+ assert sep.report_speed({"realtime_factor": 0.27}) == 0.27
+ assert sep.report_speed({"audio_seconds": 20.0, "run_seconds": 80.0}) == 0.25
+ assert sep.report_speed({"model": "x"}) is None
+ assert sep.report_speed("nope") is None