"""Add a system to this benchmark's published results, in one command. python add_system.py NAME --from DIR --display "Name in the table" [--kind rival|ours|reference|baseline] [--card "shorter name for README.md"] [--mark "SYMBOL=WHERE,..."] [--row-of OTHER] [--run run.json] [--note TEXT] [--replace] python add_system.py NAME --built --display "..." # outputs that build_testsets.py downloads and builds DIR holds the system's outputs in the layout of predictions// (benchmark.py writes outputs/NAME/ so). The files are checked and scored with the scorer of benchmark 1.0, copied to predictions/NAME/, and their scores and the system are added to results/expected.json and manifest.json; the table in README.md is rendered again (kind "ours" in bold). For kind "ours", the paired bootstrap against every other system (10,000 resamples, 95% interval, the seeds of bench.py) is stored in results/expected.json under "compared", as in benchmark 1.0. Last, `score.py check` runs. --mark puts a mark of the card's legend (benchmark.LEGEND) on the cells of the given sets or modes, e.g. "‡=pud" or "†=raw"; a cell marked ‡, § or † is never the bold best value of its column (‖ is). --row-of OTHER shows this run's raw-text columns in the row of OTHER (two runs of one model: OTHER given the words, NAME given the text). --run keeps the tool, model, revision and version fields of a run.json. --built: the outputs are not in the repository (their source allows no sharing); release.json names their group, and build_testsets.py downloads and builds them. """ from __future__ import annotations import argparse import hashlib import json import re import shutil import sys import time from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import bench # noqa: E402 (the scorer of benchmark 1.0, unchanged) import build_testsets # noqa: E402 import score # noqa: E402 from benchmark import (EXPECTED, FOLDER, LEGEND, SENT9, TASK, card_with_table, compare, expected, has, # noqa: E402 manifest, scores_of) ALLOWED = {"sentences": {f"{st}.jsonl" for st in bench.SENT_SETS}, "clauses": {f"{st}.jsonl" for st in bench.EDU_SETS}, "syntax": {f"{st}.{m}.conllu" for st in bench.SYN_SETS for m in ("gold", "raw")}, "penn": {"tud.gold.jsonl", "tud.raw.jsonl"}}[FOLDER] NEEDED = {"sentences": {f"{st}.jsonl" for st in SENT9}, "clauses": {f"{st}.jsonl" for st in bench.EDU_SETS}, "penn": {"tud.gold.jsonl", "tud.raw.jsonl"}}.get(TASK, set()) RUN_KEYS = ("tool", "engine", "corpus", "package", "processors", "model", "revision", "model_revision", "resources_version", "decode", "tag_map", "gold_mode", "raw_mode", "raw_tokenizer", "call", "versions") def sha256(p: Path) -> str: return hashlib.sha256(p.read_bytes()).hexdigest() def check_files(src: Path) -> list[Path]: folder = src / FOLDER if not folder.is_dir(): raise SystemExit(f"{src}: no {FOLDER}/ folder (the layout of predictions//)") files = sorted(p for p in folder.iterdir() if p.is_file()) extra = [p.name for p in files if p.name not in ALLOWED] if extra: raise SystemExit(f"{folder}: files this benchmark does not score: {extra}") lacking = sorted(NEEDED - {p.name for p in files}) if lacking: raise SystemExit(f"{folder}: missing {lacking}") if TASK in ("sentences", "clauses"): # ids and character offsets (and the system's probabilities) only for p in files: for line in open(p, encoding="utf-8"): r = json.loads(line) if (not {"id", "ends"} <= set(r) <= {"id", "ends", "probs"} or not all(isinstance(x, int) for x in r["ends"]) or not all(isinstance(x, (int, float)) for x in r.get("probs", []))): raise SystemExit(f"{p}: each line must be {{\"id\", \"ends\": [int, ...]}} (and \"probs\": " "[number, ...]), nothing else") return files def parse_marks(specs: list[str]) -> dict: marks: dict = {} for s in specs: sym, _, where = s.partition("=") if sym not in LEGEND or not where: raise SystemExit(f"--mark {s!r}: SYMBOL=WHERE with a symbol of {''.join(LEGEND)}") marks.setdefault(sym, []).extend(w.strip() for w in where.split(",") if w.strip()) return marks def main() -> None: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("name") src = ap.add_mutually_exclusive_group(required=True) src.add_argument("--from", dest="src", type=Path) src.add_argument("--built", action="store_true", help="outputs built by build_testsets.py (not shipped)") ap.add_argument("--display", required=True) ap.add_argument("--kind", default="rival", choices=("rival", "ours", "reference", "baseline")) ap.add_argument("--card", default=None, help="a shorter name for the table in README.md") ap.add_argument("--mark", action="append", default=[], help='e.g. "‡=pud" or "†=raw" (repeatable)') ap.add_argument("--row-of", default=None, help="show this run's raw-text columns in the row of this system") ap.add_argument("--run", type=Path, default=None, help="a run.json: its tool, model and version fields are kept") ap.add_argument("--note", default=None) ap.add_argument("--replace", action="store_true", help="replace a system of the same name") ap.add_argument("--batch", action="store_true", help="for several additions: skip the card and the check (run score.py card --write and check after)") a = ap.parse_args() if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._+-]*", a.name): raise SystemExit("NAME: letters, digits and . _ + - only") build_testsets.prepare() dest = HERE / "predictions" / a.name exp, man = expected(), manifest() if (a.name in exp["scores"] or a.name in man["systems"] or (dest.exists() and not a.built)) and not a.replace: raise SystemExit(f"{a.name} is published already (--replace to replace it)") if a.row_of and a.row_of not in man["systems"]: raise SystemExit(f"--row-of {a.row_of}: no such system") if a.built: group = f"predictions/{a.name}" if build_testsets.release()["groups"].get(group, {}).get("mode") != "built": raise SystemExit(f"{group} is not a group that build_testsets.py builds (release.json)") files = sorted((dest / FOLDER).iterdir()) else: if dest.resolve() == a.src.resolve(): raise SystemExit("--from must be a folder outside predictions/") files = check_files(a.src) got = scores_of(a.src) # checks every file against the gold data (ids, words, texts) if dest.exists(): shutil.rmtree(dest) for p in files: (dest / FOLDER).mkdir(parents=True, exist_ok=True) shutil.copyfile(p, dest / FOLDER / p.name) scores = scores_of(dest) if not a.built: assert scores == got, "the copied files score differently" info = {"name": a.display, "kind": a.kind, "tasks": [TASK], "added": time.strftime("%Y-%m-%d")} for key, value in (("card", a.card), ("note", a.note), ("marks", parse_marks(a.mark)), ("row_of", a.row_of)): if value: info[key] = value if a.run: run = json.loads(a.run.read_text(encoding="utf-8")) info["run"] = {FOLDER: {k: run[k] for k in RUN_KEYS if run.get(k) is not None}} man["systems"][a.name] = info if a.row_of: man["systems"][a.row_of]["raw_from"] = a.name man["files"] = {k: v for k, v in man["files"].items() if not k.startswith(f"predictions/{a.name}/")} for p in sorted((dest / FOLDER).iterdir()): man["files"][str(p.relative_to(HERE))] = sha256(p) man["files"] = dict(sorted(man["files"].items())) exp["scores"][a.name] = scores exp.setdefault("compared", {}).pop(a.name, None) if a.kind == "ours": sc = bench.scorer(TASK) others = [n for n in exp["scores"] if n != a.name and (HERE / "predictions" / n).is_dir()] if TASK == "penn": others = [n for n in others if sc.has(n)] # the bootstrap needs both modes exp["compared"][a.name] = {b: compare(sc, a.name, b) for b in others} if has(sc, a.name) else {} (HERE / "manifest.json").write_text(json.dumps(man, ensure_ascii=False, indent=1), encoding="utf-8") EXPECTED.write_text(json.dumps(exp, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") print(f"added {a.name} ({a.kind}): {len(files)} files in predictions/{a.name}/{FOLDER}/" + (" (built on the first run, not shipped)" if a.built else "") + ", its scores in results/expected.json" + ("" if a.batch else ", its row in README.md")) if a.batch: return card = HERE / "README.md" card.write_text(card_with_table(card.read_text(encoding="utf-8")), encoding="utf-8") sys.exit(0 if score.check(None) else 1) if __name__ == "__main__": main()