sparc-droid-annotations / scripts /read_sparc_droid.py
holgerson's picture
Add files using upload-large-folder tool
8648e1c verified
Raw History Blame Contribute Delete
5.76 kB
#!/usr/bin/env python3
"""Read and validate the SPARC DROID JSONL + HDF5 release."""
from __future__ import annotations
import argparse
from contextlib import ExitStack
import json
from pathlib import Path
from typing import Iterable, Iterator, Mapping, Sequence
import h5py
import numpy as np
VIEW_DIRS = {
"left": "droid_lerobot_left",
"right": "droid_lerobot_right",
}
def view_root(repo_root: str | Path, view: str) -> Path:
try:
dirname = VIEW_DIRS[view]
except KeyError as exc:
raise ValueError(f"view must be one of {sorted(VIEW_DIRS)}, got {view!r}") from exc
root = Path(repo_root) / "data" / dirname
if not root.is_dir():
raise FileNotFoundError(root)
return root
def manifest_paths(repo_root: str | Path, view: str) -> list[Path]:
"""Return a non-duplicating manifest list for a camera view."""
root = view_root(repo_root, view)
consolidated = root / "annotations.jsonl"
if consolidated.is_file():
return [consolidated]
nodes = sorted(root.glob("annotations_node*.jsonl"))
if not nodes:
raise FileNotFoundError(f"No annotation manifests found under {root}")
return nodes
def iter_annotations(repo_root: str | Path, view: str) -> Iterator[dict]:
for manifest in manifest_paths(repo_root, view):
with manifest.open("r", encoding="utf-8") as stream:
for line_number, line in enumerate(stream, 1):
if not line.strip():
continue
try:
yield json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON at {manifest}:{line_number}") from exc
def storage_reference(repo_root: str | Path, annotation: Mapping, view: str) -> tuple[Path, str]:
arrays = annotation.get("arrays") or {}
storage = arrays.get("storage") or {}
if "path" not in storage or "group" not in storage:
raise KeyError(f"Annotation {annotation.get('annotation_id')} has no HDF5 storage reference")
shard = view_root(repo_root, view) / storage["path"]
return shard, storage["group"]
def load_arrays(
repo_root: str | Path,
annotation: Mapping,
view: str,
keys: Sequence[str] | None = None,
) -> dict[str, np.ndarray]:
"""Load selected arrays, copying them out before closing the HDF5 file."""
shard, group_name = storage_reference(repo_root, annotation, view)
with h5py.File(shard, "r") as handle:
if group_name not in handle:
raise KeyError(f"Missing group {group_name!r} in {shard}")
group = handle[group_name]
selected = list(group.keys()) if keys is None else list(keys)
missing = [key for key in selected if key not in group]
if missing:
raise KeyError(f"Arrays absent from {group_name}: {missing}")
return {key: np.asarray(group[key]) for key in selected}
def verify(repo_root: str | Path, views: Iterable[str] = ("left", "right")) -> dict:
"""Validate IDs and every JSON-to-HDF5 path/group reference."""
result = {}
for view in views:
annotation_ids: set[str] = set()
trajectory_ids: set[str] = set()
rows = 0
with ExitStack() as stack:
handles: dict[Path, h5py.File] = {}
for annotation in iter_annotations(repo_root, view):
rows += 1
annotation_id = str(annotation["annotation_id"])
if annotation_id in annotation_ids:
raise ValueError(f"Duplicate annotation_id in {view}: {annotation_id}")
annotation_ids.add(annotation_id)
trajectory_ids.add(str(annotation["source"]["trajectory_id"]))
shard, group_name = storage_reference(repo_root, annotation, view)
if not shard.is_file():
raise FileNotFoundError(shard)
if shard not in handles:
handles[shard] = stack.enter_context(h5py.File(shard, "r"))
if group_name not in handles[shard]:
raise KeyError(f"Missing group {group_name!r} in {shard}")
result[view] = {
"annotation_rows": rows,
"unique_annotation_ids": len(annotation_ids),
"unique_trajectories": len(trajectory_ids),
}
return result
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("repo_root", type=Path)
parser.add_argument("--view", choices=sorted(VIEW_DIRS), default="right")
parser.add_argument("--limit", type=int, default=3)
parser.add_argument("--show-arrays", action="store_true")
parser.add_argument("--verify", action="store_true")
args = parser.parse_args()
if args.verify:
print(json.dumps(verify(args.repo_root), indent=2, sort_keys=True))
return
for index, annotation in enumerate(iter_annotations(args.repo_root, args.view)):
if index >= args.limit:
break
summary = {
"annotation_id": annotation["annotation_id"],
"trajectory_id": annotation["source"]["trajectory_id"],
"source_uuid": annotation["source"].get("source_uuid"),
"subtask_index": annotation["source"]["subtask_index"],
"instruction": annotation["task"]["instruction"],
"selection_score": annotation["selection"]["score"],
}
print(json.dumps(summary, indent=2, ensure_ascii=False))
if args.show_arrays:
arrays = load_arrays(args.repo_root, annotation, args.view)
print({key: {"shape": value.shape, "dtype": str(value.dtype)} for key, value in arrays.items()})
if __name__ == "__main__":
main()