File size: 9,742 Bytes
176ecd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
"""Rule-based scoring for Misraj/MathVista_Test_Split (MathVista testmini) - v2.

extract_answer(response, ex) -> str   pulls the final answer out of a model response
is_correct(pred, ex) -> bool          compares it with ex["answer"] following MathVista's
                                      normalisation (letters for multiple choice, int / float
                                      rounded to `precision` / list / normalised text).
MathVista's official pipeline extracts answers with an LLM; this is a close, free,
deterministic approximation, so numbers can differ slightly from published ones.

v2 fixes (v1 under-counted correct answers):
- \\boxed{X} is read as the answer (v1 left "{X}", which the letter pattern could not match,
  so it fell back to the whole response and picked the last "(D)" from the restated options).
- Multiple choice: an answer given as the option value ("\\boxed{2}", "130°") is mapped to its
  letter before any whole-text letter search; the whole-text fallback no longer picks up the
  option list the model copied from the prompt.
- Full-width / CJK punctuation ("选 C。", "答案:B"), Chinese answer markers, unicode minus
  ("−7"), \\( \\) wrappers, and "answer" only as a whole word.
"""
import ast
import re

NUM_RE = r"-?\d[\d,]*(?:\.\d+)?(?:[eE]-?\d+)?|-?\.\d+"
_WORDS = {w: str(i) for i, w in enumerate("zero one two three four five six seven eight nine ten eleven "
                                          "twelve thirteen fourteen fifteen sixteen seventeen eighteen "
                                          "nineteen twenty".split())}
_WORD_RE = r"\b(" + "|".join(_WORDS) + r")\b"


def _nums(s):
    """Numbers in s; spelled-out 0-20 count only when s has no digits."""
    found = re.findall(NUM_RE, s)
    if not found:
        found = [_WORDS[w.lower()] for w in re.findall(_WORD_RE, s, re.I)]
    return found

_FW = str.maketrans({":": ":", "。": ".", ",": ",", "(": "(", ")": ")", "−": "-", "–": "-",
                     "-": "-", "A": "A", "B": "B", "C": "C", "D": "D", "E": "E", "F": "F"})
MARKER_RE = (r"(?:final\s+answer|correct\s+(?:answer|option|choice)|\banswer\b|"
             r"最终答案|正确答案|答案|故选|应选|选择|选(?!项))\s*(?:is|should\s+be|would\s+be|:|是|为|应为)?\s*:?\s*")


def _boxed(t):
    """Contents of every \\boxed{...} (brace-balanced), in order."""
    out, i = [], 0
    while True:
        i = t.find("\\boxed", i)
        if i < 0:
            return out
        j = t.find("{", i)
        if j < 0:
            return out
        depth, k = 0, j
        while k < len(t):
            depth += {"{": 1, "}": -1}.get(t[k], 0)
            if depth == 0:
                break
            k += 1
        out.append(t[j + 1:k])
        i = k


def _strip_latex(s):
    s = re.sub(r"\\text\{([^{}]*)\}", r"\1", s)
    s = re.sub(r"\\(?:mathrm|textbf|mathbf)\{([^{}]*)\}", r"\1", s)
    s = re.sub(r"\\[\(\)\[\]]", " ", s)
    s = s.replace("^\\circ", "°").replace("^{\\circ}", "°").replace("\\circ", "°")
    s = s.replace("\\%", "%").replace("\\,", "").replace("\\!", "")
    return s.replace("**", "").replace("$", "").translate(_FW).strip()


def _clean(t):
    t = re.sub(r"<think>.*?</think>", "", str(t or ""), flags=re.S)
    t = re.sub(r"^.*?</think>", "", t, flags=re.S)   # an unclosed think block
    return t


def _norm_text(s, unit=""):
    s = _strip_latex(str(s)).lower()
    if unit:
        s = s.replace(str(unit).lower(), "")
    return re.sub(r"[\s\.\,\;\:\!\"'\(\)\[\]\{\}]+", " ", s).strip()


def _final_segment(t, with_flag=False):
    """Text after the last answer marker, else the last non-empty line.
    with_flag=True also returns whether a marker was found."""
    m = list(re.finditer(MARKER_RE, t, re.I))
    if m:
        seg = t[m[-1].end():].strip()
        if re.search(r"[A-Za-z0-9\u4e00-\u9fff]", seg):
            first = next((l for l in seg.splitlines() if l.strip()), seg)
            return (first.strip(), True) if with_flag else first.strip()
    lines = [l for l in t.splitlines() if l.strip()]
    seg = lines[-1] if lines else t
    return (seg, False) if with_flag else seg


def _letters(ex):
    return [chr(65 + i) for i in range(len(ex.get("choices") or []))]


def _letter_in(s, letters, first=True):
    """A choice letter written as one: (B), B), B., **B**, 'B' alone, 'option B'."""
    pats = (r"\(([A-Z])\)", r"(?:option|choice|选项|选)\s*\(?([A-Z])\b",
            r"(?<![A-Za-z0-9])([A-Z])(?![A-Za-z0-9])")
    for pat in pats:
        found = [c for c in re.findall(pat, s) if c in letters]
        if found:
            return found[0] if first else found[-1]
    return ""


def _match_choice_text(s, letters, choices):
    """Letter of the option whose text is s (exact after normalising), else ''."""
    ns = _norm_text(s)
    for l, c in zip(letters, choices):
        if ns and ns == _norm_text(c):
            return l
    return ""


def _mc(t, ex):
    letters, choices = _letters(ex), ex.get("choices") or []
    # 1. last \boxed{...}
    box = _boxed(t)
    if box:
        b = _strip_latex(box[-1])
        if b.strip().strip("()") in letters:
            return b.strip().strip("()")
        l = _match_choice_text(b, letters, choices) or _letter_in(b, letters)
        if l:
            return l
    t = _strip_latex(t)
    # 2. after the last answer marker (or the last line)
    seg, marked = _final_segment(t, with_flag=True)
    bare = re.fullmatch(r"\(?([A-Z])\)?[.:]?", seg.strip(" *"))
    if bare and bare.group(1) in letters:
        return bare.group(1)
    l = _match_choice_text(seg.strip(" .*"), letters, choices) or _letter_in(seg, letters)
    if l:
        return l
    # option text inside the final segment (longest option that appears)
    low = seg.lower()
    hits = sorted(((len(str(c)), l) for l, c in zip(letters, choices)
                   if str(c).strip() and str(c).strip().lower() in low), reverse=True)
    if hits:
        return hits[0][1]
    # 3. explicit statements anywhere ("the answer is C", "选 C"), last one wins
    found = [m.group(1) for m in re.finditer(MARKER_RE + r"\(?([A-Z])(?![A-Za-z0-9])", t, re.I)
             if m.group(1) in letters]
    if found:
        return found[-1]
    # 4. last mention of an option's text, then last standalone letter
    best, pos = "", -1
    low = t.lower()
    for l, c in zip(letters, choices):
        p = low.rfind(str(c).strip().lower())
        if len(str(c).strip()) > 2 and p > pos:
            best, pos = l, p
    return best or _letter_in(t, letters, first=False)


def extract_answer(response, ex):
    t = _clean(response)
    if not t.strip():
        return ""
    qt, at = ex.get("question_type"), ex.get("answer_type")

    if qt == "multi_choice":
        return _mc(t, ex)

    box = _boxed(t)
    if at == "list":
        src = _strip_latex(box[-1]) if box else _strip_latex(t)
        m = re.findall(r"\[[^\[\]]*\]", src)
        return m[-1] if m else ""

    if at in ("integer", "float"):
        if box:
            nums = re.findall(NUM_RE, _strip_latex(box[-1]))
            if nums:
                return nums[-1].replace(",", "")
        t = _strip_latex(t)
        lines = [l for l in t.splitlines() if l.strip()]
        m = list(re.finditer(MARKER_RE, t, re.I))
        after = t[m[-1].end():].strip() if m else ""
        first = next((l for l in after.splitlines() if l.strip()), "")
        # after a marker: its first line, then the rest of it -> first number;
        # no marker (or nothing numeric after it): the last line -> last number
        for seg, use_first in ((first, True), (after, True), (lines[-1] if lines else "", False)):
            if "=" in seg:                   # "78 - 59 = 19" -> the result after the last "="
                seg = seg.rsplit("=", 1)[1]
            nums = re.findall(NUM_RE, seg)
            if nums:
                return (nums[0] if use_first else nums[-1]).replace(",", "")
        all_nums = _nums(t) if not re.search(r"\d", t) else re.findall(NUM_RE, t)
        if not all_nums and lines:
            all_nums = _nums(lines[-1])
        word = _nums(lines[-1]) if lines else []
        if word and not re.search(r"\d", lines[-1]):
            return word[0]                   # "Only one year satisfies the condition."
        return all_nums[-1].replace(",", "") if all_nums else ""

    if box:
        return _strip_latex(box[-1])
    return _final_segment(_strip_latex(t)).strip().strip(".")


def _to_float(x):
    return float(str(x).replace(",", "").replace("%", "").strip())


def is_correct(pred, ex):
    if pred is None or str(pred).strip() == "":
        return False
    gold, at = ex["answer"], ex.get("answer_type")
    try:
        if ex.get("question_type") == "multi_choice":
            if ex.get("answer_is_letter"):
                return str(pred).strip().upper() == str(gold).strip().upper()
            letters, choices = _letters(ex), ex.get("choices") or []
            text = choices[letters.index(pred)] if pred in letters else pred
            return _norm_text(text) == _norm_text(ex.get("answer_raw", gold))
        if at == "integer":
            return int(round(_to_float(pred))) == int(round(_to_float(gold)))
        if at == "float":
            prec = int(ex.get("precision") or 2)
            return round(_to_float(pred), prec) == round(_to_float(gold), prec)
        if at == "list":
            p, g = ast.literal_eval(str(pred)), ast.literal_eval(str(gold))
            return len(p) == len(g) and all(abs(_to_float(a) - _to_float(b)) < 1e-6 for a, b in zip(p, g))
    except Exception:
        return False
    unit = ex.get("unit") or ""
    return _norm_text(pred, unit) == _norm_text(gold, unit)