rollingoat commited on
Commit
5c44e75
·
verified ·
1 Parent(s): 8a73e95

Upload sync_image_low_dim.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. sync_image_low_dim.py +355 -0
sync_image_low_dim.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synchronize image observations with low-dimensional robot data.
2
+
3
+ Uses image timestamps as the master timeline and aligns low-dimensional
4
+ datapoints (e.g., joint states) by nearest timestamp.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import os
11
+ from typing import Dict, Iterable, List, Optional, Tuple
12
+
13
+ import h5py
14
+ import numpy as np
15
+
16
+
17
+ def parse_args() -> argparse.Namespace:
18
+ parser = argparse.ArgumentParser(
19
+ description="Synchronize an image HDF5 file with a low-dimensional HDF5 file"
20
+ )
21
+ parser.add_argument("--image-h5", required=True, help="Path to the image HDF5 file")
22
+ parser.add_argument("--lowdim-h5", required=True, help="Path to the low-dimensional HDF5 file")
23
+ parser.add_argument("--output-h5", required=True, help="Destination path for the synchronized HDF5")
24
+ parser.add_argument(
25
+ "--image-timestamp-key",
26
+ default="timestamp",
27
+ help="Dataset key holding timestamps inside the image obs group",
28
+ )
29
+ parser.add_argument(
30
+ "--lowdim-timestamp-key",
31
+ default="timestamp",
32
+ help="Dataset key holding timestamps inside the low-dimensional obs group",
33
+ )
34
+ parser.add_argument(
35
+ "--image-keys",
36
+ nargs="*",
37
+ help="Optional list of image observation keys to copy (defaults to all datasets except the timestamp)",
38
+ )
39
+ parser.add_argument(
40
+ "--lowdim-keys",
41
+ nargs="*",
42
+ help="Optional list of low-dimensional observation keys to sync (defaults to all datasets except the timestamp)",
43
+ )
44
+ parser.add_argument(
45
+ "--allow-missing",
46
+ action="store_true",
47
+ help="Skip demos that miss required keys instead of raising an error",
48
+ )
49
+ parser.add_argument(
50
+ "--exclude-demo",
51
+ nargs="*",
52
+ default=None,
53
+ help="Demo names to exclude, e.g. demo_4 demo_5 demo_42",
54
+ )
55
+ parser.add_argument(
56
+ "--skip-n",
57
+ type=int,
58
+ default=0,
59
+ dest="skip_n",
60
+ help=(
61
+ "Keep every (skip_n + 1)-th frame and discard the rest. "
62
+ "E.g. --skip-n 2 keeps frames 0, 3, 6, … (default: 0 = keep all frames)."
63
+ ),
64
+ )
65
+ return parser.parse_args()
66
+
67
+
68
+ def validate_files(*paths: str) -> None:
69
+ missing = [path for path in paths if not os.path.exists(path)]
70
+ if missing:
71
+ joined = ", ".join(missing)
72
+ raise FileNotFoundError(f"Missing required file(s): {joined}")
73
+
74
+
75
+ def resolve_dataset_keys(
76
+ group: h5py.Group, timestamp_key: str, explicit: Iterable[str] | None
77
+ ) -> List[str]:
78
+ def _filter(keys: Iterable[str]) -> List[str]:
79
+ return [k for k in keys if "timestamp" not in k.lower()]
80
+
81
+ if explicit:
82
+ explicit = list(explicit)
83
+ missing = [k for k in explicit if k not in group]
84
+ if missing:
85
+ raise KeyError(f"Group {group.name} missing requested keys: {missing}")
86
+ filtered = _filter(explicit)
87
+ if not filtered:
88
+ raise KeyError("No valid keys remain after removing timestamp datasets")
89
+ return filtered
90
+ keys: List[str] = []
91
+ for key, item in group.items():
92
+ if key == timestamp_key or "timestamp" in key.lower():
93
+ continue
94
+ if isinstance(item, h5py.Dataset):
95
+ keys.append(key)
96
+ if not keys:
97
+ raise KeyError(f"Group {group.name} has no datasets besides timestamp '{timestamp_key}'")
98
+ return keys
99
+
100
+
101
+ def find_nearest_idx(array: np.ndarray, value: float) -> int:
102
+ idx = int(np.searchsorted(array, value, side="left"))
103
+ if idx == 0:
104
+ return 0
105
+ if idx >= len(array):
106
+ return len(array) - 1
107
+ prev_diff = abs(value - array[idx - 1])
108
+ next_diff = abs(array[idx] - value)
109
+ return idx - 1 if prev_diff <= next_diff else idx
110
+
111
+
112
+ def resample_sequence(
113
+ sequence: np.ndarray, follower_ts: np.ndarray, master_ts: np.ndarray
114
+ ) -> np.ndarray:
115
+ if sequence.shape[0] != follower_ts.shape[0]:
116
+ raise ValueError(
117
+ "Sequence length does not match low-dimensional timestamp count for resampling"
118
+ )
119
+ indices = [find_nearest_idx(follower_ts, t) for t in master_ts]
120
+ return sequence[indices]
121
+
122
+
123
+ def detect_timestamp_jump(timestamps: np.ndarray, threshold: float = 1.0) -> int:
124
+ """Return the index of the start of the valid segment after the last sudden jump."""
125
+ if len(timestamps) < 2:
126
+ return 0
127
+ diffs = np.diff(timestamps)
128
+ jump_indices = np.where(diffs > threshold)[0]
129
+ if jump_indices.size > 0:
130
+ return int(jump_indices[-1] + 1)
131
+ return 0
132
+
133
+
134
+ def sync_demo(
135
+ demo: str,
136
+ image_obs: h5py.Group,
137
+ lowdim_obs: h5py.Group,
138
+ image_ts_key: str,
139
+ lowdim_ts_key: str,
140
+ image_keys: List[str],
141
+ lowdim_keys: List[str],
142
+ ) -> Tuple[Optional[Dict[str, Dict[str, np.ndarray]]], np.ndarray]:
143
+ if image_ts_key not in image_obs:
144
+ raise KeyError(f"Image timestamps '{image_ts_key}' missing in {image_obs.name}")
145
+ if lowdim_ts_key not in lowdim_obs:
146
+ raise KeyError(f"Low-dim timestamps '{lowdim_ts_key}' missing in {lowdim_obs.name}")
147
+
148
+ master_timestamps = np.asarray(image_obs[image_ts_key][:], dtype=np.float64)
149
+ follower_timestamps = np.asarray(lowdim_obs[lowdim_ts_key][:], dtype=np.float64)
150
+
151
+ if master_timestamps.size == 0:
152
+ raise ValueError(f"Demo {demo} has no image timestamps to drive synchronization")
153
+ if follower_timestamps.size == 0:
154
+ raise ValueError(f"Demo {demo} has no low-dimensional timestamps")
155
+
156
+ master_cache = {key: image_obs[key][:] for key in image_keys}
157
+ follower_cache = {key: lowdim_obs[key][:] for key in lowdim_keys}
158
+
159
+ if master_cache:
160
+ min_cache_len = min(v.shape[0] for v in master_cache.values())
161
+ if master_timestamps.size > min_cache_len:
162
+ print(f"Warning: master_timestamps has {master_timestamps.size} entries but image cache has {min_cache_len}; truncating timestamps for demo {demo}.")
163
+ master_timestamps = master_timestamps[:min_cache_len]
164
+
165
+ non_zero_mask = follower_timestamps > 1e-6
166
+ if not np.all(non_zero_mask):
167
+ print(f"Warning: Discarding {np.sum(~non_zero_mask)} zero-valued timestamps from low-dim data for demo {demo}")
168
+ follower_timestamps = follower_timestamps[non_zero_mask]
169
+ for k in follower_cache:
170
+ follower_cache[k] = follower_cache[k][non_zero_mask]
171
+ if follower_timestamps.size == 0:
172
+ raise ValueError(f"Demo {demo} has only zero-valued low-dimensional timestamps")
173
+
174
+ jump_idx = detect_timestamp_jump(follower_timestamps, threshold=0.5)
175
+ if jump_idx > 0:
176
+ print(f"Warning: Sudden jump detected in low-dim timestamps for demo {demo} at index {jump_idx}. Discarding {jump_idx} samples before the jump.")
177
+ follower_timestamps = follower_timestamps[jump_idx:]
178
+ for k in follower_cache:
179
+ follower_cache[k] = follower_cache[k][jump_idx:]
180
+ if follower_timestamps.size == 0:
181
+ print(f"Warning: Discarding all low-dim timestamps due to jump for demo {demo}; skipping demo")
182
+ return None, follower_timestamps
183
+
184
+ low_start, low_end = np.min(follower_timestamps), np.max(follower_timestamps)
185
+ img_start, img_end = np.min(master_timestamps), np.max(master_timestamps)
186
+ overlap_start = max(img_start, low_start)
187
+ overlap_end = min(img_end, low_end)
188
+ print(f"Demo {demo} timestamp overlap: [{overlap_start:.3f}, {overlap_end:.3f}]")
189
+
190
+ if overlap_start > overlap_end:
191
+ print(f"Warning: No timestamp overlap between image and low-dim for demo {demo}; skipping demo")
192
+ return None, follower_timestamps
193
+
194
+ candidates_mask = (master_timestamps >= overlap_start) & (master_timestamps <= overlap_end)
195
+ candidate_indices = np.where(candidates_mask)[0]
196
+
197
+ if candidate_indices.size == 0:
198
+ print(f"Warning: No image timestamps fall within the overlap interval for demo {demo}; skipping demo")
199
+ return None, follower_timestamps
200
+
201
+ start_idx = candidate_indices[0]
202
+ end_idx = candidate_indices[-1]
203
+ print(f"Demo {demo} master start idx: {start_idx}, timestamp: {master_timestamps[start_idx]:.3f}")
204
+
205
+ master_indices = np.arange(start_idx, end_idx + 1)
206
+ master_cache_sliced = {k: v[master_indices] for k, v in master_cache.items()}
207
+
208
+ synced_images: Dict[str, List[np.ndarray]] = {key: [] for key in image_keys}
209
+ synced_lowdim: Dict[str, List[np.ndarray]] = {key: [] for key in lowdim_keys}
210
+
211
+ master_in_ts = master_timestamps[master_indices]
212
+ for local_idx, timestamp in enumerate(master_in_ts):
213
+ timestamp = float(timestamp)
214
+ follower_idx = find_nearest_idx(follower_timestamps, timestamp)
215
+ time_diff = abs(follower_timestamps[follower_idx] - timestamp)
216
+ if time_diff > 0.1:
217
+ raise ValueError(
218
+ f"Timestamp mismatch at master idx {master_indices[local_idx]} (master ts: {timestamp}, nearest follower ts: {follower_timestamps[follower_idx]}, diff: {time_diff})"
219
+ )
220
+
221
+ for key in image_keys:
222
+ synced_images[key].append(master_cache_sliced[key][local_idx])
223
+ for key in lowdim_keys:
224
+ synced_lowdim[key].append(follower_cache[key][follower_idx])
225
+
226
+ image_arrays = {key: np.stack(values, axis=0) for key, values in synced_images.items()}
227
+ lowdim_arrays = {key: np.stack(values, axis=0) for key, values in synced_lowdim.items()}
228
+
229
+ return (
230
+ {
231
+ "timestamps": master_in_ts,
232
+ "image_obs": image_arrays,
233
+ "lowdim_obs": lowdim_arrays,
234
+ },
235
+ follower_timestamps,
236
+ )
237
+
238
+
239
+ def write_demo(
240
+ demo: str,
241
+ out_root: h5py.Group,
242
+ synced: Dict[str, Dict[str, np.ndarray]],
243
+ image_ts_key: str,
244
+ actions: Optional[np.ndarray],
245
+ ) -> None:
246
+ g_demo = out_root.create_group(demo)
247
+ g_obs = g_demo.create_group("obs")
248
+
249
+ if actions is not None:
250
+ g_demo.create_dataset("actions", data=actions)
251
+ g_obs.create_dataset(image_ts_key, data=synced["timestamps"])
252
+ for key, arr in synced["image_obs"].items():
253
+ g_obs.create_dataset(key, data=arr)
254
+ for key, arr in synced["lowdim_obs"].items():
255
+ g_obs.create_dataset(key, data=arr)
256
+
257
+ g_demo.attrs["num_samples"] = synced["timestamps"].shape[0]
258
+
259
+
260
+ def main() -> None:
261
+ args = parse_args()
262
+
263
+ validate_files(args.image_h5, args.lowdim_h5)
264
+ if os.path.abspath(args.image_h5) == os.path.abspath(args.output_h5):
265
+ raise ValueError("Output file must differ from the image input file")
266
+ if os.path.abspath(args.lowdim_h5) == os.path.abspath(args.output_h5):
267
+ raise ValueError("Output file must differ from the low-dimensional input file")
268
+
269
+ with h5py.File(args.image_h5, "r") as f_image, h5py.File(args.lowdim_h5, "r") as f_lowdim:
270
+ if "data" not in f_image or "data" not in f_lowdim:
271
+ raise KeyError("Both HDF5 files must contain a top-level 'data' group")
272
+ demos = sorted(set(f_image["data"].keys()) & set(f_lowdim["data"].keys()))
273
+ if getattr(args, "exclude_demo", None):
274
+ exclude_names = set(args.exclude_demo)
275
+ unknown = exclude_names - set(demos)
276
+ if unknown:
277
+ print(f"Warning: --exclude-demo names not found and ignored: {sorted(unknown)}")
278
+ demos = [d for d in demos if d not in exclude_names]
279
+ if not demos:
280
+ raise ValueError("No demos left after applying --exclude-demo filter")
281
+ if not demos:
282
+ raise ValueError("No overlapping demos found between the provided files")
283
+
284
+ os.makedirs(os.path.dirname(os.path.abspath(args.output_h5)) or ".", exist_ok=True)
285
+ with h5py.File(args.output_h5, "w") as f_out:
286
+ g_out = f_out.create_group("data")
287
+ processed = 0
288
+ for demo in demos:
289
+ print(f"Processing demo {demo}...")
290
+ try:
291
+ image_obs = f_image["data"][demo]["obs"]
292
+ lowdim_demo = f_lowdim["data"][demo]
293
+ lowdim_obs = lowdim_demo["obs"]
294
+
295
+ image_keys = resolve_dataset_keys(
296
+ image_obs, args.image_timestamp_key, args.image_keys
297
+ )
298
+ lowdim_keys = resolve_dataset_keys(
299
+ lowdim_obs, args.lowdim_timestamp_key, args.lowdim_keys
300
+ )
301
+ result = sync_demo(
302
+ demo,
303
+ image_obs,
304
+ lowdim_obs,
305
+ args.image_timestamp_key,
306
+ args.lowdim_timestamp_key,
307
+ image_keys,
308
+ lowdim_keys,
309
+ )
310
+ if result[0] is None:
311
+ continue
312
+ synced, follower_ts = result
313
+ except Exception as exc:
314
+ if args.allow_missing:
315
+ print(f"Skipping {demo}: {exc}")
316
+ continue
317
+ raise
318
+
319
+ if args.skip_n > 0:
320
+ step = args.skip_n + 1
321
+ indices = np.arange(0, synced["timestamps"].shape[0], step)
322
+ if len(indices) < 2:
323
+ print(f" Skipping {demo}: too few frames after --skip-n {args.skip_n} subsampling.")
324
+ continue
325
+ synced["timestamps"] = synced["timestamps"][indices]
326
+ for k in synced["image_obs"]:
327
+ synced["image_obs"][k] = synced["image_obs"][k][indices]
328
+ for k in synced["lowdim_obs"]:
329
+ synced["lowdim_obs"][k] = synced["lowdim_obs"][k][indices]
330
+ print(f" [skip_n={args.skip_n}] {len(indices)} frames kept (step={step})")
331
+
332
+ actions_data = None
333
+ if "actions" in lowdim_demo:
334
+ try:
335
+ actions_source = lowdim_demo["actions"][:]
336
+ actions_data = resample_sequence(
337
+ actions_source, follower_ts, synced["timestamps"]
338
+ )
339
+ except ValueError as exc:
340
+ print(f"Skipping actions for {demo}: {exc}")
341
+
342
+ out_name = f"demo_{processed}"
343
+ write_demo(out_name, g_out, synced, args.image_timestamp_key, actions_data)
344
+ processed += 1
345
+ suffix = f" (renamed from {demo})" if out_name != demo else ""
346
+ print(f"Synchronized {out_name}{suffix}: {synced['timestamps'].shape[0]} frames")
347
+
348
+ f_out.attrs["source_image_h5"] = os.path.abspath(args.image_h5)
349
+ f_out.attrs["source_lowdim_h5"] = os.path.abspath(args.lowdim_h5)
350
+ f_out.attrs["num_synced_demos"] = processed
351
+ print(f"Finished syncing {processed} demo(s) to {args.output_h5}")
352
+
353
+
354
+ if __name__ == "__main__":
355
+ main()