File size: 33,449 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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
#!/usr/bin/env python3
"""
Multilingual Script-Fidelity Evaluation.

Evaluates ASR models on FLEURS test splits for ten languages and computes:
  - WER, CER (standard metrics)
  - Script Fidelity (SF): fraction of hypothesis characters in the target script
  - Dominant script label per utterance

Output: analysis/sf_results.csv  (one row per model × language)
        analysis/sf_utterances/   (per-utterance JSONs for qualitative analysis)

All ten FLEURS test splits, including Pashto (ps_af), are loaded via
Hugging Face datasets.

Usage
-----
  uv run python scripts/eval_multilang.py \\
      --hf-token hf_xxx \\
      --results-dir /workspace/results_multilang \\
      --hub-repo ANONYMIZED_OUTPUT_REPO \\
      --languages pashto hindi bengali malayalam somali georgian urdu arabic persian tamil \\
      --whisper-sizes tiny base small medium large-v2 large-v3 turbo \\
      --run-mms --run-seamless

Environment variables (fallbacks):
  HF_TOKEN, RESULTS_DIR, HUB_REPO
"""

import argparse, os, sys, json, re, time, unicodedata, logging
from pathlib import Path

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 numpy as np
import pandas as pd
import torch
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
from datasets import load_dataset, Audio
from evaluate import load as load_metric
from huggingface_hub import login, HfApi

# Script fidelity module (co-located in this scripts/ directory)
from script_fidelity import (
    compute_sfr, compute_sfr_batch, dominant_script, SCRIPT_CONFIGS
)

# ── LOGGING ───────────────────────────────────────────────────────────────────
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s',
    handlers=[logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger(__name__)


# ── ARGUMENT PARSING ──────────────────────────────────────────────────────────
def parse_args():
    p = argparse.ArgumentParser(description='Multilingual script-fidelity ASR benchmark')
    p.add_argument('--hf-token',    default=os.environ.get('HF_TOKEN', ''))
    p.add_argument('--results-dir', default=os.environ.get('RESULTS_DIR', './results_multilang'))
    p.add_argument('--hub-repo',    default=os.environ.get('HUB_REPO', ''))
    p.add_argument('--hub-private', action='store_true')
    p.add_argument('--languages',   nargs='+',
                   default=['pashto', 'hindi', 'bengali', 'malayalam', 'somali',
                            'georgian', 'urdu', 'arabic', 'persian', 'tamil'],
                   help='Languages to evaluate')
    p.add_argument('--whisper-sizes', nargs='*',
                   default=['tiny', 'base', 'small', 'medium', 'large-v2', 'large-v3', 'turbo'])
    p.add_argument('--run-mms',       action='store_true')
    p.add_argument('--run-seamless',  action='store_true')
    p.add_argument('--run-gemma4',    action='store_true',
                   help='Evaluate Gemma 4 E2B (requires transformers>=5.0, '
                        'soundfile; runs on MPS on Apple Silicon)')
    p.add_argument('--sample-size',   type=int, default=None,
                   help='Utterances per dataset per language (None = full set)')
    p.add_argument('--batch-size',    type=int, default=16)
    p.add_argument('--force',         action='store_true',
                   help='Rerun selected model-language pairs even if present')
    return p.parse_args()


# ── HF HUB ────────────────────────────────────────────────────────────────────
def push_to_hub(results_dir: Path, hub_repo: str, api: HfApi, private: bool = False):
    if not hub_repo:
        return
    try:
        api.create_repo(hub_repo, repo_type='dataset', private=private, exist_ok=True)
        api.upload_folder(
            folder_path=str(results_dir),
            repo_id=hub_repo,
            repo_type='dataset',
            commit_message='Update script-fidelity results',
            ignore_patterns=['*.pyc', '__pycache__'],
        )
        log.info(f'Pushed results to: {hub_repo}')
    except Exception as e:
        log.warning(f'Hub push failed: {e}')


# ── NORMALIZATION ─────────────────────────────────────────────────────────────
# Per-language normalization: strip diacritics, punctuation, numerals.
# We normalise ONLY for WER/CER computation; the raw hypothesis is used for SF.

_DIACRITIC_RE   = re.compile(r'[\u064B-\u065F\u0670]')   # Arabic diacritics
_PUNCT_ARABIC   = re.compile(r'[،؟؛!.«»()\[\]{}\u060C\u061B\u061F\u066D\u06D4\u200C\u200D]')
_DIGITS_ALL     = re.compile(r'[0-9٠-٩]')
_TATWEEL        = '\u0640'

def normalize_arabic_script(text: str) -> str:
    if not isinstance(text, str): return ''
    text = unicodedata.normalize('NFC', text)
    text = text.replace(_TATWEEL, '')
    text = _DIACRITIC_RE.sub('', text)
    text = _PUNCT_ARABIC.sub('', text)
    text = _DIGITS_ALL.sub('', text)
    return ' '.join(text.split())

def normalize_latin(text: str) -> str:
    if not isinstance(text, str): return ''
    text = unicodedata.normalize('NFC', text).lower()
    text = re.sub(r"[^\w\s'-]", '', text)
    text = _DIGITS_ALL.sub('', text)
    return ' '.join(text.split())

def normalize_indic(text: str) -> str:
    if not isinstance(text, str): return ''
    text = unicodedata.normalize('NFC', text)
    text = re.sub(r'[।॥!?,.:;()\[\]{}"\']', '', text)
    text = _DIGITS_ALL.sub('', text)
    return ' '.join(text.split())

def normalize_georgian(text: str) -> str:
    # Lowercase converts rare Asomtavruli capitals to standard Mkhedruli.
    # \w is Unicode-aware in Python re, so Georgian letters are preserved.
    if not isinstance(text, str): return ''
    text = unicodedata.normalize('NFC', text).lower()
    text = re.sub(r"[^\w\s'-]", '', text)
    text = _DIGITS_ALL.sub('', text)
    return ' '.join(text.split())

NORMALIZERS = {
    'pashto':    normalize_arabic_script,
    'urdu':      normalize_arabic_script,
    'hindi':     normalize_indic,
    'bengali':   normalize_indic,
    'malayalam': normalize_indic,
    'somali':    normalize_latin,
    'arabic':    normalize_arabic_script,
    'persian':   normalize_arabic_script,
    'tamil':     normalize_indic,
    'georgian':  normalize_georgian,
}


# ── DATASET LOADING ───────────────────────────────────────────────────────────
def load_fleurs(language: str, sample_size: int | None) -> dict:
    cfg  = SCRIPT_CONFIGS[language]
    code = cfg.fleurs_code
    log.info(f'Loading FLEURS {code} test...')
    ds = load_dataset('google/fleurs', code, split='test', trust_remote_code=True)
    ds = ds.cast_column('audio', Audio(sampling_rate=16_000))
    refs   = [ex['transcription'] for ex in ds]
    audios = [ex['audio']['array'] for ex in ds]
    if sample_size:
        import random; random.seed(42)
        idx    = sorted(random.sample(range(len(refs)), min(sample_size, len(refs))))
        refs   = [refs[i]   for i in idx]
        audios = [audios[i] for i in idx]
    log.info(f'  FLEURS {code}: {len(refs)} utterances')
    return {'refs': refs, 'audios': audios, 'language': language, 'fleurs_code': code}


# ── RESULT STORE ──────────────────────────────────────────────────────────────
class ResultStore:
    def __init__(self, csv_path: Path, force: bool = False):
        self.csv_path = csv_path
        self.force = force
        if csv_path.exists():
            self.df = pd.read_csv(csv_path)
            completed_df = self.df
            if 'source' in completed_df.columns:
                source = completed_df['source'].fillna('')
                completed_df = completed_df[source != 'paper_a_' + 'import']
            self.completed = set(zip(completed_df['model'], completed_df['language']))
            log.info(f'Resuming — {len(self.completed)} model×language combos done')
        else:
            self.df       = pd.DataFrame()
            self.completed = set()

    def is_done(self, model_id: str, language: str) -> bool:
        if self.force:
            return False
        return (model_id, language) in self.completed

    def add(self, row: dict):
        if not self.df.empty and {'model', 'language'}.issubset(self.df.columns):
            same = (
                (self.df['model'] == row['model'])
                & (self.df['language'] == row['language'])
            )
            self.df = self.df.loc[~same].copy()
        self.df = pd.concat([self.df, pd.DataFrame([row])], ignore_index=True)
        self.df.to_csv(self.csv_path, index=False)
        self.completed.add((row['model'], row['language']))
        log.info(
            f"  Saved: {row['model']:45s} / {row['language']:12s} "
            f"WER={row.get('wer_pct')}%  SFR={row.get('sfr_mean')}%"
        )


# ── COMPUTE METRICS ───────────────────────────────────────────────────────────
def compute_metrics(
    refs: list[str],
    preds: list[str],
    language: str,
    wer_metric,
    cer_metric,
) -> dict:
    norm_fn   = NORMALIZERS[language]
    refs_norm = [norm_fn(r) for r in refs]
    pred_norm = [norm_fn(p) for p in preds]

    # WER/CER — skip empty references
    pairs = [(r, p) for r, p in zip(refs_norm, pred_norm) if r.strip()]
    wer_val = cer_val = None
    if pairs:
        refs_f, preds_f = zip(*pairs)
        wer_val = round(wer_metric.compute(
            references=list(refs_f), predictions=list(preds_f)) * 100, 2)
        cer_val = round(cer_metric.compute(
            references=list(refs_f), predictions=list(preds_f)) * 100, 2)

    # Script Fidelity — computed on RAW hypothesis (before normalisation)
    sfr_scores, dom_scripts = compute_sfr_batch(preds, language)
    sfr_valid  = [s for s in sfr_scores if s is not None]
    sfr_empty  = sum(1 for s in sfr_scores if s is None)
    sfr_mean   = round(np.mean(sfr_valid) * 100, 2) if sfr_valid else None
    sfr_full   = sum(1 for s in sfr_valid if s == 1.0)   # utterances with SFR=100%
    sfr_zero   = sum(1 for s in sfr_valid if s == 0.0)   # script collapse utterances

    dom_counts = pd.Series(dom_scripts).value_counts().to_dict()

    return {
        'n':             len(refs),
        'n_pairs':       len(pairs),
        'wer_pct':       wer_val,
        'cer_pct':       cer_val,
        'sfr_mean':      sfr_mean,
        'sfr_full_pct':  round(sfr_full / max(len(sfr_valid), 1) * 100, 1),
        'sfr_zero_pct':  round(sfr_zero / max(len(sfr_valid), 1) * 100, 1),
        'sfr_empty_n':   sfr_empty,
        **{f'dom_{k}': v for k, v in dom_counts.items()},
    }, sfr_scores, dom_scripts


# ── WHISPER EVALUATION ────────────────────────────────────────────────────────
_WHISPER_MODEL_IDS = {
    'turbo': 'openai/whisper-large-v3-turbo',
}

# Whisper language token names (from Whisper tokenizer vocabulary)
# These are the forced-language token strings, not BCP-47 codes.
WHISPER_LANG_TOKENS = {
    'pashto':    'pashto',
    'urdu':      'urdu',
    'hindi':     'hindi',
    'bengali':   'bengali',
    'malayalam': 'malayalam',
    'somali':    'somali',
    'arabic':    'arabic',
    'persian':   'persian',
    'tamil':     'tamil',
    'georgian':  'georgian',
}


def eval_whisper_language(
    size: str,
    language: str,
    dataset: dict,
    store: ResultStore,
    preds_dir: Path,
    batch_size: int,
    wer_metric,
    cer_metric,
    device: str,
) -> None:
    from transformers import pipeline as hf_pipeline

    model_id   = _WHISPER_MODEL_IDS.get(size, f'openai/whisper-{size}')
    lang_token = WHISPER_LANG_TOKENS[language]

    if store.is_done(model_id, language):
        log.info(f'  Skipping {model_id}/{language} (done)'); return

    log.info(f'  Loading {model_id} for {language}...')
    pipe = hf_pipeline(
        'automatic-speech-recognition',
        model=model_id,
        device=0 if device == 'cuda' else -1,
        torch_dtype=torch.float16 if device == 'cuda' else torch.float32,
    )

    refs, audios = dataset['refs'], dataset['audios']
    log.info(f'  {model_id} on FLEURS {language} ({len(audios)} utterances)...')
    t0   = time.time()
    preds = []
    for i in tqdm(range(0, len(audios), batch_size), desc=f'W-{size}/{language}', leave=False):
        batch = audios[i:i+batch_size]
        outs  = pipe(batch, batch_size=batch_size, chunk_length_s=30,
                     generate_kwargs={'language': lang_token, 'task': 'transcribe'})
        preds.extend([o['text'] for o in outs])
    elapsed = time.time() - t0

    # Persist predictions
    pred_file = preds_dir / f'whisper_{size}_{language}_predictions.json'
    with open(pred_file, 'w', encoding='utf-8') as f:
        json.dump({'model': model_id, 'language': language,
                   'references': refs, 'predictions': preds},
                  f, ensure_ascii=False)

    metrics, sfr_scores, dom = compute_metrics(refs, preds, language, wer_metric, cer_metric)
    total_s = sum(len(a) / 16_000 for a in audios)
    store.add({
        'model':    model_id,
        'family':   'Whisper',
        'size':     size,
        'language': language,
        'rtf':      round(elapsed / total_s, 4),
        **metrics,
    })

    del pipe
    if device == 'cuda': torch.cuda.empty_cache()


# ── MMS EVALUATION ────────────────────────────────────────────────────────────
def eval_mms_language(
    language: str,
    dataset: dict,
    store: ResultStore,
    preds_dir: Path,
    batch_size: int,
    wer_metric,
    cer_metric,
    device: str,
) -> None:
    from transformers import Wav2Vec2ForCTC, AutoProcessor

    model_id = 'facebook/mms-1b-all'
    if store.is_done(model_id, language):
        log.info(f'  Skipping MMS/{language} (done)'); return

    cfg        = SCRIPT_CONFIGS[language]
    lang_codes = cfg.mms_lang

    log.info(f'  Loading {model_id} for {language}...')
    proc  = AutoProcessor.from_pretrained(model_id)
    model = Wav2Vec2ForCTC.from_pretrained(model_id, torch_dtype=torch.float16)
    model = model.to(device).eval()

    mms_lang = None
    for code in lang_codes:
        try:
            proc.tokenizer.set_target_lang(code)
            model.load_adapter(code)
            mms_lang = code
            log.info(f'  MMS adapter: {code}')
            break
        except Exception as e:
            log.warning(f'  MMS lang={code} failed: {e}')

    if mms_lang is None:
        log.error(f'  No MMS adapter for {language} — skipping')
        del model, proc
        if device == 'cuda': torch.cuda.empty_cache()
        return

    refs, audios = dataset['refs'], dataset['audios']
    log.info(f'  MMS on FLEURS {language} ({len(audios)} utterances)...')
    t0    = time.time()
    preds = []
    for i in tqdm(range(0, len(audios), batch_size), desc=f'MMS/{language}', leave=False):
        batch  = audios[i:i+batch_size]
        inputs = proc(batch, sampling_rate=16_000, return_tensors='pt', padding=True)
        inputs = {k: (v.to(device, dtype=torch.float16) if v.is_floating_point() else v.to(device))
                  for k, v in inputs.items()}
        with torch.no_grad():
            logits = model(**inputs).logits
        pred_ids = torch.argmax(logits, dim=-1)
        preds.extend(proc.batch_decode(pred_ids))
    elapsed = time.time() - t0

    pred_file = preds_dir / f'mms_1b_{language}_predictions.json'
    with open(pred_file, 'w', encoding='utf-8') as f:
        json.dump({'model': model_id, 'language': language,
                   'references': refs, 'predictions': preds},
                  f, ensure_ascii=False)

    metrics, _, _ = compute_metrics(refs, preds, language, wer_metric, cer_metric)
    total_s = sum(len(a) / 16_000 for a in audios)
    store.add({
        'model':    model_id,
        'family':   'MMS',
        'size':     '1B',
        'language': language,
        'rtf':      round(elapsed / total_s, 4),
        **metrics,
    })

    del model, proc
    if device == 'cuda': torch.cuda.empty_cache()


# ── SEAMLESSM4T EVALUATION ────────────────────────────────────────────────────
# SeamlessM4T language codes for target languages (tgt_lang parameter)
SEAMLESS_LANG_CODES = {
    'pashto':    'pbt',    # Southern Pashto (FLORES-200)
    'urdu':      'urd',
    'hindi':     'hin',
    'bengali':   'ben',
    'malayalam': 'mal',
    'somali':    'som',
    'arabic':    'arb',    # Modern Standard Arabic
    'persian':   'pes',    # Western Persian
    'tamil':     'tam',
    'georgian':  'kat',
}


def eval_seamless_language(
    language: str,
    dataset: dict,
    store: ResultStore,
    preds_dir: Path,
    batch_size: int,
    wer_metric,
    cer_metric,
    device: str,
) -> None:
    from transformers import AutoProcessor, SeamlessM4Tv2ForSpeechToText

    model_id  = 'facebook/seamless-m4t-v2-large'
    tgt_lang  = SEAMLESS_LANG_CODES.get(language)
    if tgt_lang is None:
        log.warning(f'  SeamlessM4T: no lang code for {language} — skipping')
        return

    if store.is_done(model_id, language):
        log.info(f'  Skipping SeamlessM4T/{language} (done)'); return

    log.info(f'  Loading {model_id} (~10 GB VRAM) for {language}...')
    try:
        proc = AutoProcessor.from_pretrained(model_id, use_fast=False)
    except Exception as e:
        log.warning(f'  Processor load failed ({e}); retrying with force_download...')
        proc = AutoProcessor.from_pretrained(model_id, force_download=True)

    try:
        model = SeamlessM4Tv2ForSpeechToText.from_pretrained(
            model_id, torch_dtype=torch.float16)
    except Exception as e:
        log.warning(f'  Model load failed ({e}); retrying with force_download=True...')
        model = SeamlessM4Tv2ForSpeechToText.from_pretrained(
            model_id, torch_dtype=torch.float16, force_download=True)

    model = model.to(device).eval()

    refs, audios = dataset['refs'], dataset['audios']
    s4t_batch    = max(1, batch_size // 4)
    log.info(f'  SeamlessM4T on FLEURS {language} ({len(audios)} utterances)...')
    t0    = time.time()
    preds = []
    for i in tqdm(range(0, len(audios), s4t_batch), desc=f'S4T/{language}', leave=False):
        batch  = audios[i:i+s4t_batch]
        inputs = proc(audios=batch, sampling_rate=16_000,
                      return_tensors='pt', padding=True)
        inputs = {k: (v.to(device, dtype=torch.float16) if v.is_floating_point() else v.to(device))
                  for k, v in inputs.items()}
        with torch.no_grad():
            out = model.generate(**inputs, tgt_lang=tgt_lang)
        sequences = out.sequences if hasattr(out, 'sequences') else out
        preds.extend(proc.batch_decode(sequences, skip_special_tokens=True))
    elapsed = time.time() - t0

    pred_file = preds_dir / f'seamless_m4t_v2_{language}_predictions.json'
    with open(pred_file, 'w', encoding='utf-8') as f:
        json.dump({'model': model_id, 'language': language,
                   'references': refs, 'predictions': preds},
                  f, ensure_ascii=False)

    metrics, _, _ = compute_metrics(refs, preds, language, wer_metric, cer_metric)
    total_s = sum(len(a) / 16_000 for a in audios)
    store.add({
        'model':    model_id,
        'family':   'SeamlessM4T',
        'size':     'v2-large',
        'language': language,
        'rtf':      round(elapsed / total_s, 4),
        **metrics,
    })

    del model, proc
    if device == 'cuda': torch.cuda.empty_cache()


# ── GEMMA 4 EVALUATION ───────────────────────────────────────────────────────
# Exact transcription prompt from the Gemma 4 model card.
_GEMMA4_PROMPT = (
    'Transcribe the following speech segment in its original language. '
    'Follow these specific instructions for formatting the answer:\n'
    '* Only output the transcription, with no newlines.\n'
    '* When transcribing numbers, write the digits, '
    'i.e. write 1.7 and not one point seven, and write 3 instead of three.'
)
# unsloth/gemma-4-E2B-it: Apache-2.0, no HF license gate, same weights as
# google/gemma-4-E2B-it but accessible without agreeing to Google's terms.
# E2B = Effective 2B; ~10 GB BF16, ~4 GB at 4-bit. Audio supported on E2B/E4B only.
_GEMMA4_MODEL_ID = 'unsloth/gemma-4-E2B-it'


def eval_gemma4_language(
    language: str,
    dataset: dict,
    store: ResultStore,
    preds_dir: Path,
    wer_metric,
    cer_metric,
    device: str,
) -> None:
    """Evaluate Gemma 4 E2B on one language.

    Audio arrays are written to per-utterance temp WAV files because
    processor.apply_chat_template only accepts file paths, not numpy arrays.
    Runs at batch_size=1; Gemma 4 is an autoregressive multimodal LLM.
    device_map='auto' handles placement; the device param is used for cleanup only.
    """
    import tempfile
    import soundfile as sf

    try:
        from transformers import AutoModelForMultimodalLM, AutoProcessor
    except ImportError:
        log.error('transformers>=5.0 required for AutoModelForMultimodalLM; skipping')
        return

    if store.is_done(_GEMMA4_MODEL_ID, language):
        log.info(f'  Skipping Gemma4/{language} (done)'); return

    # E2B at dtype='auto': ~10 GB BF16 on CUDA, ~10 GB float16 on MPS.
    # AutoModelForMultimodalLM is required — AutoModelForCausalLM does not
    # correctly initialise the audio encoder in Gemma 4's architecture.
    log.info(f'  Loading {_GEMMA4_MODEL_ID} (~10 GB)...')
    proc  = AutoProcessor.from_pretrained(_GEMMA4_MODEL_ID)
    model = AutoModelForMultimodalLM.from_pretrained(
        _GEMMA4_MODEL_ID,
        dtype='auto',
        device_map='auto',
    )
    model.eval()

    refs, audios = dataset['refs'], dataset['audios']
    log.info(f'  Gemma 4 on FLEURS {language} ({len(audios)} utterances)...')
    t0    = time.time()
    preds = []

    with tempfile.TemporaryDirectory() as tmpdir:
        for i, audio_array in enumerate(
                tqdm(audios, desc=f'Gemma4/{language}', leave=False)):
            wav_path = str(Path(tmpdir) / f'utt_{i}.wav')
            sf.write(wav_path, audio_array, 16_000)

            messages = [{
                'role': 'user',
                'content': [
                    {'type': 'audio', 'audio': wav_path},
                    {'type': 'text',  'text': _GEMMA4_PROMPT},
                ],
            }]
            try:
                inputs = proc.apply_chat_template(
                    messages,
                    tokenize=True,
                    return_dict=True,
                    return_tensors='pt',
                    add_generation_prompt=True,
                ).to(model.device)
                input_len = inputs['input_ids'].shape[-1]

                with torch.no_grad():
                    out = model.generate(
                        **inputs,
                        max_new_tokens=256,
                        do_sample=False,
                    )
                text = proc.decode(out[0][input_len:], skip_special_tokens=True)
                preds.append(text.strip())
            except Exception as exc:
                log.warning(f'  Gemma4 utterance {i} failed: {exc}')
                preds.append('')

    elapsed = time.time() - t0

    pred_file = preds_dir / f'gemma4_{language}_predictions.json'
    with open(pred_file, 'w', encoding='utf-8') as f:
        json.dump({'model': _GEMMA4_MODEL_ID, 'language': language,
                   'references': refs, 'predictions': preds},
                  f, ensure_ascii=False)

    metrics, _, _ = compute_metrics(refs, preds, language, wer_metric, cer_metric)
    total_s = sum(len(a) / 16_000 for a in audios)
    store.add({
        'model':    _GEMMA4_MODEL_ID,
        'family':   'Gemma4',
        'size':     'E2B',
        'language': language,
        'rtf':      round(elapsed / total_s, 4),
        **metrics,
    })

    del model, proc
    if device == 'cuda':
        torch.cuda.empty_cache()
    elif device == 'mps':
        torch.mps.empty_cache()


# ── FIGURES ───────────────────────────────────────────────────────────────────
_PAPER_FAMILIES = {'Whisper', 'MMS', 'SeamlessM4T', 'Gemma4'}


def _paper_rows(df: pd.DataFrame) -> pd.DataFrame:
    """Rows included in the main paper benchmark."""
    if 'family' not in df.columns:
        return df
    return df[df['family'].isin(_PAPER_FAMILIES)].copy()


def make_sf_heatmap(store: ResultStore, figures_dir: Path) -> None:
    """Model × language SF% heatmap — the paper's main figure."""
    df = _paper_rows(store.df)
    if df.empty or 'sfr_mean' not in df.columns:
        return

    pivot = df.pivot_table(
        index='model', columns='language', values='sfr_mean', aggfunc='first')
    if pivot.empty:
        return

    # Short model names for display
    short_names = (
        pivot.index
        .str.replace('openai/whisper-large-v3-turbo', 'Whisper turbo')
        .str.replace('openai/whisper-', 'Whisper ')
        .str.replace('facebook/mms-1b-all', 'MMS 1B')
        .str.replace('facebook/seamless-m4t-v2-large', 'SeamlessM4T v2')
        .str.replace('unsloth/gemma-4-E2B-it', 'Gemma 4 E2B')
        .str.replace('google/gemma-4-E2B-it',  'Gemma 4 E2B')
    )

    fig, ax = plt.subplots(figsize=(max(8, len(pivot.columns) * 1.5),
                                    max(5, len(pivot) * 0.5)))
    sns.heatmap(
        pivot.values,
        xticklabels=pivot.columns.tolist(),
        yticklabels=short_names.tolist(),
        annot=True, fmt='.1f',
        cmap='RdYlGn', vmin=0, vmax=100,
        linewidths=0.5, ax=ax,
        cbar_kws={'label': 'Script Fidelity (%)'},
    )
    ax.set_title('Script Fidelity (%) by Model and Language — FLEURS Test Sets')
    ax.set_xlabel('Language')
    ax.set_ylabel('Model')
    plt.tight_layout()
    out = figures_dir / 'sfr_heatmap.pdf'
    fig.savefig(out, bbox_inches='tight')
    plt.close(fig)
    log.info(f'Saved: {out}')


def make_wer_vs_sf_scatter(store: ResultStore, figures_dir: Path) -> None:
    """WER vs SF scatter — shows decoupling cases."""
    df = _paper_rows(store.df)
    if df.empty or 'sfr_mean' not in df.columns:
        return

    languages = sorted(df['language'].unique())
    n         = len(languages)
    ncols     = 5
    nrows     = int(np.ceil(n / ncols))
    fig, axes = plt.subplots(nrows, ncols, figsize=(17, 7.5), sharex=True, sharey=False)
    axes = np.array(axes).reshape(-1)

    zone_colors = {
        'collapse': '#d73027',
        'mixed': '#fdae61',
        'high': '#1a9850',
    }
    for ax, lang in zip(axes, languages):
        sub = df[df['language'] == lang].dropna(subset=['wer_pct', 'sfr_mean'])
        if sub.empty:
            ax.set_title(lang); continue
        point_colors = [
            zone_colors['collapse'] if v < 10 else
            zone_colors['mixed'] if v <= 90 else
            zone_colors['high']
            for v in sub['sfr_mean']
        ]
        ax.scatter(sub['sfr_mean'], sub['wer_pct'], color=point_colors,
                   s=55, zorder=5, edgecolor='black', linewidth=0.25)
        ax.axvline(10, color=zone_colors['collapse'], linestyle='--', linewidth=1)
        ax.axvline(90, color=zone_colors['high'], linestyle='--', linewidth=1)
        ax.set_xlabel('Script Fidelity (%)')
        ax.set_ylabel('WER (%)')
        ax.set_title(lang.capitalize())
        ax.set_xlim(-5, 105)

    for ax in axes[n:]:
        ax.axis('off')

    handles = [
        plt.Line2D([0], [0], marker='o', color='w', label='SFR < 10%',
                   markerfacecolor=zone_colors['collapse'], markeredgecolor='black', markersize=7),
        plt.Line2D([0], [0], marker='o', color='w', label='10-90%',
                   markerfacecolor=zone_colors['mixed'], markeredgecolor='black', markersize=7),
        plt.Line2D([0], [0], marker='o', color='w', label='> 90%',
                   markerfacecolor=zone_colors['high'], markeredgecolor='black', markersize=7),
    ]
    fig.legend(handles=handles, loc='lower center', ncol=3, frameon=False)
    plt.suptitle('WER vs Script Fidelity - FLEURS test sets', y=0.98)
    plt.tight_layout(rect=(0, 0.05, 1, 0.95))
    out = figures_dir / 'wer_vs_sfr_scatter.pdf'
    fig.savefig(out, bbox_inches='tight')
    plt.close(fig)
    log.info(f'Saved: {out}')


# ── MAIN ──────────────────────────────────────────────────────────────────────
def main():
    args   = parse_args()
    if torch.cuda.is_available():
        device = 'cuda'
    elif torch.backends.mps.is_available():
        device = 'mps'
    else:
        device = 'cpu'
    log.info(f'Device: {device}')
    if device == 'cuda':
        log.info(f'GPU: {torch.cuda.get_device_name(0)}  '
                 f'VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB')
    elif device == 'mps':
        log.info(f'MPS RAM available: {torch.mps.recommended_max_memory()/1e9:.1f} GB')

    if args.hf_token:
        login(token=args.hf_token)
    api = HfApi(token=args.hf_token or None)

    results_dir = Path(args.results_dir)
    preds_dir   = results_dir / 'predictions'
    results_dir.mkdir(parents=True, exist_ok=True)
    preds_dir.mkdir(exist_ok=True)

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

    wer_metric = load_metric('wer')
    cer_metric = load_metric('cer')

    store = ResultStore(results_dir / 'sf_results.csv', force=args.force)

    # Step 1: load FLEURS for each requested language.
    datasets = {}
    for lang in args.languages:
        if lang not in SCRIPT_CONFIGS:
            log.warning(f'Unknown language: {lang} — skipping')
            continue
        datasets[lang] = load_fleurs(lang, args.sample_size)

    # Step 2: Whisper
    for size in args.whisper_sizes:
        for lang, dataset in datasets.items():
            eval_whisper_language(
                size, lang, dataset, store, preds_dir,
                args.batch_size, wer_metric, cer_metric, device)
            push_to_hub(results_dir, args.hub_repo, api, args.hub_private)

    # Step 3: MMS
    if args.run_mms:
        for lang, dataset in datasets.items():
            eval_mms_language(
                lang, dataset, store, preds_dir,
                args.batch_size, wer_metric, cer_metric, device)
            push_to_hub(results_dir, args.hub_repo, api, args.hub_private)

    # Step 4: SeamlessM4T
    if args.run_seamless:
        for lang, dataset in datasets.items():
            eval_seamless_language(
                lang, dataset, store, preds_dir,
                args.batch_size, wer_metric, cer_metric, device)
            push_to_hub(results_dir, args.hub_repo, api, args.hub_private)

    # Step 5: Gemma 4
    if args.run_gemma4:
        gemma_datasets = dict(datasets)  # copy; already loaded above
        for lang, dataset in gemma_datasets.items():
            eval_gemma4_language(
                lang, dataset, store, preds_dir, wer_metric, cer_metric, device)
            push_to_hub(results_dir, args.hub_repo, api, args.hub_private)

    # Step 6: figures
    figures_dir = Path(__file__).parent.parent / 'figures'
    figures_dir.mkdir(parents=True, exist_ok=True)
    make_sf_heatmap(store, figures_dir)
    make_wer_vs_sf_scatter(store, figures_dir)

    # Final push + summary
    push_to_hub(results_dir, args.hub_repo, api, args.hub_private)
    log.info('=== DONE ===')

    if not store.df.empty and 'sfr_mean' in store.df.columns:
        pivot = store.df.pivot_table(
            index='model', columns='language', values='sfr_mean', aggfunc='first')
        log.info(f'\nSF% summary:\n{pivot.to_string()}')

        pivot_wer = store.df.pivot_table(
            index='model', columns='language', values='wer_pct', aggfunc='first')
        log.info(f'\nWER% summary:\n{pivot_wer.to_string()}')


if __name__ == '__main__':
    main()