interleaved-umm / src /action_state /gen_task1.py
Caesarrr's picture
Add files using upload-large-folder tool
60fde3b verified
"""
给定一张物体在初始视角的图片,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()