#!/usr/bin/env python3 """ Script Fidelity Rate (SFR) metric for multilingual ASR evaluation. SFR = fraction of non-whitespace, non-punctuation characters in the ASR hypothesis that belong to the expected target script block(s). A value of 1.0 means every output character is in the correct script. A value near 0 means the model produced output entirely in the wrong script — a condition termed *script collapse* (e.g. Latin transliteration or Arabic when Devanagari was expected). SFR is reference-free: it requires only the hypothesis string and a target language identifier, not a ground-truth transcription. This makes it usable as a deployment-time audit metric even when no labelled data is available. This generalises a Pashto-specific script-check heuristic to ten target languages and scripts. Usage ----- >>> from script_fidelity import compute_sfr, SCRIPT_CONFIGS >>> sfr = compute_sfr("کابل کې ښه هوا ده", "pashto") >>> assert sfr == 1.0 >>> sfr = compute_sfr("this is entirely Latin", "pashto") >>> assert sfr == 0.0 """ import re import unicodedata from dataclasses import dataclass, field from typing import Optional # ── UNICODE BLOCK RANGES ────────────────────────────────────────────────────── # Each language config lists one or more (lo, hi) inclusive code-point ranges # that define the "target script" for that language. An output character is # in-script if it falls in ANY of the target ranges OR is in the optional # unique_codepoints set. @dataclass class ScriptConfig: """Configuration for a single target script.""" name: str # human-readable label ranges: list[tuple[int, int]] # [(lo, hi), ...] inclusive unique_codepoints: set[str] = field(default_factory=set) # Optional: codepoints that CONFIRM the script even if below 70% threshold. # Useful for Pashto which shares Arabic script with Urdu/Dari but has # language-unique glyphs. fleurs_code: str = '' # google/fleurs dataset code mms_lang: list[str] = field(default_factory=list) # MMS language adapter IDs # Pashto-unique codepoints (not found in standard Arabic or Urdu): # ټ U+0679 ډ U+0688 ڼ U+06BC ړ U+0693 ښ U+069A ږ U+0696 ځ U+0681 # ۍ U+06CD ګ U+06AB ې U+06D0 ۀ U+06C0 څ U+0685 _PASHTO_UNIQUE = set('ټډڼړښږځۍګېۀڅ') SCRIPT_CONFIGS: dict[str, ScriptConfig] = { # Pashto — Perso-Arabic + Pashto-unique glyphs 'pashto': ScriptConfig( name='Pashto (Perso-Arabic)', ranges=[ (0x0600, 0x06FF), # Arabic block (covers all Perso-Arabic letters) (0x0750, 0x077F), # Arabic Supplement (0xFB50, 0xFDFF), # Arabic Presentation Forms-A (0xFE70, 0xFEFF), # Arabic Presentation Forms-B ], unique_codepoints=_PASHTO_UNIQUE, fleurs_code='ps_af', mms_lang=['pbu', 'pbt', 'pus'], ), # Urdu — Perso-Arabic (shares blocks with Pashto; no unique codepoints beyond Urdu-specific) # Urdu-unique: ں U+06BA ٹ U+0679 ڈ U+0688 ڑ U+0691 ے U+06D2 'urdu': ScriptConfig( name='Urdu (Perso-Arabic)', ranges=[ (0x0600, 0x06FF), (0x0750, 0x077F), (0xFB50, 0xFDFF), (0xFE70, 0xFEFF), ], unique_codepoints=set('ںٹڈڑے'), fleurs_code='ur_pk', # MMS 1B: no bare 'urd'; Urdu adapters are urd-script_* (not 'udu', a different lang). mms_lang=['urd-script_arabic', 'urd-script_devanagari', 'urd-script_latin'], ), # Hindi — Devanagari 'hindi': ScriptConfig( name='Hindi (Devanagari)', ranges=[ (0x0900, 0x097F), # Devanagari (0xA8E0, 0xA8FF), # Devanagari Extended ], fleurs_code='hi_in', mms_lang=['hin'], ), # Bengali — Bengali script 'bengali': ScriptConfig( name='Bengali (Bengali script)', ranges=[ (0x0980, 0x09FF), # Bengali ], fleurs_code='bn_in', mms_lang=['ben'], ), # Malayalam — Malayalam script 'malayalam': ScriptConfig( name='Malayalam (Malayalam script)', ranges=[ (0x0D00, 0x0D7F), # Malayalam ], fleurs_code='ml_in', mms_lang=['mal'], ), # Somali — Latin script (historically used Arabic; modern standard = Latin) # Somali uses basic Latin + no diacritics in standard orthography; the # main failure mode for Whisper is outputting Arabic on Somali audio. # Two separate ranges for A-Z and a-z: a single 0x41-0x7A range would # include ^ (U+005E) and ` (U+0060), both category Sk, which pass # _is_countable and would be falsely counted as in-script. 'somali': ScriptConfig( name='Somali (Latin)', ranges=[ (0x0041, 0x005A), # Basic Latin A–Z (0x0061, 0x007A), # Basic Latin a–z (0x00C0, 0x024F), # Latin Extended-A and Extended-B ], fleurs_code='so_so', mms_lang=['som'], ), # Arabic (Modern Standard Arabic) — same script family as Pashto/Urdu # Added as a control: MSA models should produce correct Arabic script. # Interesting case: does Whisper confuse Arabic audio with Urdu/Pashto? 'arabic': ScriptConfig( name='Arabic (Modern Standard Arabic)', ranges=[ (0x0600, 0x06FF), (0x0750, 0x077F), (0xFB50, 0xFDFF), (0xFE70, 0xFEFF), ], fleurs_code='ar_eg', mms_lang=['ara'], # MMS uses ISO 639-3; SeamlessM4T uses 'arb' (FLORES-200) ), # Persian/Farsi — Perso-Arabic script with Persian-specific letters # پ U+067E چ U+0686 ژ U+0698 گ U+06AF are unique to Persian vs Arabic 'persian': ScriptConfig( name='Persian/Farsi (Perso-Arabic)', ranges=[ (0x0600, 0x06FF), (0x0750, 0x077F), (0xFB50, 0xFDFF), (0xFE70, 0xFEFF), ], unique_codepoints=set('پچژگ'), fleurs_code='fa_ir', mms_lang=['fas'], # MMS uses ISO 639-3; SeamlessM4T uses 'pes' (FLORES-200) ), # Tamil — Tamil script 'tamil': ScriptConfig( name='Tamil', ranges=[ (0x0B80, 0x0BFF), # Tamil block ], fleurs_code='ta_in', mms_lang=['tam'], ), # Georgian — Mkhedruli script (unique, no Latin/Arabic overlap) # Georgian is a strong positive control: script collapse would be easy to detect. 'georgian': ScriptConfig( name='Georgian (Mkhedruli)', ranges=[ (0x10A0, 0x10FF), # Georgian (Asomtavruli + Mkhedruli) (0x2D00, 0x2D2F), # Georgian Supplement (Nuskhuri) (0x1C90, 0x1CBF), # Georgian Extended (Mtavruli capitals) ], fleurs_code='ka_ge', mms_lang=['kat'], ), } # ── HELPER FUNCTIONS ────────────────────────────────────────────────────────── def _is_in_range(cp: int, ranges: list[tuple[int, int]]) -> bool: return any(lo <= cp <= hi for lo, hi in ranges) def _is_countable(ch: str) -> bool: """Return True for characters that should count toward the SFR denominator. Whitespace, punctuation (Unicode category P*), and combining marks are excluded so that diacritics and punctuation do not artificially inflate or deflate the metric. """ cat = unicodedata.category(ch) return ( not ch.isspace() and not cat.startswith('P') # punctuation and not cat.startswith('Z') # separators and not cat.startswith('C') # control / format chars ) def compute_sfr( text: str, language: str, config: Optional[ScriptConfig] = None, ) -> float: """Compute Script Fidelity Rate for a single ASR hypothesis string. SFR is reference-free: no ground-truth transcription is needed. It can be computed in production deployments to detect script collapse without any labelled data. Parameters ---------- text : str Raw ASR hypothesis (unnormalized is fine; NFC is applied internally). language : str Key into SCRIPT_CONFIGS, e.g. 'pashto', 'hindi', 'somali'. Ignored if `config` is supplied directly. config : ScriptConfig, optional Use a custom config instead of looking up `language`. Returns ------- float Fraction in [0.0, 1.0]. Returns ``None`` if the text has no countable characters (empty / whitespace-only / punctuation-only hypothesis). A value near 0 indicates script collapse. """ if config is None: if language not in SCRIPT_CONFIGS: raise ValueError( f"Unknown language '{language}'. " f"Available: {sorted(SCRIPT_CONFIGS)}" ) config = SCRIPT_CONFIGS[language] text = unicodedata.normalize('NFC', text) if text else '' chars = [ch for ch in text if _is_countable(ch)] if not chars: return None # hypothesis is empty / only punctuation in_script = sum( 1 for ch in chars if (ch in config.unique_codepoints) or _is_in_range(ord(ch), config.ranges) ) return in_script / len(chars) def dominant_script(text: str) -> str: """Classify the dominant script of a text string. Returns one of: 'pashto', 'arabic_dari_urdu', 'devanagari', 'bengali', 'malayalam', 'latin', 'empty', or 'other'. This is a fast heuristic for tallying script distributions across a corpus. For the SF metric, use compute_sf() with a specific language config. """ if not text or not text.strip(): return 'empty' # Pashto-unique glyphs confirm Pashto unambiguously if any(ch in _PASHTO_UNIQUE for ch in text): return 'pashto' chars = [ch for ch in text if _is_countable(ch)] if not chars: return 'empty' counts: dict[str, int] = { 'arabic_dari_urdu': 0, 'devanagari': 0, 'bengali': 0, 'malayalam': 0, 'tamil': 0, 'georgian': 0, 'latin': 0, 'other': 0, } for ch in chars: cp = ord(ch) if 0x0600 <= cp <= 0x06FF or 0xFB50 <= cp <= 0xFDFF or 0xFE70 <= cp <= 0xFEFF: counts['arabic_dari_urdu'] += 1 elif 0x0900 <= cp <= 0x097F or 0xA8E0 <= cp <= 0xA8FF: counts['devanagari'] += 1 elif 0x0980 <= cp <= 0x09FF: counts['bengali'] += 1 elif 0x0D00 <= cp <= 0x0D7F: counts['malayalam'] += 1 elif 0x0B80 <= cp <= 0x0BFF: counts['tamil'] += 1 elif (0x10A0 <= cp <= 0x10FF) or (0x2D00 <= cp <= 0x2D2F) or (0x1C90 <= cp <= 0x1CBF): counts['georgian'] += 1 elif (0x0041 <= cp <= 0x007A) or (0x00C0 <= cp <= 0x024F): counts['latin'] += 1 else: counts['other'] += 1 total = len(chars) best = max(counts, key=counts.__getitem__) if counts[best] / total >= 0.5: return best return 'other' def compute_sfr_batch( texts: list[str], language: str, ) -> tuple[list[Optional[float]], list[str]]: """Vectorised version of compute_sfr + dominant_script. Returns ------- sfr_scores : list of float | None dom_scripts : list of str """ config = SCRIPT_CONFIGS[language] sfr_scores = [compute_sfr(t, language, config) for t in texts] dom = [dominant_script(t) for t in texts] return sfr_scores, dom # Backward-compatibility aliases compute_sf = compute_sfr compute_sf_batch = compute_sfr_batch # ── VALIDATION ──────────────────────────────────────────────────────────────── def _validate_pashto_calibration() -> None: """Smoke-test the Pashto SFR implementation. Checks that Pashto-unique detection works on a known positive and a known negative. """ ps_text = 'کابل کې ښه هوا ده' # contains ښ (U+069A), Pashto-unique lat_text = 'this is entirely latin output' sfr_ps = compute_sfr(ps_text, 'pashto') sfr_lat = compute_sfr(lat_text, 'pashto') assert sfr_ps == 1.0, f'Expected SFR=1.0 for Pashto text, got {sfr_ps}' assert sfr_lat == 0.0, f'Expected SFR=0.0 for Latin text against Pashto config, got {sfr_lat}' dom_ps = dominant_script(ps_text) dom_lat = dominant_script(lat_text) assert dom_ps == 'pashto', f'dominant_script failed for Pashto: {dom_ps}' assert dom_lat == 'latin', f'dominant_script failed for Latin: {dom_lat}' print('Pashto calibration: PASS') def _validate_devanagari() -> None: hi_text = 'नमस्ते' # Hindi Devanagari lat_text = 'namaste' sfr_hi = compute_sfr(hi_text, 'hindi') sfr_lat = compute_sfr(lat_text, 'hindi') assert sfr_hi == 1.0, f'Expected SFR=1.0 for Hindi, got {sfr_hi}' assert sfr_lat == 0.0, f'Expected SFR=0.0 for Latin vs Hindi config, got {sfr_lat}' print('Hindi (Devanagari) calibration: PASS') def _validate_somali() -> None: so_text = 'Somali waa luuqad' # basic Latin ar_text = 'كابل في هواء جيد' # Arabic sfr_so = compute_sfr(so_text, 'somali') sfr_ar = compute_sfr(ar_text, 'somali') assert sfr_so == 1.0, f'Expected SFR=1.0 for Somali Latin, got {sfr_so}' assert sfr_ar == 0.0, f'Expected SFR=0.0 for Arabic vs Somali config, got {sfr_ar}' print('Somali (Latin) calibration: PASS') if __name__ == '__main__': _validate_pashto_calibration() _validate_devanagari() _validate_somali() # Print config summary print('\nScript configurations:') for lang, cfg in SCRIPT_CONFIGS.items(): n_ranges = len(cfg.ranges) n_unique = len(cfg.unique_codepoints) print(f' {lang:12s} {cfg.name:35s} ranges={n_ranges} unique_codepoints={n_unique}')