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96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"""Conservative final-answer extraction and scoring for the MATH-500 pilot.



Scoring is deliberately three-way at its core: a confidently parsed answer can

be marked correct or incorrect; answers that cannot be interpreted reliably

remain unparsed. Completion extraction can additionally abstain when the output

contains a malformed or explicitly ambiguous final answer.



``math_verify`` is used when installed, but runs in a child process so a hard

wall-clock limit applies even on platforms where its own signal-based timeout

is unavailable. Without it, the fallback only compares identical normalized

answers or exact numeric scalars/fractions.

"""

from __future__ import annotations

import importlib.util
import json
import re
import subprocess
import sys
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from fractions import Fraction
from typing import Literal


ExtractionStatus = Literal["parsed", "abstained", "unparsed"]
ScoreStatus = Literal["correct", "incorrect", "abstained", "unparsed"]


@dataclass(frozen=True)
class ExtractionResult:
    status: ExtractionStatus
    answer: str | None = None
    reason: str = ""


@dataclass(frozen=True)
class ScoreResult:
    status: ScoreStatus
    predicted_answer: str | None
    expected_answer: str
    method: str
    reason: str = ""


_BOX_OPEN = re.compile(r"\\(?:boxed|fbox)\s*\{")
_FINAL_MARKER = re.compile(
    r"(?:\bfinal\s+answer\b|\banswer\b)\s*(?:is\s*)?(?:[:=]\s*)?",
    re.IGNORECASE,
)
_REASONING_AFTER_ANSWER = re.compile(
    r"\b(?:because|since|therefore|thus|so|which\s+means|this\s+gives)\b",
    re.IGNORECASE,
)
_MATH_VERIFY_WORKER = r'''

import json, sys



predicted, expected = json.load(sys.stdin)

try:

    from math_verify import ExprExtractionConfig, LatexExtractionConfig, parse, verify

except ImportError:

    print(json.dumps({"kind": "unavailable"}))

    raise SystemExit(0)



try:

    extraction = [LatexExtractionConfig(), ExprExtractionConfig()]

    parse_options = {

        "extraction_config": extraction,

        "fallback_mode": "no_fallback",

        "extraction_mode": "first_match",

        "parsing_timeout": 0,

        "raise_on_error": True,

    }

    parsed_expected = parse(expected, **parse_options)

    parsed_predicted = parse(predicted, **parse_options)

    if not parsed_expected or not parsed_predicted:

        print(json.dumps({"kind": "unparsed"}))

    else:

        matches = verify(

            parsed_expected,

            parsed_predicted,

            timeout_seconds=0,

            raise_on_error=True,

        )

        print(json.dumps({"kind": "verified", "matches": bool(matches)}))

except BaseException as exc:

    print(json.dumps({"kind": "error", "error": type(exc).__name__}))

'''


def _read_braced(text: str, open_brace: int) -> tuple[str | None, int]:
    """Read a balanced brace expression; return its contents and end offset."""
    depth = 0
    escaped = False
    for position in range(open_brace, len(text)):
        char = text[position]
        if escaped:
            escaped = False
            continue
        if char == "\\":
            escaped = True
            continue
        if char == "{":
            depth += 1
        elif char == "}":
            depth -= 1
            if depth == 0:
                return text[open_brace + 1 : position], position + 1
    return None, len(text)


def _boxed_answers(text: str) -> tuple[list[tuple[str, int, int]], bool]:
    found: list[tuple[str, int, int]] = []
    malformed = False
    for match in _BOX_OPEN.finditer(text):
        open_brace = match.end() - 1
        answer, end = _read_braced(text, open_brace)
        if answer is None:
            malformed = True
            continue
        found.append((answer.strip(), match.start(), end))
    return found, malformed


def _clean_final_candidate(candidate: str) -> str:
    candidate = candidate.strip()
    candidate = re.sub(r"^\*{1,2}|\*{1,2}$", "", candidate).strip()
    # A single terminal sentence mark is prose punctuation, not part of a value.
    candidate = re.sub(r"[.!?]+\s*$", "", candidate).strip()
    return candidate


def _answer_from_marker(text: str) -> tuple[str | None, int | None, bool]:
    """Get the tail after the last explicit answer label, if it is self-contained."""
    matches = list(_FINAL_MARKER.finditer(text))
    if not matches:
        return None, None, False
    marker = matches[-1]
    candidate = _clean_final_candidate(text[marker.end() :])
    if not candidate:
        return None, marker.start(), True
    if "\n" in candidate or _REASONING_AFTER_ANSWER.search(candidate):
        return None, marker.start(), True
    # Avoid treating a sentence that continues after the answer as a clean value.
    if len(candidate.split()) > 12:
        return None, marker.start(), True
    return candidate, marker.start(), False


def extract_final_answer(completion: str) -> ExtractionResult:
    """Extract an explicitly marked final answer without guessing from reasoning.



    Accepted forms are a final ``\\boxed{...}``/``\\fbox{...}``, a terminal

    ``answer: ...`` or ``final answer is ...`` label, or a terminal ``#### ...``

    line. A bare number or expression without one of these markers is unparsed.

    """
    if not isinstance(completion, str) or not completion.strip():
        return ExtractionResult("unparsed", reason="empty or non-text completion")

    boxes, malformed_box = _boxed_answers(completion)
    boxed: tuple[str, int, int] | None = boxes[-1] if boxes else None
    marker_answer, marker_position, malformed_marker = _answer_from_marker(completion)

    if malformed_box and (boxed is None or completion.rfind(r"\boxed") > boxed[1]):
        return ExtractionResult("abstained", reason="final boxed answer is incomplete")
    if malformed_marker and (marker_position is not None) and (
        boxed is None or marker_position >= boxed[1]
    ):
        return ExtractionResult("abstained", reason="answer label is ambiguous or followed by explanation")

    # A later explicit answer label takes precedence over an earlier boxed value.
    if marker_answer is not None and (boxed is None or marker_position >= boxed[1]):
        if re.search(r"\b(?:or|either)\b", marker_answer, re.IGNORECASE):
            return ExtractionResult("abstained", reason="final answer presents alternatives")
        return ExtractionResult("parsed", marker_answer, "terminal answer label")

    if boxed is not None:
        answer, _, end = boxed
        if not answer:
            return ExtractionResult("abstained", reason="final boxed answer is empty")
        # In a construction such as ``\\boxed{1} or \\boxed{2}``, selecting one
        # answer would be arbitrary. Earlier boxed work by itself is not ambiguous.
        if len(boxes) > 1 and re.search(
            r"\b(?:or|either)\b", completion[boxes[-2][2] : boxes[-1][1]], re.IGNORECASE
        ):
            return ExtractionResult("abstained", reason="final answer presents alternatives")
        if re.search(r"\b(?:or|either)\b", completion[end : end + 80], re.IGNORECASE):
            return ExtractionResult("abstained", reason="boxed answer is followed by an alternative")
        return ExtractionResult("parsed", answer, "last complete boxed answer")

    # Support the common GSM-style final answer marker for generated pilot text.
    final_lines = re.findall(r"(?m)^\s*####\s*(.*?)\s*$", completion)
    if final_lines:
        answer = _clean_final_candidate(final_lines[-1])
        if answer and not re.search(r"\b(?:or|either)\b", answer, re.IGNORECASE):
            return ExtractionResult("parsed", answer, "terminal #### answer line")
        return ExtractionResult("abstained", reason="final answer line is empty or ambiguous")

    return ExtractionResult("unparsed", reason="no explicit final-answer marker found")


def _unwrap_math_delimiters(value: str) -> str:
    value = value.strip().replace("−", "-").replace("+", "+").replace("×", "*").replace("÷", "/")
    value = value.replace(r"\left", "").replace(r"\right", "")
    pairs = (("$", "$"), (r"\(", r"\)"), (r"\[", r"\]"))
    changed = True
    while changed:
        changed = False
        for left, right in pairs:
            if value.startswith(left) and value.endswith(right) and len(value) >= len(left) + len(right):
                value = value[len(left) : len(value) - len(right)].strip()
                changed = True
    return value


_NUMBER = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)"
_PLAIN_FRACTION = re.compile(rf"^\s*({_NUMBER})\s*/\s*({_NUMBER})\s*$")
_LATEX_FRACTION = re.compile(rf"^\\(?:dfrac|tfrac|frac)\s*\{{\s*({_NUMBER})\s*\}}\s*\{{\s*({_NUMBER})\s*\}}$")
_SIMPLE_NUMBER = re.compile(rf"^\s*({_NUMBER})\s*$")


def _fraction_from_decimal(text: str) -> Fraction:
    if len(text) > 256:
        raise ValueError("numeric answer is too long")
    return Fraction(Decimal(text))


def _numeric_value(value: str) -> Fraction | None:
    value = _unwrap_math_delimiters(value)
    if len(value) > 512:
        return None
    match = _LATEX_FRACTION.fullmatch(value)
    if match:
        try:
            return _fraction_from_decimal(match.group(1)) / _fraction_from_decimal(match.group(2))
        except (InvalidOperation, ValueError, ZeroDivisionError):
            return None
    match = _PLAIN_FRACTION.fullmatch(value)
    if match:
        try:
            return _fraction_from_decimal(match.group(1)) / _fraction_from_decimal(match.group(2))
        except (InvalidOperation, ValueError, ZeroDivisionError):
            return None
    match = _SIMPLE_NUMBER.fullmatch(value)
    if match:
        try:
            return _fraction_from_decimal(match.group(1))
        except (InvalidOperation, ValueError, ZeroDivisionError):
            return None
    return None


def _canonical_literal(value: str) -> str:
    value = _unwrap_math_delimiters(value)
    value = re.sub(r"\s+", "", value)
    return value


def _fallback_score(predicted: str, expected: str) -> tuple[ScoreStatus, str, str]:
    predicted_number = _numeric_value(predicted)
    expected_number = _numeric_value(expected)
    if predicted_number is not None and expected_number is not None:
        if predicted_number == expected_number:
            return "correct", "exact_numeric", "exact numeric values match"
        return "incorrect", "exact_numeric", "exact numeric values differ"

    if _canonical_literal(predicted) and _canonical_literal(predicted) == _canonical_literal(expected):
        return "correct", "exact_literal", "normalized answer text matches exactly"

    return "unparsed", "none", "unsupported answer form without math_verify"


def _math_verify_available() -> bool:
    try:
        return importlib.util.find_spec("math_verify") is not None
    except (ImportError, ValueError):
        return False


def _run_math_verify(predicted: str, expected: str, timeout_seconds: float) -> tuple[str, str] | None:
    if not _math_verify_available():
        return None
    try:
        process = subprocess.Popen(
            [sys.executable, "-c", _MATH_VERIFY_WORKER],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            text=True,
        )
        try:
            stdout, _ = process.communicate(
                input=json.dumps([predicted, expected]), timeout=timeout_seconds
            )
        except subprocess.TimeoutExpired:
            process.kill()
            process.communicate()
            return "timeout", "math_verify exceeded the scoring timeout"
        if process.returncode != 0 or not stdout.strip():
            return "error", "math_verify subprocess failed"
        payload = json.loads(stdout.strip().splitlines()[-1])
    except (OSError, ValueError, json.JSONDecodeError):
        return "error", "math_verify subprocess could not be read"

    kind = payload.get("kind")
    if kind == "unavailable":
        return None
    if kind == "verified":
        return ("correct" if payload.get("matches") else "incorrect"), "math_verify equivalence check"
    if kind == "unparsed":
        return "unparsed", "math_verify could not parse one or both answers"
    if kind == "error":
        return "error", f"math_verify raised {payload.get('error', 'an error')}"
    return "error", "math_verify returned an unexpected result"


def score_extracted_answer(

    predicted_answer: str,

    expected_answer: str,

    *,

    timeout_seconds: float = 3.0,

) -> ScoreResult:
    """Score two answer strings, abstaining whenever the comparison is unclear."""
    if not isinstance(predicted_answer, str) or not predicted_answer.strip():
        return ScoreResult("unparsed", None, str(expected_answer), "none", "prediction is empty or non-text")
    if not isinstance(expected_answer, str) or not expected_answer.strip():
        return ScoreResult("unparsed", predicted_answer, str(expected_answer), "none", "reference answer is empty or non-text")
    if timeout_seconds <= 0:
        raise ValueError("timeout_seconds must be positive")

    verified = _run_math_verify(predicted_answer, expected_answer, timeout_seconds)
    if verified is not None:
        status, reason = verified
        if status == "correct":
            return ScoreResult("correct", predicted_answer, expected_answer, "math_verify", reason)
        if status == "incorrect":
            return ScoreResult("incorrect", predicted_answer, expected_answer, "math_verify", reason)
        if status == "timeout":
            return ScoreResult("unparsed", predicted_answer, expected_answer, "math_verify", reason)

    status, method, reason = _fallback_score(predicted_answer, expected_answer)
    if verified is not None and reason == "unsupported answer form without math_verify":
        reason = f"{verified[1]}; {reason}"
    return ScoreResult(status, predicted_answer, expected_answer, method, reason)


def score_completion(

    completion: str,

    expected_answer: str,

    *,

    timeout_seconds: float = 3.0,

) -> ScoreResult:
    """Extract and score a generated completion against its reference answer."""
    extracted = extract_final_answer(completion)
    if extracted.status == "unparsed":
        return ScoreResult("unparsed", None, str(expected_answer), "none", extracted.reason)
    if extracted.status == "abstained":
        return ScoreResult("abstained", None, str(expected_answer), "none", extracted.reason)
    result = score_extracted_answer(
        extracted.answer or "", expected_answer, timeout_seconds=timeout_seconds
    )
    return ScoreResult(
        result.status,
        result.predicted_answer,
        result.expected_answer,
        result.method,
        result.reason,
    )


def score_answer(

    text: str,

    reference: str,

    *,

    timeout_seconds: float = 3.0,

) -> dict[str, object]:
    """Return a JSON-serializable scoring record for a generated completion.



    ``correct`` is ``True`` for a verified match, ``False`` for a confidently

    verified mismatch, and ``None`` when extraction or comparison is uncertain.

    """
    result = score_completion(text, reference, timeout_seconds=timeout_seconds)
    correct: bool | None
    if result.status == "correct":
        correct = True
    elif result.status == "incorrect":
        correct = False
    else:
        correct = None
    return {
        "correct": correct,
        "status": result.status,
        "answer": result.predicted_answer,
        "reference": result.expected_answer,
        "method": result.method,
        "reason": result.reason,
    }


__all__ = [
    "ExtractionResult",
    "ScoreResult",
    "extract_final_answer",
    "score_answer",
    "score_completion",
    "score_extracted_answer",
]