Caesarrr commited on
Commit
c00979a
·
1 Parent(s): 71c0823

feat: add cot trace generation code for task1

Browse files
Files changed (1) hide show
  1. src/action_state/gen_task1.py +130 -38
src/action_state/gen_task1.py CHANGED
@@ -32,7 +32,10 @@ D. <image_start>[image_D]<image_end>
32
  import argparse
33
  import random
34
  import json
 
35
  from tqdm import tqdm
 
 
36
  # 导入公共工具库
37
  from utils import (
38
  CO3DDataLoader,
@@ -41,15 +44,19 @@ from utils import (
41
  get_angle_diff,
42
  format_image_path,
43
  save_jsonl_splits,
44
- get_sequence_geometry
 
45
  )
46
 
47
  class Task1Generator:
48
  def __init__(self, loader, image_prefix):
49
  self.loader = loader
50
  self.image_prefix = image_prefix
51
- # 处理 category 名称,去掉下划线,使其在 Prompt 中更自然
52
  self.cat_name = self.loader.category.replace('_', ' ')
 
 
 
 
53
 
54
  def verify(self, start_R, start_T, target_R, target_T, distractor_infos,
55
  min_angle, max_angle, min_interval, mean_center, basis):
@@ -57,22 +64,16 @@ class Task1Generator:
57
  Task 1 专用验证逻辑:
58
  确保 Start, Target, Distractors 任意两张图之间的角度差都大于 min_interval
59
  """
60
- # 1. 计算 Target 角度并检查范围
61
- # [修改] 使用 PCA 计算角度
62
  target_yaw = get_relative_yaw(start_R, start_T, target_R, target_T, mean_center, basis)
63
 
64
  if not (min_angle <= abs(target_yaw) <= max_angle):
65
  return False, None, []
66
 
67
- # 2. 计算所有干扰项角度
68
  distractor_yaws = []
69
  for d_info in distractor_infos:
70
- # [修改] 使用 PCA 计算角度
71
  d_yaw = get_relative_yaw(start_R, start_T, d_info['R'], d_info['T'], mean_center, basis)
72
  distractor_yaws.append(d_yaw)
73
 
74
- # 3. 全局互斥检查 (Global Separation Check)
75
- # 集合: [Start(0度), Target, D1, D2, D3]
76
  all_angles = [0.0, target_yaw] + distractor_yaws
77
 
78
  for i in range(len(all_angles)):
@@ -82,16 +83,63 @@ class Task1Generator:
82
 
83
  return True, target_yaw, distractor_yaws
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def generate_sample(self, seq_name, config):
86
  frames = self.loader.get_frames(seq_name)
87
- if len(frames) < 5:
88
  return None
89
 
90
- # [新增] 获取该序列的 PCA 几何信息
91
  seq_data_dict = self.loader.seq_data[seq_name]
92
- mean_center, basis, aligned_seq_data = get_sequence_geometry(seq_data_dict)
93
 
94
- # 尝试多次寻找合法组合
95
  max_attempts = 5000
96
  for _ in range(max_attempts):
97
  # A. 随机采样
@@ -99,6 +147,7 @@ class Task1Generator:
99
  start_info = aligned_seq_data[start_idx]
100
 
101
  possible_targets = [f for f in frames if f != start_idx]
 
102
  target_idx = random.choice(possible_targets)
103
  target_info = aligned_seq_data[target_idx]
104
 
@@ -107,8 +156,7 @@ class Task1Generator:
107
  distractor_indices = random.sample(remaining, 3)
108
  distractor_infos = [aligned_seq_data[d] for d in distractor_indices]
109
 
110
- # B. 验证几何约束
111
- # [修改] 传入 T 和 PCA 参数
112
  is_valid, target_yaw, distractor_yaws = self.verify(
113
  start_info['R'], start_info['T'],
114
  target_info['R'], target_info['T'],
@@ -120,25 +168,34 @@ class Task1Generator:
120
  )
121
 
122
  if is_valid:
 
 
 
 
 
 
 
 
 
123
  return self.create_entry(
124
  seq_name, start_idx, target_idx, distractor_indices,
125
- target_yaw, distractor_yaws, start_info, target_info, distractor_infos
 
126
  )
127
  return None
128
 
129
  def create_entry(self, seq_name, start_idx, target_idx, distractor_indices,
130
- target_yaw, distractor_yaws, start_info, target_info, distractor_infos):
 
131
 
132
  angle_deg, direction_str = format_angle_direction(target_yaw)
133
 
134
  # 1. 构建选项列表
135
- # 正确选项
136
  options = [{
137
  "path": format_image_path(target_info['path'], self.loader.root_path, self.image_prefix),
138
  "angle": target_yaw,
139
  "is_correct": True
140
  }]
141
- # 干扰选项
142
  for d_idx, d_yaw, d_info in zip(distractor_indices, distractor_yaws, distractor_infos):
143
  options.append({
144
  "path": format_image_path(d_info['path'], self.loader.root_path, self.image_prefix),
@@ -162,7 +219,53 @@ class Task1Generator:
162
  if opt["is_correct"]:
163
  correct_label = label
164
 
165
- # 3. 生成 Prompt (使用 self.cat_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  template_id = random.choice([1, 2])
167
  if template_id == 1:
168
  question = f"""The {self.cat_name} in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this {self.cat_name}. The direction of rotation is defined from a **top-down bird's-eye view**.
@@ -198,9 +301,10 @@ D. <image_start>[image_D]<image_end>"""
198
  "angle_degrees": angle_deg,
199
  "direction": direction_str,
200
  "raw_yaw": target_yaw,
201
- "option_angles": option_angles_meta
 
202
  },
203
- "gt_answer": correct_label
204
  }
205
 
206
  def main():
@@ -210,8 +314,7 @@ def main():
210
  parser.add_argument("--root_path", type=str, required=True, help="CO3D dataset root")
211
  parser.add_argument("--output_dir", type=str, default="output_task1", help="Output directory")
212
  parser.add_argument("--image_prefix", type=str, default="data/", help="Prefix for image paths")
213
- # [新增] 筛选名单路径
214
- parser.add_argument("--filter_path", type=str, default=None, help="Root directory for filter logs (containing category/keep.json)")
215
 
216
  # 采样配置
217
  parser.add_argument("--category", type=str, default=None, help="Specific category or None for all")
@@ -231,16 +334,12 @@ def main():
231
 
232
  args = parser.parse_args()
233
 
234
- # 初始化
235
  random.seed(args.seed)
236
- import numpy as np
237
  np.random.seed(args.seed)
238
 
239
- # 确定类别列表
240
  if args.category:
241
  categories = [args.category]
242
  else:
243
- import os
244
  data_dir = os.path.join(args.root_path, 'data', 'original')
245
  if os.path.exists(data_dir):
246
  categories = sorted([d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))])
@@ -255,9 +354,7 @@ def main():
255
  'min_interval': args.min_interval
256
  }
257
 
258
- # 主循环
259
  for cat in categories:
260
- # 1. 加载数据 (使用 Utils)
261
  loader = CO3DDataLoader(args.root_path, cat)
262
  if not loader.seq_data:
263
  continue
@@ -265,35 +362,30 @@ def main():
265
  generator = Task1Generator(loader, args.image_prefix)
266
  sequences = loader.get_sequences()
267
 
268
- # [新增] 过滤逻辑
269
  if args.filter_path:
270
  keep_file = os.path.join(args.filter_path, cat, "keep.json")
271
  if os.path.exists(keep_file):
272
  try:
273
  with open(keep_file, 'r') as f:
274
- keep_list = set(json.load(f)) # 使用 set 加速查找
275
-
276
- original_count = len(sequences)
277
  sequences = [s for s in sequences if s in keep_list]
278
- print(f"[{cat}] Filter applied: {original_count} -> {len(sequences)} sequences retained.")
279
  except Exception as e:
280
- print(f"[{cat}] Error reading keep.json: {e}. Skipping category.")
281
  sequences = []
282
  else:
283
- print(f"[{cat}] Warning: No keep.json found at {keep_file}. Skipping category.")
284
  sequences = []
285
 
286
  if not sequences:
287
  continue
288
 
289
- # 2. 生成样本
290
  for seq in tqdm(sequences, desc=f"Task1 - {cat}", leave=False):
291
  for _ in range(args.num_samples):
292
  sample = generator.generate_sample(seq, config)
293
  if sample:
294
  all_results.append(sample)
295
 
296
- # 3. 保存与切分 (使用 Utils)
297
  print(f"Total generated: {len(all_results)}")
298
  save_jsonl_splits(
299
  all_results,
 
32
  import argparse
33
  import random
34
  import json
35
+ import os
36
  from tqdm import tqdm
37
+ import numpy as np # 确保导入 numpy
38
+
39
  # 导入公共工具库
40
  from utils import (
41
  CO3DDataLoader,
 
44
  get_angle_diff,
45
  format_image_path,
46
  save_jsonl_splits,
47
+ get_sequence_geometry,
48
+ decompose_angle
49
  )
50
 
51
  class Task1Generator:
52
  def __init__(self, loader, image_prefix):
53
  self.loader = loader
54
  self.image_prefix = image_prefix
 
55
  self.cat_name = self.loader.category.replace('_', ' ')
56
+ # 定义旋转步长配置,与 create_entry 保持一致
57
+ self.ROTATION_STEPS = [15, 10]
58
+ # 定义允许的最大误差(度):如果模拟角度和真实图片角度相差超过此值,则认为该样本无效
59
+ self.MAX_COT_ERROR = 10.0
60
 
61
  def verify(self, start_R, start_T, target_R, target_T, distractor_infos,
62
  min_angle, max_angle, min_interval, mean_center, basis):
 
64
  Task 1 专用验证逻辑:
65
  确保 Start, Target, Distractors 任意两张图之间的角度差都大于 min_interval
66
  """
 
 
67
  target_yaw = get_relative_yaw(start_R, start_T, target_R, target_T, mean_center, basis)
68
 
69
  if not (min_angle <= abs(target_yaw) <= max_angle):
70
  return False, None, []
71
 
 
72
  distractor_yaws = []
73
  for d_info in distractor_infos:
 
74
  d_yaw = get_relative_yaw(start_R, start_T, d_info['R'], d_info['T'], mean_center, basis)
75
  distractor_yaws.append(d_yaw)
76
 
 
 
77
  all_angles = [0.0, target_yaw] + distractor_yaws
78
 
79
  for i in range(len(all_angles)):
 
83
 
84
  return True, target_yaw, distractor_yaws
85
 
86
+ def _get_all_relative_angles(self, start_idx, all_frames, aligned_seq_data, mean_center, basis):
87
+ """
88
+ 计算序列中所有帧相对于 start_idx 的角度。
89
+ """
90
+ start_info = aligned_seq_data[start_idx]
91
+ results = []
92
+
93
+ for f_idx in all_frames:
94
+ if f_idx == start_idx:
95
+ results.append({'idx': f_idx, 'angle': 0.0})
96
+ continue
97
+
98
+ f_info = aligned_seq_data[f_idx]
99
+ yaw = get_relative_yaw(
100
+ start_info['R'], start_info['T'],
101
+ f_info['R'], f_info['T'],
102
+ mean_center, basis
103
+ )
104
+ results.append({'idx': f_idx, 'angle': yaw})
105
+
106
+ return results
107
+
108
+ def _check_cot_feasibility(self, target_yaw, all_rel_data):
109
+ """
110
+ [新增] 检查 CoT 路径的可行性。
111
+ 如果中间某一步找不到足够接近的真实图片(误差 > MAX_COT_ERROR),则返回 False。
112
+ """
113
+ rotation_sign = 1 if target_yaw >= 0 else -1
114
+ total_delta = abs(target_yaw)
115
+ steps = decompose_angle(total_delta, self.ROTATION_STEPS)
116
+
117
+ current_simulated_angle = 0.0
118
+
119
+ for step in steps:
120
+ current_simulated_angle += (step * rotation_sign)
121
+
122
+ # 寻找最近邻的角度差
123
+ min_diff = float('inf')
124
+ for item in all_rel_data:
125
+ diff = abs(item['angle'] - current_simulated_angle)
126
+ if diff < min_diff:
127
+ min_diff = diff
128
+
129
+ # 如果最近的一张图误差都很大,说明这里缺帧,不能生成高质量 CoT
130
+ if min_diff > self.MAX_COT_ERROR:
131
+ return False
132
+
133
+ return True
134
+
135
  def generate_sample(self, seq_name, config):
136
  frames = self.loader.get_frames(seq_name)
137
+ if len(frames) < 10: # 稍微提高一点门槛,太短的序列很难凑齐中间帧
138
  return None
139
 
 
140
  seq_data_dict = self.loader.seq_data[seq_name]
141
+ mean_center, basis, aligned_seq_data = get_sequence_geometry(seq_data_dict, align_to_standard=True)
142
 
 
143
  max_attempts = 5000
144
  for _ in range(max_attempts):
145
  # A. 随机采样
 
147
  start_info = aligned_seq_data[start_idx]
148
 
149
  possible_targets = [f for f in frames if f != start_idx]
150
+ if not possible_targets: continue
151
  target_idx = random.choice(possible_targets)
152
  target_info = aligned_seq_data[target_idx]
153
 
 
156
  distractor_indices = random.sample(remaining, 3)
157
  distractor_infos = [aligned_seq_data[d] for d in distractor_indices]
158
 
159
+ # B. 验证几何约束 (Start/Target/Distractors 之间的互斥性)
 
160
  is_valid, target_yaw, distractor_yaws = self.verify(
161
  start_info['R'], start_info['T'],
162
  target_info['R'], target_info['T'],
 
168
  )
169
 
170
  if is_valid:
171
+ # === 关键修改:先获取所有帧角度,进行 CoT 可行性预检查 ===
172
+ all_rel_data = self._get_all_relative_angles(
173
+ start_idx, frames, aligned_seq_data, mean_center, basis
174
+ )
175
+
176
+ # 如果 CoT 路径中间缺图,直接跳过,重新采样
177
+ if not self._check_cot_feasibility(target_yaw, all_rel_data):
178
+ continue
179
+
180
  return self.create_entry(
181
  seq_name, start_idx, target_idx, distractor_indices,
182
+ target_yaw, distractor_yaws, start_info, target_info, distractor_infos,
183
+ all_rel_data
184
  )
185
  return None
186
 
187
  def create_entry(self, seq_name, start_idx, target_idx, distractor_indices,
188
+ target_yaw, distractor_yaws, start_info, target_info, distractor_infos,
189
+ all_rel_data):
190
 
191
  angle_deg, direction_str = format_angle_direction(target_yaw)
192
 
193
  # 1. 构建选项列表
 
194
  options = [{
195
  "path": format_image_path(target_info['path'], self.loader.root_path, self.image_prefix),
196
  "angle": target_yaw,
197
  "is_correct": True
198
  }]
 
199
  for d_idx, d_yaw, d_info in zip(distractor_indices, distractor_yaws, distractor_infos):
200
  options.append({
201
  "path": format_image_path(d_info['path'], self.loader.root_path, self.image_prefix),
 
219
  if opt["is_correct"]:
220
  correct_label = label
221
 
222
+ # ------------------------------------------------------------------
223
+ # 3. 生成 Think Process (CoT)
224
+ # ------------------------------------------------------------------
225
+
226
+ rotation_sign = 1 if target_yaw >= 0 else -1
227
+ total_delta = abs(target_yaw)
228
+ # 使用类成员变量 ROTATION_STEPS
229
+ steps = decompose_angle(total_delta, self.ROTATION_STEPS)
230
+
231
+ cot_lines = []
232
+ current_simulated_angle = 0.0
233
+ reasoning_img_counter = 0
234
+
235
+ for step_idx, step in enumerate(steps):
236
+ reasoning_img_counter += 1
237
+
238
+ current_simulated_angle += (step * rotation_sign)
239
+
240
+ # 寻找最近邻帧 (这里肯定能找到误差在 MAX_COT_ERROR 内的,因为前面检查过了)
241
+ closest_frame_data = min(all_rel_data, key=lambda x: abs(x['angle'] - current_simulated_angle))
242
+ closest_frame_idx = closest_frame_data['idx']
243
+
244
+ closest_frame_info = self.loader.get_frame_info(seq_name, closest_frame_idx)
245
+ reasoning_key = f"reasoning_image_{reasoning_img_counter}"
246
+ images_dict[reasoning_key] = format_image_path(
247
+ closest_frame_info['path'], self.loader.root_path, self.image_prefix
248
+ )
249
+
250
+ is_last_step = (step_idx == len(steps) - 1)
251
+
252
+ prefix = "After I rotate" if step_idx == 0 else "Continue rotating"
253
+
254
+ step_text = f"{prefix} {step} degrees {direction_str}, I will see <image_start>[{reasoning_key}]<image_end>"
255
+
256
+ if is_last_step:
257
+ step_text += f", which corresponds to the final view. Checking the answers, option {correct_label} matches this view best, so the final answer should be {correct_label}."
258
+ else:
259
+ step_text += ";"
260
+
261
+ cot_lines.append(step_text)
262
+
263
+ think_content = " ".join(cot_lines)
264
+ final_answer_field = f"<answer>{correct_label}</answer>"
265
+
266
+ # ------------------------------------------------------------------
267
+ # 4. 生成 Prompt
268
+ # ------------------------------------------------------------------
269
  template_id = random.choice([1, 2])
270
  if template_id == 1:
271
  question = f"""The {self.cat_name} in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this {self.cat_name}. The direction of rotation is defined from a **top-down bird's-eye view**.
 
301
  "angle_degrees": angle_deg,
302
  "direction": direction_str,
303
  "raw_yaw": target_yaw,
304
+ "option_angles": option_angles_meta,
305
+ "cot_trace": think_content
306
  },
307
+ "gt_answer": final_answer_field
308
  }
309
 
310
  def main():
 
314
  parser.add_argument("--root_path", type=str, required=True, help="CO3D dataset root")
315
  parser.add_argument("--output_dir", type=str, default="output_task1", help="Output directory")
316
  parser.add_argument("--image_prefix", type=str, default="data/", help="Prefix for image paths")
317
+ parser.add_argument("--filter_path", type=str, default=None, help="Root directory for filter logs")
 
318
 
319
  # 采样配置
320
  parser.add_argument("--category", type=str, default=None, help="Specific category or None for all")
 
334
 
335
  args = parser.parse_args()
336
 
 
337
  random.seed(args.seed)
 
338
  np.random.seed(args.seed)
339
 
 
340
  if args.category:
341
  categories = [args.category]
342
  else:
 
343
  data_dir = os.path.join(args.root_path, 'data', 'original')
344
  if os.path.exists(data_dir):
345
  categories = sorted([d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))])
 
354
  'min_interval': args.min_interval
355
  }
356
 
 
357
  for cat in categories:
 
358
  loader = CO3DDataLoader(args.root_path, cat)
359
  if not loader.seq_data:
360
  continue
 
362
  generator = Task1Generator(loader, args.image_prefix)
363
  sequences = loader.get_sequences()
364
 
 
365
  if args.filter_path:
366
  keep_file = os.path.join(args.filter_path, cat, "keep.json")
367
  if os.path.exists(keep_file):
368
  try:
369
  with open(keep_file, 'r') as f:
370
+ keep_list = set(json.load(f))
 
 
371
  sequences = [s for s in sequences if s in keep_list]
372
+ print(f"[{cat}] Filter applied: {len(sequences)} sequences retained.")
373
  except Exception as e:
374
+ print(f"[{cat}] Error reading keep.json: {e}. Skipping.")
375
  sequences = []
376
  else:
377
+ print(f"[{cat}] Warning: No keep.json found. Skipping.")
378
  sequences = []
379
 
380
  if not sequences:
381
  continue
382
 
 
383
  for seq in tqdm(sequences, desc=f"Task1 - {cat}", leave=False):
384
  for _ in range(args.num_samples):
385
  sample = generator.generate_sample(seq, config)
386
  if sample:
387
  all_results.append(sample)
388
 
 
389
  print(f"Total generated: {len(all_results)}")
390
  save_jsonl_splits(
391
  all_results,