| import re |
| from typing import Any, Dict, List, Optional |
| from collections import Counter |
|
|
|
|
| def extract_boxed_answer(text: str) -> Optional[str]: |
| """ |
| 从文本中提取\boxed{}或\\boxed{}中的答案 |
| 支持多种boxed格式:\boxed{answer}, \\boxed{answer}, \box{answer} |
| """ |
| if not text: |
| return None |
| |
| |
| patterns = [ |
| r'\\\\boxed\{([^}]*)\}', |
| r'\\boxed\{([^}]*)\}', |
| r'\\\\box\{([^}]*)\}', |
| r'\\box\{([^}]*)\}', |
| r'boxed\{([^}]*)\}', |
| r'box\{([^}]*)\}', |
| ] |
| |
| for pattern in patterns: |
| matches = re.findall(pattern, text, re.IGNORECASE) |
| if matches: |
| |
| return matches[-1].strip() |
| |
| return None |
|
|
|
|
| def extract_answer_from_response(response: str) -> str: |
| """ |
| 从响应中提取答案,优先提取boxed答案,如果没有则使用整个响应 |
| """ |
| if not response: |
| return "" |
| |
| |
| boxed_answer = extract_boxed_answer(response) |
| if boxed_answer: |
| return boxed_answer |
| |
| |
| response = response.strip() |
| |
| |
| answer_patterns = [ |
| r'(?:answer|final answer|result|solution)[\s\:]*(.+?)(?:\n|$)', |
| r'(?:the answer is)[\s\:]*(.+?)(?:\n|$)', |
| r'(?:therefore|thus|so)[\s\,]*(.+?)(?:\n|$)', |
| ] |
| |
| for pattern in answer_patterns: |
| matches = re.findall(pattern, response, re.IGNORECASE | re.MULTILINE) |
| if matches: |
| return matches[-1].strip() |
| |
| |
| lines = response.split('\n') |
| non_empty_lines = [line.strip() for line in lines if line.strip()] |
| |
| if non_empty_lines: |
| return non_empty_lines[-1] |
| |
| return response |
|
|
|
|
| def normalize_text(text: str) -> str: |
| """标准化文本用于比较,移除多余空格、标点符号并转换为小写""" |
| if not text: |
| return "" |
| |
| |
| text = text.lower().strip() |
| |
| |
| text = re.sub(r'\s+', ' ', text) |
| |
| return text.strip() |
|
|
| def token_f1_reward(norm_response: str, norm_ground_truth: str) -> float: |
| """基于词袋重叠的 token 级 F1。输入应为已规范化文本。""" |
| if not norm_response and not norm_ground_truth: |
| return 1.0 |
| if not norm_response or not norm_ground_truth: |
| return 0.0 |
|
|
| response_tokens = norm_response.split() |
| ground_truth_tokens = norm_ground_truth.split() |
|
|
| if not response_tokens or not ground_truth_tokens: |
| return 0.0 |
|
|
| response_counts = Counter(response_tokens) |
| ground_truth_counts = Counter(ground_truth_tokens) |
| common_token_count = sum((response_counts & ground_truth_counts).values()) |
|
|
| if common_token_count == 0: |
| return 0.0 |
|
|
| precision = common_token_count / sum(response_counts.values()) |
| recall = common_token_count / sum(ground_truth_counts.values()) |
|
|
| if precision + recall == 0: |
| return 0.0 |
|
|
| return 2 * precision * recall / (precision + recall) |
|
|
|
|
| def accuracy_reward(extracted_response: str, ground_truth: str) -> tuple[float, float]: |
| """标准化后先尝试直接匹配;不相等则回退到 token 级 F1。""" |
| norm_response = normalize_text(extracted_response) |
| norm_ground_truth = normalize_text(ground_truth) |
|
|
| if norm_response == norm_ground_truth: |
| return 1.0, 1.0 |
|
|
| return token_f1_reward(norm_response, norm_ground_truth), 0.0 |
|
|
|
|
| def format_reward(response: str) -> float: |
| """检查是否能从boxed格式中提取出答案""" |
| if not response or not response.strip(): |
| return 0.0 |
| |
| |
| extracted_answer = extract_boxed_answer(response) |
| |
| if extracted_answer is not None and extracted_answer.strip(): |
| return 1.0 |
| elif extracted_answer is not None: |
| return 0.5 |
| else: |
| return 0.0 |
|
|
|
|
|
|
| def compute_score(reward_inputs: List[Dict[str, Any]], format_weight: float = 0.1) -> List[Dict[str, float]]: |
| """ |
| 计算OCR-VQA响应的奖励分数,支持boxed格式的答案提取 |
| |
| Args: |
| reward_inputs: 包含response和ground_truth的字典列表 |
| format_weight: 格式分数的权重(默认0.1)- 检查是否能从boxed中提取答案 |
| |
| Returns: |
| 包含各种分数的字典列表 |
| """ |
| if not isinstance(reward_inputs, list): |
| raise ValueError("Please use `reward_type=batch` for OCR-VQA reward function.") |
| |
| scores = [] |
| for reward_input in reward_inputs: |
| response = reward_input["response"].strip() |
| ground_truth = extract_answer_from_response(reward_input["ground_truth"].strip()) |
| |
| |
| format_score = format_reward(response) |
| |
| extracted_answer = extract_answer_from_response(response) |
| |
| accuracy_score, standard_acc = accuracy_reward(extracted_answer, ground_truth) |
|
|
| |
| overall_score = (1 - format_weight) * accuracy_score + format_weight * format_score |
| |
| scores.append({ |
| "overall": overall_score, |
| "accuracy": accuracy_score, |
| "format": format_score, |
| "standard_acc": standard_acc, |
| }) |
| |
| return scores |
|
|