| """Portable helpers for the frozen Hugging Face preparation (no network calls).""" |
|
|
| from __future__ import annotations |
|
|
| import copy |
| import gzip |
| import hashlib |
| import json |
| from pathlib import Path |
|
|
| VERSION = "answerability-v1.0.0-20260928" |
| STATES = { |
| "plotqa": ["FULL", "A_SAME", "A_CHANGED", "U_MISSING", "U_INVALID"], |
| "clevr": ["FULL", "A_SAME", "A_CHANGED", "U_MISSING"], |
| "gqa": ["FULL", "A_SAME", "U_MISSING"], |
| } |
|
|
|
|
| def read_json(path): |
| return json.loads(Path(path).read_text(encoding="utf-8")) |
|
|
|
|
| def read_rows(path): |
| path = Path(path) |
| opener = gzip.open if path.suffix == ".gz" else open |
| with opener(path, "rt", encoding="utf-8") as handle: |
| return [json.loads(line) for line in handle if line.strip()] |
|
|
|
|
| def write_json(path, value): |
| path = Path(path) |
| path.parent.mkdir(parents=True, exist_ok=True) |
| path.write_text( |
| json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8" |
| ) |
|
|
|
|
| def write_rows(path, rows): |
| path = Path(path) |
| path.parent.mkdir(parents=True, exist_ok=True) |
| data = "".join( |
| json.dumps(row, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n" |
| for row in rows |
| ).encode() |
| path.write_bytes(gzip.compress(data, mtime=0) if path.suffix == ".gz" else data) |
|
|
|
|
| def digest(data): |
| return hashlib.sha256(data).hexdigest() |
|
|
|
|
| def file_digest(path): |
| with Path(path).open("rb") as handle: |
| return hashlib.file_digest(handle, "sha256").hexdigest() |
|
|
|
|
| def canonical_digest(value): |
| return digest( |
| json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() |
| ) |
|
|
|
|
| def safe_path(root, relative): |
| relative = Path(relative) |
| if relative.is_absolute() or ".." in relative.parts: |
| raise ValueError("Expected a safe relative path") |
| path = (Path(root) / relative).resolve() |
| path.relative_to(Path(root).resolve()) |
| return path |
|
|
|
|
| def changes(before, after, path=()): |
| """Encode only our edits; do not redistribute a complete upstream graph.""" |
| if before == after: |
| return [] |
| if isinstance(before, dict) and isinstance(after, dict) and before.keys() == after.keys(): |
| return [ |
| change |
| for key in sorted(before) |
| for change in changes(before[key], after[key], (*path, key)) |
| ] |
| return [{"path": list(path), "value": after}] |
|
|
|
|
| def apply_changes(world, edits): |
| world = copy.deepcopy(world) |
| for edit in edits: |
| if not edit["path"]: |
| raise ValueError("Whole-world replacement is not a reconstruction recipe") |
| cursor = world |
| for key in edit["path"][:-1]: |
| cursor = cursor[key] |
| cursor[edit["path"][-1]] = copy.deepcopy(edit["value"]) |
| return world |
|
|