Makron-code / analysis /silver_overlap.py
Urdatorn's picture
Rule-based scoring on Norma and error analysis (job 5670283)
c266841 verified
Raw History Blame Contribute Delete
5.58 kB
"""Overlap between OGA-macronized silver data and the Norma benchmark.
Usage: python3 overlap.py <silver_dir> <norma_data_dir> <out_dir>
"""
import json, sys, unicodedata, collections, glob, os
import pyarrow.parquet as pq
silver_dir, norma_dir, out_dir = sys.argv[1:4]
os.makedirs(out_dir, exist_ok=True)
APOS = {"'": "’", "ʼ": "’", "᾽": "’", "‘": "’", "᾿": "’"}
MARK = "^_"
GRAVE2ACUTE = {"̀": "́"}
def nfc(s):
return unicodedata.normalize("NFC", s)
def parse(tok):
"""marked token -> (plain chars with edge punctuation stripped, {pos: '^'|'_'})"""
chars, labels = [], {}
for ch in nfc(tok):
if ch in MARK:
if chars:
labels[len(chars) - 1] = ch
continue
chars.append(APOS.get(ch, ch))
# strip leading/trailing non-letters (keep final elision apostrophe)
def ok(c):
return unicodedata.category(c)[0] in "LM"
s = 0
while s < len(chars) and not ok(chars[s]):
s += 1
e = len(chars)
while e > s and not ok(chars[e - 1]) and not (chars[e - 1] == "’" and e - 1 > s):
e -= 1
# drop trailing punctuation after an apostrophe (e.g. "δ’,")
chars = chars[s:e]
labels = {p - s: l for p, l in labels.items() if s <= p < e}
return "".join(chars), labels
def k_exact(w):
return w
def k_norm(w): # lowercase + grave->acute, length-preserving in NFC
out = []
for ch in w:
d = unicodedata.normalize("NFD", ch.lower())
d = "".join(GRAVE2ACUTE.get(c, c) for c in d)
out.append(nfc(d))
return "".join(out)
def k_bare(w): # no diacritics, lowercase, length-preserving
return "".join(unicodedata.normalize("NFD", ch.lower())[0] for ch in w)
KEYS = {"exact": k_exact, "norm": k_norm, "bare": k_bare}
# ---------- load Norma ----------
gold = [] # (split, source, line_idx, tokens[(word, labels)])
for split in ("test", "validation"):
for i, line in enumerate(open(os.path.join(norma_dir, split + ".jsonl"), encoding="utf-8")):
r = json.loads(line)
if r["task"] != "macronize":
continue
toks = [parse(t) for t in r["text"].split()]
toks = [t for t in toks if t[0]]
gold.append((split, r["source"], i, toks))
vocab = {k: set() for k in KEYS}
NG = 4
test_ngrams = set()
for _, _, _, toks in gold:
ws = [k_norm(w) for w, _ in toks]
for w, _ in toks:
for k, f in KEYS.items():
vocab[k].add(f(w))
for j in range(len(ws) - NG + 1):
test_ngrams.add(tuple(ws[j:j + NG]))
# ---------- scan silver ----------
freq = {k: collections.Counter() for k in KEYS} # key -> silver token count
lab = collections.defaultdict(collections.Counter) # (norm_key, pos) -> label counts
lab_bare = collections.defaultdict(collections.Counter) # (bare_key, pos) -> label counts
ng_hits = set()
n_sent = n_tok = 0
for f in sorted(glob.glob(os.path.join(silver_dir, "*.parquet"))):
pf = pq.ParquetFile(f)
for batch in pf.iter_batches(batch_size=50000, columns=["macronized"]):
for sent in batch.column(0).to_pylist():
n_sent += 1
ws = []
for t in sent.split():
w, labels = parse(t)
if not w:
continue
n_tok += 1
kn = k_norm(w)
ws.append(kn)
if w in vocab["exact"]:
freq["exact"][w] += 1
if kn in vocab["norm"]:
freq["norm"][kn] += 1
for p, l in labels.items():
lab[(kn, p)][l] += 1
kb = k_bare(w)
if kb in vocab["bare"]:
freq["bare"][kb] += 1
for p, l in labels.items():
lab_bare[(kb, p)][l] += 1
for j in range(len(ws) - NG + 1):
g = tuple(ws[j:j + NG])
if g in test_ngrams:
ng_hits.add(g)
print(f"{f}: {n_sent:,} sentences, {n_tok:,} tokens", file=sys.stderr, flush=True)
# ---------- per-token / per-vowel records ----------
rows = []
for split, src, li, toks in gold:
for ti, (w, labels) in enumerate(toks):
kn, kb = k_norm(w), k_bare(w)
for p, g in sorted(labels.items()) or [(None, None)]:
c = lab.get((kn, p), collections.Counter()) if p is not None else collections.Counter()
cb = lab_bare.get((kb, p), collections.Counter()) if p is not None else collections.Counter()
rows.append(dict(
split=split, source=src, line=li, tok=ti, word=w, pos=p, gold=g,
f_exact=freq["exact"][w], f_norm=freq["norm"][kn], f_bare=freq["bare"][kb],
s_short=c["^"], s_long=c["_"], sb_short=cb["^"], sb_long=cb["_"],
))
with open(os.path.join(out_dir, "per_vowel.jsonl"), "w", encoding="utf-8") as fh:
for r in rows:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
# line-level n-gram contamination
line_rows = []
for split, src, li, toks in gold:
ws = [k_norm(w) for w, _ in toks]
grams = [tuple(ws[j:j + NG]) for j in range(len(ws) - NG + 1)]
hit = sum(g in ng_hits for g in grams)
line_rows.append(dict(split=split, source=src, line=li, ngrams=len(grams), hits=hit))
with open(os.path.join(out_dir, "per_line.jsonl"), "w", encoding="utf-8") as fh:
for r in line_rows:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
print(json.dumps(dict(silver_sentences=n_sent, silver_tokens=n_tok)), file=sys.stderr)