File size: 7,839 Bytes
2d82de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""Export LabEmbodied-Data H5 episodes to a local LeRobot v3.0 dataset.

Requires LeRobot 0.4.4. Exports joint states, joint-position targets, language,
and RGB videos. Additional annotations remain available in the source H5 files.
"""

import argparse
from contextlib import ExitStack, contextmanager
from copy import deepcopy
import json
from pathlib import Path
import tempfile

import cv2
import h5py
import numpy as np


def select_episodes(source, robot, limit):
    selected = []
    with (source / "meta/episodes.jsonl").open(encoding="utf-8") as index:
        for line in index:
            item = json.loads(line)
            if item["robot_type"] == robot and item["success"]:
                selected.append(item)
                if limit is not None and len(selected) == limit:
                    break
    if not selected:
        raise ValueError(f"No successful episodes found for robot {robot!r}")
    return selected


def episode_layout(episode, robot):
    """Read and validate the state, action, video, and timing contract."""
    if episode.attrs["robot_type"] != robot or not episode.attrs["episode_success"]:
        raise ValueError(f"Unexpected robot or unsuccessful episode: {episode.filename}")
    count = int(episode.attrs["frame_count"])
    fps = float(episode.attrs["fps"])
    if count <= 0 or fps <= 0 or not fps.is_integer():
        raise ValueError("Expected a nonempty episode with an integer frame rate")
    states, actions = episode["agent_pose"], episode["actions"]
    if states.ndim != 2 or states.shape != actions.shape or states.shape[0] != count:
        raise ValueError("States and joint-position targets must have matching (T, D) shapes")
    names = episode["agent_pose_names"].asstr()[()].tolist()
    if len(names) != states.shape[1]:
        raise ValueError("Joint names do not match the state dimension")
    features = {
        "observation.state": {"dtype": "float32", "shape": states.shape[1:], "names": names},
        "action": {"dtype": "float32", "shape": actions.shape[1:], "names": names},
    }
    cameras = sorted(key for key in episode if key.startswith("camera_") and key.endswith("_rgb"))
    if not cameras:
        raise ValueError("No camera videos found")
    for camera in cameras:
        video = episode[camera]
        shape = tuple(int(value) for value in video.attrs["image_shape"])
        if len(shape) != 3:
            raise ValueError(f"Expected a three-dimensional image shape: {camera}")
        layout = video.attrs["image_layout"]
        if layout == "HWC":
            shape = (shape[2], shape[0], shape[1])
        elif layout != "CHW":
            raise ValueError(f"Unsupported image layout: {layout}")
        if (
            shape[0] != 3
            or int(video.attrs["frame_count"]) != count
            or float(video.attrs["fps"]) != fps
        ):
            raise ValueError(f"Video layout or timing mismatch: {camera}")
        features[f"observation.images.{camera}"] = {
            "dtype": "video", "shape": shape, "names": ["channels", "height", "width"],
        }
    return int(fps), features, cameras


@contextmanager
def open_video(video, path):
    path.write_bytes(video[()].tobytes())
    capture = cv2.VideoCapture(str(path))
    try:
        if not capture.isOpened():
            raise ValueError(f"Cannot open video: {video.name}")
        yield capture
    finally:
        capture.release()


def export(source, output, repo_id, robot, limit):
    # Import lazily so --help does not require the full LeRobot installation.
    from lerobot.datasets.lerobot_dataset import LeRobotDataset

    items = select_episodes(source, robot, limit)
    with h5py.File(source / items[0]["hdf5_path"], "r") as episode:
        fps, features, cameras = episode_layout(episode, robot)
    dataset = LeRobotDataset.create(
        repo_id=repo_id, root=output, fps=fps, features=deepcopy(features),
        robot_type=robot, use_videos=True, video_backend="pyav",
        vcodec="h264", image_writer_threads=4, encoder_threads=2,
    )
    try:
        # LeRobot assigns consecutive episode indices; retain the source IDs here.
        with (output / "meta/source_episodes.jsonl").open("w", encoding="utf-8") as mapping:
            for episode_index, item in enumerate(items):
                print(f"[{episode_index + 1}/{len(items)}] {item['episode_id']}", flush=True)
                with h5py.File(source / item["hdf5_path"], "r") as episode:
                    if episode_layout(episode, robot) != (fps, features, cameras):
                        raise ValueError("Export each robot, frame rate, and feature layout separately")
                    states = np.asarray(episode["agent_pose"], dtype=np.float32)
                    actions = np.asarray(episode["actions"], dtype=np.float32)
                    task = episode["language_instruction"].asstr()[()]
                    with tempfile.TemporaryDirectory(prefix="labembodied-") as directory, ExitStack() as stack:
                        videos = {
                            camera: stack.enter_context(open_video(episode[camera], Path(directory) / f"{camera}.mp4"))
                            for camera in cameras
                        }
                        for frame_index in range(len(states)):
                            frame = {
                                "observation.state": states[frame_index],
                                "action": actions[frame_index],
                                "task": task,
                            }
                            for camera, capture in videos.items():
                                ok, bgr = capture.read()
                                key = f"observation.images.{camera}"
                                c, h, w = features[key]["shape"]
                                if not ok or bgr.shape != (h, w, c):
                                    raise ValueError(f"Missing or invalid frame {frame_index} in {camera}")
                                frame[key] = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
                            dataset.add_frame(frame)
                        for camera, capture in videos.items():
                            if capture.read()[0]:
                                raise ValueError(f"Extra video frames in {camera}")
                    dataset.save_episode(parallel_encoding=False)
                mapping.write(json.dumps({
                    "episode_index": episode_index,
                    "source_episode_id": item["episode_id"],
                    "source_hdf5_path": item["hdf5_path"],
                }) + "\n")
                mapping.flush()
    finally:
        try:
            dataset.finalize()
        finally:
            dataset.stop_image_writer()
    print(f"Saved {len(items)} episodes to {output}")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", type=Path, default=Path("."), help="Raw dataset root (default: current directory)")
    parser.add_argument("--out", type=Path, required=True, help="New output directory; must not already exist")
    parser.add_argument("--repo-id", required=True, help="LeRobot dataset ID, e.g. local/labembodied-ur5e")
    parser.add_argument("--robot", required=True, help="Robot type in the episode index, e.g. ur5e")
    parser.add_argument("--max-episodes", type=int, help="Limit the export for a small trial; omit to export all selected episodes")
    args = parser.parse_args()
    if args.out.exists():
        parser.error("Output directory already exists; choose a new --out path")
    if args.max_episodes is not None and args.max_episodes <= 0:
        parser.error("--max-episodes must be positive")
    export(args.source, args.out, args.repo_id, args.robot, args.max_episodes)


if __name__ == "__main__":
    main()