chenyuwang1 commited on
Commit
c3f1dad
·
verified ·
1 Parent(s): f1de420

Upload build_h5_shard.py

Browse files
Files changed (1) hide show
  1. build_h5_shard.py +421 -0
build_h5_shard.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HDF5 分片生成脚本:读取 MP4 与 JSON,生成符合规范的 shard_XXXX.h5
3
+
4
+ 层级设计(示例):
5
+
6
+ shard_XXXX.h5
7
+ ├── /dataset_name_0/
8
+ │ ├── @dataset_source: "AgiBot World"
9
+ │ ├── @dataset_version: "alpha"
10
+ │ ├── @num_trajectories: <N>
11
+ │ │
12
+ │ ├── /traj_0000/
13
+ │ │ ├── @task: "Pickup items in the supermarket"
14
+ │ │ ├── @task_id: "327"
15
+ │ │ ├── @episode_id: "648642"
16
+ │ │ ├── @scene_id: <init_scene_text>
17
+ │ │ ├── @robot_type: "unknown"
18
+ │ │ ├── @success: 1
19
+ │ │ ├── @num_frames: T
20
+ │ │ ├── @fps: F
21
+ │ │ ├── @duration_sec: T/F
22
+ │ │ ├── @camera_views: ["head", "left", "right", ...]
23
+ │ │ │
24
+ │ │ ├── images_head: [T, H, W, 3] uint8
25
+ │ │ ├── images_left: [T, H, W, 3] uint8
26
+ │ │ ├── images_right: [T, H, W, 3] uint8
27
+ │ │ │
28
+ │ │ ├── progress: [T] float32
29
+ │ │ ├── done: [T] bool
30
+ │ │ └── value: [T] float32
31
+
32
+ 使用方法(示例):
33
+
34
+ 1) 安装依赖(Windows):
35
+ pip install h5py numpy opencv-python
36
+
37
+ 2) 运行脚本(你的分段目录作为根,例如 648642-684757):
38
+ python build_h5_shard.py \
39
+ --dataset-name agibot_world \
40
+ --task-json e:/trae_code/20251111data/database/AgiBot_World/task_327.json \
41
+ --obs-root e:/trae_code/20251111data/OpenDriveLab___AgiBot-World/raw/main/observations/327/648642-684757 \
42
+ --task-id 327 \
43
+ --output e:/trae_code/20251111data/shard_327.h5
44
+
45
+ 3) 可选参数:
46
+ --dataset-source "AgiBot World" --dataset-version "alpha" --robot-type "franka"
47
+
48
+ 脚本会在 <obs-root>/<episode_id>/videos 下查找 MP4,并固定映射:
49
+ head_color → images_head,hand_left_color → images_left,hand_right_color → images_right。
50
+ 若 obs-root 指向上层目录(如 observations),也会在子目录中递归查找 `<episode_id>/videos`。
51
+
52
+ 注意:该脚本按时间维度进行流式写入,避免一次性加载整段视频到内存。
53
+
54
+ 分片规则:
55
+ - 单个 H5 文件最多写入 150 条轨迹(可通过 `--max-traj-per-shard` 配置)。
56
+ - 当达到上限时,自动创建新的 H5 文件,文件名基于 `--output` 增加 `_part_XXXX` 后缀。
57
+ """
58
+
59
+ import argparse
60
+ import json
61
+ import os
62
+ import sys
63
+ from typing import Dict, List, Tuple
64
+
65
+ import h5py
66
+ import numpy as np
67
+
68
+ try:
69
+ import cv2 # type: ignore
70
+ except Exception as e: # 依赖缺失时给出清晰提示
71
+ print("[ERROR] 缺少依赖 opencv-python,请先运行: pip install opencv-python")
72
+ raise
73
+
74
+
75
+ def string_array(lst: List[str]):
76
+ """将 Python 字符串列表转换为 h5py 兼容的字符串数组。"""
77
+ dt = h5py.string_dtype(encoding="utf-8")
78
+ return np.array(lst, dtype=dt)
79
+
80
+
81
+ def find_episode_videos(obs_root: str, task_id: int, episode_id: int) -> Dict[str, str]:
82
+ """
83
+ 在 <obs-root>/<episode_id>/videos 或其子目录中查找 MP4。
84
+ 固定只返回 head_color、hand_left_color、hand_right_color 三路(若存在)。
85
+ 返回: {raw_camera_key: mp4_path}
86
+ """
87
+ candidates: Dict[str, str] = {}
88
+
89
+ # 直接路径:<obs-root>/<episode_id>/videos
90
+ direct_dir = os.path.join(obs_root, str(episode_id), "videos")
91
+ if os.path.isdir(direct_dir):
92
+ for fn in os.listdir(direct_dir):
93
+ if fn.lower().endswith(".mp4"):
94
+ key = os.path.splitext(fn)[0]
95
+ candidates[key] = os.path.join(direct_dir, fn)
96
+
97
+ # 若未找到,递归在 obs_root 下寻找 `<episode_id>/videos`
98
+ if not candidates:
99
+ for root, dirs, files in os.walk(obs_root):
100
+ base = os.path.basename(root)
101
+ if base == str(episode_id) and "videos" in dirs:
102
+ vdir = os.path.join(root, "videos")
103
+ for fn in os.listdir(vdir):
104
+ if fn.lower().endswith(".mp4"):
105
+ key = os.path.splitext(fn)[0]
106
+ candidates[key] = os.path.join(vdir, fn)
107
+ break
108
+
109
+ # 过滤只保留三路
110
+ filtered: Dict[str, str] = {}
111
+ for k in ["head_color", "hand_left_color", "hand_right_color"]:
112
+ if k in candidates:
113
+ filtered[k] = candidates[k]
114
+ return filtered
115
+
116
+
117
+ def read_video_meta(path: str) -> Tuple[int, int, int, int, float]:
118
+ """读取视频的基础元信息:(frame_count, width, height, channels, fps)。channels 固定为 3。"""
119
+ cap = cv2.VideoCapture(path)
120
+ if not cap.isOpened():
121
+ raise RuntimeError(f"无法打开视频: {path}")
122
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
123
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
124
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
125
+ fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0)
126
+ if fps <= 0:
127
+ # 兜底:若无法读到 fps,则使用 30
128
+ fps = 30.0
129
+ cap.release()
130
+ return frame_count, width, height, 3, fps
131
+
132
+
133
+ def write_video_slice_to_dataset(mp4_path: str, dset: h5py.Dataset, start_idx: int, count: int) -> int:
134
+ """
135
+ 将 mp4 指定区间 [start_idx, start_idx+count) 按帧流式写入 HDF5 dset。
136
+ 返回实际写入帧数。
137
+ """
138
+ cap = cv2.VideoCapture(mp4_path)
139
+ if not cap.isOpened():
140
+ raise RuntimeError(f"无法打开视频: {mp4_path}")
141
+ cap.set(cv2.CAP_PROP_POS_FRAMES, max(0, int(start_idx)))
142
+ t = 0
143
+ while t < count:
144
+ ok, frame_bgr = cap.read()
145
+ if not ok:
146
+ break
147
+ frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
148
+ if frame_rgb.dtype != np.uint8:
149
+ frame_rgb = frame_rgb.astype(np.uint8)
150
+ dset[t, ...] = frame_rgb
151
+ t += 1
152
+ cap.release()
153
+ if t < count:
154
+ print(f"[WARN] {os.path.basename(mp4_path)} 仅写入 {t}/{count} 帧 (start={start_idx})")
155
+ return t
156
+
157
+
158
+ def build_h5_shard(
159
+ output_path: str,
160
+ dataset_name: str,
161
+ task_json_path: str,
162
+ obs_root: str,
163
+ task_id_filter: int,
164
+ dataset_source: str = "AgiBot World",
165
+ dataset_version: str = "alpha",
166
+ default_robot_type: str = "unknown",
167
+ max_traj_per_shard: int = 150,
168
+ ) -> None:
169
+ """主流程:读取 JSON 和 MP4,生成 HDF5 分片。"""
170
+ with open(task_json_path, "r", encoding="utf-8") as f:
171
+ episodes = json.load(f)
172
+ if not isinstance(episodes, list):
173
+ raise ValueError("task_json 内容应为列表(list)")
174
+
175
+ # 统计:按 action 切片写入,每个 action 作为一条轨迹
176
+ # 先收集 (episode_json, videos_dict, cam_metas, actions) 列表
177
+ ep_pool = []
178
+ for ep in episodes:
179
+ try:
180
+ ep_id = int(ep.get("episode_id"))
181
+ t_id = int(ep.get("task_id"))
182
+ except Exception:
183
+ continue
184
+ if t_id != task_id_filter:
185
+ continue
186
+ vids = find_episode_videos(obs_root, task_id_filter, ep_id)
187
+ if not vids:
188
+ # 不输出未找到视频的提示,静默跳过
189
+ continue
190
+ # 只保留三路的 meta
191
+ cam_metas = {}
192
+ for k, mp4 in vids.items():
193
+ fc, w, h, ch, fps = read_video_meta(mp4)
194
+ cam_metas[k] = (fc, w, h, ch, fps, mp4)
195
+ # 打印找到的视频视角
196
+ camera_order = ["head_color", "hand_left_color", "hand_right_color"]
197
+ present_cams = [c for c in camera_order if c in cam_metas]
198
+ view_names = []
199
+ for c in present_cams:
200
+ if c == "head_color":
201
+ view_names.append("head")
202
+ elif c == "hand_left_color":
203
+ view_names.append("left")
204
+ elif c == "hand_right_color":
205
+ view_names.append("right")
206
+ if present_cams:
207
+ print(f"[FOUND] episode {ep_id} 找到视频视角: {', '.join(view_names)}")
208
+ actions = (ep.get("label_info") or {}).get("action_config", [])
209
+ if not actions:
210
+ print(f"[INFO] episode {ep_id} 无 action_config,跳过")
211
+ continue
212
+ ep_pool.append((ep, vids, cam_metas, actions))
213
+
214
+ if not ep_pool:
215
+ raise RuntimeError("未找到任何包含动作切片的 episode,请检查 JSON 与目录。")
216
+
217
+ # 创建 HDF5 文件并累计轨迹数
218
+ # 预计算有效动作总数(用于整体进度输出)
219
+ total_actions_valid = 0
220
+ for ep, vids, cam_metas, actions in ep_pool:
221
+ camera_order = ["head_color", "hand_left_color", "hand_right_color"]
222
+ present_cams = [c for c in camera_order if c in cam_metas]
223
+ for act in actions:
224
+ try:
225
+ s = int(act.get("start_frame", 0))
226
+ e = int(act.get("end_frame", 0))
227
+ except Exception:
228
+ continue
229
+ per_cam_len = []
230
+ for c in present_cams:
231
+ total = cam_metas[c][0]
232
+ if s >= total:
233
+ length = 0
234
+ else:
235
+ length = max(0, min(e, total - 1) - s + 1)
236
+ per_cam_len.append(length)
237
+ slice_len = min(per_cam_len) if per_cam_len else 0
238
+ if slice_len > 0:
239
+ total_actions_valid += 1
240
+
241
+ # 分片路径生成函数
242
+ def _make_shard_path(base: str, idx: int) -> str:
243
+ base = os.path.abspath(base)
244
+ d = os.path.dirname(base)
245
+ stem = os.path.splitext(os.path.basename(base))[0]
246
+ return os.path.join(d, f"{stem}_part_{idx:04d}.h5")
247
+
248
+ # 打开一个新的分片文件
249
+ def _open_shard(idx: int):
250
+ path = _make_shard_path(output_path, idx)
251
+ h5 = h5py.File(path, "w")
252
+ grp = h5.create_group(f"/{dataset_name}_0")
253
+ grp.attrs["dataset_source"] = dataset_source
254
+ grp.attrs["dataset_version"] = dataset_version
255
+ print(f"[SHARD] 开始写入分片 {idx} -> {path}")
256
+ return h5, grp, path
257
+
258
+ shard_idx = 0
259
+ h5, grp_dataset, current_shard_path = _open_shard(shard_idx)
260
+ traj_count_in_shard = 0
261
+ total_traj_written = 0
262
+ processed_actions = 0
263
+
264
+ try:
265
+ for ep, vids, cam_metas, actions in ep_pool:
266
+ ep_id = int(ep.get("episode_id"))
267
+ scene_text = (ep.get("init_scene_text") or "")
268
+
269
+ # 相机视角固定映射
270
+ camera_order = ["head_color", "hand_left_color", "hand_right_color"]
271
+ present_cams = [c for c in camera_order if c in cam_metas]
272
+ view_names = []
273
+ for c in present_cams:
274
+ if c == "head_color":
275
+ view_names.append("head")
276
+ elif c == "hand_left_color":
277
+ view_names.append("left")
278
+ elif c == "hand_right_color":
279
+ view_names.append("right")
280
+
281
+ # 以第一路相机的 fps 作为参考
282
+ ref_fps = cam_metas[present_cams[0]][4] if present_cams else 30.0
283
+
284
+ for aidx, act in enumerate(actions):
285
+ try:
286
+ s = int(act.get("start_frame", 0))
287
+ e = int(act.get("end_frame", 0))
288
+ except Exception:
289
+ continue
290
+ action_text = (act.get("action_text") or "")
291
+ skill = (act.get("skill") or "")
292
+
293
+ # 对齐各相机的可用帧范围,按最小可用长度截断
294
+ # end_frame 视为包含端点,slice_len = e - s + 1
295
+ per_cam_len = []
296
+ for c in present_cams:
297
+ total = cam_metas[c][0]
298
+ if s >= total:
299
+ length = 0
300
+ else:
301
+ length = max(0, min(e, total - 1) - s + 1)
302
+ per_cam_len.append(length)
303
+ slice_len = min(per_cam_len) if per_cam_len else 0
304
+ if slice_len <= 0:
305
+ print(f"[WARN] episode {ep_id} action[{aidx}]({s}-{e}) 无有效帧,跳过")
306
+ continue
307
+
308
+ # 在当前分片内按计数命名轨迹分组
309
+ traj_grp = grp_dataset.create_group(f"traj_{traj_count_in_shard:04d}")
310
+ traj_grp.attrs["task"] = action_text
311
+ # 自动标号:<task_id>_act_<aidx>
312
+ traj_grp.attrs["task_id"] = f"{task_id_filter}_act_{aidx:03d}"
313
+ traj_grp.attrs["episode_id"] = str(ep_id)
314
+ traj_grp.attrs["scene_id"] = scene_text
315
+ traj_grp.attrs["robot_type"] = default_robot_type
316
+ traj_grp.attrs["success"] = 1
317
+ traj_grp.attrs["num_frames"] = int(slice_len)
318
+ traj_grp.attrs["fps"] = float(ref_fps)
319
+ traj_grp.attrs["duration_sec"] = float(slice_len) / float(ref_fps)
320
+ traj_grp.attrs["camera_views"] = string_array(view_names)
321
+
322
+ # 写入三路图像(若存在)
323
+ for c in present_cams:
324
+ _, w, h, _, _, mp4_path = cam_metas[c]
325
+ # 目标数据集名称
326
+ if c == "head_color":
327
+ dname = "images_head"
328
+ elif c == "hand_left_color":
329
+ dname = "images_left"
330
+ else:
331
+ dname = "images_right"
332
+
333
+ dset = traj_grp.create_dataset(
334
+ name=dname,
335
+ shape=(slice_len, h, w, 3),
336
+ dtype=np.uint8,
337
+ chunks=(1, h, w, 3),
338
+ compression="gzip",
339
+ compression_opts=4,
340
+ )
341
+ written = write_video_slice_to_dataset(mp4_path, dset, start_idx=s, count=slice_len)
342
+ if written < slice_len:
343
+ # 若未写满,仍保留数据集;进度/时长基于 slice_len
344
+ pass
345
+
346
+ # 写入 progress / done / value
347
+ prog = np.linspace(0.0, 1.0, num=slice_len, dtype=np.float32)
348
+ done = np.zeros((slice_len,), dtype=np.bool_)
349
+ done[-1] = True
350
+ value = np.zeros((slice_len,), dtype=np.float32)
351
+
352
+ traj_grp.create_dataset("progress", data=prog, dtype=np.float32)
353
+ traj_grp.create_dataset("done", data=done, dtype=np.bool_)
354
+ traj_grp.create_dataset("value", data=value, dtype=np.float32)
355
+
356
+ traj_count_in_shard += 1
357
+ total_traj_written += 1
358
+ processed_actions += 1
359
+ # 输出整体进度(单行刷新)
360
+ sys.stdout.write(
361
+ f"\r[PROGRESS] 已写入轨迹 {processed_actions}/{total_actions_valid} (episode {ep_id}, action {aidx})"
362
+ )
363
+ sys.stdout.flush()
364
+
365
+ # 达到分片上限则切换到新分片
366
+ if traj_count_in_shard >= max_traj_per_shard:
367
+ grp_dataset.attrs["num_trajectories"] = traj_count_in_shard
368
+ h5.close()
369
+ shard_idx += 1
370
+ h5, grp_dataset, current_shard_path = _open_shard(shard_idx)
371
+ traj_count_in_shard = 0
372
+
373
+ # 收尾:为最后一个分片设置轨迹数并关闭文件
374
+ grp_dataset.attrs["num_trajectories"] = traj_count_in_shard
375
+ h5.close()
376
+ # 进度换行结束
377
+ if total_actions_valid > 0:
378
+ sys.stdout.write("\n")
379
+ finally:
380
+ # 防止异常未关闭
381
+ try:
382
+ if h5 and h5.id:
383
+ grp_dataset.attrs["num_trajectories"] = traj_count_in_shard
384
+ h5.close()
385
+ except Exception:
386
+ pass
387
+
388
+ print(f"✅ 生成完成,共写入轨迹 {total_traj_written},分片数 {shard_idx + 1}")
389
+
390
+
391
+ def parse_args() -> argparse.Namespace:
392
+ p = argparse.ArgumentParser(description="AgiBot World: MP4 + JSON → HDF5 分片生成")
393
+ p.add_argument("--dataset-name", required=True, help="HDF5 顶层数据集名前缀(如 droid、bridge、agibot_world)")
394
+ p.add_argument("--task-json", required=True, help="task_[id].json 路径")
395
+ p.add_argument("--obs-root", required=True, help="observations 根目录(包含 <task_id>/<episode_id>/videos)")
396
+ p.add_argument("--task-id", type=int, required=True, help="任务 ID(如 327)")
397
+ p.add_argument("--output", required=True, help="输出 HDF5 基础文件路径(会生成 _part_XXXX.h5 分片)")
398
+ p.add_argument("--max-traj-per-shard", type=int, default=150, help="单个 H5 分片的最大轨迹数(默认 150)")
399
+ p.add_argument("--dataset-source", default="AgiBot World", help="@dataset_source 属性值")
400
+ p.add_argument("--dataset-version", default="alpha", help="@dataset_version 属性值")
401
+ p.add_argument("--robot-type", default="unknown", help="@robot_type 属性默认值")
402
+ return p.parse_args()
403
+
404
+
405
+ def main():
406
+ args = parse_args()
407
+ build_h5_shard(
408
+ output_path=args.output,
409
+ dataset_name=args.dataset_name,
410
+ task_json_path=args.task_json,
411
+ obs_root=args.obs_root,
412
+ task_id_filter=args.task_id,
413
+ dataset_source=args.dataset_source,
414
+ dataset_version=args.dataset_version,
415
+ default_robot_type=args.robot_type,
416
+ max_traj_per_shard=args.max_traj_per_shard,
417
+ )
418
+
419
+
420
+ if __name__ == "__main__":
421
+ main()