from __future__ import annotations import re FINAL_LINE_RE = re.compile(r"(?mi)^\s*FINAL:\s*(.+?)\s*$") FINAL_MARKER_RE = re.compile(r"(?i)FINAL:\s*([^\n<]+)") FINAL_ANSWER_LINE_RE = re.compile( r"(?mi)^\s*(?:\**\s*)?(?:final answer|the final answer|answer)\s*(?:is|=|:)\s*([^\n]+)$" ) BOXED_RE = re.compile(r"\\boxed\{([^{}]+)\}", flags=re.IGNORECASE) NUMERIC_RE = re.compile(r"-?\d+(?:\.\d+)?") def normalize(text: str) -> str: text = text.strip() text = re.sub(r"\s+", " ", text) return text.casefold() def clean_answer_text(text: str) -> str: text = re.sub(r"", " ", text, flags=re.IGNORECASE) text = re.sub(r"\\boxed\{([^{}]*)\}", r"\1", text) text = text.replace("$", " ") text = re.sub(r"[*`_#]+", " ", text) text = re.sub(r"^\**\s*final answer\s*(?:is|:)?\s*", "", text, flags=re.IGNORECASE) text = re.sub(r"^\**\s*the final answer\s*(?:is|:)?\s*", "", text, flags=re.IGNORECASE) text = re.sub(r"^\**\s*final\s*:\s*", "", text, flags=re.IGNORECASE) text = re.sub(r"^\**\s*answer\s*(?:is|:)?\s*", "", text, flags=re.IGNORECASE) text = re.sub(r"\s+", " ", text) return text.strip(" .:,;!?)(") def extract_final_answer(text: str) -> str: for regex in [FINAL_LINE_RE, FINAL_MARKER_RE, BOXED_RE, FINAL_ANSWER_LINE_RE]: matches = regex.findall(text) for match in reversed(matches): cleaned = clean_answer_text(match) if cleaned: return cleaned lines = [line.strip() for line in text.strip().splitlines() if line.strip()] for line in reversed(lines): cleaned = clean_answer_text(line.removeprefix("FINAL:").strip()) if cleaned: return cleaned return clean_answer_text(text) def has_final_marker(text: str) -> bool: return ( FINAL_LINE_RE.search(text) is not None or FINAL_MARKER_RE.search(text) is not None or FINAL_ANSWER_LINE_RE.search(text) is not None ) def normalize_numeric_string(text: str) -> str: value = text.strip() negative = value.startswith("-") if negative: value = value[1:] if "." in value: whole, fractional = value.split(".", 1) whole = whole.lstrip("0") or "0" fractional = fractional.rstrip("0") if not fractional: normalized = whole else: normalized = f"{whole}.{fractional}" else: normalized = value.lstrip("0") or "0" if normalized == "0": negative = False if negative: return f"-{normalized}" return normalized def answers_match(predicted: str, gold: str) -> bool: if normalize(predicted) == normalize(gold): return True gold_is_number = NUMERIC_RE.fullmatch(gold.strip()) is not None if gold_is_number: normalized_gold = normalize_numeric_string(gold) predicted_numbers = NUMERIC_RE.findall(predicted) if predicted_numbers and normalize_numeric_string(predicted_numbers[-1]) == normalized_gold: return True return False