Universal answer extractor using math-verify with fallback patterns
| 13 | logger = logging.getLogger(__name__) |
| 14 | |
| 15 | class AnswerExtractor: |
| 16 | """Universal answer extractor using math-verify with fallback patterns""" |
| 17 | |
| 18 | def __init__(self): |
| 19 | self.math_verify_timeout = 5 # seconds |
| 20 | |
| 21 | def extract_answer(self, solution: str, problem_type: str = "general", problem_id: Optional[int] = None) -> Optional[Any]: |
| 22 | """ |
| 23 | Universal answer extraction using math-verify library with fallback patterns. |
| 24 | |
| 25 | Args: |
| 26 | solution: The solution text to extract answer from |
| 27 | problem_type: Type of problem (general, imo, aime, etc.) |
| 28 | problem_id: Specific problem ID for customized extraction |
| 29 | |
| 30 | Returns: |
| 31 | Extracted answer in appropriate format (int, str, list, etc.) |
| 32 | """ |
| 33 | if not solution: |
| 34 | return None |
| 35 | |
| 36 | logger.debug(f"Extracting answer from solution (type: {problem_type}, id: {problem_id})") |
| 37 | |
| 38 | # First try math-verify for robust mathematical parsing |
| 39 | math_verify_result = self._try_math_verify(solution) |
| 40 | if math_verify_result is not None: |
| 41 | logger.debug(f"Math-verify extracted: {math_verify_result}") |
| 42 | return math_verify_result |
| 43 | |
| 44 | # Problem-specific extraction for known problem formats |
| 45 | if problem_type == "imo" and problem_id: |
| 46 | specific_result = self._extract_imo_specific(solution, problem_id) |
| 47 | if specific_result is not None: |
| 48 | logger.debug(f"IMO-specific extracted: {specific_result}") |
| 49 | return specific_result |
| 50 | |
| 51 | # AIME-style numeric extraction |
| 52 | if problem_type == "aime": |
| 53 | aime_result = self._extract_aime_answer(solution) |
| 54 | if aime_result is not None: |
| 55 | logger.debug(f"AIME-style extracted: {aime_result}") |
| 56 | return aime_result |
| 57 | |
| 58 | # General fallback patterns |
| 59 | general_result = self._extract_general_answer(solution) |
| 60 | if general_result is not None: |
| 61 | logger.debug(f"General pattern extracted: {general_result}") |
| 62 | return general_result |
| 63 | |
| 64 | logger.debug("No answer extracted") |
| 65 | return None |
| 66 | |
| 67 | def _try_math_verify(self, solution: str) -> Optional[Any]: |
| 68 | """Try to extract answer using math-verify library""" |
| 69 | try: |
| 70 | parsed_result = math_verify.parse(solution, parsing_timeout=self.math_verify_timeout) |
| 71 | if parsed_result: |
| 72 | # math-verify returns various formats, we need to normalize |