File size: 19,573 Bytes
0e6d825 | 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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | """Build the test files of this benchmark from their original sources, byte for byte.
python build_testsets.py # the files that may not be shared: download, build, check
python build_testsets.py --all [--raw DIR] [--out DIR] # every gold file from its source, checked (default out: rebuilt/)
Every original file is pinned in sources.json (a URL at a fixed revision and its SHA-256); every file built here is
pinned in checksums.json. benchmark.py, score.py and add_system.py call `prepare()` on their first run, which builds
the files that this repository does not include because their source has no licence that allows sharing them.
`--all` rebuilds the included files too, to show that each one comes from its source unchanged.
The steps are those that built benchmark 1.0 (frozen 2026-11-23), unchanged:
- sentence sets: UD_Thai-PUD test, the sentences of each article (sent_id[:6]) in order, joined with one space;
OPUS-100 en-th test, the Thai side without empty lines, blocks of 10 sentences joined with one space;
sukity/thai-sentence-boundaries, the passages, sentence ends found in whitespace-free coordinates;
ALT test split, the Thai side, one document per article in URL-test.txt, its sentences in line-number order joined
with one space (articles with a line cut into parts or two lines with one number are left out);
SET-nospace: every whitespace character removed; SET-asr: whitespace and Unicode punctuation (category P) removed;
gold ends move with the text, a sentence left empty is dropped.
- treebanks (CoNLL-U): each sentence keeps only its `# sent_id` and `# text = ` comments, LEMMA and DEPS become `_`;
SET.txt holds each sentence's text, one per line.
- the TUD paper's stored predictions: the trees of its best parser without POS input with the UPOS of its tagger
(tud-paper-best), and the trees of the same parser given its tagger's POS (paper-stanza-autopos).
- clause sets: one document per gold tree of the UD test file, the character offsets where its clause units end,
read off the tree by the rules of clause_heads, edu_spans and edu_ends below.
Python 3.9 or later; NumPy is not needed here, pyarrow only for OPUS-100 (a parquet file).
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import re
import sys
import unicodedata
import urllib.request
import zipfile
from collections import OrderedDict, defaultdict
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from scoring.conllu import format_sentence, read_conllu # noqa: E402 (the scorer's own reader, unchanged)
PUD = "ud/UD_Thai-PUD/th_pud-ud-test.conllu"
TUD = "ud/UD_Thai-TUD/th_tud-ud-test.conllu"
TDT = "ud/UD_Thai-TDT/th_tdt-ud-test.conllu"
TUDP = "nlp-chula-TUD/TUD/test.conllu"
PAPER_TREES = "nlp-chula-TUD/Prediction/tud-stanza-phayathai-agnostic_pos.conllu"
PAPER_TAGS = "nlp-chula-TUD/Prediction/tud-stanza-phayathai-auto_pos.conllu"
OPUS = "opus-100/en-th/test-00000-of-00001.parquet"
SUKITY = "thai-sentence-boundaries/data/all.jsonl"
ALT_ZIP = "alt/ALT-Parallel-Corpus-20191206.zip"
ALT_URLS = "alt/URL-test.txt"
ALT_TH = "ALT-Parallel-Corpus-20191206/data_th.txt"
USER_AGENT = "thai-benchmark-build"
def release() -> dict:
return json.loads((HERE / "release.json").read_text(encoding="utf-8"))
def checksums() -> dict:
return json.loads((HERE / "checksums.json").read_text(encoding="utf-8"))
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def fetch(raw: Path, keys: list[str], quiet: bool = False) -> None:
"""Download the given original files (keys of sources.json) into raw/, each checked against its SHA-256."""
files = json.loads((HERE / "sources.json").read_text(encoding="utf-8"))["files"]
for key in keys:
info, dest = files[key], raw / key
if dest.is_file() and sha256(dest) == info["sha256"]:
if not quiet:
print(f"ok {key}")
continue
dest.parent.mkdir(parents=True, exist_ok=True)
print(f"fetch {key} ({info['licence']})", flush=True)
part = dest.with_name(dest.name + ".part")
req = urllib.request.Request(info["url"], headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=300) as r, part.open("wb") as f:
while chunk := r.read(1 << 20):
f.write(chunk)
got = sha256(part)
if got != info["sha256"]:
part.unlink()
raise SystemExit(f"{key}: SHA-256 {got}, not the pinned {info['sha256']}: the upstream file changed")
part.replace(dest)
# ------------------------------------------------------------------------------------------------ sentence sets
def _join(sents: list[str], sep: str = " ") -> tuple[str, list[int]]:
text, ends = "", []
for k, s in enumerate(sents):
s = s.strip()
if k:
text += sep
text += s
ends.append(len(text))
return text, ends
def sent_pud(raw: Path) -> list[dict]:
docs: OrderedDict[str, list[str]] = OrderedDict()
for s in read_conllu(raw / PUD):
docs.setdefault(s.sent_id[:6], []).append(s.text)
out = []
for doc, sents in docs.items():
text, ends = _join(sents)
out.append({"id": f"pud-{doc}", "text": text, "ends": ends, "register": "news" if doc[0] == "n" else "wiki"})
return out
def sent_opus100(raw: Path, block: int = 10) -> list[dict]:
import pyarrow.parquet as pq
th = [r["translation"]["th"] for r in pq.read_table(raw / OPUS).to_pylist()]
th = [t for t in th if t.strip()]
out = []
for i in range(0, len(th), block):
text, ends = _join(th[i:i + block])
out.append({"id": f"opus100-{i // block:04d}", "text": text, "ends": ends, "register": "opus100"})
return out
def sent_sukity(raw: Path) -> list[dict]:
out = []
for i, line in enumerate(open(raw / SUKITY, encoding="utf-8")):
r = json.loads(line)
text = r["text"]
# matched in whitespace-free coordinates: poetry breaks lines inside a sentence
orig = [j for j, ch in enumerate(text) if not ch.isspace()]
flat = "".join(text[j] for j in orig)
pos, ends = 0, []
for s in r["sentences"]:
k = "".join(s.split())
a = flat.index(k, pos)
pos = a + len(k)
ends.append(orig[pos - 1] + 1)
assert pos == len(flat), f"text after the last sentence in record {i}"
out.append({"id": f"sukity-{i:04d}", "text": text, "ends": ends, "register": r["register"]})
return out
ALT_KEY = re.compile(r"^\s*SNT\.(\d+)\.(\d+)([-−]\d*)?\s*\t(.*)$")
def sent_alt(raw: Path) -> list[dict]:
"""Sentence ids are SNT.<article>.<line number>; articles with a line cut into parts (<n>-1) or two lines with
one number are left out (whether the parts are sentences, or the order of the lines, is unclear)."""
sents: dict[str, list[tuple[int, str]]] = defaultdict(list)
cut: set[str] = set()
with zipfile.ZipFile(raw / ALT_ZIP) as z, z.open(ALT_TH) as f:
for line in io.TextIOWrapper(f, encoding="utf-8"): # universal newlines, as open() (the file has CRLF)
m = ALT_KEY.match(line.rstrip("\n"))
if not m:
raise ValueError(f"unparsed line: {line[:80]!r}")
art, num, part, text = m.groups()
if part is not None:
cut.add(art)
if text.strip():
if any(n == int(num) for n, _ in sents[art]):
cut.add(art)
sents[art].append((int(num), " ".join(text.split())))
docs = []
for line in open(raw / ALT_URLS, encoding="utf-8"):
if not line.strip():
continue
art = line.split("\t")[0].removeprefix("URL.")
rows = sorted(sents.get(art, []))
if art in cut or not rows:
continue
text, ends = "", []
for k, (_, s) in enumerate(rows):
text += (" " if k else "") + s
ends.append(len(text))
docs.append({"id": f"alt-{art}", "text": text, "ends": ends, "register": "news"})
return docs
DROP = {"nospace": lambda ch: ch.isspace(),
"asr": lambda ch: ch.isspace() or unicodedata.category(ch).startswith("P")}
def derive(doc: dict, drop) -> dict:
"""The document without the dropped characters; an end moves to after the last kept character before it."""
keep = [j for j, ch in enumerate(doc["text"]) if not drop(ch)]
text = "".join(doc["text"][j] for j in keep)
ends, k = [], 0
for e in doc["ends"]:
while k < len(keep) and keep[k] < e:
k += 1
if k and (not ends or ends[-1] < k):
ends.append(k)
if not ends or ends[-1] != len(text):
ends = [x for x in ends if x < len(text)] + [len(text)]
return {**doc, "text": text, "ends": ends}
def _jsonl(rows: list[dict]) -> bytes:
return "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows).encode("utf-8")
def _sentence_files(name: str, docs: list[dict]) -> dict[str, bytes]:
out = {f"data/sentences/{name}.jsonl": _jsonl(docs)}
for cond, drop in DROP.items():
out[f"data/sentences/{name}-{cond}.jsonl"] = _jsonl([derive(d, drop) for d in docs])
return out
# ------------------------------------------------------------------------------------------------ treebanks
def _syntax_files(name: str, src: Path) -> dict[str, bytes]:
sents = read_conllu(src)
for s in sents: # the gold file keeps sent_id and text only
s.comments = [c for c in s.comments if c.startswith(("# sent_id", "# text = "))]
return {f"data/syntax/{name}.conllu": "".join(format_sentence(s) for s in sents).encode("utf-8"),
f"data/syntax/{name}.txt": "".join(s.text + "\n" for s in sents).encode("utf-8")}
def _paper_best(raw: Path) -> dict[str, bytes]:
"""The TUD paper's stored test predictions: the trees of Stanza + PhayaThaiBERT given no POS (its best parser,
Table 4: UAS 87.39, LAS 78.09) with the UPOS of its PhayaThaiBERT tagger (the auto_pos file)."""
tree, tags = read_conllu(raw / PAPER_TREES), read_conllu(raw / PAPER_TAGS)
for t, g in zip(tree, tags):
for wt, wg in zip(t.words, g.words):
assert wt.form == wg.form
wt.upos = wg.upos
return {"predictions/tud-paper-best/syntax/tudp.gold.conllu": "".join(format_sentence(s) for s in tree).encode("utf-8")}
def _paper_autopos(raw: Path) -> dict[str, bytes]:
"""The TUD paper's stored test predictions of Stanza + PhayaThaiBERT given its tagger's POS (Table 4: UAS 86.93,
LAS 77.51): the auto_pos file, read and written by the scorer's reader."""
return {"predictions/paper-stanza-autopos/syntax/tudp.gold.conllu":
"".join(format_sentence(s) for s in read_conllu(raw / PAPER_TAGS)).encode("utf-8")}
# ------------------------------------------------------------------------------------------------ clause units
# The rules of benchmark 1.0's clause sets (its builder's clause_heads, edu_spans and edu_ends, unchanged): a clause
# starts at the root and at every predicate attached by a clausal relation (advcl, ccomp, csubj, parataxis, list), and
# at a conj that is a predicate (VERB, AUX, ADJ, or with a subject, object, copula or clausal subject); acl, xcomp and
# compound start none. Every word belongs to its nearest clause head up the tree (itself included), so a connective
# (mark, cc) opens the unit of its clause. A unit is a maximal run of words with the same clause: a clause interrupted
# by an embedded one gives two runs. Relation subtypes are ignored.
CLAUSAL = {"root", "advcl", "ccomp", "csubj", "parataxis", "list"}
PREDICATE_UPOS = {"VERB", "AUX", "ADJ"}
def clause_heads(sent) -> set[int]:
words = sent.words
deps: dict[int, list[int]] = {}
for i, w in enumerate(words, 1):
deps.setdefault(w.head, []).append(i)
heads = set()
for i, w in enumerate(words, 1):
rel = w.deprel.split(":")[0]
if rel in CLAUSAL or w.head == 0:
heads.add(i)
elif rel == "conj":
kids = {words[k - 1].deprel.split(":")[0] for k in deps.get(i, [])}
if w.upos in PREDICATE_UPOS or kids & {"nsubj", "obj", "cop", "csubj"}:
heads.add(i)
return heads
def edu_spans(sent) -> list[tuple[int, int]]:
"""Clause units as word index ranges [a, b) (0-based)."""
words = sent.words
heads = clause_heads(sent)
def owner(i: int) -> int:
seen = 0
while i not in heads and i != 0 and seen < len(words) + 1:
i = words[i - 1].head
seen += 1
return i
own = [owner(i) for i in range(1, len(words) + 1)]
spans, a = [], 0
for k in range(1, len(words) + 1):
if k == len(words) or own[k] != own[a]:
spans.append((a, k))
a = k
return spans
def edu_ends(sent) -> list[int]:
"""Character offsets (in sent.text) where clause units end, the last one = the sentence end."""
return [sent.words[b - 1].end for _, b in edu_spans(sent)]
def _clause_files(name: str, src: Path) -> dict[str, bytes]:
"""One document per gold tree of the UD test file, as read (sent_id and text of the original comments)."""
return {f"data/clauses/{name}.jsonl": _jsonl([{"id": s.sent_id, "text": s.text, "ends": edu_ends(s), "register": name}
for s in read_conllu(src)])}
def penn_check(raw: Path, data: Path) -> tuple[list[str], dict]:
"""The Penn trees are the 1.0 file (a conversion of the gold TUD trees by research code that is not published).
Checked here: every tree's words, its leaves and its text are those of the UD_Thai-TUD test sentence with the
same sent_id, and its brackets are the ones the scorer counts from the tree."""
import bench
ud = {s.sent_id: s for s in read_conllu(raw / TUD)}
rows = [json.loads(x) for x in open(data / "penn/tud.jsonl", encoding="utf-8")]
bad = []
for r in rows:
s = ud.get(r["sent_id"])
if s is None:
bad.append(f"{r['sent_id']}: no UD_Thai-TUD test sentence with this sent_id")
continue
words = [w.form for w in s.words]
leaves, brackets = bench.penn_brackets(r["tree"])
for what, ok in (("words", r["words"] == words), ("leaves of the tree", leaves == words),
("text", r["text"] == s.text), ("brackets", r["brackets"] == brackets)):
if not ok:
bad.append(f"{r['sent_id']}: {what} differ")
info = {"trees": len(rows), "UD_Thai-TUD test sentences": len(ud),
"without a tree": sorted(set(ud) - {r["sent_id"] for r in rows})}
return bad, info
def groups() -> dict:
"""Each group: the original files it needs (keys of sources.json) and its builder, raw -> {path: bytes}."""
return {
"sentences/pud": ([PUD], lambda raw: _sentence_files("pud", sent_pud(raw))),
"sentences/opus100": ([OPUS], lambda raw: _sentence_files("opus100", sent_opus100(raw))),
"sentences/sukity": ([SUKITY], lambda raw: _sentence_files("sukity", sent_sukity(raw))),
"sentences/alt": ([ALT_ZIP, ALT_URLS], lambda raw: _sentence_files("alt", sent_alt(raw))),
"syntax/tud": ([TUD], lambda raw: _syntax_files("tud", raw / TUD)),
"syntax/pud": ([PUD], lambda raw: _syntax_files("pud", raw / PUD)),
"syntax/tdt": ([TDT], lambda raw: _syntax_files("tdt", raw / TDT)),
"syntax/tudp": ([TUDP], lambda raw: _syntax_files("tudp", raw / TUDP)),
"predictions/tud-paper-best": ([PAPER_TREES, PAPER_TAGS], _paper_best),
"predictions/paper-stanza-autopos": ([PAPER_TAGS], _paper_autopos),
"clauses/tud": ([TUD], lambda raw: _clause_files("tud", raw / TUD)),
"clauses/pud": ([PUD], lambda raw: _clause_files("pud", raw / PUD)),
"clauses/tdt": ([TDT], lambda raw: _clause_files("tdt", raw / TDT)),
"penn/tud": ([TUD], None), # checked, not built: see penn_check
}
def build(names: list[str], raw: Path, out: Path, write_bad: bool = False) -> list[str]:
"""Build the groups into out/; return the files whose SHA-256 differs from checksums.json. A file that differs
is written only with write_bad (for a look at it), never into the benchmark itself."""
want, bad = checksums(), []
for name in names:
keys, builder = groups()[name]
fetch(raw, keys, quiet=True)
if builder is None:
continue
for rel, blob in builder(raw).items():
same = hashlib.sha256(blob).hexdigest() == want[rel]
print(f"{'identical' if same else 'DIFFERENT'} {rel}", flush=True)
if not same:
bad.append(rel)
if same or write_bad:
(out / rel).parent.mkdir(parents=True, exist_ok=True)
(out / rel).write_bytes(blob)
return bad
def missing() -> list[str]:
"""The groups to build here: not included in the repository, and not built yet (or changed)."""
want = checksums()
return [g for g, info in release()["groups"].items() if info["mode"] == "built"
and not all((HERE / f).is_file() and sha256(HERE / f) == want[f] for f in info["files"])]
def prepare(raw: Path | None = None) -> None:
"""Build, once, the test files whose source does not allow sharing them (benchmark.py calls this)."""
todo = missing()
if not todo:
return
files = json.loads((HERE / "sources.json").read_text(encoding="utf-8"))["files"]
keys = sorted({k for g in todo for k in groups()[g][0]})
size = sum(files[k].get("bytes", 0) for k in keys) / 1e6
print(f"First run: {', '.join(g.split('/')[1] for g in todo)} may not be shared, so the original files are "
f"downloaded from their owners ({size:.1f} MB), checked and built here, once.", flush=True)
bad = build(todo, raw or HERE / "raw", HERE)
if bad:
raise SystemExit(f"these files differ from the published ones, nothing was written for them: {bad}")
print("Test files ready.\n", flush=True)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--all", action="store_true", help="rebuild every gold file from its source, also the included ones")
ap.add_argument("--raw", type=Path, default=HERE / "raw", help="where the original files are downloaded")
ap.add_argument("--out", type=Path, default=None, help="where --all writes the files it builds (default: rebuilt/)")
a = ap.parse_args()
if not a.all:
prepare(a.raw)
print("every test file is present and identical to the published one")
return
out = a.out or HERE / "rebuilt"
names = list(release()["groups"])
bad = build(names, a.raw, out, write_bad=True)
if "penn/tud" in names:
problems, info = penn_check(a.raw, HERE / "data")
print(f"penn/tud: {info['trees']} trees, every one with the words, leaves, text and brackets of its UD_Thai-TUD "
f"test sentence: {not problems}; test sentences without a tree: {info['without a tree']}")
bad += problems
print("every file identical to the published one" if not bad else f"DIFFERENT: {bad}")
raise SystemExit(1 if bad else 0)
if __name__ == "__main__":
main()
|