File size: 2,781 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""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