File size: 10,224 Bytes
60fde3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re
import copy
import logging
import traceback
from tqdm import tqdm
from tenacity import (
    retry, 
    stop_after_attempt, 
    wait_random_exponential, 
    retry_if_exception_type,
    before_sleep_log
)
from src.utils.image_utils import parse_multimodal_text, parse_multimodal_text_for_vllm

# 导入 Prompts
from src.llm_generation.prompts import (
    TASK1_SYSTEM_PROMPT, TASK1_STEP_GENERATION_PROMPT, TASK1_FINAL_VERIFICATION_PROMPT,
    TASK3_SYSTEM_PROMPT, TASK3_STEP_GENERATION_PROMPT, TASK3_FINAL_VERIFICATION_PROMPT
)

# 设置 logging
logger = logging.getLogger(__name__)

class CoTGenerator:
    def __init__(self, client, image_root, model_name="gpt-4o"):
        self.client = client
        self.image_root = image_root
        self.model_name = model_name
        # 判断是否为 vllm,其和API采用两种图片加载方式
        self.is_vllm = "VLLMClient" in client.__class__.__name__
        
        self.prompt_map = {
            "camera_view_prediction": {
                "system": TASK1_SYSTEM_PROMPT,
                "step": TASK1_STEP_GENERATION_PROMPT,
                "final": TASK1_FINAL_VERIFICATION_PROMPT
            },
            "camera_view_ordering": {
                "system": TASK3_SYSTEM_PROMPT,
                "step": TASK3_STEP_GENERATION_PROMPT,
                "final": TASK3_FINAL_VERIFICATION_PROMPT
            }
        }

    def _get_content(self, text, img_map):
        """将 prompt 中的相对路径占位符替换为绝对路径格式"""
        def repl(match):
            content = match.group(1)
            rel_path = img_map.get(content, content)
            abs_path = os.path.join(self.image_root, rel_path)
            return f"<image_start>[{abs_path}]<image_end>"
        
        text_abs = re.sub(r"<image_start>\[(.*?)\]<image_end>", repl, text)
        
        if self.is_vllm:
            return parse_multimodal_text_for_vllm(text_abs)
        else:
            return parse_multimodal_text(text_abs)

    @retry(
        stop=stop_after_attempt(5), 
        wait=wait_random_exponential(min=1, max=60),
        before_sleep=before_sleep_log(logger, logging.WARNING),
        reraise=True
    )
    def _call_llm_with_retry(self, messages):
        return self.client.call_chat(messages, model=self.model_name)

    def process_single_entry(self, entry):
        # 确定 task 种类
        # task1: camera view prediction
        # task3: camera view ordering
        task_type = entry.get('task', 'camera_view_prediction')
        # 根据种类选择对应的 prompt
        prompts = self.prompt_map.get(task_type)
        if not prompts:
            raise ValueError(f"Unknown task type: {task_type}")

        meta = entry['oracle_meta']
        img_map = entry['images']
        chain = meta['chain']
      
        # 1. 初始化
        # system prompt: system prompt template + "The question is: {question}"
        history_messages = [{"role": "system", "content": prompts["system"]}]
        # 把 question 加入历史对话中
        question = self._get_content("**Question:\n**" + entry["question"], img_map)
        history_messages.append({"role": "user", "content": question})
      
        full_trace_parts = [] 
        cot_list = []
      
        current_angle_so_far = 0.0
      
        # 2. 循环生成 Chain (Think 1...N)
        for i, step in enumerate(chain):
            # 这一步的目标图 I_k
            next_key = step['result_image_key']
            step_action = step['action']
          
            # --- A. 准备 Context ---
            # 这里的 context 是:历史消息 + 这一轮的新指令
            current_turn_messages = copy.deepcopy(history_messages)
            # 如果是第二步以后,需要给模型上一步的结果;将上一步的结果作为 User 的新输入放进去
            if i > 0:
                # 拿到上一步的 image 占位符,如 reasoning_image_1
                prev_key = chain[i-1]['result_image_key']
                # 构造 text instruction
                # instruction: 这是上一步的结果,请继续
                step_instruction_text = f"Here is the result of the previous step: <image_start>[{prev_key}]<image_end>. Proceed to the next step."
                # 使用 _get_content 方法直接将图片嵌入,并得到 content
                step_content = self._get_content(step_instruction_text, img_map)
                
                current_turn_messages.append({"role": "user", "content": step_content})

            # --- B. 准备 Task 3 特有的匹配提示 ---
            # 默认值为空字符串 (适配 Task 1)
            match_status_hint_text = ""
            
            if task_type == "camera_view_ordering":
                is_current_view_match = False
                matched_label = None
                
                # Look Back 逻辑:检查“当前看到的图”(即上一步的结果)是否是 Key Frame
                if i == 0:
                    is_current_view_match = False
                else:
                    prev_step = chain[i-1]
                    if prev_step.get('is_key_frame'):
                        is_current_view_match = True
                        # 当前看到的图,对应的是要 order 的哪个 view
                        matched_label = prev_step['matched_display_label']
                
                # 提示模型,注意当前 view 与 matched_label 的图是 match 的
                if is_current_view_match:
                    match_status_hint_text = f"The view you are looking at RIGHT NOW corresponds to **Candidate Image {matched_label}**. Explicitly identify this match."
                else:
                    match_status_hint_text = "The view you are looking at RIGHT NOW is an intermediate transition. It does NOT match any candidate image."
                    
            current_step_direction = step_action.get('direction', '')
            if current_step_direction == 'anticlockwise':
                # 逆时针 = 摄像机向右移 = 画面向左移
                physics_rule_text = "Camera moves RIGHT -> View shifts LEFT. (Features on the Right move to Center; Center moves to Left)."
            elif current_step_direction == 'clockwise':
                # 顺时针 = 摄像机向左移 = 画面向右移
                physics_rule_text = "Camera moves LEFT -> View shifts RIGHT. (Features on the Left move to Center; Center moves to Right)."
            else:
                physics_rule_text = "Maintain current view."

            # --- C. 构造参数字典 ---
            step_format_kwargs = {
                # Task 1 & 3 通用
                "total_degrees": meta.get('angle_degrees', 0),
                "direction": meta.get('direction', step_action.get('direction', '')),
                "current_angle_so_far": current_angle_so_far,
                "step_degrees": step_action.get('degrees', 0),
                "step_direction": step_action.get('direction', ''),
                "physics_rule": physics_rule_text,
                "next_image_content": self._get_content(f"<image_start>[{next_key}]<image_end>", img_map),
              
                # Task 3 特有 (Task 1 会自动忽略这个多余参数)
                "match_status_hint": match_status_hint_text,
              
                # 辅助
                "next_image_key": img_map.get(next_key, next_key)
            }
          
            # --- D. 渲染 Prompt ---
            step_prompt_template = prompts["step"]
            cheat_prompt = step_prompt_template.format(**step_format_kwargs)
          
            current_turn_messages.append({"role": "user", "content": self._get_content(cheat_prompt, img_map)})
          
            # --- E. 调用模型 ---
            reasoning_text = self._call_llm_with_retry(current_turn_messages)
            cot_list.append(reasoning_text)
          
            think_block = f"<think>{reasoning_text}</think>"
            image_block = f"<image_start>[{next_key}]<image_end>"
          
            full_trace_parts.append(think_block)
            full_trace_parts.append(image_block)
          
            # --- F. 更新 History ---
            # TODO: assistant 历史中不放 image ,其已经保留在 user query 中
            assistant_content = f"{think_block}"
            history_messages.append({"role": "assistant", "content": assistant_content})
          
            current_angle_so_far = step_action.get('total_angle_so_far', 0.0)

        # 3. 最终验证
        current_turn_messages = copy.deepcopy(history_messages)
        final_key = chain[-1]['result_image_key']
      
        final_format_kwargs = {
            # common args
            "correct_label": meta.get('correct_label', ""), 
            # task1 args
            "total_degrees": meta.get('angle_degrees', 0),
            "final_img_abs_path": img_map.get(final_key, ""),
            "direction": meta.get("direction"),
            # task3 args
            "correct_sequence_str": meta.get('correct_sequence_str', "")
        }
      
        final_prompt = prompts["final"].format(**final_format_kwargs)
        current_turn_messages.append({"role": "user", "content": self._get_content(final_prompt, img_map)})
      
        final_response_text = self._call_llm_with_retry(current_turn_messages)
        cot_list.append(final_response_text)
      
        full_trace_parts.append(f"<think>{final_response_text}</think>")

        entry['reasoning'] = "".join(full_trace_parts)
        entry['oracle_meta']['cot'] = cot_list
      
        return entry



    def process_batch(self, entries):
        results = []
        logging.basicConfig(level=logging.INFO)
      
        for entry in tqdm(entries, desc="Generating CoT"):
            try:
                res = self.process_single_entry(entry)
                results.append(res)
            except Exception as e:
                logger.error(f"Failed to process entry {entry.get('id', 'unknown')} (Error: {e})")
                print("="*30 + " ERROR TRACEBACK " + "="*30)
                traceback.print_exc()
                print("="*77)
        return results