File size: 8,771 Bytes
d0c28fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159806e
d0c28fa
159806e
 
 
d0c28fa
 
 
 
 
159806e
d0c28fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159806e
d0c28fa
159806e
 
d0c28fa
 
 
 
 
 
 
159806e
 
d0c28fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159806e
d0c28fa
159806e
 
d0c28fa
 
 
 
 
 
 
159806e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0c28fa
 
 
 
159806e
 
d0c28fa
 
 
 
 
 
 
 
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#!/usr/bin/env python3
"""Build the standalone ESI-Bench passive-single Hugging Face dataset repo."""

from __future__ import annotations

import argparse
import json
import os
import shutil
from collections import Counter
from pathlib import Path
from typing import Any


PROJECT_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_SOURCE_ROOT = PROJECT_ROOT / "outputs/passive_single"
DEFAULT_MANIFEST = DEFAULT_SOURCE_ROOT / "all_manifest.jsonl"
DEFAULT_QUESTIONS = PROJECT_ROOT / "hf_dataset/data/questions.jsonl"
DEFAULT_OUTPUT_ROOT = PROJECT_ROOT / "hf_passive_single_dataset"


def read_jsonl(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    with path.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, start=1):
            line = line.strip()
            if not line:
                continue
            try:
                value = json.loads(line)
            except json.JSONDecodeError as exc:
                raise SystemExit(f"Invalid JSON in {path}:{line_number}: {exc}") from exc
            if not isinstance(value, dict):
                raise SystemExit(f"Expected an object in {path}:{line_number}")
            rows.append(value)
    return rows


def json_text(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, separators=(",", ":"))


def relative_image_path(raw_path: str) -> Path:
    prefix = "outputs/passive_single/"
    normalized = raw_path.replace("\\", "/")
    if normalized.startswith(prefix):
        normalized = normalized[len(prefix) :]
    relative = Path(normalized)
    if relative.is_absolute() or ".." in relative.parts:
        raise SystemExit(f"Unsafe output_image path: {raw_path}")
    return relative


def action_qa(row: dict[str, Any]) -> tuple[str | None, str | None, str | None, str | None]:
    result = row.get("result")
    if not isinstance(result, dict):
        return None, None, None, None
    camera_info = result.get("camera_info")
    if not isinstance(camera_info, dict):
        return None, None, None, None
    qa = camera_info.get("qa")
    if not isinstance(qa, dict) or not qa.get("question"):
        return None, None, None, None

    answers = {
        key: qa[key]
        for key in ("answer_A", "answer_C")
        if key in qa
    }
    options: dict[str, Any] = {}
    if "choices_A" in qa:
        options["A"] = qa["choices_A"]
    if "choices_C" in qa:
        options["C"] = qa["choices_C"]
    return (
        str(qa["question"]),
        json_text(answers) if answers else None,
        "choice" if answers else None,
        json_text(options) if options else None,
    )


def public_metadata(
    manifest_row: dict[str, Any],
    question_row: dict[str, Any],
    file_name: str,
    item_id: str,
) -> dict[str, Any]:
    result = manifest_row.get("result")
    if not isinstance(result, dict):
        result = {}

    rendered_question, rendered_answer, rendered_answer_type, rendered_options = action_qa(manifest_row)

    return {
        "file_name": file_name,
        "id": item_id,
        "big_task": manifest_row.get("big_task") or result.get("big_task"),
        "small_task": manifest_row.get("small_task") or result.get("small_task"),
        "runner_task": question_row.get("runner_task") or result.get("runner_task"),
        "scene": manifest_row.get("scene") or result.get("scene"),
        "room": manifest_row.get("room") or result.get("room"),
        "question": rendered_question or question_row.get("question"),
        "answer": rendered_answer or question_row.get("answer"),
        "answer_type": rendered_answer_type or question_row.get("answer_type"),
        "options_json": rendered_options or question_row.get("options_json") or "{}",
    }


def place_image(source: Path, destination: Path, mode: str) -> str:
    destination.parent.mkdir(parents=True, exist_ok=True)
    if mode == "copy":
        shutil.copy2(source, destination)
        return "copied"
    try:
        os.link(source, destination)
        return "linked"
    except OSError:
        shutil.copy2(source, destination)
        return "copied"


def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json_text(row))
            handle.write("\n")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-root", type=Path, default=DEFAULT_SOURCE_ROOT)
    parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
    parser.add_argument("--questions", type=Path, default=DEFAULT_QUESTIONS)
    parser.add_argument("--output-root", type=Path, default=DEFAULT_OUTPUT_ROOT)
    parser.add_argument("--copy", action="store_true", help="Copy images instead of using hard links when possible.")
    parser.add_argument("--overwrite", action="store_true", help="Replace an existing generated data directory.")
    args = parser.parse_args()

    source_root = args.source_root.resolve()
    manifest_path = args.manifest.resolve()
    questions_path = args.questions.resolve()
    output_root = args.output_root.resolve()
    data_root = output_root / "data"

    if output_root == PROJECT_ROOT or output_root == source_root:
        raise SystemExit(f"Refusing unsafe output root: {output_root}")
    if data_root.exists():
        if not args.overwrite:
            raise SystemExit("Generated data already exists. Pass --overwrite to rebuild it.")
        shutil.rmtree(data_root)

    manifest_rows = read_jsonl(manifest_path)
    question_rows = read_jsonl(questions_path)
    questions_by_id = {str(row["id"]): row for row in question_rows}
    if len(questions_by_id) != len(question_rows):
        raise SystemExit("Question IDs are not unique")

    manifest_by_index = {int(row["index"]): row for row in manifest_rows}
    metadata: list[dict[str, Any]] = []
    referenced_images: set[Path] = set()
    placement_counts: Counter[str] = Counter()

    for row in manifest_rows:
        status = row.get("status")
        result = row.get("result")
        if status not in {"rendered", "rendered_warning"} or not isinstance(result, dict):
            continue

        item_id = str(result.get("id") or "")
        if not item_id or item_id not in questions_by_id:
            raise SystemExit(f"Missing standardized question metadata for rendered ID {item_id!r}")
        raw_image_path = result.get("output_image")
        if not isinstance(raw_image_path, str):
            raise SystemExit(f"Rendered ID {item_id} has no output_image")

        relative = relative_image_path(raw_image_path)
        source = source_root / relative
        if not source.is_file():
            raise SystemExit(f"Missing rendered image for ID {item_id}: {source}")
        referenced_images.add(relative)

        destination = data_root / relative
        placement_counts[place_image(source, destination, "copy" if args.copy else "link")] += 1
        metadata.append(
            public_metadata(row, questions_by_id[item_id], relative.as_posix(), item_id)
        )

    all_pngs = {
        path.relative_to(source_root)
        for path in source_root.rglob("*.png")
        if path.is_file()
    }
    recovered_images: list[str] = []
    for relative in sorted(all_pngs - referenced_images):
        prefix = relative.name.split("_", 1)[0]
        if not prefix.isdigit():
            raise SystemExit(f"Cannot recover an ID from image name: {relative}")
        item_id = f"{int(prefix):04d}"
        manifest_row = manifest_by_index.get(int(prefix))
        question_row = questions_by_id.get(item_id)
        if manifest_row is None or question_row is None:
            raise SystemExit(f"Cannot recover metadata for image: {relative}")
        placement_counts[
            place_image(source_root / relative, data_root / relative, "copy" if args.copy else "link")
        ] += 1
        metadata.append(public_metadata(manifest_row, question_row, relative.as_posix(), item_id))
        recovered_images.append(relative.as_posix())

    metadata.sort(key=lambda row: row["id"])
    if len({row["id"] for row in metadata}) != len(metadata):
        raise SystemExit("Published image IDs are not unique")
    write_jsonl(data_root / "metadata.jsonl", metadata)

    summary = {
        "manifest_rows": len(manifest_rows),
        "question_rows": len(question_rows),
        "published_images": len(metadata),
        "recovered_images": recovered_images,
        "image_placement": dict(sorted(placement_counts.items())),
    }
    print(json.dumps(summary, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())