rollingoat commited on
Commit
a9b00c0
·
verified ·
1 Parent(s): eeef484

Delete convert_synced_h5_to_lerobot.py

Browse files
Files changed (1) hide show
  1. convert_synced_h5_to_lerobot.py +0 -288
convert_synced_h5_to_lerobot.py DELETED
@@ -1,288 +0,0 @@
1
-
2
- """Convert a synced HDF5 (output of sync_image_low_dim.py) to LeRobot v2.1 format for OpenPI.
3
-
4
- Input HDF5 layout (produced by sync_image_low_dim.py):
5
- data/<demo>/obs/<timestamp_key> (T,)
6
- data/<demo>/obs/<image_key_i> (T, H, W, 3) uint8
7
- data/<demo>/obs/<lowdim_key_j> (T, D_j)
8
- data/<demo>/actions (T, A) optional
9
-
10
- Output: LeRobot v2.1 dataset written directly into <output-dir>.
11
-
12
- Example:
13
- python convert_synced_h5_to_lerobot.py \\
14
- --synced-h5 synced.h5 \\
15
- --output-dir /DATA/lerobot/my_dataset \\
16
- --fps 10 \\
17
- --task "pick up the block" \\
18
- --image-map agentview_image:base_rgb wrist_image:wrist_rgb \\
19
- --state-keys joint_positions gripper_pos \\
20
- --action-source next_state
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- import argparse
26
- import gc
27
- import sys
28
- from pathlib import Path
29
- from typing import Dict, List, Tuple
30
-
31
- import h5py
32
- import numpy as np
33
-
34
- try:
35
- import cv2
36
- _HAS_CV2 = True
37
- except ImportError:
38
- _HAS_CV2 = False
39
-
40
- from datasets import Dataset
41
-
42
-
43
- def _free_hf_dataset(dataset) -> None:
44
- """Mirror convert_to_lerobot.py: empty hf_dataset between episodes to avoid OOM."""
45
- if hasattr(dataset, "hf_dataset") and dataset.hf_dataset is not None:
46
- features = dataset.hf_dataset.features
47
- cols = dataset.hf_dataset.column_names
48
- dataset.hf_dataset = Dataset.from_dict(
49
- {c: [] for c in cols}, features=features
50
- )
51
- gc.collect()
52
-
53
-
54
- def parse_kv_list(items: List[str]) -> Dict[str, str]:
55
- out = {}
56
- for item in items:
57
- if ":" not in item:
58
- raise ValueError(f"Expected 'src:dst', got {item!r}")
59
- k, v = item.split(":", 1)
60
- out[k] = v
61
- return out
62
-
63
-
64
- def resize_image(img: np.ndarray, size: Tuple[int, int]) -> np.ndarray:
65
- """Resize HxWx3 uint8 to size=(H,W). No-op if shapes already match."""
66
- if img.shape[:2] == size:
67
- return img
68
- if not _HAS_CV2:
69
- raise RuntimeError(
70
- f"Image shape {img.shape[:2]} != target {size}; install opencv-python to resize."
71
- )
72
- return cv2.resize(img, (size[1], size[0]), interpolation=cv2.INTER_AREA)
73
-
74
-
75
- def ensure_uint8_rgb(img: np.ndarray) -> np.ndarray:
76
- if img.dtype != np.uint8:
77
- img = np.clip(img, 0, 255).astype(np.uint8)
78
- if img.ndim == 2:
79
- img = np.stack([img] * 3, axis=-1)
80
- if img.shape[-1] == 4:
81
- img = img[..., :3]
82
- return img
83
-
84
-
85
- def build_state(obs: h5py.Group, state_keys: List[str]) -> np.ndarray:
86
- parts = []
87
- for key in state_keys:
88
- arr = np.asarray(obs[key][:])
89
- if arr.ndim == 1:
90
- arr = arr[:, None]
91
- parts.append(arr.astype(np.float32))
92
- return np.concatenate(parts, axis=1)
93
-
94
-
95
- def build_actions(
96
- state: np.ndarray,
97
- demo_group: h5py.Group,
98
- source: str,
99
- ) -> np.ndarray:
100
- T = state.shape[0]
101
- if source == "hdf5_actions":
102
- if "actions" not in demo_group:
103
- raise KeyError(f"'actions' missing in {demo_group.name}; cannot use --action-source hdf5_actions")
104
- a = np.asarray(demo_group["actions"][:], dtype=np.float32)
105
- if a.shape[0] != T:
106
- raise ValueError(f"actions len {a.shape[0]} != state len {T} in {demo_group.name}")
107
- return a
108
- if source == "next_state":
109
- a = np.empty_like(state)
110
- a[:-1] = state[1:]
111
- a[-1] = state[-1]
112
- return a
113
- raise ValueError(f"Unknown --action-source {source!r}")
114
-
115
-
116
- def downsample(arr: np.ndarray, stride: int) -> np.ndarray:
117
- if stride <= 1:
118
- return arr
119
- return arr[::stride]
120
-
121
-
122
- def main() -> None:
123
- p = argparse.ArgumentParser()
124
- p.add_argument("--synced-h5", required=True)
125
- p.add_argument("--output-dir", required=True,
126
- help="Local folder to write the LeRobot dataset into (created if missing).")
127
- p.add_argument("--repo-id", default=None,
128
- help="HuggingFace repo id 'user/name'. Required only with --push-to-hub; "
129
- "otherwise auto-derived from --output-dir basename.")
130
- p.add_argument("--fps", type=int, required=True)
131
- p.add_argument("--source-fps", type=int, default=None,
132
- help="Source FPS of the synced HDF5 (estimated from timestamps if omitted).")
133
- p.add_argument("--task", required=True, help="Language instruction for all episodes.")
134
- p.add_argument("--image-map", nargs="+", required=True,
135
- help="Pairs 'hdf5_key:feature_name', e.g. agentview_image:base_rgb")
136
- p.add_argument("--state-keys", nargs="+", required=True,
137
- help="Ordered lowdim datasets to concatenate into 'state'.")
138
- p.add_argument("--action-source", choices=["next_state", "hdf5_actions"], default="next_state")
139
- p.add_argument("--image-size", type=int, nargs=2, default=None, metavar=("H", "W"),
140
- help="Resize images to (H, W). Omit to keep the native resolution.")
141
- p.add_argument("--timestamp-key", default="timestamp")
142
- p.add_argument("--robot-type", default="ur5e")
143
- p.add_argument("--image-writer-threads", type=int, default=4)
144
- p.add_argument("--push-to-hub", action="store_true")
145
- args = p.parse_args()
146
-
147
- image_map = parse_kv_list(args.image_map)
148
- img_size = tuple(args.image_size) if args.image_size else None
149
-
150
- try:
151
- from lerobot.common.datasets.lerobot_dataset import LeRobotDataset
152
- except ImportError:
153
- from lerobot.datasets.lerobot_dataset import LeRobotDataset
154
-
155
- with h5py.File(args.synced_h5, "r") as f:
156
- if "data" not in f:
157
- raise KeyError("Input HDF5 has no top-level 'data' group")
158
- demos = sorted(f["data"].keys())
159
- if not demos:
160
- raise ValueError("No demos found")
161
-
162
- # Peek first demo to infer feature shapes + action dim.
163
- first_obs = f["data"][demos[0]]["obs"]
164
- for src in image_map:
165
- if src not in first_obs:
166
- raise KeyError(f"Image key {src!r} not in {first_obs.name}")
167
- state0 = build_state(first_obs, args.state_keys)
168
- state_dim = state0.shape[1]
169
-
170
- if args.action_source == "hdf5_actions":
171
- a0 = np.asarray(f["data"][demos[0]]["actions"])
172
- action_dim = a0.shape[1] if a0.ndim > 1 else 1
173
- else:
174
- action_dim = state_dim
175
-
176
- # Estimate source FPS from first demo timestamps if not provided.
177
- if args.source_fps is None:
178
- ts = np.asarray(first_obs[args.timestamp_key][:], dtype=np.float64)
179
- if ts.size < 2:
180
- raise ValueError("Cannot estimate source fps: first demo has <2 timestamps")
181
- dt = np.median(np.diff(ts))
182
- src_fps = int(round(1.0 / dt))
183
- print(f"Estimated source FPS: {src_fps} (dt={dt:.4f}s)")
184
- else:
185
- src_fps = args.source_fps
186
-
187
- if src_fps % args.fps != 0:
188
- raise ValueError(f"source fps {src_fps} not divisible by target fps {args.fps}")
189
- stride = src_fps // args.fps
190
-
191
- if img_size is None:
192
- sample_img = np.asarray(first_obs[next(iter(image_map))][0])
193
- native_hw = sample_img.shape[:2]
194
- feat_hw = native_hw
195
- else:
196
- feat_hw = img_size
197
-
198
- features = {}
199
- for dst in image_map.values():
200
- features[dst] = {
201
- "dtype": "image",
202
- "shape": (feat_hw[0], feat_hw[1], 3),
203
- "names": ["height", "width", "channel"],
204
- }
205
- features["state"] = {
206
- "dtype": "float32",
207
- "shape": (state_dim,),
208
- "names": {"motors": [f"s{i}" for i in range(state_dim)]},
209
- }
210
- features["action"] = {
211
- "dtype": "float32",
212
- "shape": (action_dim,),
213
- "names": {"motors": [f"a{i}" for i in range(action_dim)]},
214
- }
215
-
216
- out_root = Path(args.output_dir).expanduser().resolve()
217
- out_root.parent.mkdir(parents=True, exist_ok=True)
218
- if out_root.exists():
219
- raise FileExistsError(f"--output-dir {out_root} already exists; remove it or pick a new path")
220
- repo_id = args.repo_id or f"local/{out_root.name}"
221
- if args.push_to_hub and args.repo_id is None:
222
- raise ValueError("--push-to-hub requires --repo-id 'user/name'")
223
- dataset = LeRobotDataset.create(
224
- repo_id=repo_id,
225
- fps=args.fps,
226
- robot_type=args.robot_type,
227
- features=features,
228
- use_videos=False,
229
- image_writer_threads=args.image_writer_threads,
230
- root=str(out_root),
231
- )
232
-
233
- total_frames = 0
234
- converted = 0
235
- for demo in demos:
236
- g = f["data"][demo]
237
- obs = g["obs"]
238
- try:
239
- state = build_state(obs, args.state_keys)
240
- action = build_actions(state, g, args.action_source)
241
-
242
- imgs = {}
243
- for src, dst in image_map.items():
244
- raw = np.asarray(obs[src][:])
245
- imgs[dst] = raw
246
-
247
- # Downsample all arrays consistently.
248
- state = downsample(state, stride)
249
- action = downsample(action, stride)
250
- for k in list(imgs):
251
- imgs[k] = downsample(imgs[k], stride)
252
-
253
- T = state.shape[0]
254
- if T < 2:
255
- print(f" Skip {demo}: only {T} frame(s) after downsampling")
256
- continue
257
-
258
- for t in range(T):
259
- frame = {"state": state[t].astype(np.float32),
260
- "action": action[t].astype(np.float32),
261
- "task": args.task}
262
- for dst, arr in imgs.items():
263
- img = ensure_uint8_rgb(arr[t])
264
- if img_size is not None:
265
- img = resize_image(img, img_size)
266
- frame[dst] = img
267
- dataset.add_frame(frame)
268
-
269
- dataset.save_episode()
270
- _free_hf_dataset(dataset)
271
- total_frames += T
272
- converted += 1
273
- print(f" {demo}: {T} frames")
274
- except Exception as e:
275
- print(f" ERROR on {demo}: {e}", file=sys.stderr)
276
- raise
277
-
278
- if hasattr(dataset, "finalize"):
279
- dataset.finalize()
280
-
281
- print(f"\nConverted {converted}/{len(demos)} demos, {total_frames} frames -> {out_root}")
282
-
283
- if args.push_to_hub:
284
- dataset.push_to_hub()
285
-
286
-
287
- if __name__ == "__main__":
288
- main()