Dimios45 commited on
Commit
7d5a9f9
·
verified ·
1 Parent(s): ea06097

Ship the LeRobot->robomimic converter with the dataset

Browse files
Files changed (1) hide show
  1. to_robomimic.py +242 -0
to_robomimic.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert either recorded dataset into a robomimic HDF5 for bspline/diffusion training.
2
+
3
+ Two input formats, two action spaces, one tool — so the crop, the resize and
4
+ the RGB convention are defined in exactly one place for both:
5
+
6
+ --from bspline their episode dirs (`data.pkl` + `<key>.mp4`)
7
+ -> obs {arm_pos(3), arm_quat(4), gripper_pos(1), images}
8
+ actions (N, 7) = [pos(3), rotvec(3), gripper(1)]
9
+ Their dataset class turns the rotvec into rotation_6d, so
10
+ the trained action is 10-dim: their `single_yam_rot6d`.
11
+
12
+ --from lerobot a LeRobot v3 dataset with 7-dim joint state/action
13
+ -> obs {joint_pos(7), images}
14
+ actions (N, 7) = [joint1..6 (rad), gripper]
15
+ Their `single_yam_joint` format: no rotation conversion and
16
+ no IK at deploy.
17
+
18
+ With no --crop the bspline path is byte-identical to their
19
+ `convert_to_robomimic_hdf5.py`; this tool adds cropping and the joint-space
20
+ input.
21
+
22
+ Cropping happens here rather than at record time on purpose: the recorded mp4s
23
+ stay full-resolution, so a crop can be retuned and the HDF5 rebuilt without
24
+ re-recording. Whatever rectangle you pick MUST also be applied to the
25
+ observation at deployment, or the policy sees a distribution it never trained
26
+ on. Crops are stored in the HDF5 attrs so the choice travels with the data.
27
+
28
+ python tools/to_robomimic.py --from bspline \\
29
+ --input-dir data/demos-ee-pick-duster \\
30
+ --output-path ~/bspline-policy/data/yam_ee.hdf5 \\
31
+ --crop top_image=42,28,598,414
32
+
33
+ python tools/to_robomimic.py --from lerobot \\
34
+ --repo-id Dimios45/yam-pick-duster --root data/lerobot-pick-duster \\
35
+ --output-path ~/bspline-policy/data/yam_joint.hdf5 \\
36
+ --crop top_image=42,28,598,414
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import argparse
42
+ import json
43
+ import sys
44
+ from pathlib import Path
45
+
46
+ import cv2
47
+ import h5py
48
+ import numpy as np
49
+
50
+ DEFAULT_BSPLINE_REPO = Path.home() / "bspline-policy/real_env/yam_teleop"
51
+ # Their constants.POLICY_IMAGE_WIDTH / HEIGHT — what the policy server feeds
52
+ # the network at inference, so the dataset must match.
53
+ POLICY_IMAGE_SIZE = 84
54
+
55
+ # LeRobot camera key -> the obs key their configs expect.
56
+ LEROBOT_IMAGE_KEYS = {
57
+ "observation.images.right_wrist": "wrist_image",
58
+ "observation.images.left_wrist": "wrist_image",
59
+ "observation.images.top": "top_image",
60
+ }
61
+
62
+
63
+ def _parse_crop(spec: str):
64
+ cam, _, rect = spec.partition("=")
65
+ parts = [int(v) for v in rect.split(",")]
66
+ if len(parts) != 4:
67
+ raise argparse.ArgumentTypeError(f"--crop {spec!r} must be <image_key>=x,y,w,h")
68
+ return cam.strip(), tuple(parts)
69
+
70
+
71
+ def _prepare(img: np.ndarray, key: str, crops: dict, size: int) -> np.ndarray:
72
+ """Crop (optional) then resize to the policy's input size. RGB uint8 in and out."""
73
+ if key in crops:
74
+ x, y, w, h = crops[key]
75
+ ih, iw = img.shape[:2]
76
+ w = w or (iw - x)
77
+ h = h or (ih - y)
78
+ if x < 0 or y < 0 or x + w > iw or y + h > ih:
79
+ raise SystemExit(f"crop {x},{y},{w},{h} for {key} does not fit in {iw}x{ih}")
80
+ img = img[y:y + h, x:x + w]
81
+ return cv2.resize(img, (size, size))
82
+
83
+
84
+ def _quat_xyzw_to_rotvec(quat_xyzw: np.ndarray) -> np.ndarray:
85
+ """Axis-angle from an xyzw quaternion — matches scipy's `as_rotvec`, which
86
+ is what their converter uses, without taking a scipy dependency."""
87
+ q = np.asarray(quat_xyzw, dtype=np.float64)
88
+ q = q / np.linalg.norm(q)
89
+ if q[3] < 0.0: # shortest rotation
90
+ q = -q
91
+ angle = 2.0 * np.arccos(np.clip(q[3], -1.0, 1.0))
92
+ s = np.sqrt(max(0.0, 1.0 - q[3] * q[3]))
93
+ if s < 1e-12: # tiny angle: axis is ill-conditioned, series expansion instead
94
+ return 2.0 * q[:3]
95
+ return (angle / s) * q[:3]
96
+
97
+
98
+ def convert_bspline(args, crops: dict) -> tuple[int, int, dict]:
99
+ sys.path.insert(0, str(Path(args.bspline_repo)))
100
+ try:
101
+ from episode_storage import EpisodeReader # their code, unmodified
102
+ except ImportError as e:
103
+ raise SystemExit(f"cannot import their episode_storage from {args.bspline_repo}: {e}")
104
+
105
+ root = Path(args.input_dir)
106
+ episode_dirs = sorted(d for d in root.iterdir() if d.is_dir())
107
+ if args.max_episodes:
108
+ episode_dirs = episode_dirs[:args.max_episodes]
109
+ if not episode_dirs:
110
+ raise SystemExit(f"no episode dirs under {root}")
111
+
112
+ n_frames = 0
113
+ obs_keys: dict = {}
114
+ with h5py.File(args.output_path, "w") as f:
115
+ data = f.create_group("data")
116
+ for idx, ep in enumerate(episode_dirs):
117
+ r = EpisodeReader(ep)
118
+ obs: dict[str, list] = {}
119
+ for o in r.observations:
120
+ for k, v in o.items():
121
+ v = np.asarray(v)
122
+ if v.ndim == 3:
123
+ v = _prepare(v, k, crops, args.image_size)
124
+ obs.setdefault(k, []).append(v)
125
+ actions = [np.concatenate((
126
+ np.asarray(a["arm_pos"], dtype=np.float64),
127
+ _quat_xyzw_to_rotvec(a["arm_quat"]),
128
+ np.asarray(a["gripper_pos"], dtype=np.float64),
129
+ )) for a in r.actions]
130
+
131
+ g = data.create_group(f"demo_{idx}")
132
+ for k, v in obs.items():
133
+ g.create_dataset(f"obs/{k}", data=np.array(v))
134
+ g.create_dataset("actions", data=np.array(actions))
135
+ n_frames += len(r)
136
+ obs_keys = {k: np.array(v).shape[1:] for k, v in obs.items()}
137
+ print(f" demo_{idx:<3d} {len(r):4d} frames {ep.name}")
138
+ _stamp(f, args, crops, "bspline", "single_yam_rot6d")
139
+ return len(episode_dirs), n_frames, obs_keys
140
+
141
+
142
+ def convert_lerobot(args, crops: dict) -> tuple[int, int, dict]:
143
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
144
+
145
+ ds = LeRobotDataset(args.repo_id, root=args.root)
146
+ state_dim = ds.meta.features["observation.state"]["shape"][0]
147
+ if state_dim != 7:
148
+ raise SystemExit(
149
+ f"expected a 7-dim joint state (joint1..6 + gripper), got {state_dim}. "
150
+ "This path is for single-arm joint-space datasets.")
151
+
152
+ episode_index = np.array(ds.hf_dataset["episode_index"])
153
+ n_eps = ds.num_episodes if not args.max_episodes else min(args.max_episodes, ds.num_episodes)
154
+
155
+ n_frames = 0
156
+ obs_keys: dict = {}
157
+ with h5py.File(args.output_path, "w") as f:
158
+ data = f.create_group("data")
159
+ for idx in range(n_eps):
160
+ rows = np.flatnonzero(episode_index == idx)
161
+ joint_pos, actions = [], []
162
+ images: dict[str, list] = {}
163
+ for row in rows:
164
+ item = ds[int(row)]
165
+ joint_pos.append(item["observation.state"].numpy().astype(np.float64))
166
+ actions.append(item["action"].numpy().astype(np.float64))
167
+ for cam_key, out_key in LEROBOT_IMAGE_KEYS.items():
168
+ if cam_key not in item:
169
+ continue
170
+ # LeRobot hands back CHW float32 in [0, 1], RGB.
171
+ img = (item[cam_key].numpy().transpose(1, 2, 0) * 255.0)
172
+ img = np.clip(img, 0, 255).astype(np.uint8)
173
+ images.setdefault(out_key, []).append(
174
+ _prepare(img, out_key, crops, args.image_size))
175
+
176
+ g = data.create_group(f"demo_{idx}")
177
+ g.create_dataset("obs/joint_pos", data=np.array(joint_pos))
178
+ for k, v in images.items():
179
+ g.create_dataset(f"obs/{k}", data=np.array(v))
180
+ g.create_dataset("actions", data=np.array(actions))
181
+ n_frames += len(rows)
182
+ obs_keys = {"joint_pos": (7,), **{k: np.array(v).shape[1:] for k, v in images.items()}}
183
+ print(f" demo_{idx:<3d} {len(rows):4d} frames")
184
+ _stamp(f, args, crops, "lerobot", "single_yam_joint")
185
+ return n_eps, n_frames, obs_keys
186
+
187
+
188
+ def _stamp(f, args, crops: dict, source: str, action_format: str) -> None:
189
+ """Record how this HDF5 was built, so the deployment side can reproduce the
190
+ exact image pipeline instead of relying on someone's memory."""
191
+ f.attrs["source_format"] = source
192
+ f.attrs["action_format"] = action_format
193
+ f.attrs["image_size"] = args.image_size
194
+ f.attrs["crops"] = json.dumps({k: list(v) for k, v in crops.items()})
195
+ f.attrs["gripper_convention"] = "0=open, 1=closed"
196
+
197
+
198
+ def main() -> None:
199
+ ap = argparse.ArgumentParser()
200
+ ap.add_argument("--from", dest="source", choices=("bspline", "lerobot"), required=True)
201
+ ap.add_argument("--output-path", required=True)
202
+ ap.add_argument("--crop", action="append", default=[], type=_parse_crop,
203
+ help="<image_key>=x,y,w,h, e.g. top_image=42,28,598,414 (repeatable)")
204
+ ap.add_argument("--image-size", type=int, default=POLICY_IMAGE_SIZE,
205
+ help=f"square size fed to the policy (default: {POLICY_IMAGE_SIZE})")
206
+ ap.add_argument("--max-episodes", type=int, default=0, help="0 = all")
207
+ # bspline source
208
+ ap.add_argument("--input-dir", help="[--from bspline] directory of episode dirs")
209
+ ap.add_argument("--bspline-repo", default=str(DEFAULT_BSPLINE_REPO))
210
+ # lerobot source
211
+ ap.add_argument("--repo-id", help="[--from lerobot] dataset repo id")
212
+ ap.add_argument("--root", help="[--from lerobot] local dataset root")
213
+ args = ap.parse_args()
214
+
215
+ crops = dict(args.crop)
216
+ Path(args.output_path).parent.mkdir(parents=True, exist_ok=True)
217
+
218
+ if args.source == "bspline":
219
+ if not args.input_dir:
220
+ raise SystemExit("--from bspline needs --input-dir")
221
+ n_eps, n_frames, obs_keys = convert_bspline(args, crops)
222
+ else:
223
+ if not args.repo_id:
224
+ raise SystemExit("--from lerobot needs --repo-id (and usually --root)")
225
+ n_eps, n_frames, obs_keys = convert_lerobot(args, crops)
226
+
227
+ size_mb = Path(args.output_path).stat().st_size / 1e6
228
+ print(f"\n{n_eps} demos, {n_frames} frames -> {args.output_path} ({size_mb:.0f} MB)")
229
+ print("obs keys:", {k: tuple(v) for k, v in obs_keys.items()})
230
+ print("crops :", {k: list(v) for k, v in crops.items()} or "none")
231
+ print("\nshape_meta for the task yaml:")
232
+ for k, shape in obs_keys.items():
233
+ if len(shape) == 3:
234
+ print(f" {k}:\n shape: [3, {shape[0]}, {shape[1]}]\n type: rgb")
235
+ else:
236
+ print(f" {k}:\n shape: [{shape[0]}]")
237
+ print(" action:")
238
+ print(f" shape: [{10 if args.source == 'bspline' else 7}]")
239
+
240
+
241
+ if __name__ == "__main__":
242
+ main()