"""Rebuild the Thai word-segmentation test sets from their original sources, byte for byte. python fetch_sources.py # downloads the original files into raw/ (see sources.json) python build_testsets.py # raw/ -> data/*.jsonl, then checks every file against checksums.json Requirements: Python 3.9+, pandas with pyarrow (BEST is a parquet file). Every set is natural text: one row per line, {"id", "text", "gold": [[start, end], ...]} where the gold words are the maximal non-whitespace runs of the source's tokens (a space always separates words; whitespace is never scored). Splits of BEST and ORCHID, which have no official test split with gold boundaries, are seeded 80/10/10 shuffles (seed 112, as LATTE). Sets: tud, pud (+ pudA, pudB: halves for choosing a unit), ws1000, ws160, vistec, best, bestdd, bestdev, orchidnho, orchidndd, orchiddev, khm, khmdd. `dd`: test lines that (nearly) repeat the training text are removed: equal to a line of it after removing whitespace, or at least 80% of their 12-character shingles (every 4th) found in it. bestdd and orchidndd against the train+dev part of their corpus, khmdd against khammoon's training text. Exact string matching throughout, so the result is deterministic. """ from __future__ import annotations import argparse import gzip import hashlib import json import random import re from pathlib import Path HERE = Path(__file__).resolve().parent SEED = 112 K, STRIDE, NEAR = 12, 4, 0.8 WS = re.compile(r"\s+") RUN = re.compile(r"\S+") ORCHID_TAGS = {"": " ", "": "-", "": ".", "": "(", "": ")", "": '"', "": ",", "": "/", "": "=", "": ":", "": "*", "": "+", "": ">", "": ";", "": "<", "": "'", "": "$", "": "#", "": "&", "": "?", "": "^", "": "{", "": "}", "": "!", "": "@"} def spans_of(tokens: list[str]) -> tuple[str, list[list[int]]]: """Text = the tokens joined; gold = every maximal non-whitespace run inside a token.""" text, gold, pos = "", [], 0 for tok in tokens: gold.extend([pos + m.start(), pos + m.end()] for m in RUN.finditer(tok)) text += tok pos += len(tok) return text, gold def shuffled(n: int) -> list[int]: idx = list(range(n)) random.Random(SEED).shuffle(idx) return idx def repeats(tests: list[str], refs: list[str]) -> list[bool]: """Which test texts (nearly) repeat the reference texts (whitespace ignored).""" tests = [WS.sub("", t) for t in tests] found = {t[i:i + K]: False for t in tests for i in range(0, len(t) - K + 1, STRIDE)} lines = set(tests) exact = set() for r in refs: r = WS.sub("", r) if r in lines: exact.add(r) for i in range(len(r) - K + 1): if r[i:i + K] in found: found[r[i:i + K]] = True out = [] for t in tests: g = [t[i:i + K] for i in range(0, len(t) - K + 1, STRIDE)] out.append(t in exact or (bool(g) and sum(found[x] for x in g) / len(g) >= NEAR)) return out # ---------------------------------------------------------------- sources def ud(path: Path) -> list[dict]: """CoNLL-U -> natural text: a space follows a token unless SpaceAfter=No; gold = the word forms.""" sents, toks = [], [] for line in path.read_text(encoding="utf-8").splitlines(): if not line.strip(): if toks: sents.append(toks) toks = [] continue if line.startswith("#"): continue cols = line.split("\t") if "-" in cols[0] or "." in cols[0]: continue toks.append(cols[1]) if "SpaceAfter=No" not in cols[9]: toks.append(" ") if toks: sents.append(toks) rows = [] for toks in sents: while toks and toks[-1] == " ": toks.pop() text, gold = spans_of(toks) rows.append({"text": text, "gold": gold}) return rows def wisesight(path: Path) -> list[dict]: """'|'-separated tokens, space tokens included.""" opener = gzip.open if path.suffix == ".gz" else open with opener(path, "rt", encoding="utf-8") as f: return [dict(zip(("text", "gold"), spans_of(line.rstrip("\n").split("|")))) for line in f if line.strip()] def vistec(path: Path) -> list[dict]: """VISTEC-TP-TH-2021: '|'-separated tokens with markup (, , ): the markup is removed and the written surface kept.""" tag = re.compile(r"<[^>]*>") with open(path, encoding="utf-8") as f: return [dict(zip(("text", "gold"), spans_of(tag.sub("", line.rstrip("\n")).split("|")))) for line in f if line.strip()] def best_lines(path: Path) -> list[list[str]]: """BEST 2009 (nectec/best2009 train.parquet): characters with word-start flags -> words, spaces kept.""" import pandas as pd df = pd.read_parquet(path) lines = [] for chars, begins in zip(df["char"], df["is_beginning"]): words, cur = [], "" for ch, beg in zip(chars, begins): if beg == 1 and cur: words.append(cur) cur = "" cur += ch if cur: words.append(cur) if any(w.strip() for w in words): lines.append(words) return lines def orchid_sentences(path: Path) -> list[list[str]]: """ORCHID 1997 (orchid97.crp.utf): every Thai sentence from its word lines, tags mapped back to their characters and to a space (English sentences, '%E ...', have no word lines and are skipped).""" outside, raw_text, in_words = 0, 1, 2 out, raw, toks, state = [], "", [], outside for line in path.open(encoding="utf-8"): line = line.rstrip("\n") if state == outside: if line.startswith("#") and line[1:].isdigit(): state, raw = raw_text, "" elif state == raw_text: raw += line if line.endswith("//"): state, toks = (outside if raw.startswith("%E") else in_words), [] elif line == "//": if any(w and w != "" for w in (t.replace(" ", "") for t in toks)): out.append([ORCHID_TAGS.get(t, t) for t in toks]) state = outside else: toks.append(line.rsplit("/", 1)[0]) return out def khm(path: Path) -> list[dict]: """khammoon's human test documents, split at newlines into lines (no gold word crosses a newline).""" out = [] for d, line in enumerate(path.open(encoding="utf-8")): r = json.loads(line) text = r["text"] assert "".join(r["tokens"]) == text _, spans = spans_of(r["tokens"]) start, k = 0, 0 for part in text.split("\n"): end = start + len(part) gold = [] while k < len(spans) and spans[k][1] <= end: gold.append([spans[k][0] - start, spans[k][1] - start]) k += 1 if part.strip(): out.append({"doc": d, "text": part, "gold": gold}) start = end + 1 assert k == len(spans) return out # ---------------------------------------------------------------- build def build_open(raw: Path) -> dict[str, list[dict]]: """The sets whose licence allows sharing them (they are in data/ already).""" sets: dict[str, list[dict]] = {} sets["tud"] = ud(raw / "ud/UD_Thai-TUD/th_tud-ud-test.conllu") sets["pud"] = ud(raw / "ud/UD_Thai-PUD/th_pud-ud-test.conllu") order = shuffled(len(sets["pud"])) half = len(order) // 2 for name, part in (("pudA", sorted(order[:half])), ("pudB", sorted(order[half:]))): sets[name] = [{"src_id": i, **sets["pud"][i]} for i in part] sets["ws1000"] = wisesight(raw / "wisesight1000/wisesight-1000-samples-tokenised.label.gz") sets["ws160"] = wisesight(raw / "wisesight1000/wisesight-160-samples-tokenised.label") sets["vistec"] = vistec(raw / "vistec/test.txt") return sets def build_best(raw: Path) -> dict[str, list[dict]]: lines = best_lines(raw / "best2009/train.parquet") idx = shuffled(len(lines)) cut1, cut2 = int(0.8 * len(idx)), int(0.9 * len(idx)) rows = [dict(zip(("text", "gold"), spans_of(lines[i]))) for i in idx[cut2:]] sets = {"best": rows, "bestdev": [dict(zip(("text", "gold"), spans_of(lines[i]))) for i in idx[cut1:cut2]]} dup = repeats([r["text"] for r in rows], ["".join(lines[i]) for i in idx[:cut2]]) sets["bestdd"] = [{"src_id": k, **r} for k, (r, d) in enumerate(zip(rows, dup)) if not d] return sets def build_orchid(raw: Path) -> dict[str, list[dict]]: sents = orchid_sentences(raw / "orchid/orchid97.crp.utf") nat = [spans_of(t) for t in sents] idx = shuffled(len(nat)) cut1, cut2 = int(0.8 * len(idx)), int(0.9 * len(idx)) test = idx[cut2:] sets = {"orchidnho": [{"src_id": i, "text": nat[i][0], "gold": nat[i][1]} for i in test], "orchiddev": [{"src_id": i, "text": nat[i][0], "gold": nat[i][1]} for i in idx[cut1:cut2]]} dup = repeats([nat[i][0] for i in test], [nat[i][0] for i in idx[:cut2]]) sets["orchidndd"] = [{"src_id": k, "text": nat[i][0], "gold": nat[i][1]} for k, (i, d) in enumerate(zip(test, dup)) if not d] return sets KHMDD_TEXT = ("llm_labelled/best2009.jsonl", "llm_labelled/wangchan.jsonl", "dev/best2009.jsonl") def build_khm(raw: Path, dedup: bool | None = None) -> dict[str, list[dict]]: """khammoon's test; khmdd too when its training text was fetched (780 MB, only needed for khmdd).""" sets = {"khm": khm(raw / "khammoon/test/wangchan.jsonl")} if dedup is None: dedup = all((raw / "khammoon" / f).is_file() for f in KHMDD_TEXT) if dedup: training = [] for f in KHMDD_TEXT: for line in (raw / "khammoon" / f).open(encoding="utf-8"): training.extend(json.loads(line)["text"].split("\n")) dup = repeats([r["text"] for r in sets["khm"]], training) sets["khmdd"] = [{"src_id": k, **r} for k, (r, d) in enumerate(zip(sets["khm"], dup)) if not d] return sets def build(raw: Path) -> dict[str, list[dict]]: """Every set (maintainers): the same files as before the split into groups.""" return {**build_open(raw), **build_best(raw), **build_orchid(raw), **build_khm(raw)} KEY_ORDER = ("id", "src_id", "doc", "text", "gold") def dump(rows: list[dict]) -> bytes: out = [] for i, r in enumerate(rows): r = {"id": i, **r} out.append(json.dumps({k: r[k] for k in KEY_ORDER if k in r}, ensure_ascii=False) + "\n") return "".join(out).encode("utf-8") def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--raw", type=Path, default=HERE / "raw") ap.add_argument("--out", type=Path, default=HERE / "data") ap.add_argument("--write-checksums", action="store_true", help="record the built files' SHA-256 (maintainers)") args = ap.parse_args() sets = build(args.raw) args.out.mkdir(parents=True, exist_ok=True) sums = {} for name, rows in sets.items(): blob = dump(rows) (args.out / f"{name}.jsonl").write_bytes(blob) sums[f"{name}.jsonl"] = hashlib.sha256(blob).hexdigest() print(f"{name}: {len(rows):,} lines, {sum(len(r['gold']) for r in rows):,} gold words") path = HERE / "checksums.json" if args.write_checksums: path.write_text(json.dumps(sums, indent=1) + "\n") print(f"wrote {path.name}") return want = json.loads(path.read_text()) optional = {"khmdd.jsonl"} # built only when khammoon's training text was fetched if "khmdd.jsonl" not in sums: print("khmdd skipped: it needs khammoon's training text (python fetch_sources.py, without --no-khmdd)") bad = [n for n in want if (n in sums or n not in optional) and sums.get(n) != want[n]] print("all files identical to the published ones" if not bad else f"DIFFERENT from the published files: {bad}") raise SystemExit(1 if bad else 0) if __name__ == "__main__": main()