File size: 3,613 Bytes
a0ed151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read supplemental simulation One-Shot labels beside a LeRobot v3.0 dataset.

The sidecar labels the active semantic subtask, not reward or success. Semantic
boundary adjustment bands are independent of LeRobot video-loading tolerance.
Requires only the Python standard library and PyArrow.
"""
from pathlib import Path, PurePosixPath
import hashlib
import json

import pyarrow.parquet as pq


class SubtaskAnnotations:
    def __init__(self, dataset_root, verify_manifest=True):
        self.dataset_root = Path(dataset_root)
        self.annotation_root = self.dataset_root / "annotations" / "subtasks"
        self.metadata = json.loads((self.annotation_root / "metadata.json").read_text())
        if verify_manifest:
            manifest = json.loads((self.annotation_root / "manifest.json").read_text())
            for entry in manifest["files"]:
                name = PurePosixPath(entry["path"])
                if name.is_absolute() or ".." in name.parts:
                    raise ValueError("Invalid manifest-relative file path")
                payload = (self.annotation_root / name).read_bytes()
                if len(payload) != entry["bytes"] or hashlib.sha256(payload).hexdigest() != entry["sha256"]:
                    raise ValueError("Annotation manifest checksum mismatch")
        info_path = self.dataset_root / "meta" / "info.json"
        if info_path.exists():
            info = json.loads(info_path.read_text())
            for key in ("fps", "total_episodes", "total_frames"):
                if info.get(key) != self.metadata["dataset"][key]:
                    raise ValueError("Dataset/annotation metadata mismatch: " + key)
            if info.get("codebase_version") != "v3.0":
                raise ValueError("Expected a LeRobot v3.0 dataset")
        self.table = pq.read_table(self.annotation_root / "frame_labels.parquet")
        self.by_frame = {}
        global_indices = set()
        for row in self.table.to_pylist():
            key = (row["episode_index"], row["frame_index"])
            if key in self.by_frame or row["global_index"] in global_indices:
                raise ValueError("Duplicate annotation frame/global index")
            self.by_frame[key] = row
            global_indices.add(row["global_index"])
        if len(self.by_frame) != self.metadata["dataset"]["total_frames"]:
            raise ValueError("Annotation frame count mismatch")
        if global_indices != set(range(self.metadata["dataset"]["total_frames"])):
            raise ValueError("Annotation global index grid mismatch")
        for episode in self.metadata["episodes"]:
            ep = episode["episode_index"]
            for frame in range(episode["length"]):
                row = self.by_frame.get((ep, frame))
                if row is None or row["global_index"] != episode["dataset_from_index"] + frame:
                    raise ValueError("Annotation episode/frame/global index mismatch")

    def label(self, episode_index, frame_index, global_index=None):
        row = self.by_frame[(int(episode_index), int(frame_index))]
        if global_index is not None and row["global_index"] != int(global_index):
            raise ValueError("LeRobot sample index does not match annotation")
        return dict(row)

    def for_sample(self, sample):
        """Attach explicitly to a scalar LeRobotDataset sample, before collation."""
        return self.label(sample["episode_index"], sample["frame_index"], sample["index"])


def load_subtasks(dataset_root, verify_manifest=True):
    return SubtaskAnnotations(dataset_root, verify_manifest=verify_manifest)