File size: 24,844 Bytes
cc7d399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#!/usr/bin/env python3
"""Downstream MT validation for Gemma 4 ASR outputs.

The script translates gold FLEURS transcripts, baseline Gemma 4 ASR outputs,
and script-aware Gemma 4 ASR outputs into English with NLLB. It then measures
how much translation quality drops relative to gold-transcript MT.
"""

from __future__ import annotations

import argparse
import json
import logging
import random
import sys
from collections import defaultdict, deque
from pathlib import Path
from types import ModuleType


ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).parent))
from runtime_cache import configure_runtime_cache

configure_runtime_cache(ROOT)

import pandas as pd
import torch
from huggingface_hub import hf_hub_download
from tqdm import tqdm
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

from script_fidelity import SCRIPT_CONFIGS, compute_sfr


LANGUAGES = [
    "pashto",
    "urdu",
    "arabic",
    "persian",
    "hindi",
    "bengali",
    "malayalam",
    "tamil",
    "somali",
    "georgian",
]

NLLB_LANG_CODES = {
    "pashto": "pbt_Arab",
    "urdu": "urd_Arab",
    "arabic": "arb_Arab",
    "persian": "pes_Arab",
    "hindi": "hin_Deva",
    "bengali": "ben_Beng",
    "malayalam": "mal_Mlym",
    "tamil": "tam_Taml",
    "somali": "som_Latn",
    "georgian": "kat_Geor",
}

VARIANTS = {
    "gold": "Gold transcript",
    "baseline": "Gemma 4 baseline ASR",
    "script_hint": "Gemma 4 script-aware ASR",
}

MODEL_ID = "unsloth/gemma-4-E2B-it"
TARGET_LANG = "eng_Latn"


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
    handlers=[logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger("downstream_mt")
sacrebleu: ModuleType | None = None


def require_sacrebleu() -> ModuleType:
    global sacrebleu
    if sacrebleu is not None:
        return sacrebleu
    try:
        import sacrebleu as sacrebleu_module
    except ModuleNotFoundError as exc:
        raise SystemExit(
            "Missing dependency: sacrebleu. Run `uv pip install -r requirements.txt` "
            "from paper_sfr, then rerun this script."
        ) from exc
    sacrebleu = sacrebleu_module
    return sacrebleu


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Translate Gemma 4 ASR outputs to English and score downstream MT damage."
    )
    parser.add_argument("--mt-model", default="facebook/nllb-200-distilled-600M")
    parser.add_argument("--baseline-predictions-dir", default=str(ROOT / "results_gemma4" / "predictions"))
    parser.add_argument(
        "--script-hint-predictions-dir",
        default=str(ROOT / "results_gemma4_prompt_mitigation" / "predictions"),
    )
    parser.add_argument("--mitigation-summary", default=str(ROOT / "analysis" / "gemma4_prompt_mitigation_summary.csv"))
    parser.add_argument("--results-dir", default=str(ROOT / "results_gemma4_downstream_mt"))
    parser.add_argument("--summary-csv", default=str(ROOT / "analysis" / "gemma4_downstream_mt_summary.csv"))
    parser.add_argument("--utterance-csv", default=str(ROOT / "analysis" / "gemma4_downstream_mt_utterances.csv"))
    parser.add_argument("--correlation-csv", default=str(ROOT / "analysis" / "gemma4_downstream_mt_correlations.csv"))
    parser.add_argument("--languages", nargs="+", default=LANGUAGES)
    parser.add_argument(
        "--max-examples-per-language",
        type=int,
        default=100,
        help="Use 0 for all aligned examples. The default keeps the run deadline-friendly.",
    )
    parser.add_argument(
        "--sample-mode",
        choices=["random", "stratified_sfr", "first"],
        default="stratified_sfr",
        help="stratified_sfr includes low-, mixed-, and high-SFR baseline examples when available.",
    )
    parser.add_argument("--batch-size", type=int, default=16)
    parser.add_argument("--max-input-tokens", type=int, default=256)
    parser.add_argument("--max-new-tokens", type=int, default=128)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--force", action="store_true", help="Recompute translation JSON files.")
    parser.add_argument("--summarize-only", action="store_true", help="Reuse saved translation JSON files.")
    parser.add_argument("--validate-only", action="store_true", help="Check alignment and exit before loading MT.")
    parser.add_argument("--device", choices=["auto", "cpu", "cuda", "mps"], default="auto")
    return parser.parse_args()


def clean_model_name(model_id: str) -> str:
    return (
        model_id.replace("/", "_")
        .replace("-", "_")
        .replace(".", "_")
        .replace(" ", "_")
    )


def prediction_path(preds_dir: Path, language: str, variant: str) -> Path:
    if variant == "baseline":
        return preds_dir / f"gemma4_{language}_predictions.json"
    if variant == "script_hint":
        return preds_dir / f"gemma4_script_hint_{language}_predictions.json"
    raise ValueError(f"Prediction variant has no file: {variant}")


def read_prediction_file(path: Path) -> tuple[list[str], list[str]]:
    if not path.exists():
        raise FileNotFoundError(path)
    with open(path, encoding="utf-8") as handle:
        data = json.load(handle)
    refs = data.get("references", [])
    preds = data.get("predictions", [])
    if not refs or not preds:
        raise ValueError(f"Prediction file lacks references or predictions: {path}")
    return refs, preds


def download_fleurs_tsv(fleurs_code: str) -> Path:
    try:
        return Path(
            hf_hub_download(
                repo_id="google/fleurs",
                filename=f"data/{fleurs_code}/test.tsv",
                repo_type="dataset",
            )
        )
    except Exception as exc:
        raise SystemExit(
            "Could not load FLEURS test metadata. The downstream MT script only "
            "needs data/{lang}/test.tsv files, but Hugging Face access is required "
            "unless those files are already cached. Check network access or pre-cache "
            "the FLEURS metadata files."
        ) from exc


def read_fleurs_tsv(path: Path) -> list[dict]:
    records = []
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            parts = line.rstrip("\n").split("\t")
            if len(parts) < 4:
                continue
            records.append(
                {
                    "id": str(parts[0]),
                    "file_name": parts[1],
                    "raw_transcription": parts[2],
                    "text": parts[3],
                }
            )
    return records


def load_fleurs_text_records(language: str) -> list[dict]:
    code = SCRIPT_CONFIGS[language].fleurs_code
    return read_fleurs_tsv(download_fleurs_tsv(code))


def load_english_reference_by_id() -> dict[str, str]:
    return {record["id"]: record["text"] for record in read_fleurs_tsv(download_fleurs_tsv("en_us"))}


def align_records_to_prediction_refs(language: str, records: list[dict], refs: list[str]) -> list[dict]:
    by_text: dict[str, deque[dict]] = defaultdict(deque)
    for record in records:
        by_text[record["text"]].append(record)

    aligned = []
    missing = []
    for idx, ref in enumerate(refs):
        bucket = by_text.get(ref)
        if not bucket:
            missing.append((idx, ref))
            continue
        aligned.append(bucket.popleft())

    if missing:
        preview = "; ".join(f"{idx}: {text[:80]}" for idx, text in missing[:3])
        raise ValueError(
            f"{language}: could not align {len(missing)} prediction references "
            f"to FLEURS test.tsv transcriptions. First misses: {preview}"
        )
    return aligned


def make_aligned_examples(
    language: str,
    english_by_id: dict[str, str],
    baseline_preds_dir: Path,
    script_hint_preds_dir: Path,
) -> list[dict]:
    src_records = load_fleurs_text_records(language)
    gold_refs, baseline_preds = read_prediction_file(
        prediction_path(baseline_preds_dir, language, "baseline")
    )
    _, hint_preds = read_prediction_file(
        prediction_path(script_hint_preds_dir, language, "script_hint")
    )

    if len(hint_preds) != len(gold_refs):
        raise ValueError(
            f"{language}: script-hint predictions ({len(hint_preds)}) do not match "
            f"baseline references ({len(gold_refs)})."
        )
    aligned_records = align_records_to_prediction_refs(language, src_records, gold_refs)

    examples = []
    missing_english = 0
    for idx, record in enumerate(aligned_records):
        english_ref = english_by_id.get(record["id"])
        if english_ref is None:
            missing_english += 1
            continue
        examples.append(
            {
                "language": language,
                "example_id": record["id"],
                "source_ref": gold_refs[idx],
                "english_ref": english_ref,
                "baseline_pred": baseline_preds[idx],
                "script_hint_pred": hint_preds[idx],
                "baseline_sfr_utt": compute_sfr(baseline_preds[idx], language),
                "script_hint_sfr_utt": compute_sfr(hint_preds[idx], language),
            }
        )

    if missing_english:
        log.warning("%s: skipped %d examples without English FLEURS reference IDs", language, missing_english)
    if not examples:
        raise ValueError(f"{language}: no examples aligned to English FLEURS by ID")
    return examples


def select_examples(
    examples: list[dict],
    max_examples: int,
    mode: str,
    seed: int,
) -> list[dict]:
    if max_examples <= 0 or len(examples) <= max_examples:
        return examples

    if mode == "first":
        return examples[:max_examples]

    rng = random.Random(seed)
    if mode == "random":
        return [examples[i] for i in sorted(rng.sample(range(len(examples)), max_examples))]

    bins = {"low": [], "mixed": [], "high": []}
    for idx, ex in enumerate(examples):
        score = ex["baseline_sfr_utt"]
        if score is None:
            bins["mixed"].append(idx)
        elif score < 0.10:
            bins["low"].append(idx)
        elif score < 0.90:
            bins["mixed"].append(idx)
        else:
            bins["high"].append(idx)

    selected: set[int] = set()
    target_per_bin = max(1, max_examples // 3)
    for name in ["low", "mixed", "high"]:
        candidates = bins[name][:]
        rng.shuffle(candidates)
        selected.update(candidates[:target_per_bin])

    remaining = [idx for idx in range(len(examples)) if idx not in selected]
    rng.shuffle(remaining)
    for idx in remaining:
        if len(selected) >= max_examples:
            break
        selected.add(idx)

    return [examples[i] for i in sorted(selected)]


def choose_device(requested: str) -> str:
    if requested != "auto":
        return requested
    if torch.cuda.is_available():
        return "cuda"
    if torch.backends.mps.is_available():
        return "mps"
    return "cpu"


def load_mt_model(model_id: str, device: str):
    log.info("Loading MT model: %s", model_id)
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    kwargs = {}
    if device == "cuda":
        kwargs["torch_dtype"] = torch.float16
    model = AutoModelForSeq2SeqLM.from_pretrained(model_id, **kwargs)
    model = model.to(device).eval()
    return tokenizer, model


def translation_json_path(translations_dir: Path, model_id: str, language: str, variant: str) -> Path:
    return translations_dir / f"{clean_model_name(model_id)}_{language}_{variant}_translations.json"


def load_saved_translations(path: Path, expected_n: int) -> list[str] | None:
    if not path.exists():
        return None
    with open(path, encoding="utf-8") as handle:
        data = json.load(handle)
    translations = data.get("translations", [])
    if len(translations) != expected_n:
        log.warning("Ignoring %s because it has %d rows, expected %d", path, len(translations), expected_n)
        return None
    return translations


def save_translations(path: Path, payload: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as handle:
        json.dump(payload, handle, ensure_ascii=False)


def translate_texts(
    texts: list[str],
    tokenizer,
    model,
    source_lang: str,
    target_lang: str,
    device: str,
    batch_size: int,
    max_input_tokens: int,
    max_new_tokens: int,
    desc: str,
) -> list[str]:
    tokenizer.src_lang = source_lang
    forced_bos = tokenizer.convert_tokens_to_ids(target_lang)
    if forced_bos is None or forced_bos == tokenizer.unk_token_id:
        raise ValueError(f"Tokenizer does not know target language token: {target_lang}")

    outputs = [""] * len(texts)
    active = [(idx, text.strip()) for idx, text in enumerate(texts) if str(text).strip()]
    for start in tqdm(range(0, len(active), batch_size), desc=desc, leave=False):
        batch = active[start:start + batch_size]
        batch_indices = [idx for idx, _ in batch]
        batch_texts = [text for _, text in batch]
        inputs = tokenizer(
            batch_texts,
            return_tensors="pt",
            padding=True,
            truncation=True,
            max_length=max_input_tokens,
        ).to(device)
        with torch.no_grad():
            generated = model.generate(
                **inputs,
                forced_bos_token_id=forced_bos,
                max_new_tokens=max_new_tokens,
                num_beams=1,
            )
        decoded = tokenizer.batch_decode(generated, skip_special_tokens=True)
        for idx, text in zip(batch_indices, decoded):
            outputs[idx] = text.strip()
    return outputs


def get_or_run_translations(
    examples: list[dict],
    variant: str,
    language: str,
    args: argparse.Namespace,
    translations_dir: Path,
    tokenizer,
    model,
    device: str,
) -> list[str]:
    path = translation_json_path(translations_dir, args.mt_model, language, variant)
    if not args.force:
        saved = load_saved_translations(path, len(examples))
        if saved is not None:
            log.info("Reusing %s", path)
            return saved
    if args.summarize_only:
        raise FileNotFoundError(f"Missing saved translations for summarize-only mode: {path}")

    if variant == "gold":
        texts = [ex["source_ref"] for ex in examples]
    elif variant == "baseline":
        texts = [ex["baseline_pred"] for ex in examples]
    elif variant == "script_hint":
        texts = [ex["script_hint_pred"] for ex in examples]
    else:
        raise ValueError(variant)

    translations = translate_texts(
        texts=texts,
        tokenizer=tokenizer,
        model=model,
        source_lang=NLLB_LANG_CODES[language],
        target_lang=TARGET_LANG,
        device=device,
        batch_size=args.batch_size,
        max_input_tokens=args.max_input_tokens,
        max_new_tokens=args.max_new_tokens,
        desc=f"MT/{language}/{variant}",
    )
    save_translations(
        path,
        {
            "mt_model": args.mt_model,
            "source_language": language,
            "source_lang_code": NLLB_LANG_CODES[language],
            "target_lang_code": TARGET_LANG,
            "variant": variant,
            "variant_label": VARIANTS[variant],
            "translations": translations,
        },
    )
    return translations


def corpus_scores(hypotheses: list[str], references: list[str]) -> dict[str, float]:
    scorer = require_sacrebleu()
    return {
        "chrf": round(scorer.corpus_chrf(hypotheses, [references]).score, 2),
        "bleu": round(scorer.corpus_bleu(hypotheses, [references]).score, 2),
    }


def sentence_chrf(hypothesis: str, reference: str) -> float:
    scorer = require_sacrebleu()
    return round(scorer.sentence_chrf(hypothesis, [reference]).score, 2)


def read_mitigation_summary(path: Path) -> pd.DataFrame:
    if not path.exists():
        raise FileNotFoundError(f"Missing mitigation summary: {path}")
    df = pd.read_csv(path)
    required = {
        "language",
        "baseline_sfr_mean",
        "script_hint_sfr_mean",
        "delta_sfr",
        "baseline_wer_pct",
        "script_hint_wer_pct",
        "delta_wer",
    }
    missing = required - set(df.columns)
    if missing:
        raise ValueError(f"Mitigation summary lacks columns: {sorted(missing)}")
    return df.set_index("language")


def make_language_rows(
    language: str,
    examples: list[dict],
    translations: dict[str, list[str]],
    stats: pd.DataFrame,
    args: argparse.Namespace,
) -> tuple[dict, list[dict]]:
    english_refs = [ex["english_ref"] for ex in examples]
    scores = {
        variant: corpus_scores(translations[variant], english_refs)
        for variant in VARIANTS
    }
    stat = stats.loc[language]
    summary = {
        "language": language,
        "n_aligned": len(examples),
        "sample_mode": args.sample_mode,
        "max_examples_per_language": args.max_examples_per_language,
        "mt_model": args.mt_model,
        "src_lang_code": NLLB_LANG_CODES[language],
        "baseline_sfr_mean": stat["baseline_sfr_mean"],
        "script_hint_sfr_mean": stat["script_hint_sfr_mean"],
        "delta_sfr": stat["delta_sfr"],
        "baseline_wer_pct": stat["baseline_wer_pct"],
        "script_hint_wer_pct": stat["script_hint_wer_pct"],
        "delta_wer": stat["delta_wer"],
        "gold_chrf": scores["gold"]["chrf"],
        "baseline_chrf": scores["baseline"]["chrf"],
        "script_hint_chrf": scores["script_hint"]["chrf"],
        "baseline_chrf_drop": round(scores["gold"]["chrf"] - scores["baseline"]["chrf"], 2),
        "script_hint_chrf_drop": round(scores["gold"]["chrf"] - scores["script_hint"]["chrf"], 2),
        "chrf_recovery": round(scores["script_hint"]["chrf"] - scores["baseline"]["chrf"], 2),
        "gold_bleu": scores["gold"]["bleu"],
        "baseline_bleu": scores["baseline"]["bleu"],
        "script_hint_bleu": scores["script_hint"]["bleu"],
        "baseline_bleu_drop": round(scores["gold"]["bleu"] - scores["baseline"]["bleu"], 2),
        "script_hint_bleu_drop": round(scores["gold"]["bleu"] - scores["script_hint"]["bleu"], 2),
        "bleu_recovery": round(scores["script_hint"]["bleu"] - scores["baseline"]["bleu"], 2),
    }

    utterance_rows = []
    for idx, ex in enumerate(examples):
        gold_chrf = sentence_chrf(translations["gold"][idx], ex["english_ref"])
        baseline_chrf = sentence_chrf(translations["baseline"][idx], ex["english_ref"])
        hint_chrf = sentence_chrf(translations["script_hint"][idx], ex["english_ref"])
        utterance_rows.append(
            {
                "language": language,
                "example_id": ex["example_id"],
                "baseline_sfr_utt": None if ex["baseline_sfr_utt"] is None else round(ex["baseline_sfr_utt"] * 100, 2),
                "script_hint_sfr_utt": None if ex["script_hint_sfr_utt"] is None else round(ex["script_hint_sfr_utt"] * 100, 2),
                "gold_chrf_sent": gold_chrf,
                "baseline_chrf_sent": baseline_chrf,
                "script_hint_chrf_sent": hint_chrf,
                "baseline_chrf_drop_sent": round(gold_chrf - baseline_chrf, 2),
                "script_hint_chrf_drop_sent": round(gold_chrf - hint_chrf, 2),
                "chrf_recovery_sent": round(hint_chrf - baseline_chrf, 2),
                "english_ref": ex["english_ref"],
                "source_ref": ex["source_ref"],
                "baseline_pred": ex["baseline_pred"],
                "script_hint_pred": ex["script_hint_pred"],
                "gold_mt": translations["gold"][idx],
                "baseline_mt": translations["baseline"][idx],
                "script_hint_mt": translations["script_hint"][idx],
            }
        )
    return summary, utterance_rows


def spearman(xs: pd.Series, ys: pd.Series) -> float | None:
    paired = pd.DataFrame({"x": xs, "y": ys}).dropna()
    if len(paired) < 3:
        return None
    value = paired["x"].rank(method="average").corr(paired["y"].rank(method="average"))
    return None if pd.isna(value) else round(float(value), 3)


def write_correlations(summary_df: pd.DataFrame, path: Path) -> None:
    rows = [
        {
            "x": "baseline_sfr_mean",
            "y": "baseline_chrf_drop",
            "spearman_r": spearman(summary_df["baseline_sfr_mean"], summary_df["baseline_chrf_drop"]),
            "n": len(summary_df),
            "expected_direction": "negative",
        },
        {
            "x": "baseline_wer_pct",
            "y": "baseline_chrf_drop",
            "spearman_r": spearman(summary_df["baseline_wer_pct"], summary_df["baseline_chrf_drop"]),
            "n": len(summary_df),
            "expected_direction": "positive",
        },
        {
            "x": "delta_sfr",
            "y": "chrf_recovery",
            "spearman_r": spearman(summary_df["delta_sfr"], summary_df["chrf_recovery"]),
            "n": len(summary_df),
            "expected_direction": "positive",
        },
        {
            "x": "delta_wer",
            "y": "chrf_recovery",
            "spearman_r": spearman(summary_df["delta_wer"], summary_df["chrf_recovery"]),
            "n": len(summary_df),
            "expected_direction": "negative",
        },
    ]
    path.parent.mkdir(parents=True, exist_ok=True)
    pd.DataFrame(rows).to_csv(path, index=False)


def main() -> None:
    args = parse_args()
    baseline_preds_dir = Path(args.baseline_predictions_dir)
    script_hint_preds_dir = Path(args.script_hint_predictions_dir)
    results_dir = Path(args.results_dir)
    translations_dir = results_dir / "translations"
    results_dir.mkdir(parents=True, exist_ok=True)
    translations_dir.mkdir(parents=True, exist_ok=True)

    fh = logging.FileHandler(results_dir / "eval_downstream_mt.log")
    fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
    log.addHandler(fh)

    stats = read_mitigation_summary(Path(args.mitigation_summary))
    missing_stats = [lang for lang in args.languages if lang not in stats.index]
    if missing_stats:
        raise SystemExit(f"Mitigation summary lacks languages: {', '.join(missing_stats)}")

    english_by_id = load_english_reference_by_id()
    device = choose_device(args.device)
    log.info("Device: %s", device)

    tokenizer = model = None
    if not args.summarize_only and not args.validate_only:
        tokenizer, model = load_mt_model(args.mt_model, device)

    summary_rows = []
    utterance_rows = []
    validation_rows = []
    for lang in args.languages:
        if lang not in NLLB_LANG_CODES:
            raise ValueError(f"No NLLB language code configured for {lang}")
        examples = make_aligned_examples(lang, english_by_id, baseline_preds_dir, script_hint_preds_dir)
        total_aligned = len(examples)
        examples = select_examples(
            examples,
            max_examples=args.max_examples_per_language,
            mode=args.sample_mode,
            seed=args.seed,
        )
        log.info("%s: %d aligned examples selected", lang, len(examples))
        validation_rows.append(
            {
                "language": lang,
                "total_aligned": total_aligned,
                "selected": len(examples),
                "sample_mode": args.sample_mode,
                "max_examples_per_language": args.max_examples_per_language,
                "src_lang_code": NLLB_LANG_CODES[lang],
            }
        )

        if args.validate_only:
            continue

        translations = {}
        for variant in VARIANTS:
            translations[variant] = get_or_run_translations(
                examples,
                variant,
                lang,
                args,
                translations_dir,
                tokenizer,
                model,
                device,
            )
        summary, rows = make_language_rows(lang, examples, translations, stats, args)
        summary_rows.append(summary)
        utterance_rows.extend(rows)

    if args.validate_only:
        alignment_csv = results_dir / "alignment_check.csv"
        pd.DataFrame(validation_rows).to_csv(alignment_csv, index=False)
        log.info("Wrote %s", alignment_csv)
        return

    summary_df = pd.DataFrame(summary_rows)
    utterance_df = pd.DataFrame(utterance_rows)
    Path(args.summary_csv).parent.mkdir(parents=True, exist_ok=True)
    summary_df.to_csv(args.summary_csv, index=False)
    utterance_df.to_csv(args.utterance_csv, index=False)
    write_correlations(summary_df, Path(args.correlation_csv))
    log.info("Wrote %s", args.summary_csv)
    log.info("Wrote %s", args.utterance_csv)
    log.info("Wrote %s", args.correlation_csv)


if __name__ == "__main__":
    main()