File size: 9,486 Bytes
6bd4371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
'''
Norma Syllabarum Graecarum loading and scoring, for the HF dataset layout
(https://huggingface.co/datasets/Urdatorn/norma: data/test.jsonl and
data/validation.jsonl, one {"text", "source", "task"} record per line).

Scored positions are the gold-marked (^ or _) dichrona in open syllables,
as in the original eval_norma.py:

- test: every source ships a "macronize" and a "syllabify" version of each
  line, in the same order. The syllabify line gives syllable openness, which
  is carried over to the macronize line with a difflib alignment.
- validation: there are no syllabify lines, so every gold mark is scored.

The bracket-tiling, open-syllable and alignment helpers are taken from
grc-macronizer/macron_model/eval_norma.py (commit 456c970).

Metrics (`metrics()`), following Table 1 of the paper:
- per label (long "_", short "^"): accuracy = recall = correct / gold
  positions with that label; precision = correct / predictions of that
  label; F1; coverage = share of those gold positions that got any mark.
- mixed (micro-averaged): accuracy = recall = correct / all positions,
  with an unmarked position counted as wrong; precision = correct / marked
  positions; F1 is their harmonic mean; coverage = marked / all positions.
  This reproduces every mixed row of Table 1 from its per-label counts.
- default_short_accuracy: like mixed accuracy, but an unmarked position
  counts as a "short" guess (the model cards' headline number).
'''

import collections
import difflib
import json
import re
import unicodedata
from dataclasses import dataclass
from typing import Dict, List, Optional

from grc_utils import vowel
from huggingface_hub import hf_hub_download

DEFAULT_REPO = "Urdatorn/norma"
MARK_CHARS = "^_"
SHORT, LONG = "^", "_"


def nfc(s):
    return unicodedata.normalize("NFC", s)


# ---------------------------------------------------------------------------
# Helpers from eval_norma.py
# ---------------------------------------------------------------------------

_BETWEEN_BRACKETS_RE = re.compile(r'([\]\}])([^\[\]\{\}]+)([\[\{])')
_TRAILING_RE = re.compile(r'([\]\}])([^\[\]\{\}]+)$')
_LEADING_RE = re.compile(r'^([^\[\{]+)([\[\{])')
_BRACKET_RE = re.compile(r'([\[\{])([^\[\]\{\}]*)([\]\}])')


def _move_text_into_brackets(line):
    prev = None
    while prev != line:
        prev = line
        line = _BETWEEN_BRACKETS_RE.sub(
            lambda m: m.group(1)[:-1] + m.group(2) + m.group(1)[-1] + m.group(3), line)
    m = _TRAILING_RE.search(line)
    if m:
        line = line[: m.start()] + m.group(1)[:-1] + m.group(2) + m.group(1)[-1]
    m = _LEADING_RE.match(line)
    if m:
        line = m.group(2) + m.group(1) + line[m.end():]
    return line


def _syllable_is_open(content):
    core = content
    while core and not core[-1].isalpha():
        core = core[:-1]
    return bool(core) and vowel(core[-1])


def parse_syllabify_line(line):
    chars, opens = [], []
    for m in _BRACKET_RE.finditer(_move_text_into_brackets(line)):
        content = m.group(2)
        is_open = _syllable_is_open(content)
        chars.extend(content)
        opens.extend([is_open] * len(content))
    return "".join(chars), opens


def parse_marked_line(line):
    plain, marks = [], []
    i, n = 0, len(line)
    while i < n:
        ch = line[i]
        if ch in MARK_CHARS:
            i += 1
            continue
        nxt = line[i + 1] if i + 1 < n else ""
        if nxt and nxt in MARK_CHARS:
            plain.append(ch)
            marks.append(nxt)
            i += 2
        else:
            plain.append(ch)
            marks.append(None)
            i += 1
    return "".join(plain), marks


def _align_flags(src_text, src_flags, dst_text):
    out = [None] * len(dst_text)
    sm = difflib.SequenceMatcher(None, src_text, dst_text, autojunk=False)
    for tag, i1, i2, j1, j2 in sm.get_opcodes():
        if tag == "equal":
            for k in range(i2 - i1):
                out[j1 + k] = src_flags[i1 + k]
    return out


def _map_output_onto_reference(output_plain, ref_plain):
    ref_to_out = [None] * len(ref_plain)
    sm = difflib.SequenceMatcher(None, output_plain.lower(), ref_plain.lower(), autojunk=False)
    for tag, i1, i2, j1, j2 in sm.get_opcodes():
        if tag == "equal":
            for k in range(i2 - i1):
                ref_to_out[j1 + k] = i1 + k
    return ref_to_out


# ---------------------------------------------------------------------------
# Loading
# ---------------------------------------------------------------------------

@dataclass
class LineRecord:
    source: str
    line_idx: int            # index within this source's macronize lines
    plain: str               # input text, marks stripped
    gold_marks: List[Optional[str]]
    scored: List[bool]       # position is part of the evaluation set


def load_split(split, repo_id=DEFAULT_REPO, revision=None, path=None):
    if path is None:
        path = hf_hub_download(repo_id, f"data/{split}.jsonl", repo_type="dataset",
                               revision=revision)
    mac, syl = collections.defaultdict(list), collections.defaultdict(list)
    with open(path, encoding="utf-8") as fh:
        for line in fh:
            r = json.loads(line)
            (mac if r["task"] == "macronize" else syl)[r["source"]].append(nfc(r["text"]))

    records = []
    for source, lines in mac.items():
        slines = syl.get(source)
        if slines is not None and len(slines) != len(lines):
            raise ValueError(f"{split}/{source}: {len(lines)} macronize vs {len(slines)} syllabify lines")
        for k, mline in enumerate(lines):
            plain, marks = parse_marked_line(mline)
            if slines is not None:
                sp_text, sp_opens = parse_syllabify_line(slines[k])
                opens = _align_flags(sp_text, sp_opens, plain)
            else:
                opens = [True] * len(plain)
            scored = [bool(o) and m is not None for o, m in zip(opens, marks)]
            records.append(LineRecord(source, k, plain, marks, scored))
    return records


# ---------------------------------------------------------------------------
# Scoring
# ---------------------------------------------------------------------------

def _word_at(text, j):
    s = text.rfind(" ", 0, j) + 1
    e = text.find(" ", j)
    return text[s: e if e != -1 else len(text)]


def score(records, outputs):
    '''Returns one dict per scored position: source, line, char, word, gold, pred.'''
    assert len(records) == len(outputs)
    positions = []
    for rec, out in zip(records, outputs):
        out_plain, out_marks = parse_marked_line(nfc(out))
        ref_to_out = _map_output_onto_reference(out_plain, rec.plain)
        for j, is_scored in enumerate(rec.scored):
            if not is_scored:
                continue
            oi = ref_to_out[j]
            positions.append(dict(
                source=rec.source, line=rec.line_idx, char=j, word=_word_at(rec.plain, j),
                gold=rec.gold_marks[j], pred=out_marks[oi] if oi is not None else None,
            ))
    return positions


def _label_stats(positions, label):
    gold = [p for p in positions if p["gold"] == label]
    n_pred = sum(p["pred"] == label for p in positions)
    tp = sum(p["pred"] == label for p in gold)
    r = tp / len(gold) if gold else 0.0
    pr = tp / n_pred if n_pred else 0.0
    f1 = 2 * pr * r / (pr + r) if pr + r else 0.0
    cov = sum(p["pred"] is not None for p in gold) / len(gold) if gold else 0.0
    return dict(n=len(gold), accuracy=r, precision=pr, recall=r, f1=f1, coverage=cov)


def metrics(positions, by_source=True):
    n = len(positions)
    out = {"n": n}
    if not n:
        return out
    lab = {"long": _label_stats(positions, LONG), "short": _label_stats(positions, SHORT)}
    out.update(lab)
    correct = sum(p["pred"] == p["gold"] for p in positions)
    n_pred = sum(p["pred"] is not None for p in positions)
    mp, mr = (correct / n_pred if n_pred else 0.0), correct / n
    out["mixed"] = dict(  # micro-averaged over the two labels, as in Table 1
        n=n, accuracy=mr, precision=mp, recall=mr,
        f1=2 * mp * mr / (mp + mr) if mp + mr else 0.0,
        coverage=n_pred / n,
    )
    out["default_short_accuracy"] = sum((p["pred"] or SHORT) == p["gold"] for p in positions) / n
    out["constant_short_accuracy"] = sum(p["gold"] == SHORT for p in positions) / n
    if by_source:
        per = collections.defaultdict(list)
        for p in positions:
            per[p["source"]].append(p)
        out["per_source"] = {s: metrics(ps, by_source=False) for s, ps in sorted(per.items())}
    return out


def format_table(m):
    rows = ["label    n      Acc     P       R       F1      Cov"]
    for k in ("long", "short", "mixed"):
        s = m[k]
        rows.append(f"{k:<8} {s['n']:<6} {100*s['accuracy']:6.1f}  {100*s['precision']:6.1f}  "
                    f"{100*s['recall']:6.1f}  {100*s['f1']:6.1f}  {100*s['coverage']:6.1f}")
    rows.append(f"defaults-to-short accuracy: {100*m['default_short_accuracy']:.2f}   "
                f"constant-short: {100*m['constant_short_accuracy']:.2f}")
    if "per_source" in m:
        rows.append("source           n     mixed-Acc  mixed-F1  Cov")
        for s, ms in m["per_source"].items():
            rows.append(f"  {s:<14} {ms['n']:<5} {100*ms['mixed']['accuracy']:8.1f}  "
                        f"{100*ms['mixed']['f1']:8.1f}  {100*ms['mixed']['coverage']:5.1f}")
    return "\n".join(rows)