#!/usr/bin/env python3 """Build the lightweight Hugging Face Dataset Viewer split. The full dataset payload lives in scene ZIP archives. This script creates a small Parquet table that embeds RGB preview images and records the archive member paths for the heavier modalities. """ from __future__ import annotations import argparse import json import re from pathlib import Path from zipfile import ZipFile from datasets import Dataset, Features, Image, Sequence, Value CAMERA_RE = re.compile( r"cam(?P\d+)_az(?P-?\d+(?:\.\d+)?)_el(?P-?\d+(?:\.\d+)?)" ) FEATURES = Features( { "sample_id": Value("string"), "scene_zip_id": Value("string"), "scene_id": Value("string"), "arrangement_id": Value("string"), "camera_label": Value("string"), "camera_index": Value("int32"), "azimuth_deg": Value("float32"), "elevation_deg": Value("float32"), "image": Image(), "archive": Value("string"), "rgb_path": Value("string"), "depth_z_path": Value("string"), "depth_euclidean_path": Value("string"), "normal_worldspace_path": Value("string"), "normal_camspace_path": Value("string"), "mask_combined_path": Value("string"), "object_mask_paths": Sequence(Value("string")), "metadata_path": Value("string"), "scene_graph_path": Value("string"), "blend_path": Value("string"), "colmap_cameras_path": Value("string"), "colmap_images_path": Value("string"), "colmap_points3d_path": Value("string"), "render_width": Value("int32"), "render_height": Value("int32"), "num_cameras": Value("int32"), "num_objects": Value("int32"), "num_edges": Value("int32"), "camera_fx_px": Value("float32"), "camera_fy_px": Value("float32"), "camera_fov_h_deg": Value("float32"), "camera_fov_v_deg": Value("float32"), "camera_position_world_m": Sequence(Value("float32")), "object_ids": Sequence(Value("int32")), "object_names": Sequence(Value("string")), "object_classes": Sequence(Value("string")), "relation_triplets": Sequence(Value("string")), } ) def load_json(zf: ZipFile, member: str) -> dict: return json.loads(zf.read(member).decode("utf-8")) def path_if_present(names: set[str], path: str) -> str | None: return path if path in names else None def camera_from_metadata(metadata: dict, camera_label: str) -> dict: for camera in metadata.get("cameras", []): if camera.get("label") == camera_label: return camera return {} def relation_triplets(scene_graph: dict) -> list[str]: triplets = [] for edge in scene_graph.get("edges", []): relations = edge.get("relations", {}) relation_text = "/".join( str(relations.get(key, "unknown")) for key in ("proximity", "vertical", "horizontal") ) triplets.append(f"{edge.get('source')}->{edge.get('target')}:{relation_text}") return triplets def arrangement_dirs(names: set[str]) -> list[str]: return sorted({name.split("/", 1)[0] for name in names if name.startswith("arr_") and "/" in name}) def build_rows(repo_root: Path) -> list[dict]: rows: list[dict] = [] zip_paths = sorted(repo_root.glob("scene_*.zip")) if not zip_paths: raise FileNotFoundError("No scene_*.zip archives found") for zip_path in zip_paths: scene_zip_id = zip_path.stem with ZipFile(zip_path) as zf: names = set(zf.namelist()) for arrangement_id in arrangement_dirs(names): metadata_path = f"{arrangement_id}/metadata.json" scene_graph_path = f"{arrangement_id}/scene_graph.json" if metadata_path not in names or scene_graph_path not in names: continue metadata = load_json(zf, metadata_path) scene_graph = load_json(zf, scene_graph_path) render = metadata.get("render", {}) nodes = scene_graph.get("nodes", []) relation_rows = relation_triplets(scene_graph) object_ids = [int(node["id"]) for node in nodes if "id" in node] object_names = [str(node.get("object_name", "")) for node in nodes] object_classes = [str(node.get("class", "")) for node in nodes] rgb_paths = sorted( name for name in names if name.startswith(f"{arrangement_id}/rgb/") and name.endswith(".png") ) for rgb_path in rgb_paths: camera_label = Path(rgb_path).stem camera_match = CAMERA_RE.fullmatch(camera_label) if camera_match is None: continue camera = camera_from_metadata(metadata, camera_label) intrinsics = camera.get("intrinsics", {}) extrinsics = camera.get("extrinsics", {}) stem = camera_label object_mask_prefix = f"{arrangement_id}/masks/{stem}_obj" rows.append( { "sample_id": f"{scene_zip_id}_{arrangement_id}_{camera_label}", "scene_zip_id": scene_zip_id, "scene_id": str(scene_graph.get("scene_id", f"{scene_zip_id}_{arrangement_id}")), "arrangement_id": arrangement_id, "camera_label": camera_label, "camera_index": int(camera_match.group("camera_index")), "azimuth_deg": float(camera_match.group("azimuth")), "elevation_deg": float(camera_match.group("elevation")), "image": { "bytes": zf.read(rgb_path), "path": f"{zip_path.name}::{rgb_path}", }, "archive": zip_path.name, "rgb_path": rgb_path, "depth_z_path": path_if_present( names, f"{arrangement_id}/depth/{stem}_zdepth.exr" ), "depth_euclidean_path": path_if_present( names, f"{arrangement_id}/depth/{stem}_euclidean.exr" ), "normal_worldspace_path": path_if_present( names, f"{arrangement_id}/normals/{stem}_worldspace.exr" ), "normal_camspace_path": path_if_present( names, f"{arrangement_id}/normals/{stem}_camspace.exr" ), "mask_combined_path": path_if_present( names, f"{arrangement_id}/masks/{stem}_combined.exr" ), "object_mask_paths": sorted( name for name in names if name.startswith(object_mask_prefix) and name.endswith(".exr") ), "metadata_path": metadata_path, "scene_graph_path": scene_graph_path, "blend_path": path_if_present(names, f"{arrangement_id}/scene.blend"), "colmap_cameras_path": path_if_present( names, f"{arrangement_id}/colmap/cameras.txt" ), "colmap_images_path": path_if_present( names, f"{arrangement_id}/colmap/images.txt" ), "colmap_points3d_path": path_if_present( names, f"{arrangement_id}/colmap/points3D.txt" ), "render_width": int(render.get("resolution_x", 0)), "render_height": int(render.get("resolution_y", 0)), "num_cameras": int(render.get("num_cameras", 0)), "num_objects": int(scene_graph.get("num_objects", len(nodes))), "num_edges": len(scene_graph.get("edges", [])), "camera_fx_px": intrinsics.get("fx_px"), "camera_fy_px": intrinsics.get("fy_px"), "camera_fov_h_deg": intrinsics.get("fov_h_deg"), "camera_fov_v_deg": intrinsics.get("fov_v_deg"), "camera_position_world_m": extrinsics.get("position_world_m", []), "object_ids": object_ids, "object_names": object_names, "object_classes": object_classes, "relation_triplets": relation_rows, } ) return rows def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-root", type=Path, default=Path("."), help="Dataset repository root") parser.add_argument( "--output", type=Path, default=Path("data/viewer/train.parquet"), help="Output Parquet file, relative to --repo-root unless absolute", ) args = parser.parse_args() repo_root = args.repo_root.resolve() output_path = args.output if args.output.is_absolute() else repo_root / args.output output_path.parent.mkdir(parents=True, exist_ok=True) rows = build_rows(repo_root) dataset = Dataset.from_list(rows, features=FEATURES) bytes_written = dataset.to_parquet( output_path, batch_size=100, compression="zstd", write_page_index=True, ) print(f"Wrote {len(dataset)} rows to {output_path} ({bytes_written} bytes)") if __name__ == "__main__": main()