File size: 4,859 Bytes
96ac6f7 | 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 | """Reasoning-language measurement with GlotLID (cis-lmu/glotlid, fastText).
A trace is split into segments; each segment with enough letters gets a label; shares are char-weighted."""
import os, re, unicodedata
import fasttext
fasttext.FastText.eprint = lambda *a, **k: None
_model = None
# Labels GlotLID uses for the same language (from data/lid_calibration.json on gold FLORES sentences)
ALIAS = {"tgl_Latn": {"fil_Latn"}, "zsm_Latn": {"ind_Latn"}, "ind_Latn": {"zsm_Latn"},
"arb_Arab": {"ars_Arab", "ary_Arab", "arz_Arab", "apc_Arab", "acm_Arab", "ajp_Arab", "aeb_Arab", "acq_Arab"}}
def is_target(lab, target):
return lab == target or lab in ALIAS.get(target, ())
def _letter(ch):
return ch.isalpha() or unicodedata.category(ch).startswith("M") # Myanmar/Khmer vowel signs are marks
def model():
global _model
if _model is None:
_model = fasttext.load_model(os.path.join(os.path.dirname(os.path.abspath(__file__)), "models", "glotlid", "model.bin"))
return _model
def segments(text):
for s in re.split(r"(?<=[.!?。])\s+|\n+", text):
s = s.strip()
letters = sum(_letter(ch) for ch in s)
if letters >= 12 and letters / max(1, len(s)) >= 0.5: # skip pure math like "7+5=12"
yield s
def label(s):
# ponytail: call the C++ binding directly; fasttext's python wrapper breaks on numpy>=2 (copy=False)
p, lab = model().f.predict(s.replace("\n", " ") + "\n", 1, 0.0, "strict")[0]
return lab.replace("__label__", ""), float(p)
def _grams(s, n=5):
s = re.sub(r"\s+", " ", s.lower())
return {s[i:i + n] for i in range(max(1, len(s) - n + 1))}
def quoted(seg, prompt_grams, thr=0.6):
"""True if >= thr of the segment's char 5-grams occur in the prompt, i.e. the model is quoting its input."""
g = _grams(seg)
return bool(prompt_grams) and len(g & prompt_grams) / len(g) >= thr
def profile(text, target, exclude=None):
"""Char-weighted shares of target / English / other in `text`, plus where English first appears (0..1).
exclude: the prompt text; segments that quote it are dropped (robustness metric, not the pre-registered one)."""
segs = list(segments(text or ""))
if exclude:
pg = _grams(exclude)
segs = [s for s in segs if not quoted(s, pg)]
if not segs:
return {"n_seg": 0, "target_share": None, "eng_share": None, "other_share": None,
"first_eng_pos": None, "top_other": None}
tot = tgt = eng = 0; other = {}; first_eng = None; pos = 0; full = len(text)
for s in segs:
lab, _ = label(s); w = len(s); tot += w
if is_target(lab, target):
tgt += w
elif lab == "eng_Latn":
eng += w
if first_eng is None:
first_eng = round(text.find(s) / max(1, full), 3)
else:
other[lab] = other.get(lab, 0) + w
top = max(other, key=other.get) if other else None
return {"n_seg": len(segs), "target_share": round(tgt / tot, 3), "eng_share": round(eng / tot, 3),
"other_share": round(1 - (tgt + eng) / tot, 3), "first_eng_pos": first_eng, "top_other": top}
_lingua = None
def lingua_eng_share(text, exclude=None):
"""Independent second detector (Lingua, rule+n-gram) for the headline metric: char share of English segments."""
global _lingua
if _lingua is None:
from lingua import LanguageDetectorBuilder
_lingua = LanguageDetectorBuilder.from_all_languages().with_low_accuracy_mode().build()
segs = list(segments(text or ""))
if exclude:
pg = _grams(exclude)
segs = [s for s in segs if not quoted(s, pg)]
if not segs:
return None
tot = sum(len(s) for s in segs)
eng = sum(len(s) for s in segs if (lang := _lingua.detect_language_of(s)) is not None and lang.name == "ENGLISH")
return round(eng / tot, 3)
if __name__ == "__main__":
idt = "Saya perlu menjumlahkan dua belas dan tiga puluh. Hasilnya adalah empat puluh dua, jadi jawabannya jelas."
ent = "We need to add twelve and thirty. The result is forty two, so the answer is clear."
mix = idt + "\n" + ent
p = profile(idt, "ind_Latn"); assert p["target_share"] == 1.0, p
p = profile(ent, "ind_Latn"); assert p["eng_share"] == 1.0, p
p = profile(mix, "ind_Latn"); assert 0.4 < p["eng_share"] < 0.6 and p["first_eng_pos"] > 0.4, p
assert profile("7+5=12", "ind_Latn")["n_seg"] == 0
# quoting the prompt is not "thinking in the language"
prompt = "Saya perlu menjumlahkan dua belas dan tiga puluh."
q = "Saya perlu menjumlahkan dua belas dan tiga puluh. " + ent
assert profile(q, "ind_Latn")["target_share"] > 0.3 and profile(q, "ind_Latn", exclude=prompt)["eng_share"] == 1.0
assert abs(lingua_eng_share(ent) - 1.0) < 1e-9 and lingua_eng_share(idt) == 0.0
print("lid self-check ok")
|