File size: 5,577 Bytes
c266841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""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)