TrieTran commited on
Commit
3255c6b
·
verified ·
1 Parent(s): c278bb8

Upload folder using huggingface_hub

Browse files
hdf5_data/hdf5_maker.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert a single task folder with sequences into LIBERO-like demos with fields:
3
+
4
+ actions, gripper_states, joint_states, robot_states, ee_states,
5
+ agentview_images, eye_in_hand_images, agentview_depths, eye_in_hand_depths,
6
+ agentview_segs, eye_in_hand_segs, agentview_boxes, eye_in_hand_boxes,
7
+ rewards, dones
8
+
9
+ Expected layout (per task):
10
+ taskX/
11
+ success/
12
+ <seq_name>/
13
+ camera_base.mp4 # agentview RGB
14
+ camera_wrist.mp4 # eye-in-hand RGB
15
+ trajectory.pkl # dict-like (see below)
16
+ masks/
17
+ <seq_name>/
18
+ masks/
19
+ 000000_id1.png, 000000_id2.png, 000001_id1.png, ...
20
+
21
+ We infer T (timesteps) from trajectory.pkl (preferred keys: robot_gripper_pose, timestamp).
22
+ We parse mask PNGs named "{frame:06d}_id{instance}.png" into a per-frame label map,
23
+ and compute per-frame boxes per instance id.
24
+
25
+ Trajectory .pkl keys (examples):
26
+ ['robot_eef_pose', 'robot_eef_pose_vel', 'robot_joint', 'robot_joint_vel',
27
+ 'robot_gripper_pose', 'timestamp', 'task_description']
28
+
29
+ Actions policy:
30
+ - If 'robot_joint_vel' exists: actions = robot_joint_vel (T, DoF)
31
+ - Else if 'robot_eef_pose_vel' exists: actions = robot_eef_pose_vel (T, 6/7)
32
+ - Else: finite-difference of 'robot_joint' (pad last row with zeros).
33
+
34
+ Depth and eye-in-hand segs:
35
+ - If no depth available, we create zero arrays with the correct length and frame shape.
36
+ - If only one set of masks exists (agentview), we mirror it to eye-in-hand segs for compatibility.
37
+
38
+ Boxes:
39
+ - Stored in metainfo JSON as lists of [x1,y1,x2,y2] per frame (pixel coords).
40
+
41
+ Requires: numpy, opencv-python, h5py, pillow (PIL)
42
+ """
43
+ import argparse, json, os, pickle, re, sys
44
+ from dataclasses import dataclass
45
+ from pathlib import Path
46
+ from typing import List, Tuple, Dict, Sequence, Optional, Any
47
+ import imageio
48
+
49
+ import numpy as np
50
+ import h5py
51
+ import cv2
52
+
53
+ from PIL import Image
54
+
55
+ MASK_RE = re.compile(r'^(?P<frame>\d+)_id(?P<inst>\d+)\.(?:png|jpg|jpeg|bmp)$', re.IGNORECASE)
56
+
57
+
58
+ # ---------- helpers ----------
59
+ def _ensure_uint8_rgb(img: np.ndarray) -> np.ndarray:
60
+ arr = np.asarray(img)
61
+ if arr.ndim == 2: arr = np.stack([arr]*3, axis=-1)
62
+ if arr.shape[-1] == 4: arr = arr[..., :3]
63
+ if arr.dtype != np.uint8:
64
+ if np.issubdtype(arr.dtype, np.floating) and arr.max() <= 1.0:
65
+ arr = (arr * 255.0 + 0.5).astype(np.uint8)
66
+ else:
67
+ arr = np.clip(arr, 0, 255).astype(np.uint8)
68
+ return arr
69
+
70
+ def _label_to_color(label_map: np.ndarray,
71
+ color_map: Optional[Dict[int, Tuple[int,int,int]]] = None):
72
+ H, W = label_map.shape
73
+ colored = np.zeros((H, W, 3), dtype=np.uint8)
74
+ color_map = {} if color_map is None else dict(color_map)
75
+ for lid in np.unique(label_map):
76
+ if lid == 0: continue
77
+ if lid not in color_map:
78
+ rng = np.random.RandomState(lid * 9973 % (2**31-1))
79
+ color_map[lid] = tuple(int(x) for x in rng.randint(40, 220, size=3))
80
+ colored[label_map == lid] = color_map[lid]
81
+ return colored, color_map
82
+
83
+ def _overlay(rgb: np.ndarray, over_rgb: np.ndarray, alpha: float = 0.5) -> np.ndarray:
84
+ out = (1.0 - alpha) * rgb.astype(np.float32) + alpha * over_rgb.astype(np.float32)
85
+ return np.clip(out, 0, 255).astype(np.uint8)
86
+
87
+ def _draw_bboxes(rgb: np.ndarray,
88
+ bboxes: Sequence[Tuple[int, Sequence[int]]],
89
+ color_map: Optional[Dict[int, Tuple[int,int,int]]] = None) -> np.ndarray:
90
+ img = rgb.copy()
91
+ color_map = {} if color_map is None else color_map
92
+ defined_labels = {'id40': 'bottle 1',
93
+ 'id20': 'bottle 2',
94
+ 'id60': 'bowl 1',
95
+ 'id100': 'robot',
96
+ 'id80': 'bowl 1'}
97
+ for seg_id, box in bboxes:
98
+ x, y, x2, y2 = [int(v) for v in box]
99
+ if seg_id not in color_map:
100
+ rng = np.random.RandomState(seg_id * 9973 % (2**31-1))
101
+ color_map[seg_id] = tuple(int(x) for x in rng.randint(40, 220, size=3))
102
+ bgr = color_map[seg_id][::-1]
103
+ cv2.rectangle(img, (x, y), (x2, y2), bgr, 2)
104
+ label = defined_labels[f"id{seg_id}"]
105
+ (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
106
+ cv2.rectangle(img, (x, y - th - 4), (x + tw + 4, y), bgr, -1)
107
+ cv2.putText(img, label, (x + 2, y - 4),
108
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1, cv2.LINE_AA)
109
+ return img
110
+
111
+ # ---------- main ----------
112
+ def save_annotation_video_imageio(
113
+ agentview_images: List[np.ndarray],
114
+ agentview_segs: List[np.ndarray],
115
+ agentview_bboxes: List[List[Tuple[int, Sequence[int]]]],
116
+ out_path: str,
117
+ fps: int = 20,
118
+ resize: Optional[Tuple[int,int]] = None,
119
+ seg_alpha: float = 0.5,
120
+ layout: str = "hstack"
121
+ ) -> str:
122
+ """Save annotated rollout video with raw | bbox | seg-overlay panels using imageio."""
123
+ assert len(agentview_images) == len(agentview_segs) == len(agentview_bboxes)
124
+ T = len(agentview_images)
125
+ if T == 0:
126
+ raise ValueError("No frames to render")
127
+
128
+ imgs = [_ensure_uint8_rgb(f) for f in agentview_images]
129
+ segs = [np.asarray(s, dtype=np.int32) for s in agentview_segs]
130
+
131
+ H, W = imgs[0].shape[:2]
132
+ if resize is not None:
133
+ W, H = resize
134
+ imgs = [cv2.resize(im, (W, H), interpolation=cv2.INTER_LINEAR) for im in imgs]
135
+ segs = [cv2.resize(s, (W, H), interpolation=cv2.INTER_NEAREST) for s in segs]
136
+ else:
137
+ imgs = [cv2.resize(im, (W, H), interpolation=cv2.INTER_LINEAR) if im.shape[:2] != (H, W) else im for im in imgs]
138
+ segs = [cv2.resize(s, (W, H), interpolation=cv2.INTER_NEAREST) if s.shape != (H, W) else s for s in segs]
139
+
140
+ color_map: Dict[int, Tuple[int,int,int]] = {}
141
+
142
+ def compose(t: int) -> np.ndarray:
143
+ raw = imgs[t]
144
+ box_img = _draw_bboxes(raw, agentview_bboxes[t], color_map=color_map)
145
+ seg_col, cm2 = _label_to_color(segs[t], color_map=color_map)
146
+ color_map.update(cm2)
147
+ seg_overlay = _overlay(raw, seg_col, alpha=seg_alpha)
148
+ if layout == "hstack":
149
+ return np.concatenate([raw, box_img, seg_overlay], axis=1)
150
+ else: # grid
151
+ top = np.concatenate([raw, box_img], axis=1)
152
+ bot = np.concatenate([seg_overlay, seg_col], axis=1)
153
+ return np.concatenate([top, bot], axis=0)
154
+
155
+ # --- Use imageio.get_writer ---
156
+ with imageio.get_writer(out_path, fps=fps, codec="libx264") as writer:
157
+ for t in range(T):
158
+ frame = compose(t)
159
+ writer.append_data(frame) # frame must be (H,W,3) uint8
160
+
161
+ return out_path
162
+
163
+ def natural_key(s: str):
164
+ return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]
165
+
166
+ def process_gripper_pose(robot_gripper_pose):
167
+ raw = np.array(robot_gripper_pose) # shape (T,)
168
+ # binary states (open=1, closed=0)
169
+ state = raw.astype(np.int32)
170
+
171
+ # deltas using "previous" rule
172
+ delta = np.zeros_like(state[:-1])
173
+ prev = -1
174
+ for t in range(0, len(state)-1):
175
+ if state[t] != state[t+1]:
176
+ delta[t] = 1 if state[t] < state[t+1] else -1
177
+ prev = delta[t]
178
+ else:
179
+ delta[t] = prev # carry forward previous action
180
+
181
+ return delta
182
+
183
+ def process_video_rgb(path: Path) -> List[np.ndarray]:
184
+ if cv2 is None:
185
+ raise RuntimeError("OpenCV not available. Please install opencv-python.")
186
+ cap = cv2.VideoCapture(str(path))
187
+ if not cap.isOpened():
188
+ raise RuntimeError(f"Cannot open video: {path}")
189
+ frames = []
190
+ while True:
191
+ ok, frame = cap.read()
192
+ if not ok:
193
+ break
194
+ # Resize to 256x256 and convert BGR->RGB
195
+ frame = cv2.resize(frame, (256, 256), interpolation=cv2.INTER_LINEAR)
196
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
197
+ frames.append(frame)
198
+ cap.release()
199
+ return frames
200
+
201
+ def parse_masks_dir(H, W, masks_dir: Path) -> Dict[int, Dict[int, np.ndarray]]:
202
+ """
203
+ Return nested dict: frame_idx -> {inst_id -> binary mask (H,W,1)}
204
+ """
205
+ out: Dict[int, Dict[int, np.ndarray]] = {}
206
+ for f in sorted(masks_dir.iterdir(), key=lambda x: natural_key(x.name)):
207
+ if not f.is_file(): continue
208
+ m = MASK_RE.match(f.name)
209
+ if not m: continue
210
+ frame = int(m.group("frame"))
211
+ inst = int(m.group("inst"))
212
+ arr = np.array(Image.open(f).convert("L").resize((W, H))) # (H,W) grayscale
213
+ bin_mask = (arr > 0).astype(np.uint8)[..., None] # (H,W,1)
214
+ out.setdefault(frame, {})[inst] = bin_mask
215
+ return out
216
+
217
+ def labelmap_and_boxes(H, W, per_inst: Dict[int, np.ndarray]) -> Tuple[np.ndarray, List[List[int]]]:
218
+ """
219
+ From {inst_id -> (H,W,1) mask}, build label map (H,W) with labels 30..K*30,
220
+ and compute boxes as [x1,y1,x2,y2] for each instance (label>0), in order of inst_id.
221
+ Returns (labelmap, boxes)
222
+ """
223
+ if not per_inst:
224
+ return np.zeros((H,W,1), dtype=np.int32), []
225
+ # Determine shape
226
+ labelmap = np.zeros((H,W,1), dtype=np.int32)
227
+ boxes: List[List[int]] = []
228
+ # Sort instances for stable order
229
+ for idx, inst_id in enumerate(sorted(per_inst.keys())):
230
+ m = per_inst[inst_id][..., 0].astype(bool)
231
+ label = (idx + 1)*20 # 0 reserved as background
232
+ labelmap[m] = label
233
+ # Bounding box
234
+ ys, xs = np.where(m)
235
+ if len(xs) == 0 or len(ys) == 0:
236
+ pass
237
+ else:
238
+ x1, x2 = int(xs.min()), int(xs.max())
239
+ y1, y2 = int(ys.min()), int(ys.max())
240
+ boxes.append([label, [x1, y1, x2, y2]])
241
+ return labelmap, boxes
242
+
243
+ def detect_noops_with_gripper_window(
244
+ actions: np.ndarray,
245
+ gripper_col: int = -1,
246
+ tol: float = 1e-6,
247
+ window: int = 6,
248
+ ):
249
+ """
250
+ Return a boolean vector is_noop[T] where True marks a no-op step.
251
+ A step is no-op if (a) all non-gripper dims are ~0 (|x|<tol), and
252
+ (b) it's not within `window` frames after a gripper open/close change.
253
+
254
+ Parameters
255
+ ----------
256
+ actions : (T, D) array
257
+ Action vectors over time.
258
+ gripper_col : int
259
+ Index of the gripper signal column (default: last col).
260
+ tol : float
261
+ Tolerance to treat movement dims as zero.
262
+ window : int
263
+ Number of frames after a gripper state change to mark as active (non-noop).
264
+
265
+ Returns
266
+ -------
267
+ is_noop : (T,) bool array
268
+ True where the step is considered a no-op.
269
+ active_gripper_window : (T,) bool array
270
+ True where we are within the post-change window (non-noop region).
271
+ """
272
+ a = np.asarray(actions)
273
+ assert a.ndim == 2 and a.shape[0] > 0, "actions must be (T, D)"
274
+ T, D = a.shape
275
+
276
+ # 1) movement no-op: all non-gripper dims are near zero
277
+ if gripper_col < 0:
278
+ g_idx = D + gripper_col
279
+ else:
280
+ g_idx = gripper_col
281
+ assert 0 <= g_idx < D
282
+
283
+ if D > 1:
284
+ move = np.concatenate([a[:, :g_idx], a[:, g_idx+1:]], axis=1)
285
+ movement_noop = np.all(np.abs(move) < tol, axis=1)
286
+ else:
287
+ movement_noop = np.ones(T, dtype=bool) # only gripper present
288
+
289
+ # 2) gripper activity window: detect state changes and mark window frames
290
+ g = a[:, g_idx]
291
+
292
+ # Convert to binary state: open=1, closed=0 (by sign/threshold)
293
+ # Works for {-1,0,1} or continuous values (e.g., widths).
294
+ state = (g > 0).astype(np.int8)
295
+
296
+ # Change points where state flips
297
+ changes = np.flatnonzero(np.diff(state, prepend=state[0]) != 0)
298
+
299
+ active_gripper_window = np.zeros(T, dtype=bool)
300
+ for t0 in changes:
301
+ t1 = min(t0 + window, T)
302
+ active_gripper_window[t0:t1] = True
303
+
304
+ # Final no-op = movement_noop and NOT in gripper activity window
305
+ is_noop = movement_noop & (~active_gripper_window)
306
+ return is_noop, active_gripper_window
307
+
308
+ def process_sequence(seq_name: str, task_dir: Path, out_dir: Path, sequence_rename: Path):
309
+ s_dir = task_dir / "success" / seq_name
310
+ m_dir = task_dir / "masks" / seq_name / "masks"
311
+
312
+ # --- Load trajectory ---
313
+ pkl_path = s_dir / "trajectory.pkl"
314
+ with open(pkl_path, "rb") as f:
315
+ traj = pickle.load(f)
316
+
317
+ task_description = traj['task_description'].lower().replace('.', '')
318
+ T = len(traj['robot_eef_pose']) - 1
319
+
320
+ delta_eef = traj['robot_eef_pose'][1:,:] - traj['robot_eef_pose'][:-1,:]
321
+ delta_gripper = process_gripper_pose(traj['robot_gripper_pose'])
322
+ delta_gripper = delta_gripper.reshape(T, 1)
323
+ actions = np.concatenate([delta_eef, delta_gripper], axis=1)
324
+
325
+ # --- Read videos as RGB ---
326
+ base_vid = s_dir / "camera_base.mp4"
327
+ agentview_images = process_video_rgb(base_vid)
328
+ agentview_images = agentview_images[:T]
329
+ H, W, _ = agentview_images[0].shape
330
+
331
+ # --- Parse masks into label maps + boxes ---
332
+ per_frame = parse_masks_dir(H, W, m_dir)
333
+ agentview_segs = []
334
+ agentview_bboxes = []
335
+
336
+ for t, inst_dict in per_frame.items():
337
+ if t >= T: continue
338
+ labelmap, boxes = labelmap_and_boxes(H, W, inst_dict)
339
+ if labelmap.size == 0: # in case masks are missing
340
+ continue
341
+ if (labelmap.shape[0] != H) or (labelmap.shape[1] != W):
342
+ # Resize nearest to match video shape
343
+ labelmap = np.array(Image.fromarray(labelmap.astype(np.int32)).resize((W, H), resample=Image.NEAREST))
344
+ agentview_segs.append(labelmap)
345
+ agentview_bboxes.append(boxes)
346
+
347
+ # save_annotation_video_imageio(
348
+ # agentview_images, agentview_segs, agentview_bboxes,
349
+ # out_path="annotations.mp4", fps=20, resize=(256,256)
350
+ # )
351
+ # 1/0
352
+ # print(len(agentview_images))
353
+ # print(len(agentview_segs))
354
+ # print(len(agentview_bboxes))
355
+ # print(len(actions))
356
+ # print(actions);
357
+ # is_noop, active_win = detect_noops_with_gripper_window(actions, gripper_col=-1, tol=1e-5, window=6)
358
+ data = {
359
+ "episode_key": sequence_rename,
360
+ "agentview_images": agentview_images,
361
+ "agentview_segs": agentview_segs,
362
+ "agentview_boxes": agentview_bboxes,
363
+ "actions": actions,
364
+ "task_description": task_description,
365
+ }
366
+ return data
367
+
368
+ def write_episode(
369
+ out_dir: str,
370
+ task_name: str,
371
+ episode: Dict[str, Any],
372
+ ):
373
+ """
374
+ {
375
+ "episode_key": "20250711-13h_52m_58s",
376
+ "agentview_images": [...], # list[(H,W,3) uint8]
377
+ "agentview_segs": [...], # list[(H,W) int]
378
+ "agentview_boxes": [...], # list[list[(id, [x,y,w,h])]]
379
+ "actions": np.ndarray or None, # (T,D)
380
+ "task_description": "string", # optional
381
+ },
382
+ """
383
+ episode_key = episode["episode_key"]
384
+ h5_filename = f"{task_name}_{episode_key}.hdf5"
385
+ meta_filename = f"{task_name}_{episode_key}_metainfo.json"
386
+
387
+ h5_path = os.path.join(out_dir, h5_filename)
388
+ meta_path = os.path.join(out_dir, meta_filename)
389
+
390
+ # Load or start metainfo (single JSON for all episodes)
391
+ if os.path.exists(meta_path):
392
+ with open(meta_path, "r") as f:
393
+ metainfo = json.load(f)
394
+ else:
395
+ metainfo = {task_name: {}}
396
+
397
+ with h5py.File(h5_path, "a") as f: # append if file already exists
398
+ root = f.require_group("data")
399
+ ep = episode
400
+ episode_key = ep["episode_key"]
401
+ agentview_images = ep["agentview_images"]
402
+ agentview_segs = ep["agentview_segs"]
403
+ agentview_boxes = ep["agentview_boxes"]
404
+ actions = ep.get("actions", None)
405
+ task_description = ep.get("task_description", "")
406
+
407
+ # --- lengths & alignment ---
408
+ lens = [len(agentview_images), len(agentview_segs), len(agentview_boxes)]
409
+ if actions is not None: lens.append(len(actions))
410
+ T = min(l for l in lens if l > 0)
411
+ assert T > 0, f"[{episode_key}] nothing to write"
412
+
413
+ agentview_images = agentview_images[:T]
414
+ agentview_segs = agentview_segs[:T]
415
+ agentview_boxes = agentview_boxes[:T]
416
+ if actions is None:
417
+ actions = np.zeros((T, 1), dtype=np.float32)
418
+ else:
419
+ actions = np.asarray(actions)[:T]
420
+
421
+ # --- stack visuals ---
422
+ agentview_rgb = np.stack(agentview_images, axis=0) # (T,H,W,3)
423
+ agentview_seg = np.stack([np.asarray(s, dtype=np.int32) for s in agentview_segs], axis=0) # (T,H,W)
424
+ _, H, W, _ = agentview_seg.shape
425
+
426
+ # --- placeholders for missing streams/states ---
427
+ eye_in_hand_rgb = np.zeros_like(agentview_rgb, dtype=np.uint8)
428
+ agentview_depth = np.zeros((T, H, W), dtype=np.float32)
429
+ eye_in_hand_depth = np.zeros((T, H, W), dtype=np.float32)
430
+ eye_in_hand_seg = np.zeros((T, H, W), dtype=np.int32)
431
+
432
+ gripper_states = np.zeros((T, 1), dtype=np.float32)
433
+ joint_states = np.zeros((T, 0), dtype=np.float32)
434
+ ee_states = np.zeros((T, 6), dtype=np.float32) # [pos(3), ori(3)]
435
+ robot_states = np.zeros((T, 0), dtype=np.float32)
436
+
437
+ dones = np.zeros(T, dtype=np.uint8); dones[-1] = 1
438
+ rewards = np.zeros(T, dtype=np.uint8); rewards[-1] = 1
439
+
440
+ # --- create / overwrite episode group ---
441
+ if episode_key in root:
442
+ del root[episode_key] # clean if re-writing
443
+ ep_grp = root.create_group(episode_key)
444
+ obs_grp = ep_grp.create_group("obs")
445
+
446
+ # states
447
+ obs_grp.create_dataset("gripper_states", data=gripper_states)
448
+ obs_grp.create_dataset("joint_states", data=joint_states)
449
+ obs_grp.create_dataset("ee_states", data=ee_states)
450
+ obs_grp.create_dataset("ee_pos", data=ee_states[:, :3])
451
+ obs_grp.create_dataset("ee_ori", data=ee_states[:, 3:])
452
+
453
+ # visuals
454
+ obs_grp.create_dataset("agentview_rgb", data=agentview_rgb)
455
+ obs_grp.create_dataset("eye_in_hand_rgb", data=eye_in_hand_rgb)
456
+ obs_grp.create_dataset("agentview_depth", data=agentview_depth)
457
+ obs_grp.create_dataset("eye_in_hand_depth", data=eye_in_hand_depth)
458
+ obs_grp.create_dataset("agentview_seg", data=agentview_seg)
459
+ obs_grp.create_dataset("eye_in_hand_seg", data=eye_in_hand_seg)
460
+
461
+ # top-level (episode)
462
+ ep_grp.create_dataset("actions", data=actions)
463
+ ep_grp.create_dataset("robot_states", data=robot_states)
464
+ ep_grp.create_dataset("rewards", data=rewards)
465
+ ep_grp.create_dataset("dones", data=dones)
466
+
467
+ # --- update metainfo JSON for this episode ---
468
+ if task_name not in metainfo:
469
+ metainfo[task_name] = {}
470
+ if episode_key not in metainfo[task_name]:
471
+ metainfo[task_name][episode_key] = {}
472
+
473
+ metainfo[task_name][episode_key].update({
474
+ "success": True,
475
+ "initial_state": robot_states[0].tolist() if len(robot_states) else [],
476
+ "task_nouns": [], # fill if you want
477
+ "task_description": task_description,
478
+ "exo_boxes": agentview_boxes, # per-frame boxes you provided
479
+ "ego_boxes": [[] for _ in range(T)], # none available
480
+ })
481
+
482
+ # write/merge metainfo once at the end
483
+ with open(meta_path, "w") as f:
484
+ json.dump(metainfo, f, indent=2)
485
+
486
+ return {"hdf5": h5_path, "metainfo": meta_path}
487
+
488
+ def main():
489
+ p = argparse.ArgumentParser(description="Convert sequences to LIBERO-like demos.")
490
+ p.add_argument("--task_dir", type=str, help="Path to task folder (contains success/ and masks/).")
491
+ p.add_argument("--out_root", type=str, required=True, help="Target directory where <task_name>/<task_name>_<seq>.hdf5 is written.")
492
+ args = p.parse_args()
493
+
494
+ task_dir = Path(args.task_dir).expanduser().resolve()
495
+ task_name = task_dir.name
496
+ out_root = Path(args.out_root).expanduser().resolve()
497
+ out_root.mkdir(parents=True, exist_ok=True)
498
+
499
+ success_dir = task_dir / "success"
500
+ masks_dir = task_dir / "masks"
501
+ if not success_dir.is_dir() or not masks_dir.is_dir():
502
+ print("[ERROR] task_dir must contain 'success/' and 'masks/'")
503
+ sys.exit(1)
504
+
505
+ success_seqs = {d.name for d in success_dir.iterdir() if d.is_dir()}
506
+ mask_seqs = {d.name for d in masks_dir.iterdir() if d.is_dir()}
507
+ seqs = sorted(list(success_seqs & mask_seqs), key=natural_key)
508
+
509
+ results = []
510
+ from tqdm import tqdm
511
+ for i, name in tqdm(enumerate(seqs)):
512
+ info = process_sequence(name, task_dir, out_root, sequence_rename=f'demo_{i+1}')
513
+
514
+ write_episode(
515
+ out_dir=args.out_root,
516
+ task_name=info['task_description'],
517
+ episode=info,
518
+ )
519
+
520
+ # # Write a small manifest JSON
521
+ # manifest = {"task": task_name, "outputs": results}
522
+ # (out_root / f"{task_name}_manifest.json").write_text(json.dumps(manifest, indent=2))
523
+ # print(f"[DONE] Manifest saved to {out_root / (task_name + '_manifest.json')}")
524
+
525
+ if __name__ == "__main__":
526
+ main()
hdf5_data/hdf5_merger.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import argparse
3
+ import json
4
+ import os
5
+ import time
6
+
7
+ import cv2
8
+ import h5py
9
+ import numpy as np
10
+ import tqdm
11
+
12
+ def sort_key_hdf5(name):
13
+ # extract number after 'demo_'
14
+ number = int(name.split('_')[-1].split('.')[0])
15
+ return number
16
+
17
+ def sort_key_metainfo(name):
18
+ # extract number after 'demo_'
19
+ number = int(name.split('_')[-2].split('.')[0])
20
+ return number
21
+
22
+ def recursive_merge(dest, src):
23
+ for key, value in src.items():
24
+ if key in dest and isinstance(dest[key], dict) and isinstance(value, dict):
25
+ recursive_merge(dest[key], value)
26
+ else:
27
+ dest[key] = value
28
+
29
+ def recursive_copy(src, dest):
30
+ for key in src.keys():
31
+ if isinstance(src[key], h5py.Group):
32
+ new_grp = dest.create_group(key)
33
+ recursive_copy(src[key], new_grp)
34
+ elif isinstance(src[key], h5py.Dataset):
35
+ src.copy(key, dest)
36
+ for attr_key in src.attrs:
37
+ dest.attrs[attr_key] = src.attrs[attr_key]
38
+
39
+ def main(args):
40
+
41
+ # Prepare JSON file to record success/false and initial states per episode
42
+ metainfo_json_dict = {}
43
+ metainfo_json_out_path = os.path.join(args.out_dir, f"./metainfo.json")
44
+ with open(metainfo_json_out_path, "w") as f:
45
+ # Just test that we can write to this file (we overwrite it later)
46
+ json.dump(metainfo_json_dict, f)
47
+
48
+ # Get task suite
49
+ task_suite = ['task1', 'task2', 'task3']
50
+ num_tasks_in_suite = 3
51
+
52
+ # Iterate through the task suites
53
+ for task_id in tqdm.tqdm(range(num_tasks_in_suite)):
54
+ # Get task in suite
55
+ task = task_suite[task_id]
56
+ data_dir = os.path.join('./', task)
57
+ data_files = os.listdir(data_dir)
58
+
59
+ hdf5_files = [_file for _file in data_files if '.hdf5' in _file]
60
+ hdf5_files = sorted(hdf5_files, key=sort_key_hdf5)
61
+ meta_files = [_file for _file in data_files if '_metainfo.json' in _file]
62
+ meta_files = sorted(meta_files, key=sort_key_metainfo)
63
+
64
+ # Create new HDF5 file for regenerated demos
65
+ new_data_path = os.path.join(args.out_dir, f"{task}_demo.hdf5")
66
+ new_data_file = h5py.File(new_data_path, "w")
67
+ grp = new_data_file.create_group("data")
68
+
69
+ for idx, hdf5_name in tqdm.tqdm(enumerate(hdf5_files)):
70
+ hdf5_name = os.path.join(data_dir, hdf5_name)
71
+ traj_data_file = h5py.File(hdf5_name, "r")
72
+ traj_data = traj_data_file["data"]
73
+
74
+ # Copy trajectory data
75
+ for ep_key in traj_data.keys():
76
+ src_grp = traj_data[ep_key]
77
+ dest_grp = grp.create_group(ep_key)
78
+ recursive_copy(src_grp, dest_grp)
79
+
80
+ traj_data_file.close()
81
+
82
+ meta_name = os.path.join(data_dir, meta_files[idx])
83
+ with open(meta_name, "r") as f:
84
+ # Just test that we can write to this file (we overwrite it later)
85
+ meta_data = json.load(f)
86
+ meta_data_key = list(meta_data.keys())[0]
87
+ demo_data_key = list(meta_data[meta_data_key].keys())[0]
88
+ indexed_meta_data = meta_data[meta_data_key][demo_data_key]
89
+
90
+ # Recursively merge the meta data
91
+ recursive_merge(metainfo_json_dict, meta_data)
92
+
93
+ # Write metainfo dict to JSON file
94
+ # (We repeatedly overwrite, rather than doing this once at the end, just in case the script crashes midway)
95
+ with open(metainfo_json_out_path, "w") as f:
96
+ json.dump(metainfo_json_dict, f, indent=2)
97
+
98
+ # if idx > 1:
99
+ # break
100
+
101
+ new_data_file.close()
102
+
103
+ if __name__ == '__main__':
104
+ # Parse command-line arguments
105
+ parser = argparse.ArgumentParser()
106
+ parser.add_argument("--in_dir", default='./')
107
+ parser.add_argument("--out_dir", default='./')
108
+ args = parser.parse_args()
109
+
110
+ main(args)
hdf5_data/task1-annotations.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70c664c2e5321593ce12185e2f5a826f3c926d3775fe519841ca3e52c60c9db8
3
+ size 224491
hdf5_data/task2-annotations.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95f0f79d402b5e78b0cd64cc99a392cb052e04cf1a08852bde213b396f857766
3
+ size 281863
hdf5_data/task3-annotations.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4d046df2c6722c1771c473aa735201635fb9ac2f1d6eb723672613bd707e3ff
3
+ size 411912