Datasets:

Modalities:
Text
Formats:
json
Languages:
Thai
ArXiv:
License:
yacht's picture
Initial release
b35eaa3
Raw History Blame Contribute Delete
6.99 kB
"""Scoring of the Thai word-segmentation benchmark (standard library + NumPy).
Gold words are the [start, end) spans of a test row. A system's words are the maximal non-whitespace runs inside
its tokens, placed on the line by `align` (which tolerates dropped or merged spaces, spaces deleted inside a token,
Latin case changes, TLTK's <Fail> markup, and characters a system rewrote, dropped or inserted). Whitespace always
separates words and is never scored. Word F1 is corpus-level (micro); boundary F1 is khammoon's metric: the cut
points between two non-whitespace characters.
"""
from __future__ import annotations
import difflib
import gzip
import json
import re
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
WORD = re.compile(r"\S+")
def read_jsonl(path: Path) -> list[dict]:
opener = gzip.open if str(path).endswith(".gz") else open
with opener(path, "rt", encoding="utf-8") as f:
return [json.loads(line) for line in f]
def load_set(name: str, data_dir: Path = HERE / "data") -> list[dict]:
return read_jsonl(data_dir / f"{name}.jsonl")
# ---------------------------------------------------------------- alignment of system tokens to the line
def _match_skipping_spaces(text: str, q: int, tok: str):
chars, n = "".join(tok.split()), len(text)
if not chars:
return None
while q < n and text[q].isspace():
q += 1
s = i = q
for c in chars:
while i < n and text[i].isspace():
i += 1
if i >= n or text[i].lower() != c.lower():
return None
i += 1
return s, i
def _align_sequential(text: str, tokens: list[str]):
spans, pos, missing, n = [], 0, 0, len(text)
for tok in tokens:
tok = tok.replace("<Fail>", "").replace("</Fail>", "")
if not tok:
continue
s, q = None, pos
while True:
if text.startswith(tok, q) or text[q:q + len(tok)].lower() == tok.lower():
s = q
break
if q < n and text[q].isspace():
q += 1
continue
break
if s is None and (m := _match_skipping_spaces(text, pos, tok)):
s, e = m
spans.extend((s + w.start(), s + w.end()) for w in WORD.finditer(text[s:e]))
pos = e
continue
if s is None:
core = tok.strip()
if not core:
continue
k = text.find(core, pos)
if k < 0 or k - pos > 8:
missing += 1
continue
s, tok = k, core
e = s + len(tok)
spans.extend((s + m.start(), s + m.end()) for m in WORD.finditer(text[s:e]))
pos = e
return spans, missing
def _fold(c: str) -> str:
lc = c.lower()
return lc if len(lc) == 1 else c
def _align_characters(text: str, tokens: list[str]):
"""difflib alignment of the system's non-space characters to the line's (see the module docstring)."""
if "<Fail>" not in text:
tokens = [t.replace("<Fail>", "").replace("</Fail>", "") for t in tokens]
S, s_orig, forced, prev_ws = [], [], [], False
for i, c in enumerate(text):
if c.isspace():
prev_ws = True
continue
forced.append(prev_ws and bool(S))
S.append(c)
s_orig.append(i)
prev_ws = False
J, jb = [], []
for t in tokens:
first, prev_ws = True, False
for c in t:
if c.isspace():
prev_ws = True
continue
J.append(c)
jb.append(first or prev_ws)
first, prev_ws = False, False
n = len(S)
jfirst, jlast = [None] * n, [None] * n
sm = difflib.SequenceMatcher(None, [_fold(c) for c in J], [_fold(c) for c in S], autojunk=False)
for tag, a0, a1, b0, b1 in sm.get_opcodes():
if tag == "equal" or (tag == "replace" and a1 - a0 == b1 - b0):
for d in range(b1 - b0):
jfirst[b0 + d] = jlast[b0 + d] = a0 + d
elif tag == "replace":
for k in range(b0, b1):
jfirst[k], jlast[k] = a0, a1 - 1
spans, start = [], None
for k in range(n):
if jfirst[k] is None:
if start is not None:
spans.append((start, k))
start = None
continue
if start is None:
start = k
elif forced[k] or any(jb[m] for m in range(jlast[k - 1] + 1, jfirst[k] + 1)):
spans.append((start, k))
start = k
if start is not None:
spans.append((start, n))
return [(s_orig[a], s_orig[b - 1] + 1) for a, b in spans]
def align(text: str, tokens: list[str]) -> list[tuple[int, int]]:
"""A system's word spans on the line: in order, and by characters where a token cannot be placed."""
if "".join(tokens) == text:
spans, pos = [], 0
for t in tokens:
spans.extend((pos + m.start(), pos + m.end()) for m in WORD.finditer(t))
pos += len(t)
return spans
spans, missing = _align_sequential(text, tokens)
return _align_characters(text, tokens) if missing else spans
def word_spans(row: dict, pred: dict) -> set[tuple[int, int]]:
"""A prediction row is {"id", "tokens": [...]} or {"id", "words": [[start, end], ...]} (already placed)."""
if "words" in pred:
return set(map(tuple, pred["words"]))
return set(align(row["text"], pred["tokens"]))
# ---------------------------------------------------------------- metrics
def word_counts(rows: list[dict], preds: list[dict]) -> np.ndarray:
"""Per line: (correct words, predicted words, gold words)."""
assert len(rows) == len(preds), (len(rows), len(preds))
out = np.zeros((len(rows), 3), np.int64)
for i, (r, p) in enumerate(zip(rows, preds)):
P, G = word_spans(r, p), set(map(tuple, r["gold"]))
out[i] = (len(P & G), len(P), len(G))
return out
def boundary_counts(rows: list[dict], preds: list[dict]) -> np.ndarray:
"""Per line: (correct, predicted, gold) cut points between two non-whitespace characters."""
def cuts(text, spans):
pts = {p for s, e in spans for p in (s, e)}
return {p for p in pts if 0 < p < len(text) and not text[p - 1].isspace() and not text[p].isspace()}
out = np.zeros((len(rows), 3), np.int64)
for i, (r, p) in enumerate(zip(rows, preds)):
P, G = cuts(r["text"], word_spans(r, p)), cuts(r["text"], r["gold"])
out[i] = (len(P & G), len(P), len(G))
return out
def f1(c: np.ndarray) -> np.ndarray:
"""F1 (%) of (correct, predicted, gold) in the last axis."""
return 100 * 2 * c[..., 0] / np.maximum(c[..., 1] + c[..., 2], 1)
def bootstrap_weights(n: int, seed: int, rounds: int = 1000) -> np.ndarray:
"""Resampling weights of n lines (the same for every system: paired)."""
return np.random.default_rng(seed).multinomial(n, np.full(n, 1.0 / n), size=rounds)