OpenThai2.0-NLP-Core-Benchmark / ner /build_testsets.py
yacht's picture
OpenThai2.0-NLP-Core-Benchmark 1.1: test sets, scorers and system outputs for six Thai tasks.
0e6d825
Raw History Blame Contribute Delete
4.58 kB
"""Build the test set of this folder from its source: ThaiNER v2.2 is not in this repository.
python build_testsets.py # data/thainer22-test.jsonl, checked against checksums.json
ThaiNER v2.2 (https://huggingface.co/datasets/pythainlp/thainer-corpus-v2.2) is downloaded at the revision in
sources.json, and each downloaded file is checked by its SHA-256. A record of the test split holds words, spaces among
them as tokens, with one BIO tag per word. It becomes its text, the words joined, and its entities as
[start, end, type] character offsets, end exclusive. An I- tag after O or after another type starts an entity, as
seqeval does by default. Whitespace and zero-width characters at the edges of an entity are moved out of it. The
records keep the order of the split, with the ids test-00000 to test-01471. score.py, benchmark.py and add_system.py
call prepare() on their first run, so this script is needed only to rebuild the file.
"""
from __future__ import annotations
import hashlib
import json
import re
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from scoring.ner import trim # noqa: E402
GOLD = HERE / "data" / "thainer22-test.jsonl"
RAW = HERE / "raw"
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for block in iter(lambda: f.read(1 << 20), b""):
h.update(block)
return h.hexdigest()
def fetch() -> dict[str, Path]:
"""The source files at their pinned revision, checked."""
from huggingface_hub import hf_hub_download
src = json.loads((HERE / "sources.json").read_text(encoding="utf-8"))["thainer-v2.2"]
out = {}
for name, digest in src["files"].items():
path = Path(hf_hub_download(src["repository"], name, repo_type="dataset", revision=src["revision"],
local_dir=RAW))
if sha256(path) != digest:
raise SystemExit(f"{name}: the downloaded file differs from sources.json")
out[name] = path
return out
def label_names(card: Path) -> list[str]:
"""The class labels of the dataset card, in id order ('0': B-PERSON, ...)."""
pairs = re.findall(r"^\s+'(\d+)': (\S+)$", card.read_text(encoding="utf-8"), re.M)
pairs.sort(key=lambda p: int(p[0]))
assert [int(i) for i, _ in pairs] == list(range(len(pairs))), pairs
return [n for _, n in pairs]
def decode(words: list[str], tags: list[int], names: list[str]) -> tuple[str, list[list]]:
"""The text of a record and its entities as character spans."""
text = "".join(words)
ents, cur, pos = [], None, 0
for w, t in zip(words, tags):
a, b = pos, pos + len(w)
pos = b
lab = names[t]
if lab == "O":
if cur:
ents.append(cur)
cur = None
continue
bio, typ = lab.split("-", 1)
if bio == "B" or cur is None or cur[2] != typ:
if cur:
ents.append(cur)
cur = [a, b, typ]
else:
cur[1] = b
if cur:
ents.append(cur)
out = []
for a, b, typ in ents:
a2, b2 = trim(text, a, b)
if a2 < b2:
out.append([a2, b2, typ])
return text, out
def expected() -> str:
return json.loads((HERE / "checksums.json").read_text(encoding="utf-8"))["data/thainer22-test.jsonl"]
def build() -> Path:
import pyarrow.parquet as pq
files = fetch()
names = label_names(files["README.md"])
rows = pq.read_table(files["data/test-00000-of-00001.parquet"]).to_pylist()
GOLD.parent.mkdir(parents=True, exist_ok=True)
with GOLD.open("w", encoding="utf-8", newline="\n") as f:
for i, r in enumerate(rows):
text, ents = decode(r["words"], r["ner"], names)
f.write(json.dumps({"id": f"test-{i:05d}", "text": text, "entities": ents}, ensure_ascii=False) + "\n")
if sha256(GOLD) != expected():
GOLD.unlink()
raise SystemExit("data/thainer22-test.jsonl differs from checksums.json: the source or the build changed")
return GOLD
def prepare() -> Path:
"""The test set, built once from its source (about 1 MB to download)."""
if GOLD.is_file() and sha256(GOLD) == expected():
return GOLD
print("ThaiNER v2.2 is not in this repository: downloading its test split from its source at a pinned "
"revision, then building and checking the set, once.", flush=True)
return build()
if __name__ == "__main__":
print(build().relative_to(HERE), "built and checked")