Download score.py from pirolen/bar-lem: direct link, hf CLI and curl.
- Browser
- Download file 6.27 kB
-
https://huggingface.co/datasets/pirolen/bar-lem/resolve/main/score.py
- Command line
-
hf download hf://datasets/pirolen/bar-lem/score.py
-
curl -L -o score.py https://huggingface.co/datasets/pirolen/bar-lem/resolve/main/score.py
6.27 kB
| """Scorer for the Bar-Lem test split. | |
| Reports exact-match accuracy, split by identity and non-identity rows. The headline | |
| number is non-identity STRICT: identity rows, where the surface form already equals its | |
| lemma, are solvable by copying the input, so overall accuracy overstates lemmatization | |
| skill. Matching is case-insensitive. | |
| `--fold-stress` additionally ignores acute and grave accents on both sides, worth about | |
| +0.9 points overall; see "Known label defect" on the dataset card. | |
| Predictions: one per line in gold-file order, or JSONL with an `id` field plus one of | |
| `pred` / `prediction` / `output`. | |
| Usage: | |
| python score.py --gold test.jsonl --pred predictions.jsonl | |
| python score.py --gold test.jsonl --pred predictions.jsonl --by-region | |
| python score.py --gold test.jsonl --pred predictions.txt --fold-stress | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import unicodedata | |
| from pathlib import Path | |
| # Combining acute (U+0301) and grave (U+0300). The BWB prints these as stress | |
| # marks on headwords; they are not part of German orthography and no model can | |
| # infer them from the input. Combining diaeresis (U+0308) is NOT dropped -- | |
| # umlauts are real orthography and must still be predicted. | |
| STRESS_MARKS = ("́", "̀") | |
| def fold_stress(s: str) -> str: | |
| """NFD-decompose, drop acute/grave, recompose. Keeps umlauts and ß.""" | |
| d = unicodedata.normalize("NFD", s) | |
| return unicodedata.normalize("NFC", "".join(c for c in d if c not in STRESS_MARKS)) | |
| def norm(s: str, stress: bool) -> str: | |
| """Both sides of a comparison go through this, so scoring stays symmetric.""" | |
| # casefold(), not lower(): it maps ß to "ss", so "Fuß" and "FUSS" compare equal. | |
| # Casing is not penalized because BWB headword capitalization is a dictionary | |
| # convention rather than something to be predicted from the attestation. | |
| s = s.strip().casefold() | |
| return fold_stress(s) if stress else s | |
| def load_gold(path: Path) -> list[dict]: | |
| with path.open(encoding="utf-8") as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def load_preds(path: Path, gold: list[dict]) -> list[str]: | |
| """Predictions in gold-file order, from either accepted input format. | |
| JSONL keyed by `id` is preferred: it is order-independent and a missing row | |
| is reported rather than silently shifting every later comparison. Plain text | |
| is accepted as a fallback and is matched by position. | |
| """ | |
| lines = [l for l in path.read_text(encoding="utf-8").splitlines() if l.strip()] | |
| # Try to read the file as id-keyed JSONL. Emptying by_id and breaking means | |
| # "this is not JSONL after all" -- fall through to positional matching below. | |
| by_id = {} | |
| for line in lines: | |
| if not line.lstrip().startswith("{"): | |
| by_id = {} | |
| break | |
| try: | |
| r = json.loads(line) | |
| except json.JSONDecodeError: | |
| by_id = {} | |
| break | |
| key = next((k for k in ("pred", "prediction", "output") if k in r), None) | |
| if "id" not in r or key is None: | |
| by_id = {} | |
| break | |
| by_id[r["id"]] = r[key] | |
| if by_id: | |
| # Every gold row must have a prediction; scoring a subset would silently | |
| # report a number that is not comparable to the published ones. | |
| missing = [r["id"] for r in gold if r["id"] not in by_id] | |
| if missing: | |
| raise SystemExit(f"{len(missing)} gold ids missing from predictions, " | |
| f"e.g. {missing[:3]}") | |
| return [by_id[r["id"]] for r in gold] | |
| # Positional fallback: the count must match exactly, or row i is being scored | |
| # against the wrong gold. | |
| if len(lines) != len(gold): | |
| raise SystemExit(f"plain-text predictions have {len(lines)} lines but gold " | |
| f"has {len(gold)} rows") | |
| return lines | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--gold", type=Path, default=Path("test.jsonl")) | |
| ap.add_argument("--pred", type=Path, required=True) | |
| ap.add_argument("--fold-stress", action="store_true", | |
| help="ignore acute/grave accents on both sides (see card)") | |
| ap.add_argument("--by-region", action="store_true", | |
| help="also break accuracy down by dialect region") | |
| args = ap.parse_args() | |
| gold = load_gold(args.gold) | |
| preds = load_preds(args.pred, gold) | |
| stress = args.fold_stress | |
| # One exact-match verdict per row, bucketed by whether the row is trivially | |
| # copyable. Identity rows are not excluded, just reported apart, so both the | |
| # headline and the inflated overall figure stay visible. | |
| buckets: dict[str, list[int]] = {"non-identity": [], "identity": []} | |
| regions: dict[str, list[int]] = {} | |
| for row, pred in zip(gold, preds): | |
| hit = int(norm(pred, stress) == norm(row["target_lemma"], stress)) | |
| buckets["identity" if row["is_identity"] else "non-identity"].append(hit) | |
| # Rows with no region (38 %) are left out of the regional table rather | |
| # than pooled into an "unknown" bucket that invites over-reading. | |
| if row.get("region"): | |
| regions.setdefault(row["region"], []).append(hit) | |
| def pct(hits: list[int]) -> str: | |
| return f"{100 * sum(hits) / len(hits):.1f} %" if hits else "n/a" | |
| overall = buckets["non-identity"] + buckets["identity"] | |
| print(f"gold: {args.gold} pred: {args.pred}" | |
| f"{' [stress folded]' if stress else ''}\n") | |
| print(f"{'subset':<16}{'n':>7}{'STRICT':>10}") | |
| for name in ("non-identity", "identity"): | |
| print(f"{name:<16}{len(buckets[name]):>7}{pct(buckets[name]):>10}") | |
| print(f"{'overall':<16}{len(overall):>7}{pct(overall):>10}") | |
| print(f"\nheadline (non-identity STRICT): {pct(buckets['non-identity'])}") | |
| if args.by_region: | |
| # Only OB/NB/OP carry enough rows to compare; the rest are tens of rows. | |
| print(f"\n{'region':<16}{'n':>7}{'STRICT':>10}") | |
| for reg, hits in sorted(regions.items(), key=lambda kv: -len(kv[1])): | |
| print(f"{reg:<16}{len(hits):>7}{pct(hits):>10}") | |
| if __name__ == "__main__": | |
| main() | |