File size: 16,857 Bytes
c7f75e8
 
 
 
 
 
b73b7d0
c7f75e8
b73b7d0
c7f75e8
 
 
 
 
 
 
 
b73b7d0
c7f75e8
b73b7d0
c7f75e8
b73b7d0
c7f75e8
 
 
 
 
 
 
 
 
a104ac4
24d1e42
3e0a7cf
c00979a
a104ac4
c00979a
 
24d1e42
 
 
8e74163
 
 
 
 
60fde3b
c00979a
24d1e42
 
 
 
 
b73b7d0
24d1e42
c00979a
60fde3b
c00979a
60fde3b
c7f75e8
8e74163
 
a104ac4
24d1e42
 
a104ac4
8e74163
 
b73b7d0
24d1e42
a104ac4
8e74163
 
 
 
b73b7d0
 
 
 
 
24d1e42
 
 
a104ac4
 
60fde3b
c00979a
 
 
60fde3b
c00979a
 
 
 
 
 
 
60fde3b
c00979a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24d1e42
 
c00979a
24d1e42
 
8e74163
60fde3b
8e74163
24d1e42
 
 
 
60fde3b
a104ac4
24d1e42
c00979a
a104ac4
60fde3b
a104ac4
24d1e42
a104ac4
 
60fde3b
24d1e42
c00979a
24d1e42
8e74163
 
 
24d1e42
 
8e74163
 
c7f75e8
24d1e42
a104ac4
c00979a
 
60fde3b
c00979a
 
 
 
 
 
24d1e42
 
c00979a
 
a104ac4
24d1e42
a104ac4
24d1e42
c00979a
 
c7f75e8
24d1e42
c7f75e8
24d1e42
 
 
a104ac4
 
 
24d1e42
 
 
 
a104ac4
 
c7f75e8
24d1e42
c7f75e8
60fde3b
24d1e42
 
 
c7f75e8
24d1e42
a104ac4
60fde3b
 
 
24d1e42
60fde3b
 
 
 
 
 
 
 
 
a104ac4
24d1e42
c00979a
60fde3b
c00979a
 
 
 
 
 
60fde3b
c00979a
 
60fde3b
 
 
c00979a
60fde3b
c00979a
 
 
60fde3b
 
 
c00979a
 
 
 
60fde3b
 
 
 
 
 
 
 
 
 
 
 
 
c00979a
 
 
c7f75e8
 
24d1e42
c7f75e8
24d1e42
c7f75e8
 
 
 
 
 
24d1e42
c7f75e8
24d1e42
c7f75e8
24d1e42
c7f75e8
 
 
 
 
 
60fde3b
 
 
a104ac4
24d1e42
 
 
a104ac4
60fde3b
 
a104ac4
 
c7f75e8
 
60fde3b
 
 
c7f75e8
60fde3b
 
c7f75e8
 
a104ac4
24d1e42
a104ac4
24d1e42
 
 
b73b7d0
c00979a
a104ac4
24d1e42
 
 
 
a104ac4
24d1e42
b73b7d0
 
 
a104ac4
24d1e42
b73b7d0
 
 
 
a104ac4
 
24d1e42
a104ac4
 
 
 
 
 
 
 
24d1e42
a104ac4
24d1e42
a104ac4
 
 
24d1e42
 
 
 
 
 
a104ac4
24d1e42
 
a104ac4
c7f75e8
24d1e42
 
3e0a7cf
 
 
 
 
 
c00979a
3e0a7cf
c00979a
3e0a7cf
c00979a
3e0a7cf
 
c00979a
3e0a7cf
 
 
 
c7f75e8
24d1e42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7f75e8
 
a104ac4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
"""
给定一张物体在初始视角的图片,camera将围绕该静止物体进行水平移动。旋转的方向(顺时针或逆时针)是基于从物体正上方俯视(鸟瞰视角)的平面来定义的。模型需要根据给定的旋转方向和角度,推断出新视角下的物体图像,并从四个图像中选出正确的一项。

注:{angle}就是 xx degrees, {direction} 就是 clockwise / anticlockwise

1.
The {object} in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this {object}. The direction of rotation is defined from a **top-down bird's-eye view**.

Please identify the view of the {object} after the camera rotates {angle} {direction} based on this top-down perspective, and select the correct answer.

A. <image_start>[image_A]<image_end>
B. <image_start>[image_B]<image_end>
C. <image_start>[image_C]<image_end>
D. <image_start>[image_D]<image_end>


2.
Given the initial view of a **static** {object}: <image_start>[image_1]<image_end>.

Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera {angle} {direction} around the {object}.

Which of the following images shows what the {object} looks like from this new position?

A. <image_start>[image_A]<image_end>
B. <image_start>[image_B]<image_end>
C. <image_start>[image_C]<image_end>
D. <image_start>[image_D]<image_end>

"""


import argparse
import random
import json
import os
from tqdm import tqdm
import numpy as np # 确保导入 numpy

# 导入公共工具库
from utils import (
    CO3DDataLoader, 
    get_relative_yaw,
    format_angle_direction,
    get_angle_diff,
    format_image_path,
    save_jsonl_splits,
    get_sequence_geometry_pca,
    decompose_angle
)

class Task1Generator:
    def __init__(self, loader, image_prefix):
        self.loader = loader
        self.image_prefix = image_prefix
        self.cat_name = self.loader.category.replace('_', ' ')
        # 定义旋转步长配置,与 create_entry 保持一致
        self.ROTATION_STEPS = [30, 15] 
        # 定义允许的最大误差(度):如果模拟角度和真实图片角度相差超过此值,则认为该样本无效
        self.MAX_COT_ERROR = 10.0

    def verify(self, start_R, start_T, target_R, target_T, distractor_infos, 
               min_angle, max_angle, min_interval, mean_center, basis):
        """
        Task 1 专用验证逻辑:
        确保 Start, Target, Distractors 任意两张图之间的角度差都大于 min_interval
        """
        target_yaw = get_relative_yaw(start_R, start_T, target_R, target_T, mean_center, basis)
        
        if not (min_angle <= abs(target_yaw) <= max_angle):
            return False, None, []

        distractor_yaws = []
        for d_info in distractor_infos:
            d_yaw = get_relative_yaw(start_R, start_T, d_info['R'], d_info['T'], mean_center, basis)
            distractor_yaws.append(d_yaw)

        all_angles = [0.0, target_yaw] + distractor_yaws
        
        for i in range(len(all_angles)):
            for j in range(i + 1, len(all_angles)):
                if get_angle_diff(all_angles[i], all_angles[j]) < min_interval:
                    return False, None, []
                    
        return True, target_yaw, distractor_yaws

    def _get_all_relative_angles(self, start_idx, all_frames, seq_data_dict, mean_center, basis):
        """
        计算序列中所有帧相对于 start_idx 的角度。
        """
        start_info = seq_data_dict[start_idx]
        results = []
        
        for f_idx in all_frames:
            if f_idx == start_idx:
                results.append({'idx': f_idx, 'angle': 0.0})
                continue
                
            f_info = seq_data_dict[f_idx]
            yaw = get_relative_yaw(
                start_info['R'], start_info['T'], 
                f_info['R'], f_info['T'], 
                mean_center, basis
            )
            results.append({'idx': f_idx, 'angle': yaw})
            
        return results

    def _check_cot_feasibility(self, target_yaw, all_rel_data):
        """
        [新增] 检查 CoT 路径的可行性。
        如果中间某一步找不到足够接近的真实图片(误差 > MAX_COT_ERROR),则返回 False。
        """
        rotation_sign = 1 if target_yaw >= 0 else -1
        total_delta = abs(target_yaw)
        steps = decompose_angle(total_delta, self.ROTATION_STEPS)
        
        current_simulated_angle = 0.0
        
        for step in steps:
            current_simulated_angle += (step * rotation_sign)
            
            # 寻找最近邻的角度差
            min_diff = float('inf')
            for item in all_rel_data:
                diff = abs(item['angle'] - current_simulated_angle)
                if diff < min_diff:
                    min_diff = diff
            
            # 如果最近的一张图误差都很大,说明这里缺帧,不能生成高质量 CoT
            if min_diff > self.MAX_COT_ERROR:
                return False
                
        return True

    def generate_sample(self, seq_name, config):
        frames = self.loader.get_frames(seq_name)
        if len(frames) < 10: # 稍微提高一点门槛,太短的序列很难凑齐中间帧
            return None

        seq_data_dict = self.loader.seq_data[seq_name]
        mean_center, basis, _ = get_sequence_geometry_pca(seq_data_dict)

        max_attempts = 5000
        for _ in range(max_attempts):
            # A. 随机采样
            start_idx = random.choice(frames)
            start_info = seq_data_dict[start_idx]
            
            possible_targets = [f for f in frames if f != start_idx]
            if not possible_targets: continue
            target_idx = random.choice(possible_targets)
            target_info = seq_data_dict[target_idx]
            
            remaining = [f for f in frames if f != start_idx and f != target_idx]
            if len(remaining) < 3: continue
            distractor_indices = random.sample(remaining, 3)
            distractor_infos = [seq_data_dict[d] for d in distractor_indices]

            # B. 验证几何约束 (Start/Target/Distractors 之间的互斥性)
            is_valid, target_yaw, distractor_yaws = self.verify(
                start_info['R'], start_info['T'],
                target_info['R'], target_info['T'],
                distractor_infos,
                config['min_angle'], 
                config['max_angle'], 
                config['min_interval'],
                mean_center, basis
            )

            if is_valid:
                # === 关键修改:先获取所有帧角度,进行 CoT 可行性预检查 ===
                all_rel_data = self._get_all_relative_angles(
                    start_idx, frames, seq_data_dict, mean_center, basis
                )
                
                # 如果 CoT 路径中间缺图,直接跳过,重新采样
                if not self._check_cot_feasibility(target_yaw, all_rel_data):
                    continue
                
                return self.create_entry(
                    seq_name, start_idx, target_idx, distractor_indices,
                    target_yaw, distractor_yaws, start_info, target_info, distractor_infos,
                    all_rel_data 
                )
        return None

    def create_entry(self, seq_name, start_idx, target_idx, distractor_indices, 
                     target_yaw, distractor_yaws, start_info, target_info, distractor_infos,
                     all_rel_data):
        
        angle_deg, direction_str = format_angle_direction(target_yaw)
        
        # 1. 构建选项列表
        options = [{
            "path": format_image_path(target_info['path'], self.loader.root_path, self.image_prefix),
            "angle": target_yaw,
            "is_correct": True
        }]
        for d_idx, d_yaw, d_info in zip(distractor_indices, distractor_yaws, distractor_infos):
            options.append({
                "path": format_image_path(d_info['path'], self.loader.root_path, self.image_prefix),
                "angle": d_yaw,
                "is_correct": False
            })
        
        random.shuffle(options)
        
        # 2. 映射到 A, B, C, D (保持不变,但记录正确答案的 Label)
        images_dict = {
            "image_1": format_image_path(start_info['path'], self.loader.root_path, self.image_prefix)
        }
        option_labels = ['A', 'B', 'C', 'D']
        correct_label = ""
        
        # 用于 Oracle 数据的选项信息
        options_meta = {} 
        
        for label, opt in zip(option_labels, options):
            img_key = f"image_{label}"
            images_dict[img_key] = opt["path"]
            
            options_meta[label] = {
                "image_key": img_key,
                "angle": opt["angle"],
                "is_correct": opt["is_correct"]
            }
            
            if opt["is_correct"]:
                correct_label = label
        # ------------------------------------------------------------------
        # 3. 构建 Oracle Chain (核心修改)
        # ------------------------------------------------------------------
        
        rotation_sign = 1 if target_yaw >= 0 else -1
        total_delta = abs(target_yaw)
        steps = decompose_angle(total_delta, self.ROTATION_STEPS)
        
        oracle_chain = []
        current_simulated_angle = 0.0
        
        # 记录每一步的详细信息
        for step_idx, step_angle in enumerate(steps):
            current_simulated_angle += (step_angle * rotation_sign)
            
            # 寻找最近邻帧
            closest_frame_data = min(all_rel_data, key=lambda x: abs(x['angle'] - current_simulated_angle))
            closest_frame_idx = closest_frame_data['idx']
            closest_frame_info = self.loader.get_frame_info(seq_name, closest_frame_idx)
            
            # 定义这一步产生的中间图的 key
            reasoning_key = f"reasoning_image_{step_idx + 1}"
            images_dict[reasoning_key] = format_image_path(
                closest_frame_info['path'], self.loader.root_path, self.image_prefix
            )
            
            # 构造 Chain Item
            chain_item = {
                "step_index": step_idx + 1,
                "action": {
                    "type": "rotate",
                    "degrees": step_angle,
                    "direction": direction_str,
                    "total_angle_so_far": current_simulated_angle
                },
                "result_image_key": reasoning_key,
                "is_final_step": (step_idx == len(steps) - 1)
            }
            oracle_chain.append(chain_item)
        # ------------------------------------------------------------------
        # 4. 生成 Prompt
        # ------------------------------------------------------------------
        template_id = random.choice([1, 2])
        if template_id == 1:
            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**.

Please identify the view of the {self.cat_name} after the camera rotates {angle_deg} degrees {direction_str} based on this top-down perspective, and select the correct answer.

A. <image_start>[image_A]<image_end>
B. <image_start>[image_B]<image_end>
C. <image_start>[image_C]<image_end>
D. <image_start>[image_D]<image_end>"""
        else:
            question = f"""Given the initial view of a **static** {self.cat_name}: <image_start>[image_1]<image_end>.

Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera {angle_deg} degrees {direction_str} around the {self.cat_name}.

Which of the following images shows what the {self.cat_name} looks like from this new position?

A. <image_start>[image_A]<image_end>
B. <image_start>[image_B]<image_end>
C. <image_start>[image_C]<image_end>
D. <image_start>[image_D]<image_end>"""

        # ------------------------------------------------------------------
        # 5. 返回结构化数据 (不再包含 cot_trace 字符串)
        # ------------------------------------------------------------------
        return {
            "id": f"task1_{seq_name}_{start_idx}_{target_idx}",
            "task": "camera_view_prediction",
            "sequence": seq_name,
            "question": question,
            "images": images_dict, # 包含 start, options, 和所有的 reasoning_images
            "oracle_meta": {
                "start_frame": start_idx,
                "target_frame": target_idx,
                "angle_degrees": angle_deg,
                "direction": direction_str,
                "correct_label": correct_label,
                "options": options_meta,
                "chain": oracle_chain # 这是给 LLM 看的“剧本”
            },
            # gt_answer 字段暂时留空或只放答案,等 Stage 2 再填入完整的 CoT
            "gt_answer": f"<answer>{correct_label}</answer>" 
        }

def main():
    parser = argparse.ArgumentParser(description="Generate Task 1: Camera View Prediction")
    
    # 路径配置
    parser.add_argument("--root_path", type=str, required=True, help="CO3D dataset root")
    parser.add_argument("--output_dir", type=str, default="output_task1", help="Output directory")
    parser.add_argument("--image_prefix", type=str, default="data/", help="Prefix for image paths")
    parser.add_argument("--filter_path", type=str, default=None, help="Root directory for filter logs")
    
    # 采样配置
    parser.add_argument("--category", type=str, default=None, help="Specific category or None for all")
    parser.add_argument("--num_samples", type=int, default=1, help="Samples per sequence")
    parser.add_argument("--seed", type=int, default=42)
    
    # 几何约束配置
    parser.add_argument("--min_angle", type=float, default=40.0)
    parser.add_argument("--max_angle", type=float, default=140.0)
    parser.add_argument("--min_interval", type=float, default=25.0)
    
    # 切分配置
    parser.add_argument("--train_ratio", type=float, default=0.8)
    parser.add_argument("--val_ratio", type=float, default=0.1)
    parser.add_argument("--test_ratio", type=float, default=0.1)
    parser.add_argument("--max_items", type=int, default=10000)

    args = parser.parse_args()
    
    random.seed(args.seed)
    np.random.seed(args.seed)
    
    if args.category:
        categories = [args.category]
    else:
        data_dir = os.path.join(args.root_path, 'data', 'original')
        if os.path.exists(data_dir):
            categories = sorted([d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))])
        else:
            print(f"Error: {data_dir} not found.")
            return

    all_results = []
    config = {
        'min_angle': args.min_angle,
        'max_angle': args.max_angle,
        'min_interval': args.min_interval
    }

    for cat in categories:
        loader = CO3DDataLoader(args.root_path, cat)
        if not loader.seq_data:
            continue
            
        generator = Task1Generator(loader, args.image_prefix)
        sequences = loader.get_sequences()

        if args.filter_path:
            keep_file = os.path.join(args.filter_path, cat, "keep.json")
            if os.path.exists(keep_file):
                try:
                    with open(keep_file, 'r') as f:
                        keep_list = set(json.load(f))
                    sequences = [s for s in sequences if s in keep_list]
                    print(f"[{cat}] Filter applied: {len(sequences)} sequences retained.")
                except Exception as e:
                    print(f"[{cat}] Error reading keep.json: {e}. Skipping.")
                    sequences = []
            else:
                print(f"[{cat}] Warning: No keep.json found. Skipping.")
                sequences = []
        
        if not sequences:
            continue
        
        for seq in tqdm(sequences, desc=f"Task1 - {cat}", leave=False):
            for _ in range(args.num_samples):
                sample = generator.generate_sample(seq, config)
                if sample:
                    all_results.append(sample)

    print(f"Total generated: {len(all_results)}")
    save_jsonl_splits(
        all_results, 
        args.output_dir, 
        ratios=(args.train_ratio, args.val_ratio, args.test_ratio),
        max_items=args.max_items,
        seed=args.seed
    )
    print(f"Done. Output saved to {args.output_dir}")

if __name__ == "__main__":
    main()