| 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 |
|
|
| |
| 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 |
| ) |
|
|
| |
| 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 |
| |
| 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_type = entry.get('task', 'camera_view_prediction') |
| |
| 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'] |
| |
| |
| |
| history_messages = [{"role": "system", "content": prompts["system"]}] |
| |
| 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 |
| |
| |
| for i, step in enumerate(chain): |
| |
| next_key = step['result_image_key'] |
| step_action = step['action'] |
| |
| |
| |
| current_turn_messages = copy.deepcopy(history_messages) |
| |
| if i > 0: |
| |
| prev_key = chain[i-1]['result_image_key'] |
| |
| |
| step_instruction_text = f"Here is the result of the previous step: <image_start>[{prev_key}]<image_end>. Proceed to the next step." |
| |
| step_content = self._get_content(step_instruction_text, img_map) |
| |
| current_turn_messages.append({"role": "user", "content": step_content}) |
|
|
| |
| |
| match_status_hint_text = "" |
| |
| if task_type == "camera_view_ordering": |
| is_current_view_match = False |
| matched_label = None |
| |
| |
| 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 |
| |
| matched_label = prev_step['matched_display_label'] |
| |
| |
| 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." |
|
|
| |
| step_format_kwargs = { |
| |
| "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), |
| |
| |
| "match_status_hint": match_status_hint_text, |
| |
| |
| "next_image_key": img_map.get(next_key, next_key) |
| } |
| |
| |
| 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)}) |
| |
| |
| 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) |
| |
| |
| |
| 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) |
|
|
| |
| current_turn_messages = copy.deepcopy(history_messages) |
| final_key = chain[-1]['result_image_key'] |
| |
| final_format_kwargs = { |
| |
| "correct_label": meta.get('correct_label', ""), |
| |
| "total_degrees": meta.get('angle_degrees', 0), |
| "final_img_abs_path": img_map.get(final_key, ""), |
| "direction": meta.get("direction"), |
| |
| "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 |
| |