Caesarrr commited on
Commit
0132476
·
1 Parent(s): 24d1e42

feat: add gen_task2 v1

Browse files
Files changed (1) hide show
  1. src/action_state/gen_task2.py +292 -1
src/action_state/gen_task2.py CHANGED
@@ -29,4 +29,295 @@ B. <image_start>[image_B]<image_end>
29
  C. <image_start>[image_C]<image_end>
30
  D. <image_start>[image_D]<image_end>
31
 
32
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  C. <image_start>[image_C]<image_end>
30
  D. <image_start>[image_D]<image_end>
31
 
32
+ """
33
+
34
+ import argparse
35
+ import random
36
+ from tqdm import tqdm
37
+ import numpy as np
38
+
39
+ # 导入公共工具库 (假设 utils.py 在同一目录下)
40
+ from utils import (
41
+ CO3DDataLoader,
42
+ get_relative_yaw,
43
+ format_angle_direction,
44
+ get_angle_diff,
45
+ format_image_path,
46
+ save_jsonl_splits
47
+ )
48
+
49
+ class Task2Generator:
50
+ def __init__(self, loader, image_prefix):
51
+ self.loader = loader
52
+ self.image_prefix = image_prefix
53
+ # 处理 category 名称,去掉下划线
54
+ self.cat_name = self.loader.category.replace('_', ' ')
55
+
56
+ def verify(self, start_R, target_R, distractor_Rs, min_angle, max_angle, min_interval):
57
+ """
58
+ 验证逻辑与 Task 1 相同:
59
+ 确保 Start, Target, Distractors 视觉上是可区分的。
60
+ 虽然 Task 2 是多步移动,但最终我们需要区分的是"最终位置"的视图。
61
+ """
62
+ # 1. 计算 Target 角度并检查范围
63
+ target_yaw = get_relative_yaw(start_R, target_R)
64
+ if not (min_angle <= abs(target_yaw) <= max_angle):
65
+ return False, None, []
66
+
67
+ # 2. 计算所有干扰项角度
68
+ distractor_yaws = [get_relative_yaw(start_R, dR) for dR in distractor_Rs]
69
+
70
+ # 3. 全局互斥检查
71
+ all_angles = [0.0, target_yaw] + distractor_yaws
72
+
73
+ for i in range(len(all_angles)):
74
+ for j in range(i + 1, len(all_angles)):
75
+ if get_angle_diff(all_angles[i], all_angles[j]) < min_interval:
76
+ return False, None, []
77
+
78
+ return True, target_yaw, distractor_yaws
79
+
80
+ def _generate_instruction_sequence(self, total_yaw):
81
+ """
82
+ 将总角度 total_yaw 拆解为 2 到 3 步的旋转指令序列。
83
+ 例如:Total 40 -> Step1: 90, Step2: -50
84
+ """
85
+ target_deg = int(round(total_yaw))
86
+ num_steps = random.choices([3, 4], weights=[0.5, 0.5])[0]
87
+
88
+ max_attempts = 100
89
+ for _ in range(max_attempts):
90
+ steps = []
91
+ current_sum = 0
92
+
93
+ # 生成前 n-1 步
94
+ for _ in range(num_steps - 1):
95
+ # 随机生成一个较大的角度步骤,范围 [-120, 120],避开过小的角度
96
+ step = 0
97
+ while abs(step) < 20:
98
+ step = random.randint(-90, 90)
99
+ steps.append(step)
100
+ current_sum += step
101
+
102
+ # 计算最后一步
103
+ final_step = target_deg - current_sum
104
+
105
+ # 验证最后一步是否合理 (不能太小,也不能太大)
106
+ if 20 <= abs(final_step) <= 90:
107
+ steps.append(final_step)
108
+
109
+ # 生成文本描述
110
+ instruction_parts = []
111
+ for i, step in enumerate(steps):
112
+ val, direction = format_angle_direction(step)
113
+ action = f"rotate {val} degrees {direction}"
114
+ if i == 0:
115
+ instruction_parts.append(action)
116
+ else:
117
+ instruction_parts.append(f"then {action}")
118
+
119
+ instruction_str = ", ".join(instruction_parts)
120
+ return instruction_str, steps
121
+
122
+ # 如果尝试多次失败,回退到直接一步 (虽然不太可能发生)
123
+ val, direction = format_angle_direction(target_deg)
124
+ return f"rotate {val} degrees {direction}", [target_deg]
125
+
126
+ def generate_sample(self, seq_name, config):
127
+ frames = self.loader.get_frames(seq_name)
128
+ if len(frames) < 5:
129
+ return None
130
+
131
+ max_attempts = 5000
132
+ for _ in range(max_attempts):
133
+ # A. 随机采样 Start, Target, Distractors
134
+ start_idx = random.choice(frames)
135
+ start_info = self.loader.get_frame_info(seq_name, start_idx)
136
+
137
+ possible_targets = [f for f in frames if f != start_idx]
138
+ target_idx = random.choice(possible_targets)
139
+ target_info = self.loader.get_frame_info(seq_name, target_idx)
140
+
141
+ remaining = [f for f in frames if f != start_idx and f != target_idx]
142
+ if len(remaining) < 3: continue
143
+ distractor_indices = random.sample(remaining, 3)
144
+ distractor_infos = [self.loader.get_frame_info(seq_name, d) for d in distractor_indices]
145
+
146
+ # B. 验证几何约束
147
+ is_valid, target_yaw, distractor_yaws = self.verify(
148
+ start_info['R'],
149
+ target_info['R'],
150
+ [d['R'] for d in distractor_infos],
151
+ config['min_angle'],
152
+ config['max_angle'],
153
+ config['min_interval']
154
+ )
155
+
156
+ if is_valid:
157
+ # C. 生成指令序列
158
+ instruction_seq, steps_breakdown = self._generate_instruction_sequence(target_yaw)
159
+
160
+ return self.create_entry(
161
+ seq_name, start_idx, target_idx, distractor_indices,
162
+ target_yaw, distractor_yaws,
163
+ start_info, target_info, distractor_infos,
164
+ instruction_seq, steps_breakdown
165
+ )
166
+ return None
167
+
168
+ def create_entry(self, seq_name, start_idx, target_idx, distractor_indices,
169
+ target_yaw, distractor_yaws, start_info, target_info, distractor_infos,
170
+ instruction_seq, steps_breakdown):
171
+
172
+ # 1. 构建选项列表
173
+ options = [{
174
+ "path": format_image_path(target_info['path'], self.loader.root_path, self.image_prefix),
175
+ "angle": target_yaw,
176
+ "is_correct": True
177
+ }]
178
+
179
+ for d_idx, d_yaw, d_info in zip(distractor_indices, distractor_yaws, distractor_infos):
180
+ options.append({
181
+ "path": format_image_path(d_info['path'], self.loader.root_path, self.image_prefix),
182
+ "angle": d_yaw,
183
+ "is_correct": False
184
+ })
185
+
186
+ random.shuffle(options)
187
+
188
+ # 2. 映射到 A, B, C, D
189
+ images_dict = {
190
+ "image_1": format_image_path(start_info['path'], self.loader.root_path, self.image_prefix)
191
+ }
192
+ option_labels = ['A', 'B', 'C', 'D']
193
+ option_angles_meta = {}
194
+ correct_label = ""
195
+
196
+ for label, opt in zip(option_labels, options):
197
+ images_dict[f"image_{label}"] = opt["path"]
198
+ option_angles_meta[label] = opt["angle"]
199
+ if opt["is_correct"]:
200
+ correct_label = label
201
+
202
+ # 3. 生成 Prompt (Task 2 模板)
203
+ template_id = random.choice([1, 2])
204
+
205
+ if template_id == 1:
206
+ question = f"""The object in the image <image_start>[image_1]<image_end> remains **static**.
207
+
208
+ Imagine a camera rotating around this object. The direction of rotation is defined from a **top-down bird's-eye view**.
209
+
210
+ Please identify the view of the object after the camera follows this sequence of rotations: {instruction_seq}. Based on this top-down perspective, select the correct answer.
211
+
212
+ A. <image_start>[image_A]<image_end>
213
+ B. <image_start>[image_B]<image_end>
214
+ C. <image_start>[image_C]<image_end>
215
+ D. <image_start>[image_D]<image_end>"""
216
+
217
+ else:
218
+ question = f"""Given the initial view of a static object: <image_start>[image_1]<image_end>.
219
+
220
+ Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera according to the following instructions: {instruction_seq}.
221
+
222
+ Which of the following images shows what the object looks like from this new position?
223
+
224
+ A. <image_start>[image_A]<image_end>
225
+ B. <image_start>[image_B]<image_end>
226
+ C. <image_start>[image_C]<image_end>
227
+ D. <image_start>[image_D]<image_end>"""
228
+
229
+ return {
230
+ "id": f"task2_{seq_name}_{start_idx}_{target_idx}",
231
+ "task": "camera_view_sequence_prediction", # 区分于 Task 1
232
+ "sequence": seq_name,
233
+ "category": self.loader.category,
234
+ "question": question,
235
+ "images": images_dict,
236
+ "metadata": {
237
+ "start_frame": start_idx,
238
+ "target_frame": target_idx,
239
+ "total_yaw": target_yaw,
240
+ "instruction_sequence": instruction_seq,
241
+ "steps_degrees": steps_breakdown,
242
+ "option_angles": option_angles_meta
243
+ },
244
+ "gt_answer": correct_label
245
+ }
246
+
247
+ def main():
248
+ parser = argparse.ArgumentParser(description="Generate Task 2: Sequence Camera View Prediction")
249
+
250
+ # 路径配置
251
+ parser.add_argument("--root_path", type=str, required=True, help="CO3D dataset root")
252
+ parser.add_argument("--output_dir", type=str, default="output_task2", help="Output directory")
253
+ parser.add_argument("--image_prefix", type=str, default="data/", help="Prefix for image paths")
254
+
255
+ # 采样配置
256
+ parser.add_argument("--category", type=str, default=None, help="Specific category or None for all")
257
+ parser.add_argument("--num_samples", type=int, default=1, help="Samples per sequence")
258
+ parser.add_argument("--seed", type=int, default=42)
259
+
260
+ # 几何约束配置 (与 Task 1 保持一致,用于筛选 Start/Target)
261
+ parser.add_argument("--min_angle", type=float, default=40.0)
262
+ parser.add_argument("--max_angle", type=float, default=140.0)
263
+ parser.add_argument("--min_interval", type=float, default=25.0)
264
+
265
+ # 切分配置
266
+ parser.add_argument("--train_ratio", type=float, default=0.8)
267
+ parser.add_argument("--val_ratio", type=float, default=0.1)
268
+ parser.add_argument("--test_ratio", type=float, default=0.1)
269
+ parser.add_argument("--max_items", type=int, default=10000)
270
+
271
+ args = parser.parse_args()
272
+
273
+ # 初始化
274
+ random.seed(args.seed)
275
+ np.random.seed(args.seed)
276
+
277
+ # 确定类别列表
278
+ if args.category:
279
+ categories = [args.category]
280
+ else:
281
+ import os
282
+ data_dir = os.path.join(args.root_path, 'data', 'original')
283
+ if os.path.exists(data_dir):
284
+ categories = sorted([d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))])
285
+ else:
286
+ print(f"Error: {data_dir} not found.")
287
+ return
288
+
289
+ all_results = []
290
+ config = {
291
+ 'min_angle': args.min_angle,
292
+ 'max_angle': args.max_angle,
293
+ 'min_interval': args.min_interval
294
+ }
295
+
296
+ # 主循环
297
+ for cat in categories:
298
+ loader = CO3DDataLoader(args.root_path, cat)
299
+ if not loader.seq_data:
300
+ continue
301
+
302
+ generator = Task2Generator(loader, args.image_prefix)
303
+ sequences = loader.get_sequences()
304
+
305
+ for seq in tqdm(sequences, desc=f"Task2 - {cat}", leave=False):
306
+ for _ in range(args.num_samples):
307
+ sample = generator.generate_sample(seq, config)
308
+ if sample:
309
+ all_results.append(sample)
310
+
311
+ # 保存与切分
312
+ print(f"Total generated: {len(all_results)}")
313
+ save_jsonl_splits(
314
+ all_results,
315
+ args.output_dir,
316
+ ratios=(args.train_ratio, args.val_ratio, args.test_ratio),
317
+ max_items=args.max_items,
318
+ seed=args.seed
319
+ )
320
+ print(f"Done. Output saved to {args.output_dir}")
321
+
322
+ if __name__ == "__main__":
323
+ main()