Datasets:
Tasks:
Token Classification
Modalities:
Text
Formats:
json
Languages:
Thai
Size:
10K - 100K
ArXiv:
License:
Download benchmark.py from iapp/OpenThai2.0-WordSeg-Benchmark: direct link, hf CLI and curl.
- Browser
- Download file 6.15 kB
-
https://huggingface.co/datasets/iapp/OpenThai2.0-WordSeg-Benchmark/resolve/main/benchmark.py
- Command line
-
hf download hf://datasets/iapp/OpenThai2.0-WordSeg-Benchmark/benchmark.py
-
curl -L -o benchmark.py https://huggingface.co/datasets/iapp/OpenThai2.0-WordSeg-Benchmark/resolve/main/benchmark.py
6.15 kB
| """OpenThai2.0-WordSeg-Benchmark 1.0: score a Thai word segmenter on the seven test sets in one call. | |
| from benchmark import evaluate | |
| evaluate(segment, name="my-segmenter") # segment(text) -> list of tokens | |
| python benchmark.py --module my_package:segment --name my-segmenter | |
| python benchmark.py --predictions my_outputs/ --name my-segmenter # my_outputs/SET.jsonl, {"id", "tokens"} | |
| It prints word F1 and boundary F1 on every set and their averages, next to the published systems, and saves | |
| results-NAME.json. The first run builds the three test sets that may not be shared (BEST, ORCHID, khammoon's test): | |
| it downloads their original files from their owners (about 50 MB), checks their SHA-256 and builds them, once. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import importlib | |
| import json | |
| import sys | |
| import time | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(HERE)) | |
| from thaiws import boundary_counts, f1, load_set, read_jsonl, word_counts # noqa: E402 | |
| BENCHMARK, VERSION = "OpenThai2.0-WordSeg-Benchmark", "1.0" | |
| SETS = [("tud", "TUD"), ("pud", "PUD"), ("ws160", "WS160"), ("vistec", "VISTEC"), ("bestdd", "BEST"), | |
| ("orchidndd", "ORCHID"), ("khm", "khm")] | |
| DATA, RAW = HERE / "data", HERE / "raw" | |
| def prepare() -> None: | |
| """Build, once, the test sets whose licence does not allow sharing them.""" | |
| missing = [s for s, _ in SETS if not (DATA / f"{s}.jsonl").exists()] | |
| if not missing: | |
| return | |
| import build_testsets | |
| import fetch_sources | |
| groups = {"bestdd": build_testsets.build_best, "orchidndd": build_testsets.build_orchid, | |
| "khm": lambda raw: build_testsets.build_khm(raw, dedup=False)} | |
| unknown = [s for s in missing if s not in groups] | |
| if unknown: | |
| raise SystemExit(f"data/{unknown[0]}.jsonl is missing: download the benchmark again") | |
| print("First run: BEST, ORCHID and khammoon's test may not be shared, so they are downloaded from their " | |
| "owners and built here (about 50 MB, once).", flush=True) | |
| bad = fetch_sources.fetch(RAW, sets=set(missing), quiet=True) | |
| if bad: | |
| raise SystemExit(f"these source files differ from the versions the benchmark was built from: {bad}") | |
| want = json.loads((HERE / "checksums.json").read_text()) | |
| for s in missing: | |
| for name, rows in groups[s](RAW).items(): | |
| blob = build_testsets.dump(rows) | |
| if hashlib.sha256(blob).hexdigest() != want[f"{name}.jsonl"]: | |
| raise SystemExit(f"{name}: the built file differs from the published one") | |
| (DATA / f"{name}.jsonl").write_bytes(blob) | |
| print("Test sets ready.\n", flush=True) | |
| def evaluate(segment=None, name: str = "my-segmenter", predictions: str | Path | None = None, batch: bool = False, | |
| save: bool = True) -> dict: | |
| """Score `segment` (a function: text -> list of tokens; with batch=True: list of texts -> list of token lists), | |
| or the files of a `predictions` folder (SET.jsonl, one {"id", "tokens"} per line of data/SET.jsonl).""" | |
| if (segment is None) == (predictions is None): | |
| raise ValueError("give either a segment function or a predictions folder") | |
| prepare() | |
| word, boundary = {}, {} | |
| print(f"{BENCHMARK} {VERSION}: {name}\n", flush=True) | |
| for s, label in SETS: | |
| rows = load_set(s) | |
| t0 = time.time() | |
| if predictions is not None: | |
| preds = read_jsonl(Path(predictions) / f"{s}.jsonl") | |
| if [p["id"] for p in preds] != [r["id"] for r in rows]: | |
| raise SystemExit(f"{predictions}/{s}.jsonl: one line per line of data/{s}.jsonl, in the same order") | |
| else: | |
| texts = [r["text"] for r in rows] | |
| tokens = list(segment(texts)) if batch else [list(segment(t)) for t in texts] | |
| preds = [{"id": r["id"], "tokens": list(t)} for r, t in zip(rows, tokens)] | |
| word[s] = round(float(f1(word_counts(rows, preds).sum(0))), 2) | |
| boundary[s] = round(float(f1(boundary_counts(rows, preds).sum(0))), 2) | |
| print(f" {label:7s} word F1 {word[s]:6.2f} boundary F1 {boundary[s]:6.2f} ({len(rows):,} lines, " | |
| f"{time.time() - t0:.0f} s)", flush=True) | |
| average = round(sum(word.values()) / len(word), 2) | |
| average_boundary = round(sum(boundary.values()) / len(boundary), 2) | |
| print(f" {'Average':7s} word F1 {average:6.2f} boundary F1 {average_boundary:6.2f}\n") | |
| expected = json.loads((HERE / "results" / "expected.json").read_text()) | |
| board = sorted([(v["avg7"], expected["boundary_f1_sets"][k]["avg7"], k) for k, v in expected["averages"].items() | |
| if "(unit rule)" not in k] + [(average, average_boundary, f"> {name}")], reverse=True) | |
| print("Average F1 with the published systems:\n word boundary") | |
| for v, b, k in board: | |
| print(f" {v:6.2f} {b:6.2f} {k}") | |
| result = {"benchmark": BENCHMARK, "version": VERSION, "system": name, "date": time.strftime("%Y-%m-%d"), | |
| "word_f1": word, "boundary_f1": boundary, "average_word_f1": average, | |
| "average_boundary_f1": average_boundary} | |
| if save: | |
| path = Path(f"results-{name}.json") | |
| path.write_text(json.dumps(result, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") | |
| print(f"\nSaved {path}") | |
| return result | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| src = ap.add_mutually_exclusive_group(required=True) | |
| src.add_argument("--module", help="MODULE:FUNCTION, a function text -> list of tokens") | |
| src.add_argument("--predictions", help="a folder with SET.jsonl files of {\"id\", \"tokens\"}") | |
| ap.add_argument("--name", default="my-segmenter") | |
| ap.add_argument("--batch", action="store_true", help="the function takes a list of texts") | |
| args = ap.parse_args() | |
| segment = None | |
| if args.module: | |
| mod, _, fn = args.module.partition(":") | |
| segment = getattr(importlib.import_module(mod), fn) | |
| evaluate(segment, name=args.name, predictions=args.predictions, batch=args.batch) | |
| if __name__ == "__main__": | |
| main() | |