Wendy-Fly commited on
Commit
f2fa404
·
verified ·
1 Parent(s): 0197974

Upload demo_test_all_v4_resume.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. demo_test_all_v4_resume.py +139 -0
demo_test_all_v4_resume.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import tensorflow as tf
4
+ from android_env.proto.a11y import android_accessibility_forest_pb2
5
+ import json
6
+ import os
7
+ from google.protobuf.json_format import MessageToJson
8
+ from tqdm import tqdm
9
+
10
+
11
+ def parse_node(node, nodes, depth=0, parent_bounds=None):
12
+ # 提取节点信息
13
+ class_name = node.get("className", "Unknown")
14
+ # 获取 viewIdResourceName 并简化输出,只保留资源名部分
15
+ view_id = node.get("viewIdResourceName", "")
16
+ simplified_view_id = view_id.split(":")[-1] if view_id else ""
17
+ simplified_view_id = ' '.join(simplified_view_id.split('_'))
18
+ simplified_view_id = simplified_view_id.replace('id/','')
19
+
20
+ bounds = node.get("boundsInScreen", {})
21
+ bounds_str = f"[{bounds.get('left', 0)}, {bounds.get('top', 0)}, {bounds.get('right', 0)}, {bounds.get('bottom', 0)}]"
22
+
23
+ if parent_bounds and bounds == parent_bounds:
24
+ bounds_str = ""
25
+
26
+ node_str = f"{' ' * depth}└── {simplified_view_id} {f'({bounds_str})' if bounds_str else ''}"
27
+
28
+ children_str = ""
29
+ if "childIds" in node:
30
+ children = [child for child in nodes if 'uniqueId' in child and child['uniqueId'] in node['childIds']]
31
+ for child in children:
32
+ children_str += "\n" + parse_node(child, nodes, depth + 1, bounds)
33
+
34
+ return node_str + children_str
35
+
36
+
37
+ def parse_tree(window_data):
38
+ # 获取树的根节点(Window信息)
39
+ window_info = window_data['windows'][0]
40
+ window_type = window_info.get('windowType', 'Unknown')
41
+ root_node_str = f"Window ({window_type})"
42
+ nodes = window_info['tree']['nodes']
43
+ root_node_str += "\n" + parse_node(nodes[0], nodes, 1)
44
+ return root_node_str
45
+
46
+
47
+
48
+ # 设置路径
49
+ output_dir = "output_data"
50
+ os.makedirs(output_dir, exist_ok=True)
51
+
52
+ intermediate_json_path = os.path.join("/inspire/hdd/ws-ba572160-47f8-4ca1-984e-d6bcdeb95dbb/a100-maybe/wangbaode/NIPS_2025/Agent/Dataset/android_env/intermediate_data_8k_succ.json")
53
+ intermediate_json_path_new = os.path.join("/inspire/hdd/ws-ba572160-47f8-4ca1-984e-d6bcdeb95dbb/a100-maybe/wangbaode/NIPS_2025/Agent/Dataset/android_env/intermediate_data.jsonl")
54
+
55
+
56
+
57
+ # === 恢复已处理的 episode_id 列表 ===
58
+ processed_episodes = set()
59
+ all_data = []
60
+
61
+ if os.path.exists(intermediate_json_path):
62
+ with open(intermediate_json_path, "r", encoding="utf-8") as f:
63
+ try:
64
+ all_data = json.load(f)
65
+ for record in all_data:
66
+ processed_episodes.add(record["episode_id"])
67
+ print(f"恢复 {len(processed_episodes)} 条已处理记录")
68
+ except Exception as e:
69
+ print(f"读取中间文件失败: {e}")
70
+
71
+ # === 加载 TFRecord 数据 ===
72
+ filenames = tf.io.gfile.glob('/inspire/hdd/ws-ba572160-47f8-4ca1-984e-d6bcdeb95dbb/a100-maybe/wangbaode/NIPS_2025/Agent/Dataset/AndControl/android_control*')
73
+ raw_dataset = tf.data.TFRecordDataset(filenames, compression_type='GZIP')
74
+
75
+ # === 遍历数据集 ===
76
+ record_index = len(all_data) # 从当前进度继续
77
+
78
+ for raw_record in tqdm(raw_dataset, desc="遍历 TFRecords"):
79
+ try:
80
+ example = tf.train.Example.FromString(raw_record.numpy())
81
+
82
+ episode_id = example.features.feature['episode_id'].int64_list.value[0]
83
+ if episode_id in processed_episodes:
84
+ continue # 已处理过,跳过
85
+
86
+ goal = example.features.feature['goal'].bytes_list.value[0].decode('utf-8')
87
+ screenshots = example.features.feature['screenshots'].bytes_list.value
88
+ accessibility_trees = [
89
+ android_accessibility_forest_pb2.AndroidAccessibilityForest().FromString(tree)
90
+ for tree in example.features.feature['accessibility_trees'].bytes_list.value
91
+ ]
92
+ screenshot_widths = list(example.features.feature['screenshot_widths'].int64_list.value)
93
+ screenshot_heights = list(example.features.feature['screenshot_heights'].int64_list.value)
94
+ actions = [a.decode('utf-8') for a in example.features.feature['actions'].bytes_list.value]
95
+ step_instructions = [s.decode('utf-8') for s in example.features.feature['step_instructions'].bytes_list.value]
96
+
97
+ # 构造数据
98
+ data = {
99
+ "episode_id": episode_id,
100
+ "goal": goal,
101
+ "screenshots": [],
102
+ "screenshot_widths": screenshot_widths,
103
+ "screenshot_heights": screenshot_heights,
104
+ "actions": actions,
105
+ "step_instructions": step_instructions,
106
+ "accessibility_trees": []
107
+ }
108
+
109
+ # 保存截图
110
+ for i, img in enumerate(screenshots):
111
+ path = os.path.join(output_dir, f"screenshot_{episode_id}_{i}.png")
112
+ with open(path, "wb") as f:
113
+ f.write(img)
114
+ data["screenshots"].append(path)
115
+
116
+ # 转换可达性树
117
+ for tree in accessibility_trees:
118
+ json_dict = json.loads(MessageToJson(tree))
119
+ tree_output = parse_tree(json_dict)
120
+ data["accessibility_trees"].append(tree_output)
121
+
122
+ # 加入列表
123
+ all_data.append(data)
124
+ processed_episodes.add(episode_id)
125
+
126
+ # 覆盖写入中间 JSON 文件(可断点续跑)
127
+ # with open(intermediate_json_path_new, "a+", encoding="utf-8") as f:
128
+ # json.dump(all_data, f, indent=2, ensure_ascii=False)
129
+
130
+ # 逐条追加写入 JSONL
131
+ with open(intermediate_json_path_new, "a+", encoding="utf-8") as fout:
132
+ fout.write(json.dumps(data, ensure_ascii=False) + "\n")
133
+
134
+ print(f"✅ 已处理 episode_id={episode_id}")
135
+
136
+ except Exception as e:
137
+ print(f"❌ 处理失败,跳过该记录:{e}")
138
+ continue
139
+