| |
| """ |
| 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 |
|
|
|
|
| |
| |
| |
| |
| |
|
|
| @dataclass |
| class ScriptConfig: |
| """Configuration for a single target script.""" |
| name: str |
| ranges: list[tuple[int, int]] |
| unique_codepoints: set[str] = field(default_factory=set) |
| |
| |
| |
| fleurs_code: str = '' |
| mms_lang: list[str] = field(default_factory=list) |
|
|
|
|
| |
| |
| |
| _PASHTO_UNIQUE = set('ټډڼړښږځۍګېۀڅ') |
|
|
| SCRIPT_CONFIGS: dict[str, ScriptConfig] = { |
|
|
| |
| 'pashto': ScriptConfig( |
| name='Pashto (Perso-Arabic)', |
| ranges=[ |
| (0x0600, 0x06FF), |
| (0x0750, 0x077F), |
| (0xFB50, 0xFDFF), |
| (0xFE70, 0xFEFF), |
| ], |
| unique_codepoints=_PASHTO_UNIQUE, |
| fleurs_code='ps_af', |
| mms_lang=['pbu', 'pbt', 'pus'], |
| ), |
|
|
| |
| |
| 'urdu': ScriptConfig( |
| name='Urdu (Perso-Arabic)', |
| ranges=[ |
| (0x0600, 0x06FF), |
| (0x0750, 0x077F), |
| (0xFB50, 0xFDFF), |
| (0xFE70, 0xFEFF), |
| ], |
| unique_codepoints=set('ںٹڈڑے'), |
| fleurs_code='ur_pk', |
| |
| mms_lang=['urd-script_arabic', 'urd-script_devanagari', 'urd-script_latin'], |
| ), |
|
|
| |
| 'hindi': ScriptConfig( |
| name='Hindi (Devanagari)', |
| ranges=[ |
| (0x0900, 0x097F), |
| (0xA8E0, 0xA8FF), |
| ], |
| fleurs_code='hi_in', |
| mms_lang=['hin'], |
| ), |
|
|
| |
| 'bengali': ScriptConfig( |
| name='Bengali (Bengali script)', |
| ranges=[ |
| (0x0980, 0x09FF), |
| ], |
| fleurs_code='bn_in', |
| mms_lang=['ben'], |
| ), |
|
|
| |
| 'malayalam': ScriptConfig( |
| name='Malayalam (Malayalam script)', |
| ranges=[ |
| (0x0D00, 0x0D7F), |
| ], |
| fleurs_code='ml_in', |
| mms_lang=['mal'], |
| ), |
|
|
| |
| |
| |
| |
| |
| |
| 'somali': ScriptConfig( |
| name='Somali (Latin)', |
| ranges=[ |
| (0x0041, 0x005A), |
| (0x0061, 0x007A), |
| (0x00C0, 0x024F), |
| ], |
| fleurs_code='so_so', |
| mms_lang=['som'], |
| ), |
|
|
| |
| |
| |
| 'arabic': ScriptConfig( |
| name='Arabic (Modern Standard Arabic)', |
| ranges=[ |
| (0x0600, 0x06FF), |
| (0x0750, 0x077F), |
| (0xFB50, 0xFDFF), |
| (0xFE70, 0xFEFF), |
| ], |
| fleurs_code='ar_eg', |
| mms_lang=['ara'], |
| ), |
|
|
| |
| |
| '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'], |
| ), |
|
|
| |
| 'tamil': ScriptConfig( |
| name='Tamil', |
| ranges=[ |
| (0x0B80, 0x0BFF), |
| ], |
| fleurs_code='ta_in', |
| mms_lang=['tam'], |
| ), |
|
|
| |
| |
| 'georgian': ScriptConfig( |
| name='Georgian (Mkhedruli)', |
| ranges=[ |
| (0x10A0, 0x10FF), |
| (0x2D00, 0x2D2F), |
| (0x1C90, 0x1CBF), |
| ], |
| fleurs_code='ka_ge', |
| mms_lang=['kat'], |
| ), |
| } |
|
|
|
|
| |
|
|
| 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') |
| and not cat.startswith('Z') |
| and not cat.startswith('C') |
| ) |
|
|
|
|
| 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 |
|
|
| 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' |
|
|
| |
| 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 |
|
|
|
|
| |
| compute_sf = compute_sfr |
| compute_sf_batch = compute_sfr_batch |
|
|
|
|
| |
|
|
| 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 = 'کابل کې ښه هوا ده' |
| 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 = 'नमस्ते' |
| 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' |
| ar_text = 'كابل في هواء جيد' |
|
|
| 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('\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}') |
|
|