File size: 1,891 Bytes
248020f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | """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()
|