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: Clean up dialogue scored against the level asked, the bed's scaling measured, Whisper fetched with --asr, and the job's own transcript scored without it

Claudefd30be88f2f3
diff --git a/scripts/eval/lib/metric-info.mjs b/scripts/eval/lib/metric-info.mjs
index 9afcf1a1..7ebc5c48 100644
--- a/scripts/eval/lib/metric-info.mjs
+++ b/scripts/eval/lib/metric-info.mjs
@@ -19,6 +19,7 @@ export const METRIC_INFO = {
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 },
+ remixSiSdr: { label: "Clean dialogue SI-SDR", better: "higher", unit: "dB vs voice + bed at the level asked", 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 },
@@ -27,6 +28,7 @@ export const METRIC_INFO = {
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 },
+ bedScale: { label: "Bed scaling", better: "none", unit: "dB vs input − voice (0 = as subtracted)", 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 },
diff --git a/scripts/eval/metrics/fuobe_metrics/download.py b/scripts/eval/metrics/fuobe_metrics/download.py
index 0abbf6b9..3732eb9a 100644
--- a/scripts/eval/metrics/fuobe_metrics/download.py
+++ b/scripts/eval/metrics/fuobe_metrics/download.py
@@ -1,4 +1,4 @@
-"""Fetch the metric weights at their pinned revisions: python -m fuobe_metrics.download [--identity] [--dinov2] [--no-aesthetic].
+"""Fetch the metric weights at their pinned revisions: python -m fuobe_metrics.download [--identity] [--dinov2] [--asr] [--no-aesthetic].
They go to FUOBE_EVAL_CACHE (default ~/.cache/fuobe-eval); scoring downloads them on first use otherwise."""
from __future__ import annotations
@@ -16,12 +16,15 @@ def main(argv=None) -> int:
ap.add_argument("--scrfd", action="store_true", help="also the SCRFD detector AuraFace ships (licence unclear), for --face-detector scrfd")
ap.add_argument("--no-aesthetic", action="store_true", help="skip CLIP ViT-L/14 and the aesthetic head (about 1.7 GB)")
ap.add_argument("--dinov2", action="store_true", help="also DINOv2 ViT-S/14 (Apache-2.0, 88 MB) for --style-model dinov2")
+ ap.add_argument("--asr", action="store_true", help="also Whisper base.en (MIT, about 290 MB) for the separation suite's word error rate")
args = ap.parse_args(argv)
wanted = [("clip-b32", MODELS["clip-b32"]["file"])]
if not args.no_aesthetic:
wanted += [("clip-l14", MODELS["clip-l14"]["file"]), ("aesthetic-v2", MODELS["aesthetic-v2"]["file"])]
if args.dinov2:
wanted += [("dinov2-small", MODELS["dinov2-small"]["file"])]
+ if args.asr:
+ wanted += [("whisper-base-en", f) for f in MODELS["whisper-base-en"]["files"]]
if args.identity:
wanted += [("auraface", MODELS["auraface"]["recognition"]), ("yunet", MODELS["yunet"]["file"])]
if args.scrfd:
diff --git a/scripts/eval/metrics/fuobe_metrics/registry.py b/scripts/eval/metrics/fuobe_metrics/registry.py
index 37883a91..56721bd6 100644
--- a/scripts/eval/metrics/fuobe_metrics/registry.py
+++ b/scripts/eval/metrics/fuobe_metrics/registry.py
@@ -13,8 +13,8 @@ FAMILIES = {
"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",
+ "voiceSiSdr", "remixSiSdr", "musicSiSdr", "effectsSiSdr", "backgroundSiSdr", "voiceSdr", "backgroundSdr",
+ "mixError", "bedLevel", "bedPeak", "bedScale", "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).
@@ -47,6 +47,8 @@ METRICS = {
"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"},
+ "remixSiSdr": {"label": "Clean dialogue SI-SDR", "better": "higher", "unit": "dB against the voice + the known bed at the level asked"},
+ "bedScale": {"label": "Bed scaling", "better": "none", "unit": "dB, the bed against input − voice (0 = as subtracted; AudioMerge's peak scaling shows negative)"},
"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)"},
diff --git a/scripts/eval/metrics/fuobe_metrics/score.py b/scripts/eval/metrics/fuobe_metrics/score.py
index 8d5170e8..d8088c0c 100644
--- a/scripts/eval/metrics/fuobe_metrics/score.py
+++ b/scripts/eval/metrics/fuobe_metrics/score.py
@@ -113,6 +113,16 @@ def references_of(job: dict) -> tuple[dict[str, pathlib.Path], dict]:
return stems, meta
+def remix_levels(job: dict) -> dict | None:
+ """The levels a Clean up dialogue job asked for (graph C's voiceDb, musicDb, effectsDb), or None for a split."""
+ extra = ((job.get("request") or {}).get("params") or {}).get("extra") or {}
+ if "musicDb" not in extra and "effectsDb" not in extra:
+ return None
+ music, effects = float(extra.get("musicDb", -100)), float(extra.get("effectsDb", -100))
+ # The suite sets music and effects together; when they differ, the bed is scored at the louder one.
+ return {"voiceDb": float(extra.get("voiceDb", 0)), "musicDb": music, "effectsDb": effects, "bedDb": max(music, effects)}
+
+
def input_file(job: dict) -> pathlib.Path | None:
ins = job.get("inputs") or {}
for k in ("audio", "video"):
@@ -385,6 +395,9 @@ class Scorer:
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"]
+ scale = sep.bed_scale(got["background"], got["voice"], mix)
+ if scale is not None:
+ res["bedScale"] = scale
for name in ("voice", "music", "effects", "background"):
if name in got and name in refs:
ref = audio_channels(refs[name], sr)
@@ -393,6 +406,20 @@ class Scorer:
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)
+ # Clean up dialogue (graph C): one file, the dialogue with the music and effects at the levels asked for. It is
+ # scored against what was asked (the voice plus the known bed at that level) and for where the bed landed.
+ remix = remix_levels(job)
+ if remix is not None and "voice" in got and "voice" in refs and "background" in refs:
+ vref, bref = audio_channels(refs["voice"], sr), audio_channels(refs["background"], sr)
+ if vref is not None and bref is not None:
+ want = sep.mono(vref) * 10 ** (remix["voiceDb"] / 20) + sep.mono(bref) * 10 ** (remix["bedDb"] / 20)
+ res["remixSiSdr"] = round(sep.si_sdr(got["voice"], want), 2)
+ gains = sep.remix_gains(got["voice"], vref, bref)
+ if gains["bed"] is not None:
+ res["bedLevel"] = gains["bed"]
+ res["bedPeak"] = round(sep.peak_db(got["voice"]), 2)
+ res["_remix"] = {**remix, "gains": gains}
+ notes.append(f"one file (the dialogue with music and effects at {remix['bedDb']:g} dB): voiceSiSdr is against the voice alone, remixSiSdr against the voice plus the known bed at that level, bedLevel the bed's gain in it")
if "background" in got and "background" in refs:
ref = audio_channels(refs["background"], sr)
lv = sep.bed_level(got["background"], ref)
@@ -433,18 +460,25 @@ class Scorer:
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)
+ voice = audio_track(stems["voice"]) if "voice" in stems else None
+ heard = audio_track(src) if src is not None else None
+ if voice is None and heard is None:
+ return res
+ # Whisper is optional (pnpm eval:setup --asr): without it the job's own transcript is still scored.
+ try:
+ asr = self.asr()
+ except Missing as e:
+ # Recorded under its own name so the family keeps running for the jobs that have a transcript.
+ self.skipped.setdefault("wer (Whisper)", str(e))
+ res["_note"] = f"wer and werInput skipped: {e}"
+ return res
+ if voice is not None:
+ hyp = asr.text(voice)
+ res["wer"] = round(sep.wer(text, hyp)["wer"], 4)
+ res["_heard"] = hyp
+ if heard is not None:
+ res["werInput"] = round(sep.wer(text, asr.text(heard))["wer"], 4)
return res
diff --git a/scripts/eval/metrics/fuobe_metrics/separation.py b/scripts/eval/metrics/fuobe_metrics/separation.py
index 100dcf56..88fa5549 100644
--- a/scripts/eval/metrics/fuobe_metrics/separation.py
+++ b/scripts/eval/metrics/fuobe_metrics/separation.py
@@ -134,6 +134,36 @@ def bed_level(est, ref) -> dict:
return {"delta": round(rms_db(e) - rms_db(r), 2), "peak": round(peak_db(e), 2), "peakRef": round(peak_db(r), 2)}
+def bed_scale(bed, voice, mix) -> float | None:
+ """How a bed made as "the input minus the speech" was scaled, in dB: the least-squares gain of the bed against
+ mix − voice (a mono voice taken from every channel, as AudioMerge broadcasts it). 0 = as subtracted; AudioMerge
+ divides the whole result by its peak when that is over full scale, which shows as −(the overshoot in dB)."""
+ b, v, m = as_channels(bed), as_channels(voice), as_channels(mix)
+ if v.shape[0] == 1 and m.shape[0] > 1:
+ v = np.repeat(v, m.shape[0], axis=0)
+ elif m.shape[0] == 1 and v.shape[0] > 1:
+ v = v.mean(axis=0, keepdims=True)
+ v, m = crop(v, m)
+ unscaled = m - v
+ e, u = crop(*match_channels(b, unscaled))
+ den = float(np.sum(u * u))
+ if den <= EPS:
+ return None
+ g = float(np.sum(e * u)) / den
+ return round(20.0 * math.log10(g), 3) if g > 0 else None
+
+
+def remix_gains(out, voice, bed) -> dict:
+ """A remix (the dialogue with the music and effects mixed back under it, Clean up dialogue) against its known
+ parts: the least-squares gains of the voice and the bed in it, solved together on the mono mean, as dB (0 = as in
+ the input). The model's own errors are uncorrelated with the parts, so a bed asked at −18 dB reads about −18."""
+ o, v, b = crop(mono(out)[None, :], mono(voice)[None, :], mono(bed)[None, :])
+ a = np.stack([v[0], b[0]], axis=1)
+ (gv, gb), *_ = np.linalg.lstsq(a, o[0], rcond=None)
+ db = lambda g: round(20.0 * math.log10(g), 2) if g > 1e-6 else None # noqa: E731
+ return {"voice": db(float(gv)), "bed": db(float(gb))}
+
+
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."""
diff --git a/scripts/eval/metrics/tests/test_separation_scorer.py b/scripts/eval/metrics/tests/test_separation_scorer.py
new file mode 100644
index 00000000..edbb6d3d
--- /dev/null
+++ b/scripts/eval/metrics/tests/test_separation_scorer.py
@@ -0,0 +1,181 @@
+"""The separation scorer between the maths and a run: stem names folded from what providers write, Demucs's stems
+summed into a bed, the alignment, the fast stereo bed's scaling, Clean up dialogue's one file, the WER family with a
+fake ASR (and without one), and the download of the Whisper weights. Needs ffmpeg (the scorer reads files with it)."""
+
+import argparse
+import json
+import pathlib
+import shutil
+import subprocess
+
+import numpy as np
+import pytest
+
+from fuobe_metrics import download, score
+from fuobe_metrics import separation as sep
+from fuobe_metrics.models import Missing
+
+pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None, reason="needs ffmpeg")
+
+SR = 44100
+N = SR # one second
+RNG = np.random.default_rng(3)
+TEXT = "the quick brown fox jumps over the lazy dog"
+
+
+def write(path: pathlib.Path, x: np.ndarray, float_wav: bool = False) -> None:
+ x = np.atleast_2d(x)
+ pcm = x.T.astype("<f4").tobytes()
+ codec = ["-c:a", "pcm_f32le"] if float_wav else ["-c:a", "flac", "-sample_fmt", "s32", "-bits_per_raw_sample", "24"]
+ path.parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "f32le", "-ar", str(SR), "-ac", str(x.shape[0]), "-i", "-", *codec, str(path)], input=pcm, check=True)
+
+
+def parts():
+ t = np.arange(N) / SR
+ voice = 0.2 * np.sin(2 * np.pi * 300 * t) * (1 + 0.5 * np.sin(2 * np.pi * 3 * t))
+ music = np.stack([0.15 * np.sin(2 * np.pi * 110 * t), 0.12 * np.sin(2 * np.pi * 165 * t)])
+ effects = 0.05 * RNG.standard_normal((2, N))
+ return np.stack([voice, voice]), music, effects
+
+
+def case(tmp_path):
+ """A mix with known parts and meta.json, like make-separation.py writes."""
+ voice, music, effects = parts()
+ bed = music + effects
+ mix = voice + bed
+ refs = tmp_path / "refs"
+ for name, x in [("mix", mix), ("voice", voice), ("music", music), ("effects", effects), ("background", bed)]:
+ write(refs / f"{name}.flac", x)
+ (refs / "meta.json").write_text(json.dumps({"text": TEXT, "sampleRate": SR}), encoding="utf8")
+ return {"dir": tmp_path, "refs": refs, "voice": voice, "music": music, "effects": effects, "bed": bed, "mix": mix}
+
+
+def job(case, outputs, extra=None, transcript=None):
+ run = case["dir"]
+ files = []
+ for i, (stem, x) in enumerate(outputs):
+ f = f"outputs/j/{i}.flac"
+ write(run / f, x)
+ files.append({"file": f, "kind": "audio", **({"stem": stem} if stem else {})})
+ if transcript is not None:
+ (run / "outputs/j/t-transcript.txt").write_text(transcript, encoding="utf8")
+ files.append({"file": "outputs/j/t-transcript.txt", "kind": "text", "role": "transcript"})
+ return {
+ "id": "j",
+ "inputs": {"audio": str(case["refs"] / "mix.flac")},
+ "references": [str(p) for p in sorted(case["refs"].glob("*.flac"))],
+ "request": {"params": {"extra": extra or {}}},
+ "outputs": files,
+ }
+
+
+def scorer(run_dir):
+ s = score.Scorer(argparse.Namespace(device="cpu"))
+ s.run_dir = run_dir
+ return s
+
+
+def test_stem_names_fold_and_an_unnamed_first_output_is_the_voice(case):
+ voice, bed = case["voice"], case["bed"]
+ j = job(case, [(None, voice), ("residual", bed), ("drums", 0.5 * bed)])
+ stems = score.audio_outputs(case["dir"], j)
+ assert set(stems) == {"voice", "background", "drums"}
+ j = job(case, [("vocals", voice), ("no_vocals", bed), ("sfx", case["effects"]), ("music", case["music"])])
+ assert set(score.audio_outputs(case["dir"], j)) == {"voice", "background", "effects", "music"}
+
+
+def test_references_and_meta(case):
+ j = job(case, [("voice", case["voice"])])
+ refs, meta = score.references_of(j)
+ assert set(refs) == {"mix", "voice", "music", "effects", "background"}
+ assert meta["text"] == TEXT
+
+
+def test_separation_of_a_clean_split(case):
+ # The fast stereo bed: the input minus the mono speech, every channel.
+ j = job(case, [("voice", case["voice"][:1]), ("background", case["mix"] - case["voice"][:1])])
+ res = scorer(case["dir"]).m_separation(j, [])
+ assert res["voiceSiSdr"] > 60 and res["backgroundSiSdr"] > 60
+ assert res["mixError"] < -60
+ assert abs(res["bedLevel"]) < 0.01 and abs(res["bedScale"]) < 0.01
+ assert res["stereoCorrGap"] < 0.01
+
+
+def test_a_bed_scaled_down_under_full_scale_shows(case):
+ # AudioMerge divides a result that peaks over 1.0 by its peak: here 1.25, about −1.94 dB.
+ j = job(case, [("voice", case["voice"]), ("background", (case["mix"] - case["voice"]) / 1.25)])
+ res = scorer(case["dir"]).m_separation(j, [])
+ assert res["bedScale"] == pytest.approx(-1.938, abs=0.01)
+ assert res["bedLevel"] == pytest.approx(-1.94, abs=0.02)
+ assert res["backgroundSiSdr"] > 60 # the scale alone doesn't change SI-SDR
+
+
+def test_demucs_stems_are_summed_into_a_bed_and_a_late_stem_is_lined_up(case):
+ bed = case["bed"]
+ late = lambda x: sep.shift(x, -300) # noqa: E731 (300 samples late, like a decoder's priming)
+ j = job(case, [("vocals", late(case["voice"])), ("drums", late(0.5 * bed)), ("bass", late(0.25 * bed)), ("other", late(0.25 * bed))])
+ res = scorer(case["dir"]).m_separation(j, [])
+ # Lined up, only the last 300 samples are missing (about 22 dB for one second); unaligned it would be far lower.
+ assert res["backgroundSiSdr"] > 18
+ assert res["voiceSiSdr"] > 18
+ assert "shifted 300 samples" in res["_note"] or "shifted -300 samples" in res["_note"]
+
+
+def test_clean_dialogue_is_scored_against_the_level_asked(case):
+ # Graph C: one file, the dialogue with the music and effects at −18 dB, mono.
+ g = 10 ** (-18 / 20)
+ out = sep.mono(case["voice"]) + g * sep.mono(case["bed"])
+ extra = {"separationModel": "DBS-BSRNN-DnR", "channels": "mono", "voiceDb": 0, "musicDb": -18, "effectsDb": -18}
+ j = job(case, [("voice", out)], extra=extra)
+ res = scorer(case["dir"]).m_separation(j, [])
+ assert res["remixSiSdr"] > 60
+ assert res["bedLevel"] == pytest.approx(-18, abs=0.05)
+ assert 15 < res["voiceSiSdr"] < 30 # the bed under it counts as "not the voice" here
+ assert "mixError" not in res and "bedScale" not in res
+ assert score.remix_levels(j) == {"voiceDb": 0.0, "musicDb": -18.0, "effectsDb": -18.0, "bedDb": -18.0}
+ assert score.remix_levels(job(case, [("voice", out)], extra={"channels": "mono"})) is None
+
+
+class FakeAsr:
+ def text(self, audio, sr=16000):
+ return TEXT if len(audio) else ""
+
+
+def test_wer_with_a_fake_asr_and_without_one(case, monkeypatch):
+ j = job(case, [("voice", case["voice"])], transcript="the quick brown fox jumps over a lazy dog")
+ s = scorer(case["dir"])
+ s._asr = FakeAsr()
+ res = s.m_wer(j, [])
+ assert res["wer"] == 0 and res["werInput"] == 0
+ assert res["werTranscript"] == pytest.approx(1 / 9, abs=1e-3)
+ # Without Whisper the job's own transcript is still scored, and the family isn't switched off for later jobs.
+ s = scorer(case["dir"])
+
+ def missing():
+ raise Missing("speech recognition needs transformers: run pnpm eval:setup --asr")
+
+ monkeypatch.setattr(s, "asr", missing)
+ res = s.m_wer(j, [])
+ assert res["werTranscript"] == pytest.approx(1 / 9, abs=1e-3)
+ assert "wer" not in res and "werInput" not in res and "skipped" in res["_note"]
+ assert "wer" not in s.skipped and "wer (Whisper)" in s.skipped
+
+
+def test_download_asr_fetches_whisper_at_its_revision(monkeypatch):
+ got = []
+ monkeypatch.setattr(download, "_download", lambda key, f: got.append((key, f)) or f"/cache/{f}")
+ assert download.main(["--asr", "--no-aesthetic"]) == 0
+ whisper = [f for k, f in got if k == "whisper-base-en"]
+ assert set(whisper) == set(download.MODELS["whisper-base-en"]["files"])
+ assert "model.safetensors" in whisper
+
+
+def test_bed_scale_and_remix_gains_on_plain_arrays():
+ voice, music, effects = parts()
+ mix = voice + music + effects
+ assert sep.bed_scale((mix - voice[:1]) / 2, voice[:1], mix) == pytest.approx(-6.021, abs=0.01)
+ assert sep.bed_scale(np.zeros_like(mix), voice, np.zeros_like(mix)) is None
+ g = sep.remix_gains(voice[0] + 0.1 * (music + effects).mean(0), voice, music + effects)
+ assert g["voice"] == pytest.approx(0, abs=0.01) and g["bed"] == pytest.approx(-20, abs=0.05)