"""Evaluation runner parsing testset.toml and producing eval_report.md and json.""" import json import time import tomllib 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, output_report_dir: Path | None = None) -> dict[str, Any]: """Run evaluation over songs defined in testset.toml.""" 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