File size: 6,810 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/env python3
"""Reconstruct GQA locally from user-obtained upstream data; no downloads/uploads."""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from hf_release_common import (
    apply_changes,
    canonical_digest,
    digest,
    read_json,
    read_rows,
    write_json,
    write_rows,
)

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))


def reconstruct(dataset, questions_path, graphs_path, images, output):
    from explicit_learning.executors.gqa import GQASemanticExecutor, compile_gqa_program
    from explicit_learning.renderers.gqa import normalize_gqa_source_image, render_gqa_observation
    from explicit_learning.sources.gqa import build_gqa_world

    recipes = read_rows(dataset / "evidence/gqa/reconstruction.jsonl.gz")
    if len(recipes) != 3000 or len({row["item_id"] for row in recipes}) != 3000:
        raise ValueError("Expected exactly 3,000 GQA view recipes")
    questions, graphs = read_json(questions_path), read_json(graphs_path)
    output.mkdir(parents=True, exist_ok=False)
    (output / "images").mkdir()
    cache, records, evidence, view_ids = {}, [], [], set()
    executor = GQASemanticExecutor()
    for recipe in recipes:
        qid, image_id = recipe["source_question_id"], recipe["source_image_id"]
        if qid not in cache:
            source_question = questions[qid]
            if str(source_question["imageId"]) != image_id:
                raise ValueError("Upstream question/image identity differs")
            if digest(source_question["question"].encode()) != recipe["question_sha256"]:
                raise ValueError("Upstream question text differs from evaluated question")
            world = build_gqa_world(graphs[image_id], image_id=image_id, question_id=qid)
            if canonical_digest(world) != recipe["source_world_sha256"]:
                raise ValueError("Upstream scene graph differs from evaluated graph")
            program = compile_gqa_program(qid, source_question)
            if canonical_digest(program.to_dict()) != recipe["program_sha256"]:
                raise ValueError("Upstream program differs from evaluated program")
            source_image = images / (image_id + ".jpg")
            source_image.resolve().relative_to(images.resolve())
            normalized = normalize_gqa_source_image(
                source_image.read_bytes(), width=recipe["width"], height=recipe["height"]
            )
            if digest(normalized) != recipe["normalized_source_sha256"]:
                raise ValueError(
                    "Source photograph/codec differs; use the frozen Pillow environment and original GQA/VG JPEG"
                )
            cache[qid] = (source_question["question"], world, program, normalized)
        question, before, program, normalized = cache[qid]
        after = apply_changes(before, recipe["world_edits"])
        rendered = render_gqa_observation(
            normalized, after, masked_node_id=recipe["masked_node_id"], seed=recipe["seed"]
        )
        if digest(rendered.image_jpeg) != recipe["image_sha256"]:
            raise ValueError("Reconstructed view is not byte-identical to the evaluated image")
        execution = executor.execute(program, world=after)
        expected = recipe["executor_evidence"]["after"]
        if (
            execution.status != expected["status"]
            or execution.answer_canonical != expected["answer_canonical"]
        ):
            raise ValueError("Source-program evidence replay differs")
        completions = {
            key: apply_changes(before, edits) for key, edits in recipe["completion_edits"].items()
        }
        if completions:
            answers = [executor.execute(program, world=world) for world in completions.values()]
            if (
                len(answers) != 2
                or any(answer.status != "UNIQUE" for answer in answers)
                or answers[0].answer_canonical == answers[1].answer_canonical
            ):
                raise ValueError("Symbolic scene alternatives do not yield distinct answers")
        item_id = recipe["item_id"]
        if item_id in view_ids or Path(item_id).name != item_id:
            raise ValueError("Duplicate or unsafe item ID")
        view_ids.add(item_id)
        (output / "images" / (item_id + ".jpg")).write_bytes(rendered.image_jpeg)
        records.append(
            {
                "file_name": "images/" + item_id + ".jpg",
                "item_id": item_id,
                "group_id": recipe["group_id"],
                "question": question,
                "state": recipe["state"],
                "target": recipe["target"],
                "answerable": recipe["answerable"],
                "source": "gqa",
            }
        )
        evidence.append(
            {
                "item_id": item_id,
                "program": program.to_dict(),
                "world_before": before,
                "world_after": after,
                **completions,
            }
        )
    write_rows(output / "metadata.jsonl", records)
    write_rows(output / "source-label-evidence.jsonl.gz", evidence)
    result = {
        "status": "passed",
        "views": len(records),
        "groups": len(cache),
        "byte_identical_images": len(records),
        "upstream_question_program_graph_joins": len(cache),
        "source_program_replays": len(records),
        "scope": "Scene-program/edit evidence only; no photographic complete-world pixel proof is claimed.",
        "publication_performed": False,
    }
    write_json(output / "reconstruction-validation.json", result)
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset", type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument(
        "--questions", type=Path, required=True, help="GQA v1.2 val_balanced_questions.json"
    )
    parser.add_argument("--scene-graphs", type=Path, required=True, help="GQA val_sceneGraphs.json")
    parser.add_argument(
        "--images",
        type=Path,
        required=True,
        help="Directory of original upstream {image_id}.jpg files",
    )
    parser.add_argument(
        "--output",
        type=Path,
        required=True,
        help="New local directory, outside the upload candidate",
    )
    args = parser.parse_args()
    if args.output.resolve().is_relative_to(args.dataset.resolve()):
        parser.error(
            "Reconstruct outside the upload candidate to preserve its redistribution boundary"
        )
    print(
        json.dumps(
            reconstruct(args.dataset, args.questions, args.scene_graphs, args.images, args.output)
        )
    )


if __name__ == "__main__":
    main()