File size: 3,168 Bytes
036572b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""CraftQuantities-Bench scorer. Standard library only; no network.

    python evaluate.py --bench jsonl/bench.jsonl --predictions my_predictions.jsonl
    python evaluate.py --bench jsonl/bench.jsonl --self-check

predictions: one JSON object per line, {"id": "<bench id>", "prediction": <number or text>}.
A text prediction is read as its first number ("1,234.5 yd³" -> 1234.5). A missing id counts as wrong.

An item passes when |prediction - expected_value| < 0.5 * 10^-tolerance_decimal_places (absent means 2), the rule the
site's own test suite applies to the same vectors (https://craftquantities.com/api/v1/validation.json, toleranceMeaning).
--self-check scores the expected values against themselves; it must print 100.00%.
"""
import argparse
import json
import math
import re
import sys
from collections import defaultdict

NUMBER = re.compile(r"[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:[eE][-+]?\d+)?|[-+]?\.\d+(?:[eE][-+]?\d+)?")


def parse(value):
    if isinstance(value, bool) or value is None:
        return None
    if isinstance(value, (int, float)):
        return float(value)
    m = NUMBER.search(str(value).replace("−", "-"))
    return float(m.group(0).replace(",", "")) if m else None


def read_jsonl(path):
    with open(path, encoding="utf-8") as fh:
        return [json.loads(line) for line in fh if line.strip()]


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--bench", required=True)
    group = ap.add_mutually_exclusive_group(required=True)
    group.add_argument("--predictions")
    group.add_argument("--self-check", action="store_true")
    ap.add_argument("--details", help="write one line per item with the verdict to this JSONL file")
    args = ap.parse_args()

    items = read_jsonl(args.bench)
    if args.self_check:
        preds = {it["id"]: it["expected_value"] for it in items}
    else:
        preds = {}
        for p in read_jsonl(args.predictions):
            preds[p["id"]] = p.get("prediction")

    by_cat = defaultdict(lambda: [0, 0])
    passed = 0
    details = []
    for it in items:
        tdp = it.get("tolerance_decimal_places")
        tol = 0.5 * 10 ** -(2 if tdp is None else tdp)
        got = parse(preds.get(it["id"]))
        ok = got is not None and math.isfinite(got) and abs(got - it["expected_value"]) < tol
        passed += ok
        by_cat[it["category"]][0] += ok
        by_cat[it["category"]][1] += 1
        details.append({"id": it["id"], "expected": it["expected_value"], "unit": it["expected_unit"], "prediction": got, "tolerance": tol, "pass": ok})

    total = len(items)
    print(f"CraftQuantities-Bench: {passed}/{total} = {100 * passed / total:.2f}%")
    for cat, (ok, n) in sorted(by_cat.items()):
        print(f"  {cat:32s} {ok:5d}/{n:<5d} {100 * ok / n:6.2f}%")
    if args.details:
        with open(args.details, "w", encoding="utf-8") as fh:
            for d in details:
                fh.write(json.dumps(d) + "\n")
    return 0 if (not args.self_check or passed == total) else 1


if __name__ == "__main__":
    sys.exit(main())