Datasets:
Tasks:
Question Answering
Modalities:
Text
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
airframe
harmotence
distributed-reasoning
constraint-satisfaction
relational-coupling
synthetic-data
License:
Download scorer.py from ClarusC64/AF-HARM-01: direct link, hf CLI and curl.
- Browser
- Download file 5.33 kB
-
https://huggingface.co/datasets/ClarusC64/AF-HARM-01/resolve/main/scorer.py
- Command line
-
hf download hf://datasets/ClarusC64/AF-HARM-01/scorer.py
-
curl -L -o scorer.py https://huggingface.co/datasets/ClarusC64/AF-HARM-01/resolve/main/scorer.py
5.33 kB
| #!/usr/bin/env python3 | |
| """AF-HARM-01 v0.1 exact JSON scorer. Standard library only.""" | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import pathlib | |
| import sys | |
| from collections import defaultdict | |
| VERSION = "0.1" | |
| def parse_json(raw): | |
| def unique(pairs): | |
| result = {} | |
| for key, value in pairs: | |
| if key in result: | |
| raise ValueError("Duplicate key: " + key) | |
| result[key] = value | |
| return result | |
| def reject_constant(value): | |
| raise ValueError("Invalid JSON constant: " + value) | |
| return json.loads(raw, object_pairs_hook=unique, parse_constant=reject_constant) | |
| def equal(a, b): | |
| if type(a) is not type(b): | |
| return False | |
| if isinstance(a, dict): | |
| return a.keys() == b.keys() and all(equal(a[k], b[k]) for k in a) | |
| if isinstance(a, list): | |
| return len(a) == len(b) and all(equal(x, y) for x, y in zip(a, b)) | |
| return a == b | |
| def load(path, columns): | |
| with open(path, newline="", encoding="utf-8-sig") as handle: | |
| reader = csv.DictReader(handle) | |
| if not reader.fieldnames or not set(columns).issubset(reader.fieldnames): | |
| raise ValueError("Missing columns in " + str(path)) | |
| records = {} | |
| for row in reader: | |
| key = (row.get("id") or "").strip() | |
| if not key or key in records: | |
| raise ValueError("Blank or duplicate ID in " + str(path)) | |
| records[key] = row | |
| return records | |
| def sha(path): | |
| return hashlib.sha256(path.read_bytes()).hexdigest() | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--predictions", required=True, type=pathlib.Path) | |
| parser.add_argument("--gold", type=pathlib.Path, default=pathlib.Path("data/test.csv")) | |
| parser.add_argument("--output", type=pathlib.Path, default=pathlib.Path("scores.json")) | |
| parser.add_argument("--include-answers", action="store_true") | |
| args = parser.parse_args(argv) | |
| try: | |
| gold = load(args.gold, ["id", "family", "expected_answer"]) | |
| predictions = load(args.predictions, ["id", "prediction"]) | |
| if not gold: | |
| raise ValueError("Empty gold file") | |
| unknown = set(predictions) - set(gold) | |
| if unknown: | |
| raise ValueError("Unknown prediction IDs: " + ", ".join(sorted(unknown)[:10])) | |
| expected = {} | |
| for key, row in gold.items(): | |
| try: | |
| expected[key] = parse_json(row["expected_answer"]) | |
| if not isinstance(expected[key], dict): | |
| raise ValueError("Gold must be an object") | |
| except (ValueError, TypeError, RecursionError) as exc: | |
| raise ValueError("Invalid gold answer " + key) from exc | |
| by_family = defaultdict(lambda: {"total": 0, "correct": 0, "missing": 0, "invalid_format": 0}) | |
| details = [] | |
| for key, row in gold.items(): | |
| raw = (predictions.get(key, {}).get("prediction") or "").strip() | |
| missing = not raw | |
| invalid = False | |
| actual = None | |
| if raw: | |
| try: | |
| actual = parse_json(raw) | |
| invalid = not isinstance(actual, dict) | |
| except (ValueError, TypeError, RecursionError): | |
| invalid = True | |
| correct = not missing and not invalid and equal(actual, expected[key]) | |
| stats = by_family[row["family"]] | |
| stats["total"] += 1 | |
| stats["correct"] += int(correct) | |
| stats["missing"] += int(missing) | |
| stats["invalid_format"] += int(invalid) | |
| detail = {"id": key, "family": row["family"], "correct": correct, "missing": missing, "invalid_format": invalid} | |
| if args.include_answers: | |
| detail["expected_answer"] = expected[key] | |
| detail["prediction"] = raw | |
| details.append(detail) | |
| total = len(gold) | |
| correct = sum(s["correct"] for s in by_family.values()) | |
| missing = sum(s["missing"] for s in by_family.values()) | |
| invalid = sum(s["invalid_format"] for s in by_family.values()) | |
| report = {"dataset": "AF-HARM-01", "scorer_version": VERSION, "total": total, "correct": correct, | |
| "accuracy": round(correct / total, 6), "missing": missing, "invalid_format": invalid, | |
| "complete": not (missing or invalid), | |
| "by_family": {k: {**v, "accuracy": round(v["correct"] / v["total"], 6)} for k, v in sorted(by_family.items())}, | |
| "sha256": {"gold": sha(args.gold), "predictions": sha(args.predictions), "scorer": sha(pathlib.Path(__file__))}, | |
| "scope": "Final-answer accuracy on finite distributed constraint tasks; not proof of decentralized learning or Harmotence.", | |
| "details": details} | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") | |
| print(json.dumps({k: v for k, v in report.items() if k != "details"}, indent=2)) | |
| return 1 if missing or invalid else 0 | |
| except (OSError, ValueError, csv.Error, RecursionError) as exc: | |
| print("Error: " + str(exc), file=sys.stderr) | |
| return 2 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |