File size: 22,332 Bytes
62600b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
#!/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()