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"[{abs_path}]" text_abs = re.sub(r"\[(.*?)\]", 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: [{prev_key}]. 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"[{next_key}]", 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"{reasoning_text}" image_block = f"[{next_key}]" 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"{final_response_text}") 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