tarsai2025 commited on
Commit
25fbec9
·
verified ·
1 Parent(s): 3931cf9

Upload libero_plus/postprocess_hdf5_metadata.py

Browse files
libero_plus/postprocess_hdf5_metadata.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ Post-process LIBERO HDF5 files:
4
+ - Read language instruction from:
5
+ task_visualizations/libero_10/{task_name}/task_description_id.txt
6
+ - Extract line 2 and line 3
7
+ - Write into HDF5: data.problem_info.language_instruction(s)
8
+ """
9
+
10
+ import os
11
+ import h5py
12
+ import json
13
+ import argparse
14
+ from tqdm import tqdm
15
+ from pathlib import Path
16
+
17
+
18
+ def read_lang_lines(txt_path):
19
+ """Read non-empty lines and return line 1 and 2 (index 1 and 2)"""
20
+ with open(txt_path, 'r', encoding='utf-8') as f:
21
+ lines = [line.strip() for line in f.readlines() if line.strip()]
22
+ if len(lines) < 3:
23
+ raise ValueError(f"Not enough lines in {txt_path}, got {len(lines)}")
24
+ return lines[1], lines[2] # 第二行和第三行
25
+
26
+
27
+ def postprocess_all_hdf5s(hdf5_dir, viz_parent_dir="task_visualizations"):
28
+ """
29
+ :param hdf5_dir: 包含 .hdf5 文件的目录,如 "libero_10"
30
+ :param viz_parent_dir: 可视化根目录,下有子目录如 libero_10/
31
+ """
32
+ # 获取所有 HDF5 文件
33
+ hdf5_files = [f for f in os.listdir(hdf5_dir) if f.endswith(".hdf5")]
34
+ hdf5_files.sort()
35
+
36
+ if not hdf5_files:
37
+ print(f"❌ No HDF5 files found in {hdf5_dir}")
38
+ return
39
+
40
+ print(f"Found {len(hdf5_files)} HDF5 files.")
41
+
42
+ for fname in tqdm(hdf5_files, desc="Updating HDF5 metadata"):
43
+ hdf5_path = os.path.join(hdf5_dir, fname)
44
+ task_name = Path(fname).stem # 去掉 .hdf5,保留完整名(含 _demo)
45
+
46
+ # 构造 visualization 目录路径
47
+ viz_dir = os.path.join(viz_parent_dir, Path(hdf5_dir).name, task_name)
48
+ desc_txt_path = os.path.join(viz_dir, "task_description_id.txt")
49
+
50
+ if not os.path.exists(desc_txt_path):
51
+ print(f"⚠️ Missing task_description_id.txt: {desc_txt_path}")
52
+ continue
53
+
54
+ try:
55
+ lang_inst, lang_inst_with_id = read_lang_lines(desc_txt_path)
56
+ except Exception as e:
57
+ print(f"❌ Failed to read {desc_txt_path}: {e}")
58
+ continue
59
+
60
+ # 修改 HDF5 文件
61
+ try:
62
+ with h5py.File(hdf5_path, "a") as f:
63
+ if "data" not in f:
64
+ print(f"❌ Group 'data' not found in {hdf5_path}")
65
+ continue
66
+ data_grp = f["data"]
67
+
68
+ # 读取或初始化 problem_info
69
+ if "problem_info" in data_grp.attrs:
70
+ prob_info_str = data_grp.attrs["problem_info"]
71
+ if isinstance(prob_info_str, bytes):
72
+ prob_info_str = prob_info_str.decode("utf-8")
73
+ problem_info = json.loads(prob_info_str)
74
+ else:
75
+ problem_info = {}
76
+
77
+ # 更新字段
78
+ problem_info["language_instruction"] = lang_inst
79
+ problem_info["language_instruction_with_id"] = lang_inst_with_id
80
+
81
+ # 写回属性(modify 支持变长字符串)
82
+ data_grp.attrs.modify("problem_info", json.dumps(problem_info, ensure_ascii=False))
83
+
84
+ print(f"✅ Updated: {fname}")
85
+
86
+ except Exception as e:
87
+ print(f"❌ Error writing to {hdf5_path}: {e}")
88
+
89
+
90
+ if __name__ == "__main__":
91
+ parser = argparse.ArgumentParser(description="Add language_instruction fields from task_description_id.txt")
92
+ parser.add_argument(
93
+ "--hdf5-dir",
94
+ type=str,
95
+ default="libero_spatial",
96
+ help="Directory containing the HDF5 files (e.g., libero_object/)"
97
+ )
98
+ parser.add_argument(
99
+ "--viz-parent-dir",
100
+ type=str,
101
+ default="task_visualizations",
102
+ help="Parent directory of visualizations (default: task_visualizations/)"
103
+ )
104
+
105
+ args = parser.parse_args()
106
+
107
+ postprocess_all_hdf5s(args.hdf5_dir, args.viz_parent_dir)
108
+
109
+ # object