zzhowe1207's picture
Upload rl_code/examples/reward_function/ocr_vqa.py with huggingface_hub
4f0b533 verified
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
# 匹配各种boxed格式的正则表达式,按优先级排序
patterns = [
r'\\\\boxed\{([^}]*)\}', # \\boxed{answer} (两个反斜杠)
r'\\boxed\{([^}]*)\}', # \boxed{answer} (一个反斜杠)
r'\\\\box\{([^}]*)\}', # \\box{answer} (两个反斜杠)
r'\\box\{([^}]*)\}', # \box{answer} (一个反斜杠)
r'boxed\{([^}]*)\}', # boxed{answer} (无反斜杠)
r'box\{([^}]*)\}', # box{answer} (无反斜杠)
]
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答案
boxed_answer = extract_boxed_answer(response)
if boxed_answer:
return boxed_answer
# 如果没有boxed格式,尝试其他提取策略
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
# 尝试从boxed格式中提取答案
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 # 有boxed格式但答案为空
else:
return 0.0 # 没有boxed格式
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 reward
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