feat(eval): implement evaluation metrics (timing MAE, pitch accuracy, WER) and runner
This commit is contained in:
@ -1,6 +1,6 @@
|
|||||||
"""Evaluation package."""
|
"""Evaluation package."""
|
||||||
|
|
||||||
from songsplit.eval.metrics import calculate_timing_metrics
|
from songsplit.eval.metrics import evaluate_vocals, normalize_text_for_wer
|
||||||
from songsplit.eval.run_eval import run_evaluation
|
from songsplit.eval.run_eval import run_evaluation
|
||||||
|
|
||||||
__all__ = ["calculate_timing_metrics", "run_evaluation"]
|
__all__ = ["evaluate_vocals", "normalize_text_for_wer", "run_evaluation"]
|
||||||
|
|||||||
@ -1,8 +1,122 @@
|
|||||||
"""Quality metrics against UltraStar reference (timing, pitch, WER)."""
|
"""Quality metrics comparing predicted vocals against UltraStar reference ground-truth."""
|
||||||
|
|
||||||
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
import jiwer
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
def calculate_timing_metrics(predicted: list[dict[str, Any]], reference: list[dict[str, Any]]) -> dict[str, float]:
|
from songsplit.export.ultrastar import UltraStarSong
|
||||||
"""Calculate mean/median syllable onset error in ms and fraction within +-100ms."""
|
from songsplit.schema.vocals import VocalsDocument
|
||||||
raise NotImplementedError("Metrics will be implemented in M2.")
|
|
||||||
|
|
||||||
|
def normalize_text_for_wer(text: str) -> str:
|
||||||
|
"""Normalize text: remove punctuation, lowercase, normalize whitespace."""
|
||||||
|
# Remove UltraStar formatting tokens (~, -, etc.) and standard punctuation
|
||||||
|
text = re.sub(r"[^\w\s]", "", text)
|
||||||
|
text = re.sub(r"\s+", " ", text)
|
||||||
|
return text.strip().lower()
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_vocals(
|
||||||
|
predicted: VocalsDocument,
|
||||||
|
reference: UltraStarSong,
|
||||||
|
max_match_distance_sec: float = 0.5,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Calculate comprehensive timing, pitch, and WER metrics against UltraStar reference."""
|
||||||
|
# Flatten reference syllables
|
||||||
|
ref_notes = []
|
||||||
|
for line in reference.lines:
|
||||||
|
for note in line:
|
||||||
|
# Skip empty whitespace notes
|
||||||
|
if note.text.strip():
|
||||||
|
ref_notes.append(note)
|
||||||
|
|
||||||
|
# Flatten predicted syllables
|
||||||
|
pred_syllables = []
|
||||||
|
for line in predicted.lines:
|
||||||
|
for syl in line.syllables:
|
||||||
|
if syl.text.strip():
|
||||||
|
pred_syllables.append(syl)
|
||||||
|
|
||||||
|
if not ref_notes or not pred_syllables:
|
||||||
|
return {
|
||||||
|
"num_ref_syllables": len(ref_notes),
|
||||||
|
"num_pred_syllables": len(pred_syllables),
|
||||||
|
"mae_timing_ms": 0.0,
|
||||||
|
"median_timing_ms": 0.0,
|
||||||
|
"fraction_within_100ms": 0.0,
|
||||||
|
"strict_pitch_accuracy": 0.0,
|
||||||
|
"octave_equiv_pitch_accuracy": 0.0,
|
||||||
|
"wer": 1.0 if not pred_syllables and ref_notes else 0.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Match each reference syllable to nearest predicted syllable within max_match_distance_sec
|
||||||
|
timing_errors_ms = []
|
||||||
|
strict_pitch_correct = []
|
||||||
|
octave_pitch_correct = []
|
||||||
|
|
||||||
|
matched_pred_indices = set()
|
||||||
|
for ref in ref_notes:
|
||||||
|
best_idx = None
|
||||||
|
best_diff = float("inf")
|
||||||
|
|
||||||
|
for idx, pred in enumerate(pred_syllables):
|
||||||
|
diff = abs(pred.start - ref.start_sec)
|
||||||
|
if diff < best_diff and diff <= max_match_distance_sec:
|
||||||
|
best_diff = diff
|
||||||
|
best_idx = idx
|
||||||
|
|
||||||
|
if best_idx is not None:
|
||||||
|
matched_pred_indices.add(best_idx)
|
||||||
|
pred = pred_syllables[best_idx]
|
||||||
|
timing_errors_ms.append(best_diff * 1000.0)
|
||||||
|
|
||||||
|
# Pitch check
|
||||||
|
pitch_diff = abs(pred.midi - ref.midi)
|
||||||
|
is_strict = pitch_diff <= 0.5
|
||||||
|
strict_pitch_correct.append(1.0 if is_strict else 0.0)
|
||||||
|
|
||||||
|
# Octave equivalent pitch check (mod 12)
|
||||||
|
mod_diff = pitch_diff % 12.0
|
||||||
|
octave_diff = min(mod_diff, 12.0 - mod_diff)
|
||||||
|
is_octave = octave_diff <= 0.5
|
||||||
|
octave_pitch_correct.append(1.0 if is_octave else 0.0)
|
||||||
|
else:
|
||||||
|
# Unmatched reference note -> penalty
|
||||||
|
timing_errors_ms.append(max_match_distance_sec * 1000.0)
|
||||||
|
strict_pitch_correct.append(0.0)
|
||||||
|
octave_pitch_correct.append(0.0)
|
||||||
|
|
||||||
|
# 1. Timing metrics
|
||||||
|
mae_timing_ms = float(np.mean(timing_errors_ms)) if timing_errors_ms else 0.0
|
||||||
|
median_timing_ms = float(np.median(timing_errors_ms)) if timing_errors_ms else 0.0
|
||||||
|
fraction_within_100ms = (
|
||||||
|
float(np.mean([1.0 if err <= 100.0 else 0.0 for err in timing_errors_ms])) if timing_errors_ms else 0.0
|
||||||
|
)
|
||||||
|
|
||||||
|
# 2. Pitch metrics
|
||||||
|
strict_pitch_acc = float(np.mean(strict_pitch_correct)) if strict_pitch_correct else 0.0
|
||||||
|
octave_pitch_acc = float(np.mean(octave_pitch_correct)) if octave_pitch_correct else 0.0
|
||||||
|
|
||||||
|
# 3. WER metric
|
||||||
|
ref_words_raw = "".join(r.text for r in ref_notes)
|
||||||
|
pred_words_raw = "".join(p.text for p in pred_syllables)
|
||||||
|
norm_ref = normalize_text_for_wer(ref_words_raw)
|
||||||
|
norm_pred = normalize_text_for_wer(pred_words_raw)
|
||||||
|
|
||||||
|
if norm_ref:
|
||||||
|
wer_score = float(jiwer.wer(norm_ref, norm_pred))
|
||||||
|
else:
|
||||||
|
wer_score = 0.0 if not norm_pred else 1.0
|
||||||
|
|
||||||
|
return {
|
||||||
|
"num_ref_syllables": len(ref_notes),
|
||||||
|
"num_pred_syllables": len(pred_syllables),
|
||||||
|
"mae_timing_ms": mae_timing_ms,
|
||||||
|
"median_timing_ms": median_timing_ms,
|
||||||
|
"fraction_within_100ms": fraction_within_100ms,
|
||||||
|
"strict_pitch_accuracy": strict_pitch_acc,
|
||||||
|
"octave_equiv_pitch_accuracy": octave_pitch_acc,
|
||||||
|
"wer": wer_score,
|
||||||
|
}
|
||||||
|
|||||||
@ -1,8 +1,102 @@
|
|||||||
"""Evaluation runner for testset.toml."""
|
"""Evaluation runner parsing testset.toml and producing eval_report.md and json."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
import tomllib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from songsplit.eval.metrics import evaluate_vocals
|
||||||
|
from songsplit.export.ultrastar import parse_ultrastar
|
||||||
|
from songsplit.pipeline import PipelineContext, get_default_pipeline
|
||||||
|
from songsplit.schema.vocals import VocalsDocument
|
||||||
|
|
||||||
|
|
||||||
def run_evaluation(testset_config: Path) -> dict[str, str]:
|
def run_evaluation(testset_config: Path, output_report_dir: Path | None = None) -> dict[str, Any]:
|
||||||
"""Run full evaluation suite across test songs."""
|
"""Run evaluation over songs defined in testset.toml."""
|
||||||
raise NotImplementedError("Evaluation runner will be implemented in M2.")
|
testset_config = testset_config.resolve()
|
||||||
|
with open(testset_config, "rb") as f:
|
||||||
|
config_data = tomllib.load(f)
|
||||||
|
|
||||||
|
report_dir = output_report_dir or testset_config.parent
|
||||||
|
report_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
songs = config_data.get("songs", [])
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for song_entry in songs:
|
||||||
|
name = song_entry.get("name", "Unnamed")
|
||||||
|
audio_path = Path(song_entry["audio"]).resolve()
|
||||||
|
ref_path = Path(song_entry["reference"]).resolve()
|
||||||
|
lang = song_entry.get("lang", "de")
|
||||||
|
|
||||||
|
song_out_dir = report_dir / "eval_runs" / name
|
||||||
|
ctx = PipelineContext(
|
||||||
|
source_file=audio_path,
|
||||||
|
output_dir=song_out_dir,
|
||||||
|
lang=lang,
|
||||||
|
target_stage="s4_pitch",
|
||||||
|
)
|
||||||
|
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
runner = get_default_pipeline()
|
||||||
|
meta = runner.run(ctx)
|
||||||
|
elapsed_sec = time.perf_counter() - t0
|
||||||
|
|
||||||
|
vocals_json = song_out_dir / "vocals.json"
|
||||||
|
if not vocals_json.exists():
|
||||||
|
results.append(
|
||||||
|
{
|
||||||
|
"name": name,
|
||||||
|
"status": "failed",
|
||||||
|
"error": "vocals.json not produced",
|
||||||
|
"elapsed_sec": elapsed_sec,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
with open(vocals_json, encoding="utf-8") as vf:
|
||||||
|
pred_vocals = VocalsDocument.model_validate(json.load(vf))
|
||||||
|
|
||||||
|
ref_song = parse_ultrastar(ref_path)
|
||||||
|
metrics = evaluate_vocals(pred_vocals, ref_song)
|
||||||
|
metrics["name"] = name
|
||||||
|
metrics["status"] = "success"
|
||||||
|
metrics["elapsed_sec"] = elapsed_sec
|
||||||
|
metrics["stages_done"] = meta.stages_done
|
||||||
|
results.append(metrics)
|
||||||
|
|
||||||
|
# Generate Markdown Report
|
||||||
|
md_lines = [
|
||||||
|
"# songsplit Evaluationsbericht (Eval Report)",
|
||||||
|
"",
|
||||||
|
f"Konfiguration: `{testset_config.name}`",
|
||||||
|
f"Getestete Songs: {len(results)}",
|
||||||
|
"",
|
||||||
|
"| Song | Status | Timing MAE (ms) | Timing <= 100ms | Noten (strikt) | Noten (+-Oktav) | WER | Laufzeit (s) |",
|
||||||
|
"|---|---|---|---|---|---|---|---|",
|
||||||
|
]
|
||||||
|
|
||||||
|
for r in results:
|
||||||
|
if r.get("status") == "success":
|
||||||
|
md_lines.append(
|
||||||
|
f"| {r['name']} | OK | {r['mae_timing_ms']:.1f} | "
|
||||||
|
f"{r['fraction_within_100ms'] * 100:.1f}% | {r['strict_pitch_accuracy'] * 100:.1f}% | "
|
||||||
|
f"{r['octave_equiv_pitch_accuracy'] * 100:.1f}% | {r['wer']:.2f} | {r['elapsed_sec']:.1f}s |"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
md_lines.append(
|
||||||
|
f"| {r.get('name', 'Song')} | FEHLER ({r.get('error')}) | - | - | - | - | - | {r.get('elapsed_sec', 0.0):.1f}s |"
|
||||||
|
)
|
||||||
|
|
||||||
|
report_md_path = report_dir / "eval_report.md"
|
||||||
|
report_json_path = report_dir / "eval_report.json"
|
||||||
|
|
||||||
|
with open(report_md_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write("\n".join(md_lines) + "\n")
|
||||||
|
|
||||||
|
report_data = {"songs": results, "timestamp": time.time()}
|
||||||
|
with open(report_json_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(report_data, f, indent=2)
|
||||||
|
|
||||||
|
return report_data
|
||||||
|
|||||||
81
tests/test_metrics.py
Normal file
81
tests/test_metrics.py
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
"""Unit tests for evaluation metrics (timing, pitch, WER)."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from songsplit.eval.metrics import evaluate_vocals, normalize_text_for_wer
|
||||||
|
from songsplit.export.ultrastar import UltraStarNote, UltraStarSong
|
||||||
|
from songsplit.schema.vocals import VocalLine, VocalsDocument, VocalSyllable
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_text_for_wer():
|
||||||
|
raw = "Hallo, Welt! Wie geht's?"
|
||||||
|
norm = normalize_text_for_wer(raw)
|
||||||
|
assert norm == "hallo welt wie gehts"
|
||||||
|
|
||||||
|
|
||||||
|
def test_evaluate_vocals_perfect_match():
|
||||||
|
# Ground truth: 2 syllables
|
||||||
|
ref_song = UltraStarSong(
|
||||||
|
headers={"BPM": "480", "GAP": "1000"},
|
||||||
|
lines=[
|
||||||
|
[
|
||||||
|
UltraStarNote(":", 0, 4, 0, "Hal", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||||
|
UltraStarNote(":", 4, 4, 2, "lo", start_sec=1.5, end_sec=2.0, midi=62.0),
|
||||||
|
]
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
pred_doc = VocalsDocument(
|
||||||
|
lines=[
|
||||||
|
VocalLine(
|
||||||
|
start=1.0,
|
||||||
|
end=2.0,
|
||||||
|
syllables=[
|
||||||
|
VocalSyllable(text="Hal", start=1.0, end=1.5, midi=60.0),
|
||||||
|
VocalSyllable(text="lo", start=1.5, end=2.0, midi=62.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
metrics = evaluate_vocals(pred_doc, ref_song)
|
||||||
|
assert metrics["mae_timing_ms"] == pytest.approx(0.0)
|
||||||
|
assert metrics["median_timing_ms"] == pytest.approx(0.0)
|
||||||
|
assert metrics["fraction_within_100ms"] == pytest.approx(1.0)
|
||||||
|
assert metrics["strict_pitch_accuracy"] == pytest.approx(1.0)
|
||||||
|
assert metrics["octave_equiv_pitch_accuracy"] == pytest.approx(1.0)
|
||||||
|
assert metrics["wer"] == pytest.approx(0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_evaluate_vocals_octave_error_and_timing_offset():
|
||||||
|
ref_song = UltraStarSong(
|
||||||
|
headers={"BPM": "480", "GAP": "1000"},
|
||||||
|
lines=[
|
||||||
|
[
|
||||||
|
# Note at 60.0, start 1.0
|
||||||
|
UltraStarNote(":", 0, 4, 0, "Test", start_sec=1.0, end_sec=1.5, midi=60.0),
|
||||||
|
]
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Prediction is offset by 50ms and has octave error (72.0 vs 60.0)
|
||||||
|
pred_doc = VocalsDocument(
|
||||||
|
lines=[
|
||||||
|
VocalLine(
|
||||||
|
start=1.05,
|
||||||
|
end=1.55,
|
||||||
|
syllables=[
|
||||||
|
VocalSyllable(text="Test", start=1.05, end=1.55, midi=72.0),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
metrics = evaluate_vocals(pred_doc, ref_song)
|
||||||
|
assert metrics["mae_timing_ms"] == pytest.approx(50.0, abs=1.0)
|
||||||
|
assert metrics["fraction_within_100ms"] == pytest.approx(1.0)
|
||||||
|
# Strict pitch should fail (72 != 60)
|
||||||
|
assert metrics["strict_pitch_accuracy"] == pytest.approx(0.0)
|
||||||
|
# Octave equivalent pitch should succeed (72 % 12 == 60 % 12)
|
||||||
|
assert metrics["octave_equiv_pitch_accuracy"] == pytest.approx(1.0)
|
||||||
|
assert metrics["wer"] == pytest.approx(0.0)
|
||||||
Reference in New Issue
Block a user