esi-bench-passive-single / scripts /export_passive_single.py
jiagengliu02's picture
Use one all split and remove reports (part 10)
159806e verified
Raw
History Blame Contribute Delete
8.77 kB
#!/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())