hf-agents-final / answer_format.py
Takeshi7172's picture
Upload 7 files
248020f verified
Raw History Blame Contribute Delete
1.89 kB
"""Answer normaliser for GAIA exact-match scoring (stdlib only)."""
import re
from typing import Callable, Optional
_WRAPPER = re.compile(r"^\s*(?:final\s+answer|answer)\s*:\s*", re.IGNORECASE)
_ABBREV = re.compile(r"(?:[A-Z]\.){2,}$")
_UNIT_HINT = re.compile(r"\b(unit|units|symbol|percent sign|with the)\b", re.IGNORECASE)
_NUMBER = re.compile(r"^\$?\s*(-?\d[\d,]*(?:\.\d+)?|-?\.\d+)\s*%?\s*(?:[A-Za-z]+)?$")
_THOUSANDS = re.compile(r"^-?\d{1,3}(?:,\d{3})+(?:\.\d+)?$")
_QUOTES = ('"', "'", "“", "”")
def strip_wrapper(text: str, question: str) -> str:
return _WRAPPER.sub("", text.strip(), count=1).strip()
def strip_quotes(text: str, question: str) -> str:
if len(text) >= 2 and text[0] in _QUOTES and text[-1] in _QUOTES:
return text[1:-1].strip()
return text
def strip_trailing_period(text: str, question: str) -> str:
if text.endswith(".") and not _ABBREV.search(text):
return text[:-1].rstrip()
return text
def number_rule(text: str, question: str) -> str:
if _UNIT_HINT.search(question) or "comma" in question.lower():
return text
match = _NUMBER.match(text)
if not match:
return text
digits = match.group(1)
if "," in digits:
if not _THOUSANDS.match(digits):
return text
digits = digits.replace(",", "")
return digits
def list_spacing(text: str, question: str) -> str:
if "comma" not in question.lower():
return text
return re.sub(r"\s*,\s*", ", ", text)
RULES: "tuple[Callable[[str, str], str], ...]" = (
strip_wrapper,
strip_quotes,
strip_trailing_period,
number_rule,
list_spacing,
)
def normalize_answer(raw: Optional[str], question: str) -> str:
if raw is None or not str(raw).strip():
return ""
text = str(raw)
for rule in RULES:
text = rule(text, question or "")
return text.strip()