#!/usr/bin/env python3 from __future__ import annotations import argparse import csv import json import sys from collections import Counter, defaultdict from dataclasses import dataclass from pathlib import Path from typing import Iterable sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) from romani_asr.manifest import read_manifest_csv # noqa: E402 from romani_asr.metrics import edit_distance # noqa: E402 from romani_asr.text import has_non_latin_script, normalize_for_metric # noqa: E402 DEFAULT_RUNS = [ ( "whisper_auto", Path("artifacts/evals/whisper-large-v3-turbo-zero-shot"), ), ( "whisper_slovak", Path("artifacts/evals/whisper-large-v3-turbo-zero-shot-slovak-prompt"), ), ( "whisper_romani_lora", Path("artifacts/evals/whisper-turbo-lora-romani-token-decoder-checkpoint-655"), ), ( "whisper_romani_lora_guarded", Path("artifacts/evals/whisper-turbo-lora-romani-token-decoder-checkpoint-655-guarded"), ), ] @dataclass(frozen=True) class RunSpec: name: str path: Path def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Analyze ASR predictions and write error-analysis artifacts." ) parser.add_argument( "--manifest", type=Path, default=Path("artifacts/manifests/test.csv"), ) parser.add_argument( "--run", action="append", default=[], help="Run spec in NAME=EVAL_DIR form. Defaults to measured Whisper runs.", ) parser.add_argument( "--output-dir", type=Path, default=Path("artifacts/analysis/whisper-error-analysis"), ) parser.add_argument( "--best-run", default="whisper_romani_lora_guarded", help="Run name to use for detailed cleanup and confusion analysis.", ) parser.add_argument("--top-k", type=int, default=20) return parser.parse_args() def parse_runs(values: list[str]) -> list[RunSpec]: if not values: return [RunSpec(name, path) for name, path in DEFAULT_RUNS if path.exists()] runs: list[RunSpec] = [] for value in values: if "=" not in value: raise ValueError(f"--run must be NAME=EVAL_DIR, got: {value}") name, path_text = value.split("=", 1) if not name.strip(): raise ValueError(f"--run name cannot be empty: {value}") runs.append(RunSpec(name.strip(), Path(path_text))) return runs def read_predictions(eval_dir: Path) -> dict[str, dict[str, str]]: path = eval_dir / "predictions.csv" with path.open(newline="", encoding="utf-8") as handle: return {row["file_name"]: row for row in csv.DictReader(handle)} def rate(reference: str, hypothesis: str, unit: str, keep_diacritics: bool) -> float: ref = normalize_for_metric(reference, keep_diacritics=keep_diacritics) hyp = normalize_for_metric(hypothesis, keep_diacritics=keep_diacritics) ref_units = ref.split() if unit == "word" else list(ref) hyp_units = hyp.split() if unit == "word" else list(hyp) if not ref_units: return 0.0 return edit_distance(ref_units, hyp_units) / len(ref_units) def corpus_rate( rows: list[dict[str, object]], run_name: str, unit: str, keep_diacritics: bool, ) -> float: total_errors = 0 total_units = 0 for row in rows: ref = normalize_for_metric( str(row["reference"]), keep_diacritics=keep_diacritics, ) hyp = normalize_for_metric( str(row[f"{run_name}_prediction"]), keep_diacritics=keep_diacritics, ) ref_units = ref.split() if unit == "word" else list(ref) hyp_units = hyp.split() if unit == "word" else list(hyp) total_errors += edit_distance(ref_units, hyp_units) total_units += len(ref_units) if total_units == 0: return 0.0 return total_errors / total_units def align(reference: list[str], hypothesis: list[str]) -> list[tuple[str, str, str]]: rows = len(reference) + 1 cols = len(hypothesis) + 1 costs = [[0] * cols for _ in range(rows)] back = [[""] * cols for _ in range(rows)] for i in range(1, rows): costs[i][0] = i back[i][0] = "del" for j in range(1, cols): costs[0][j] = j back[0][j] = "ins" for i, ref_item in enumerate(reference, start=1): for j, hyp_item in enumerate(hypothesis, start=1): candidates = [ (costs[i - 1][j] + 1, "del"), (costs[i][j - 1] + 1, "ins"), ( costs[i - 1][j - 1] + (ref_item != hyp_item), "eq" if ref_item == hyp_item else "sub", ), ] cost, op = min(candidates, key=lambda item: item[0]) costs[i][j] = cost back[i][j] = op aligned: list[tuple[str, str, str]] = [] i = len(reference) j = len(hypothesis) while i > 0 or j > 0: op = back[i][j] if op in {"eq", "sub"}: aligned.append((op, reference[i - 1], hypothesis[j - 1])) i -= 1 j -= 1 elif op == "del": aligned.append((op, reference[i - 1], "")) i -= 1 elif op == "ins": aligned.append((op, "", hypothesis[j - 1])) j -= 1 else: raise RuntimeError("Alignment backtrace failed") aligned.reverse() return aligned def write_csv(path: Path, fieldnames: list[str], rows: Iterable[dict[str, object]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fieldnames, extrasaction="ignore") writer.writeheader() writer.writerows(rows) def fmt(value: float) -> str: return f"{value:.3f}" def duration_bucket(duration_sec: float) -> str: if duration_sec < 1.0: return "<1s" if duration_sec < 2.0: return "1-2s" if duration_sec < 4.0: return "2-4s" return ">=4s" def repetition_features(text: str) -> tuple[float, int]: normalized = normalize_for_metric(text) tokens = normalized.split() max_token_share = 0.0 if tokens: token_counts = Counter(tokens) max_token_share = max(token_counts.values()) / len(tokens) longest_char_run = 0 current_char = "" current_run = 0 for ch in normalized: if ch == current_char: current_run += 1 else: current_char = ch current_run = 1 longest_char_run = max(longest_char_run, current_run) return max_token_share, longest_char_run def average(values: Iterable[float]) -> float: values = list(values) if not values: return 0.0 return sum(values) / len(values) def main() -> None: args = parse_args() runs = parse_runs(args.run) if not runs: raise SystemExit("No eval runs found. Pass --run NAME=EVAL_DIR.") manifest_rows = read_manifest_csv(args.manifest) predictions = {run.name: read_predictions(run.path) for run in runs} missing = { run.name: [ row["file_name"] for row in manifest_rows if row["file_name"] not in predictions[run.name] ] for run in runs } missing = {name: files for name, files in missing.items() if files} if missing: raise SystemExit(f"Prediction files are missing manifest rows: {missing}") per_utterance: list[dict[str, object]] = [] for row in manifest_rows: file_name = row["file_name"] reference = row["transcript"] duration_sec = float(row["duration_sec"]) out: dict[str, object] = { "file_name": file_name, "audio_path": row["audio_path"], "duration_sec": f"{duration_sec:.3f}", "duration_bucket": duration_bucket(duration_sec), "flag": row["flag"], "source_group": row["source_group"], "reference": reference, "reference_metric": normalize_for_metric(reference), "reference_word_count": len(normalize_for_metric(reference).split()), "reference_char_count": len(normalize_for_metric(reference)), } for run in runs: prediction = predictions[run.name][file_name]["prediction"] max_token_share, longest_char_run = repetition_features(prediction) out[f"{run.name}_prediction"] = prediction out[f"{run.name}_wer"] = rate(reference, prediction, "word", True) out[f"{run.name}_cer"] = rate(reference, prediction, "char", True) out[f"{run.name}_wer_ascii"] = rate(reference, prediction, "word", False) out[f"{run.name}_cer_ascii"] = rate(reference, prediction, "char", False) out[f"{run.name}_non_latin"] = has_non_latin_script(prediction) ref_chars = max(1, len(normalize_for_metric(reference))) hyp_chars = len(normalize_for_metric(prediction)) out[f"{run.name}_char_ratio"] = hyp_chars / ref_chars out[f"{run.name}_max_token_share"] = max_token_share out[f"{run.name}_longest_char_run"] = longest_char_run per_utterance.append(out) run_summary: list[dict[str, object]] = [] for run in runs: rows = per_utterance total_latency = sum( float(predictions[run.name][row["file_name"]].get("latency_sec", 0.0)) for row in manifest_rows ) run_summary.append( { "run": run.name, "path": str(run.path), "count": len(rows), "wer": corpus_rate(rows, run.name, "word", True), "cer": corpus_rate(rows, run.name, "char", True), "wer_ascii": corpus_rate(rows, run.name, "word", False), "cer_ascii": corpus_rate(rows, run.name, "char", False), "non_latin_outputs": sum( bool(row[f"{run.name}_non_latin"]) for row in rows ), "exact_matches": sum( float(row[f"{run.name}_wer"]) == 0.0 for row in rows ), "mean_latency_sec": total_latency / len(rows) if rows else 0.0, "total_latency_sec": total_latency, } ) best_name = args.best_run if args.best_run in predictions else runs[-1].name baseline_name = ( "whisper_slovak" if "whisper_slovak" in predictions and best_name != "whisper_slovak" else runs[0].name ) detailed_rows: list[dict[str, object]] = [] for row in per_utterance: best_cer = float(row[f"{best_name}_cer"]) base_cer = float(row[f"{baseline_name}_cer"]) best_wer = float(row[f"{best_name}_wer"]) char_ratio = float(row[f"{best_name}_char_ratio"]) reasons: list[str] = [] if best_cer >= 0.25: reasons.append("high_cer") if best_wer >= 1.0: reasons.append("high_wer") if best_cer - base_cer >= 0.05: reasons.append("regression_vs_baseline") if char_ratio >= 1.5: reasons.append("over_generation") if char_ratio <= 0.6: reasons.append("under_generation") if ( float(row[f"{best_name}_max_token_share"]) >= 0.4 and len(str(row[f"{best_name}_prediction"]).split()) >= 8 ) or int(row[f"{best_name}_longest_char_run"]) >= 20: reasons.append("repetition_loop") if bool(row[f"{best_name}_non_latin"]): reasons.append("non_latin_output") if reasons: detailed_rows.append( { **row, "review_reasons": ",".join(reasons), "baseline_cer": base_cer, "best_cer": best_cer, "cer_delta_vs_baseline": best_cer - base_cer, } ) detailed_rows.sort( key=lambda row: ( float(row["best_cer"]), float(row["cer_delta_vs_baseline"]), float(row[f"{best_name}_wer"]), ), reverse=True, ) char_confusions: Counter[tuple[str, str]] = Counter() word_confusions: Counter[tuple[str, str]] = Counter() for row in per_utterance: ref = normalize_for_metric(str(row["reference"])) hyp = normalize_for_metric(str(row[f"{best_name}_prediction"])) for op, ref_item, hyp_item in align(list(ref), list(hyp)): if op == "sub": char_confusions[(ref_item, hyp_item)] += 1 for op, ref_item, hyp_item in align(ref.split(), hyp.split()): if op == "sub": word_confusions[(ref_item, hyp_item)] += 1 bucket_rows: list[dict[str, object]] = [] for group_key in ["duration_bucket", "flag", "source_group"]: grouped: dict[str, list[dict[str, object]]] = defaultdict(list) for row in per_utterance: grouped[str(row[group_key])].append(row) for value, rows in sorted(grouped.items()): bucket_rows.append( { "group": group_key, "value": value, "count": len(rows), f"{best_name}_wer": corpus_rate(rows, best_name, "word", True), f"{best_name}_cer": corpus_rate(rows, best_name, "char", True), f"{baseline_name}_wer": corpus_rate( rows, baseline_name, "word", True ), f"{baseline_name}_cer": corpus_rate( rows, baseline_name, "char", True ), } ) output_dir = args.output_dir output_dir.mkdir(parents=True, exist_ok=True) per_fields = [ "file_name", "audio_path", "duration_sec", "duration_bucket", "flag", "source_group", "reference", "reference_metric", "reference_word_count", "reference_char_count", ] for run in runs: per_fields.extend( [ f"{run.name}_prediction", f"{run.name}_wer", f"{run.name}_cer", f"{run.name}_wer_ascii", f"{run.name}_cer_ascii", f"{run.name}_non_latin", f"{run.name}_char_ratio", f"{run.name}_max_token_share", f"{run.name}_longest_char_run", ] ) write_csv(output_dir / "per_utterance.csv", per_fields, per_utterance) write_csv( output_dir / "run_summary.csv", [ "run", "path", "count", "wer", "cer", "wer_ascii", "cer_ascii", "non_latin_outputs", "exact_matches", "mean_latency_sec", "total_latency_sec", ], run_summary, ) review_fields = [ "file_name", "audio_path", "duration_sec", "flag", "source_group", "review_reasons", "reference", ] if baseline_name != best_name: review_fields.append(f"{baseline_name}_prediction") review_fields.extend( [ f"{best_name}_prediction", "baseline_cer", "best_cer", "cer_delta_vs_baseline", f"{best_name}_wer", f"{best_name}_char_ratio", f"{best_name}_max_token_share", f"{best_name}_longest_char_run", ] ) write_csv(output_dir / "review_candidates.csv", review_fields, detailed_rows) bucket_fields = ["group", "value", "count", f"{best_name}_wer", f"{best_name}_cer"] if baseline_name != best_name: bucket_fields.extend([f"{baseline_name}_wer", f"{baseline_name}_cer"]) write_csv(output_dir / "bucket_summary.csv", bucket_fields, bucket_rows) write_csv( output_dir / "char_confusions.csv", ["reference_char", "prediction_char", "count"], ( { "reference_char": ref_item, "prediction_char": hyp_item, "count": count, } for (ref_item, hyp_item), count in char_confusions.most_common() ), ) write_csv( output_dir / "word_substitutions.csv", ["reference_word", "prediction_word", "count"], ( { "reference_word": ref_item, "prediction_word": hyp_item, "count": count, } for (ref_item, hyp_item), count in word_confusions.most_common() ), ) summary = { "manifest": str(args.manifest), "best_run": best_name, "baseline_run": baseline_name, "runs": run_summary, "review_candidate_count": len(detailed_rows), "outputs": { "per_utterance": str(output_dir / "per_utterance.csv"), "run_summary": str(output_dir / "run_summary.csv"), "review_candidates": str(output_dir / "review_candidates.csv"), "bucket_summary": str(output_dir / "bucket_summary.csv"), "char_confusions": str(output_dir / "char_confusions.csv"), "word_substitutions": str(output_dir / "word_substitutions.csv"), }, } (output_dir / "summary.json").write_text( json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8", ) top_improvements = [] top_regressions = [] if baseline_name != best_name: top_improvements = sorted( per_utterance, key=lambda row: float(row[f"{baseline_name}_cer"]) - float(row[f"{best_name}_cer"]), reverse=True, )[: args.top_k] top_regressions = sorted( per_utterance, key=lambda row: float(row[f"{best_name}_cer"]) - float(row[f"{baseline_name}_cer"]), reverse=True, )[: args.top_k] lines = [ "# ASR Error Analysis", "", f"Manifest: `{args.manifest}`", f"Best run for detailed analysis: `{best_name}`", f"Comparison baseline: `{baseline_name}`", "", "## Run Summary", "", "| Run | WER | CER | ASCII WER | ASCII CER | Exact | Non-Latin | Mean Latency |", "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |", ] for row in run_summary: lines.append( "| " f"{row['run']} | {fmt(float(row['wer']))} | " f"{fmt(float(row['cer']))} | {fmt(float(row['wer_ascii']))} | " f"{fmt(float(row['cer_ascii']))} | {row['exact_matches']} | " f"{row['non_latin_outputs']} | {fmt(float(row['mean_latency_sec']))}s |" ) lines.extend( [ "", "## What To Review First", "", f"- Review candidates: {len(detailed_rows)} clips", "- Prioritize rows marked `high_cer`, `regression_vs_baseline`, " "`over_generation`, `under_generation`, or `repetition_loop`.", "- Listen before editing labels; the CSV identifies likely problems, " "not guaranteed transcript mistakes.", "", ] ) if baseline_name != best_name: lines.extend(["## Top Improvements", ""]) for row in top_improvements[:10]: delta = float(row[f"{baseline_name}_cer"]) - float(row[f"{best_name}_cer"]) lines.extend( [ f"### {row['file_name']} (+{fmt(delta)} CER)", "", f"- REF: {row['reference']}", f"- {baseline_name}: {row[f'{baseline_name}_prediction']}", f"- {best_name}: {row[f'{best_name}_prediction']}", "", ] ) lines.extend(["## Top Regressions", ""]) for row in top_regressions[:10]: delta = float(row[f"{best_name}_cer"]) - float( row[f"{baseline_name}_cer"] ) lines.extend( [ f"### {row['file_name']} (-{fmt(delta)} CER)", "", f"- REF: {row['reference']}", f"- {baseline_name}: {row[f'{baseline_name}_prediction']}", f"- {best_name}: {row[f'{best_name}_prediction']}", "", ] ) else: lines.extend(["## Worst Outputs", ""]) for row in detailed_rows[:10]: lines.extend( [ f"### {row['file_name']} (CER {fmt(float(row['best_cer']))})", "", f"- Reasons: {row['review_reasons']}", f"- REF: {row['reference']}", f"- {best_name}: {row[f'{best_name}_prediction'][:500]}", "", ] ) lines.extend( [ "## Common Character Substitutions", "", "| Reference | Prediction | Count |", "| --- | --- | ---: |", ] ) for (ref_item, hyp_item), count in char_confusions.most_common(15): ref_label = ref_item if ref_item != " " else "`space`" hyp_label = hyp_item if hyp_item != " " else "`space`" lines.append(f"| {ref_label} | {hyp_label} | {count} |") lines.extend( [ "", "## Output Files", "", "- `per_utterance.csv`: every prediction with per-clip WER/CER", "- `review_candidates.csv`: clips to listen to first", "- `bucket_summary.csv`: error by duration, flag, and source group", "- `char_confusions.csv`: best-run character substitutions", "- `word_substitutions.csv`: best-run word substitutions", ] ) (output_dir / "summary.md").write_text("\n".join(lines) + "\n", encoding="utf-8") print(json.dumps(summary, indent=2, ensure_ascii=False), flush=True) if __name__ == "__main__": main()