Datasets:
Tasks:
Token Classification
Modalities:
Text
Formats:
json
Languages:
Thai
Size:
10K - 100K
ArXiv:
License:
File size: 12,413 Bytes
b35eaa3 | 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 | """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 = {"<space>": " ", "<minus>": "-", "<full_stop>": ".", "<left_parenthesis>": "(",
"<right_parenthesis>": ")", "<quotation>": '"', "<comma>": ",", "<slash>": "/", "<equal>": "=",
"<colon>": ":", "<asterisk>": "*", "<plus>": "+", "<greater_than>": ">", "<semi_colon>": ";",
"<less_than>": "<", "<apostrophe>": "'", "<dollar>": "$", "<number>": "#", "<ampersand>": "&",
"<question_mark>": "?", "<circumflex_accent>": "^", "<left_curly_bracket>": "{",
"<right_curly_bracket>": "}", "<exclamation>": "!", "<at_mark>": "@"}
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 (<ne>, <compound>, <msp value=...>): 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 <space> 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 != "<space>" 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()
|