cillegio commited on
Commit
b8a600a
·
verified ·
1 Parent(s): 553c3f9

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. README.md +163 -0
  2. az_numbers.py +159 -0
  3. containment.csv +12 -0
  4. gl_pairs.csv +12 -0
  5. grapheme_sets.py +100 -0
  6. lsgr.py +99 -0
  7. signal_density.csv +7 -0
README.md ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - az
4
+ - kk
5
+ - ky
6
+ - tt
7
+ - ba
8
+ - tg
9
+ - tk
10
+ - uz
11
+ tags:
12
+ - evaluation
13
+ - metric
14
+ - speech-recognition
15
+ - turkic
16
+ - low-resource
17
+ ---
18
+
19
+ # LSGR — Language-Specific Grapheme Recall
20
+
21
+ A training-free diagnostic for one specific failure of multilingual speech
22
+ recognition: **writing the wrong language's orthography**.
23
+
24
+ Across the Turkic family nearly every language sits beside a better-resourced
25
+ neighbour that shares its script — Azerbaijani beside Turkish, Kazakh and
26
+ Kyrgyz and Tatar and Bashkir beside Russian. A model that has seen far more of
27
+ the neighbour will often transcribe the target language *as* the neighbour. The
28
+ output is fluent, confident, and reads as a working transcript to anyone who
29
+ does not speak the language.
30
+
31
+ Neither standard metric exposes it. WER punishes the output but never says why.
32
+ CER actively hides it, because the phonemes are approximately right. In our
33
+ evaluation a system writing Turkish orthography for Azerbaijani scored **91.4%
34
+ WER against 60.7% CER** — a gap that reads as "difficult audio", not "wrong
35
+ language".
36
+
37
+ ## The index
38
+
39
+ Let `G_L` be the graphemes present in the target orthography and absent from
40
+ the neighbour's. Over a corpus of (reference, hypothesis) pairs, with counts
41
+ pooled rather than averaged per utterance:
42
+
43
+ ```
44
+ R = Σ G_L characters in reference
45
+ H = Σ G_L characters in hypothesis
46
+ O = Σ min(ref count, hyp count) per utterance
47
+
48
+ precision = O/H recall = O/R LSGR = F1(precision, recall)
49
+ ```
50
+
51
+ **Why F1 rather than recall.** Bare recall is unbounded above and rewards
52
+ over-production. A Whisper turbo variant emitted 1.51× the reference's schwas
53
+ and scored 151% — better than perfect, and nothing of the sort. Bounding the
54
+ overlap at `min(ref, hyp)` charges for inventing the marker as well as for
55
+ omitting it; that system scores F1 0.690 from precision 0.574, which is what
56
+ "sprays schwas" should look like.
57
+
58
+ ## Usage
59
+
60
+ ```python
61
+ from lsgr import lsgr, pooled
62
+ from grapheme_sets import g_set
63
+
64
+ G = g_set("az", "tr") # -> {'ə', 'q', 'x'}, derived, not curated
65
+ pooled(zip(references, hypotheses), G)
66
+ # {'n_ref': .., 'n_hyp': .., 'precision': .., 'recall': .., 'f1': ..}
67
+ ```
68
+
69
+ `G_L` is a set difference computed from two alphabets at import time. There is
70
+ no per-pair configuration and no hand-edited list. Deriving it matters: we
71
+ hand-picked `{ə}` for Azerbaijani and the derivation returned `{ə, q, x}` —
72
+ two further letters Turkish lacks that we had missed, both frequent and both
73
+ systematically rewritten by Turkish-dominant models.
74
+
75
+ ## Files
76
+
77
+ | file | |
78
+ |---|---|
79
+ | `lsgr.py` | the scorer; `python3 lsgr.py` runs its self-tests |
80
+ | `grapheme_sets.py` | alphabets for 13 languages; `python3 grapheme_sets.py` prints every derived set |
81
+ | `az_numbers.py` | Azerbaijani number canonicalisation for WER (see below) |
82
+ | `gl_pairs.csv` | derived `G_L` for 11 language pairs |
83
+ | `containment.csv` | forward and reverse set sizes per pair |
84
+ | `signal_density.csv` | measured usability per pair, over FLEURS |
85
+
86
+ ## Two things to check before trusting a score on a new pair
87
+
88
+ **Containment.** For az/tr, kk/ru, ky/ru, tt/ru and ba/ru the *reverse* set is
89
+ empty: the neighbour's alphabet is a strict subset of the target's. These
90
+ orthographies are the dominant one plus extra letters. That is exactly why
91
+ one-sided recall works — writing the neighbour's orthography can only mean
92
+ omitting letters. Where containment fails (uz/tr has seven Turkish-exclusive
93
+ graphemes) a two-sided variant should be stronger; it is proposed in the paper
94
+ and is untested.
95
+
96
+ **Signal density.** `|G_L|` says nothing about usability — ten rare letters
97
+ carry less signal than one frequent vowel. What matters is the share of
98
+ utterances containing at least one `G_L` character, since an utterance with
99
+ none cannot be scored. Measured over 400 FLEURS transcripts per language:
100
+
101
+ | pair | \|G_L\| | % of characters | % utterances scorable |
102
+ |---|---:|---:|---:|
103
+ | kk/ru | 9 | 12.50 | **99.8** |
104
+ | az/tr | 3 | 10.79 | **99.5** |
105
+ | tg/ru | 6 | 5.17 | **99.2** |
106
+ | uz/tr | 3 | 3.55 | **97.5** |
107
+ | ky/ru | 3 | 5.00 | **88.8** |
108
+ | ca/es | 2 | 0.15 | **18.0** |
109
+
110
+ The Catalan/Spanish control **fails**, and that is the honest boundary of the
111
+ method: four in five Catalan sentences contain no `ç` and cannot be scored at
112
+ all. Measure coverage on any available text before trusting the score on a new
113
+ pair. Every Turkic pair tested clears 88%.
114
+
115
+ ## What LSGR does not measure
116
+
117
+ **It measures conformance to the target orthography, not language
118
+ understanding.** The same multilingual model, switched to Azerbaijani's
119
+ Cyrillic adapter and to South Azerbaijani's Arabic-script adapter, scores 0.000
120
+ in both cases while transcribing the speech essentially correctly in another
121
+ script — identical to systems writing Turkish. A score of 0.000 has two causes
122
+ and the index cannot separate them. Pair it with script identification when the
123
+ claim is about language support.
124
+
125
+ Also: `G_L` members are not always perfectly exclusive. `ə` is absent from
126
+ Turkish entirely, but `q` and `x` occur in Turkish loanwords and proper nouns,
127
+ so a Turkish-writing system scores slightly above zero rather than exactly zero.
128
+
129
+ And a system can score 1.0 while getting every word wrong. **LSGR is read
130
+ beside WER, never instead of it.**
131
+
132
+ ## On the number canonicaliser
133
+
134
+ `az_numbers.py` is not part of LSGR, but it is needed to reproduce our WER
135
+ figures and is useful independently. Corpora disagree about whether a number is
136
+ digits or words — our own call corpus writes digits on 14.3% of lines and
137
+ number words on 15.5% — so a correct number scores as a substitution.
138
+
139
+ It expands digits to words on both sides at scoring time, never the reverse:
140
+ `bir` is also the indefinite article, so `bir az` is "a little", not "1 az", and
141
+ rewriting words to digits would corrupt ordinary prose. Ordinals collapse to
142
+ cardinals on both sides, so `2003-cü` and `İki min üçüncü` meet at `iki min üç`
143
+ — a comparison key, not a transcription.
144
+
145
+ ## Citation
146
+
147
+ The companion theoretical framework:
148
+
149
+ ```bibtex
150
+ @misc{ibrahimzade2026ttc,
151
+ title = {Cross-Lingual Transfer and Parameter-Efficient Adaptation in the
152
+ Turkic Language Family: A Theoretical Framework for Low-Resource
153
+ Language Models},
154
+ author = {Ibrahimzade, O. and Tabasaransky, K.},
155
+ year = {2026},
156
+ eprint = {2604.06202},
157
+ archivePrefix = {arXiv},
158
+ primaryClass = {cs.CL}
159
+ }
160
+ ```
161
+
162
+ The LSGR paper is in preparation; this repository will carry its citation on
163
+ publication.
az_numbers.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonicalise numbers in Azerbaijani text, for scoring only.
2
+
3
+ The corpora disagree about how to write a number, and so does any single one of
4
+ them: our own call corpus writes digits on 14.3% of lines and number words on
5
+ 15.5%. Soniox writes "108" for an identifier and "iki min üçüncü" for a date,
6
+ which is correct on both counts and unscoreable against a model that chose the
7
+ other form. Edit distance sees unrelated tokens and charges a full substitution
8
+ for a number the model got right.
9
+
10
+ So this runs on the reference *and* the hypothesis before scoring, never on
11
+ training targets. Two rules make it safe:
12
+
13
+ digits -> words, never the reverse. "2003" -> "iki min üç" is deterministic.
14
+ "bir" -> "1" is wrong most of the time, because bir is also the indefinite
15
+ article: "bir az" is "a little", not "1 az". Rewriting words to digits would
16
+ corrupt ordinary prose across every corpus we have.
17
+
18
+ ordinals collapse to cardinals on both sides. "2003-cü" and "iki min üçüncü"
19
+ both become "iki min üç". That is not a correct transcription of either, and
20
+ it does not need to be -- it is a comparison key, and its only job is that two
21
+ spellings of the same spoken number produce the same tokens.
22
+
23
+ Roman numerals are folded in too: the corpora write "XIX əsr" where a model
24
+ emits "19-cu əsr", which is the same disagreement wearing a different alphabet.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import re
29
+
30
+ ONES = ["", "bir", "iki", "üç", "dörd", "beş", "altı", "yeddi", "səkkiz", "doqquz"]
31
+ TENS = ["", "on", "iyirmi", "otuz", "qırx", "əlli", "altmış", "yetmiş",
32
+ "səksən", "doxsan"]
33
+ SCALES = [(10 ** 9, "milyard"), (10 ** 6, "milyon"), (1000, "min"), (100, "yüz")]
34
+
35
+ # Ordinal word -> the cardinal it is built from. Listed rather than derived
36
+ # because the suffix follows vowel harmony and the stems are not all regular
37
+ # (doqquz -> doqquzuncu, altı -> altıncı, qırx -> qırxıncı).
38
+ ORDINALS = {
39
+ "birinci": "bir", "ikinci": "iki", "üçüncü": "üç", "dördüncü": "dörd",
40
+ "beşinci": "beş", "altıncı": "altı", "yeddinci": "yeddi",
41
+ "səkkizinci": "səkkiz", "doqquzuncu": "doqquz", "onuncu": "on",
42
+ "iyirminci": "iyirmi", "otuzuncu": "otuz", "qırxıncı": "qırx",
43
+ "əllinci": "əlli", "altmışıncı": "altmış", "yetmişinci": "yetmiş",
44
+ "səksəninci": "səksən", "doxsanıncı": "doxsan", "yüzüncü": "yüz",
45
+ "mininci": "min", "milyonuncu": "milyon",
46
+ }
47
+
48
+ ROMAN_VALUES = {"i": 1, "v": 5, "x": 10, "l": 50, "c": 100, "d": 500, "m": 1000}
49
+ # Roman numerals up to 99, which covers what actually appears here: centuries
50
+ # and volume numbers. Written as the standard subtractive grammar rather than a
51
+ # flat alternation, because a flat one cannot backtrack into "XIX" -- it commits
52
+ # to the leading X and then finds an I it has no rule for.
53
+ ROMAN_RX = re.compile(
54
+ r"(?<![\w])((?=[IVXL])(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3}))(?![\w])")
55
+
56
+ # A digit run, optionally carrying an Azerbaijani ordinal suffix: 19-cu, 2003-cü,
57
+ # 1-ci. The suffix is dropped, matching what happens to the ordinal words.
58
+ DIGIT_RX = re.compile(r"(?<!\w)(\d+)\s*-?\s*(?:[cç][ıiuü]|[ıiuü]nc[ıiuü])?(?!\w)",
59
+ re.IGNORECASE)
60
+
61
+
62
+ def int_to_az_words(n: int) -> str:
63
+ """Cardinal form. 0 -> sıfır, 100 -> yüz (not "bir yüz"), 1000 -> min."""
64
+ if n == 0:
65
+ return "sıfır"
66
+ if n < 0:
67
+ return "mənfi " + int_to_az_words(-n)
68
+ out: list[str] = []
69
+ for value, name in SCALES:
70
+ if n >= value:
71
+ count = n // value
72
+ # "yüz" and "min" stand alone at a count of one; "milyon" and
73
+ # "milyard" take an explicit "bir".
74
+ if count > 1 or value >= 10 ** 6:
75
+ out.append(int_to_az_words(count))
76
+ out.append(name)
77
+ n %= value
78
+ if n >= 10:
79
+ out.append(TENS[n // 10])
80
+ n %= 10
81
+ if n > 0:
82
+ out.append(ONES[n])
83
+ return " ".join(out)
84
+
85
+
86
+ def roman_to_int(s: str) -> int | None:
87
+ s = s.lower()
88
+ total = prev = 0
89
+ for ch in reversed(s):
90
+ v = ROMAN_VALUES.get(ch)
91
+ if v is None:
92
+ return None
93
+ total += -v if v < prev else v
94
+ prev = max(prev, v)
95
+ return total or None
96
+
97
+
98
+ def _expand_digits(m: re.Match) -> str:
99
+ raw = m.group(1)
100
+ # A long run is an identifier -- a phone number, an account -- and is read
101
+ # out rather than said as one quantity. Grouping it in pairs matches how
102
+ # these are spoken and, more to the point, matches whatever the other side
103
+ # did with the same digits.
104
+ if len(raw) > 6:
105
+ return " ".join(int_to_az_words(int(raw[i:i + 2]))
106
+ for i in range(0, len(raw), 2))
107
+ try:
108
+ return int_to_az_words(int(raw))
109
+ except ValueError:
110
+ return raw
111
+
112
+
113
+ def _expand_roman(m: re.Match) -> str:
114
+ s = m.group(1)
115
+ # A single character is left alone. In Azerbaijani "I" is the capital
116
+ # dotless i and "V" and "L" start ordinary words, so a one-letter match is
117
+ # far more often a letter than a numeral.
118
+ if len(s) < 2:
119
+ return s
120
+ v = roman_to_int(s)
121
+ return int_to_az_words(v) if v else s
122
+
123
+
124
+ def normalise_numbers(text: str, romans: bool = True) -> str:
125
+ """Canonical number form, for comparison only -- never for training text."""
126
+ if not text:
127
+ return text
128
+ if romans:
129
+ text = ROMAN_RX.sub(_expand_roman, text)
130
+ text = DIGIT_RX.sub(_expand_digits, text)
131
+ # ordinal words down to their cardinals, so "üçüncü" meets the "üç" that
132
+ # "2003-cü" just became
133
+ return " ".join(ORDINALS.get(w.lower(), w) for w in text.split())
134
+
135
+
136
+ if __name__ == "__main__":
137
+ CASES = [
138
+ ("2003-cü ildə", "iki min üç ildə"),
139
+ ("İki min üçüncü ildə", "İki min üç ildə"),
140
+ ("XIX əsrin əvvəllərində", "on doqquz əsrin əvvəllərində"),
141
+ ("19-cu əsrin əvvəllərində", "on doqquz əsrin əvvəllərində"),
142
+ ("27 manat", "iyirmi yeddi manat"),
143
+ ("108, düzdürmü?", "yüz səkkiz, düzdürmü?"),
144
+ ("3 dəqiqədən sonra", "üç dəqiqədən sonra"),
145
+ ("bir az gözlə", "bir az gözlə"), # the article must survive
146
+ ("Birinci yaşayış yeri", "bir yaşayış yeri"),
147
+ ("1000 nəfər", "min nəfər"),
148
+ ("2500", "iki min beş yüz"),
149
+ ("0", "sıfır"),
150
+ ]
151
+ bad = 0
152
+ for src, want in CASES:
153
+ got = normalise_numbers(src)
154
+ ok = got == want
155
+ bad += not ok
156
+ print(f"{'ok ' if ok else 'FAIL'} {src!r}\n -> {got!r}"
157
+ + ("" if ok else f"\n want {want!r}"))
158
+ print(f"\n{len(CASES)-bad}/{len(CASES)} passed")
159
+ raise SystemExit(1 if bad else 0)
containment.csv ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ target,neighbour,forward_size,reverse_size,containment,one_sided_sufficient
2
+ az,tr,3,0,True,yes
3
+ kk,ru,9,0,True,yes
4
+ ky,ru,3,0,True,yes
5
+ tt,ru,6,0,True,yes
6
+ ba,ru,9,0,True,yes
7
+ tg,ru,6,4,False,no
8
+ tk,tr,6,4,False,no
9
+ gag,tr,3,1,False,mostly
10
+ uz,tr,3,7,False,no
11
+ ba,tt,4,1,False,mostly
12
+ ca,es,2,1,False,mostly
gl_pairs.csv ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ target,neighbour,case,size,G_L
2
+ az,tr,"same script, dominant neighbour",3,q x ə
3
+ kk,ru,"same script, dominant neighbour",9,і ғ қ ң ү ұ һ ә ө
4
+ ky,ru,"same script, dominant neighbour",3,ң ү ө
5
+ tt,ru,"same script, dominant neighbour",6,җ ң ү һ ә ө
6
+ ba,ru,"same script, dominant neighbour",9,ғ ҙ ҡ ң ҫ ү һ ә ө
7
+ tg,ru,"same script, dominant neighbour",6,ғ қ ҳ ҷ ӣ ӯ
8
+ tk,tr,"same script, dominant neighbour",6,w ä é ý ň ž
9
+ gag,tr,"same script, dominant neighbour",3,ä ê ț
10
+ uz,tr,"same script, related Latin Turkic",3,q x ʻ
11
+ ba,tt,two low-resource languages,4,ғ ҙ ҡ ҫ
12
+ ca,es,"same script, dominant neighbour",2,· ç
grapheme_sets.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Alphabets for Turkic and neighbouring languages, and the G_L sets they imply.
2
+
3
+ The claim LSGR rests on is that the distinguishing grapheme set is *derived*,
4
+ not curated: give the tool two orthographies and it returns the characters one
5
+ has and the other lacks. So the alphabets are the input here and every G_L is a
6
+ set difference computed at import time. Nothing below is hand-tuned, and where a
7
+ pair produces a bad G_L that is a result about the pair, not a bug to paper over.
8
+
9
+ Three structurally different cases appear, and they are not equally interesting:
10
+
11
+ same script, dominant neighbour az/tr, kk/ru, ky/ru, tt/ru, uz/tr ...
12
+ The case LSGR was built for. A model trained mostly on the neighbour
13
+ emits the neighbour's orthography, and G_L catches it.
14
+
15
+ different script uz-Latin/ru-Cyrillic, tg/fa
16
+ LSGR is unnecessary: the failure is visible to anyone glancing at the
17
+ output, and a script detector settles it in one line. Listed so the paper
18
+ can say explicitly where the index adds nothing.
19
+
20
+ two low-resource languages ba/tt
21
+ The hard case, and the most novel. Bashkir and Tatar are close, share a
22
+ script, and share most of their non-Russian letters. G_L shrinks to the
23
+ handful that actually separate them, which is exactly where a metric
24
+ earns its keep -- and where it may fail.
25
+
26
+ Alphabets are the standard modern orthographies. Marked (v) where verified
27
+ against a published alphabet; the rest should be checked before publication.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ # Lower case only; comparisons fold case. Digraphs are deliberately not modelled
32
+ # -- LSGR counts characters, and a digraph made of shared letters carries no
33
+ # distinguishing signal anyway.
34
+ ALPHABETS: dict[str, str] = {
35
+ # --- Latin ---------------------------------------------------------
36
+ "tr": "abcçdefgğhıijklmnoöprsştuüvyz", # (v)
37
+ "az": "abcçdeəfgğhxıijkqlmnoöprsştuüvyz", # (v)
38
+ "tk": "aäbçdeéfghijžklmnňoöprsştuüwyýz", # Turkmen
39
+ "uz": "abdefghijklmnopqrstuvxyzoʻgʻ", # Uzbek Latin
40
+ "gag": "aäbcçdeêfghıijklmnoöprsştțuüvyz", # Gagauz
41
+ "es": "abcdefghijklmnñopqrstuvwxyz",
42
+ "ca": "abcçdefghijklmnopqrstuvwxyz·",
43
+ # --- Cyrillic ------------------------------------------------------
44
+ "ru": "абвгдеёжзийклмнопрстуфхцчшщъыьэюя", # (v)
45
+ "kk": "аәбвгғдеёжзийкқлмнңоөпрстуұүфхһцчшщъыіьэюя", # Kazakh (v)
46
+ "ky": "абвгдеёжзийклмнңоөпрстуүфхцчшщъыьэюя", # Kyrgyz
47
+ "tt": "аәбвгдеёжҗзийклмнңоөпрстуүфхһцчшщъыьэюя", # Tatar
48
+ "ba": "аәбвгғдеёжзийкҡлмнңоөпрҫстуүфхһцчшщъыьэюяҙ", # Bashkir
49
+ "tg": "абвгғдеёжзиӣйкқлмнопрстуӯфхҳчҷшъэюя", # Tajik
50
+ }
51
+
52
+ # target -> the better-resourced language whose orthography a multilingual model
53
+ # is most likely to emit instead. Chosen by resource asymmetry and contact, not
54
+ # by linguistic family: Tajik is Iranian, not Turkic, and is here precisely
55
+ # because its neighbour relationship is with Russian orthographically.
56
+ PAIRS: list[tuple[str, str, str]] = [
57
+ ("az", "tr", "same script, dominant neighbour"),
58
+ ("kk", "ru", "same script, dominant neighbour"),
59
+ ("ky", "ru", "same script, dominant neighbour"),
60
+ ("tt", "ru", "same script, dominant neighbour"),
61
+ ("ba", "ru", "same script, dominant neighbour"),
62
+ ("tg", "ru", "same script, dominant neighbour"),
63
+ ("tk", "tr", "same script, dominant neighbour"),
64
+ ("gag", "tr", "same script, dominant neighbour"),
65
+ ("uz", "tr", "same script, related Latin Turkic"),
66
+ ("ba", "tt", "two low-resource languages"),
67
+ ("ca", "es", "same script, dominant neighbour"),
68
+ ]
69
+
70
+
71
+ def g_set(target: str, neighbour: str) -> set[str]:
72
+ """Characters the target orthography has and the neighbour lacks."""
73
+ t, n = set(ALPHABETS[target]), set(ALPHABETS[neighbour])
74
+ return t - n
75
+
76
+
77
+ def report() -> None:
78
+ print("%-9s %-9s %-34s %4s %s" %
79
+ ("target", "vs", "case", "|G|", "G_L"))
80
+ print("-" * 96)
81
+ for tgt, nb, case in PAIRS:
82
+ g = sorted(g_set(tgt, nb))
83
+ warn = ""
84
+ if not g:
85
+ warn = " <- EMPTY: index inapplicable"
86
+ elif len(g) == 1:
87
+ warn = " <- single marker, like az/tr"
88
+ print("%-9s %-9s %-34s %4d %s%s" %
89
+ (tgt, nb, case, len(g), " ".join(g), warn))
90
+
91
+ print("\nReverse direction, which is not symmetric and is worth reporting:")
92
+ print("%-9s %-9s %4s %s" % ("target", "vs", "|G|", "G_L"))
93
+ print("-" * 70)
94
+ for tgt, nb, _ in PAIRS:
95
+ g = sorted(g_set(nb, tgt))
96
+ print("%-9s %-9s %4d %s" % (nb, tgt, len(g), " ".join(g)))
97
+
98
+
99
+ if __name__ == "__main__":
100
+ report()
lsgr.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Language-Specific Grapheme Recall, and why it is scored as an F1.
2
+
3
+ When a target language L has a better-resourced close neighbour C, multilingual
4
+ systems transcribe L *as* C. The output is fluent and reads as a working
5
+ transcript to anyone who does not speak L. WER punishes it, but WER punishes
6
+ everything, so a high WER never says *why*; CER makes it look mild, because the
7
+ phonemes are approximately right.
8
+
9
+ G_L is the set of graphemes that occur in L's orthography and not in C's, which
10
+ falls out of the two alphabets with no supervision or training data.
11
+
12
+ Scored as precision/recall/F1 over grapheme *counts*, not as bare recall.
13
+ Recall alone is unbounded above and rewards over-production: in our evaluation a
14
+ Whisper turbo variant emitted 1.51x the reference's schwas and scored 151%,
15
+ which reads as "better than perfect" and is nothing of the sort. Counting the
16
+ overlap as min(hyp, ref) bounds the score at 1.0 and charges for inventing the
17
+ marker as well as for omitting it.
18
+
19
+ What the index does NOT measure, stated here because the evaluation makes it
20
+ unmissable: it is a test of conformance to the target *orthography*, not of
21
+ language understanding. Two MMS adapters that transcribe Azerbaijani correctly
22
+ into Cyrillic and Arabic script both score 0.0, exactly as the systems that
23
+ transcribe it as Turkish do. Those are different failures and the index cannot
24
+ tell them apart. For a deployment that requires a specific script that
25
+ distinction may not matter; for a claim about language support it matters a
26
+ great deal, so report script detection alongside it or state the limit.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ # Graphemes in Azerbaijani (Latin) that Turkish does not have. Schwa is the
31
+ # whole story here -- it is frequent, it is unambiguous, and Turkish has no
32
+ # counterpart -- but the set form is what makes the construction transferable.
33
+ AZ_VS_TR = set("əƏ")
34
+
35
+ # Reference sets for other pairs the construction applies to unchanged. Listed
36
+ # to make the point that G_L is derived, not tuned.
37
+ PAIRS = {
38
+ ("az", "tr"): AZ_VS_TR,
39
+ ("kk", "ru"): set("әғқңөұүһӘҒҚҢӨҰҮҺ"),
40
+ ("ca", "es"): set("çÇ"),
41
+ ("fa", "ar"): set("پچژگ"),
42
+ ("ha", "en"): set("ɓɗƙƁƊƘ"),
43
+ }
44
+
45
+
46
+ def counts(text: str, graphemes: set[str]) -> int:
47
+ return sum(1 for ch in (text or "") if ch in graphemes)
48
+
49
+
50
+ def lsgr(ref: str, hyp: str, graphemes: set[str] = AZ_VS_TR) -> dict[str, float]:
51
+ """Precision, recall and F1 over target-specific grapheme counts.
52
+
53
+ A reference with no target-specific graphemes carries no signal, so the
54
+ caller gets n_ref = 0 and should pool rather than average: per-utterance
55
+ averaging would let short schwa-free lines dominate.
56
+ """
57
+ r = counts(ref, graphemes)
58
+ h = counts(hyp, graphemes)
59
+ overlap = min(r, h)
60
+ p = overlap / h if h else 0.0
61
+ rec = overlap / r if r else 0.0
62
+ f1 = (2 * p * rec / (p + rec)) if (p + rec) else 0.0
63
+ return {"n_ref": r, "n_hyp": h, "precision": p, "recall": rec, "f1": f1}
64
+
65
+
66
+ def pooled(pairs, graphemes: set[str] = AZ_VS_TR) -> dict[str, float]:
67
+ """LSGR over a corpus: sum the counts, then compute once.
68
+
69
+ Pooling rather than averaging, for the same reason WER is pooled over words.
70
+ """
71
+ R = H = O = 0
72
+ for ref, hyp in pairs:
73
+ r, h = counts(ref, graphemes), counts(hyp, graphemes)
74
+ R += r
75
+ H += h
76
+ O += min(r, h)
77
+ p = O / H if H else 0.0
78
+ rec = O / R if R else 0.0
79
+ f1 = (2 * p * rec / (p + rec)) if (p + rec) else 0.0
80
+ return {"n_ref": R, "n_hyp": H, "precision": p, "recall": rec, "f1": f1}
81
+
82
+
83
+ if __name__ == "__main__":
84
+ CASES = [
85
+ ("perfect", "əə bir", "əə bir", 1.0),
86
+ ("wrong orthography", "əə bir", "ee bir", 0.0),
87
+ ("half omitted", "əəəə", "əə", 2 / 3),
88
+ ("doubled", "əə", "əəəə", 2 / 3),
89
+ ("empty hyp", "əə", "", 0.0),
90
+ ("no signal in ref", "bir az", "bir az", 0.0),
91
+ ]
92
+ bad = 0
93
+ for name, ref, hyp, want in CASES:
94
+ got = lsgr(ref, hyp)["f1"]
95
+ ok = abs(got - want) < 1e-9
96
+ bad += not ok
97
+ print(f"{'ok ' if ok else 'FAIL'} {name:<20} f1={got:.3f} want={want:.3f}")
98
+ print(f"\n{len(CASES)-bad}/{len(CASES)} passed")
99
+ raise SystemExit(1 if bad else 0)
signal_density.csv ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ target,neighbour,size,pct_of_characters,pct_utterances_with_signal,n_transcripts,source
2
+ kk,ru,9,12.5,99.8,400,google/fleurs
3
+ az,tr,3,10.79,99.5,400,google/fleurs
4
+ tg,ru,6,5.17,99.2,400,google/fleurs
5
+ uz,tr,3,3.55,97.5,400,google/fleurs
6
+ ky,ru,3,5.0,88.8,400,google/fleurs
7
+ ca,es,2,0.15,18.0,400,google/fleurs