File size: 5,757 Bytes
8648e1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()