muhammad0-0hreden commited on
Commit
176ecd6
·
verified ·
1 Parent(s): ebf6a9a

Add mm_scoring.py

Browse files
Files changed (1) hide show
  1. mm_scoring.py +235 -0
mm_scoring.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rule-based scoring for Misraj/MathVista_Test_Split (MathVista testmini) - v2.
2
+
3
+ extract_answer(response, ex) -> str pulls the final answer out of a model response
4
+ is_correct(pred, ex) -> bool compares it with ex["answer"] following MathVista's
5
+ normalisation (letters for multiple choice, int / float
6
+ rounded to `precision` / list / normalised text).
7
+ MathVista's official pipeline extracts answers with an LLM; this is a close, free,
8
+ deterministic approximation, so numbers can differ slightly from published ones.
9
+
10
+ v2 fixes (v1 under-counted correct answers):
11
+ - \\boxed{X} is read as the answer (v1 left "{X}", which the letter pattern could not match,
12
+ so it fell back to the whole response and picked the last "(D)" from the restated options).
13
+ - Multiple choice: an answer given as the option value ("\\boxed{2}", "130°") is mapped to its
14
+ letter before any whole-text letter search; the whole-text fallback no longer picks up the
15
+ option list the model copied from the prompt.
16
+ - Full-width / CJK punctuation ("选 C。", "答案:B"), Chinese answer markers, unicode minus
17
+ ("−7"), \\( \\) wrappers, and "answer" only as a whole word.
18
+ """
19
+ import ast
20
+ import re
21
+
22
+ NUM_RE = r"-?\d[\d,]*(?:\.\d+)?(?:[eE]-?\d+)?|-?\.\d+"
23
+ _WORDS = {w: str(i) for i, w in enumerate("zero one two three four five six seven eight nine ten eleven "
24
+ "twelve thirteen fourteen fifteen sixteen seventeen eighteen "
25
+ "nineteen twenty".split())}
26
+ _WORD_RE = r"\b(" + "|".join(_WORDS) + r")\b"
27
+
28
+
29
+ def _nums(s):
30
+ """Numbers in s; spelled-out 0-20 count only when s has no digits."""
31
+ found = re.findall(NUM_RE, s)
32
+ if not found:
33
+ found = [_WORDS[w.lower()] for w in re.findall(_WORD_RE, s, re.I)]
34
+ return found
35
+
36
+ _FW = str.maketrans({":": ":", "。": ".", ",": ",", "(": "(", ")": ")", "−": "-", "–": "-",
37
+ "-": "-", "A": "A", "B": "B", "C": "C", "D": "D", "E": "E", "F": "F"})
38
+ MARKER_RE = (r"(?:final\s+answer|correct\s+(?:answer|option|choice)|\banswer\b|"
39
+ r"最终答案|正确答案|答案|故选|应选|选择|选(?!项))\s*(?:is|should\s+be|would\s+be|:|是|为|应为)?\s*:?\s*")
40
+
41
+
42
+ def _boxed(t):
43
+ """Contents of every \\boxed{...} (brace-balanced), in order."""
44
+ out, i = [], 0
45
+ while True:
46
+ i = t.find("\\boxed", i)
47
+ if i < 0:
48
+ return out
49
+ j = t.find("{", i)
50
+ if j < 0:
51
+ return out
52
+ depth, k = 0, j
53
+ while k < len(t):
54
+ depth += {"{": 1, "}": -1}.get(t[k], 0)
55
+ if depth == 0:
56
+ break
57
+ k += 1
58
+ out.append(t[j + 1:k])
59
+ i = k
60
+
61
+
62
+ def _strip_latex(s):
63
+ s = re.sub(r"\\text\{([^{}]*)\}", r"\1", s)
64
+ s = re.sub(r"\\(?:mathrm|textbf|mathbf)\{([^{}]*)\}", r"\1", s)
65
+ s = re.sub(r"\\[\(\)\[\]]", " ", s)
66
+ s = s.replace("^\\circ", "°").replace("^{\\circ}", "°").replace("\\circ", "°")
67
+ s = s.replace("\\%", "%").replace("\\,", "").replace("\\!", "")
68
+ return s.replace("**", "").replace("$", "").translate(_FW).strip()
69
+
70
+
71
+ def _clean(t):
72
+ t = re.sub(r"<think>.*?</think>", "", str(t or ""), flags=re.S)
73
+ t = re.sub(r"^.*?</think>", "", t, flags=re.S) # an unclosed think block
74
+ return t
75
+
76
+
77
+ def _norm_text(s, unit=""):
78
+ s = _strip_latex(str(s)).lower()
79
+ if unit:
80
+ s = s.replace(str(unit).lower(), "")
81
+ return re.sub(r"[\s\.\,\;\:\!\"'\(\)\[\]\{\}]+", " ", s).strip()
82
+
83
+
84
+ def _final_segment(t, with_flag=False):
85
+ """Text after the last answer marker, else the last non-empty line.
86
+ with_flag=True also returns whether a marker was found."""
87
+ m = list(re.finditer(MARKER_RE, t, re.I))
88
+ if m:
89
+ seg = t[m[-1].end():].strip()
90
+ if re.search(r"[A-Za-z0-9\u4e00-\u9fff]", seg):
91
+ first = next((l for l in seg.splitlines() if l.strip()), seg)
92
+ return (first.strip(), True) if with_flag else first.strip()
93
+ lines = [l for l in t.splitlines() if l.strip()]
94
+ seg = lines[-1] if lines else t
95
+ return (seg, False) if with_flag else seg
96
+
97
+
98
+ def _letters(ex):
99
+ return [chr(65 + i) for i in range(len(ex.get("choices") or []))]
100
+
101
+
102
+ def _letter_in(s, letters, first=True):
103
+ """A choice letter written as one: (B), B), B., **B**, 'B' alone, 'option B'."""
104
+ pats = (r"\(([A-Z])\)", r"(?:option|choice|选项|选)\s*\(?([A-Z])\b",
105
+ r"(?<![A-Za-z0-9])([A-Z])(?![A-Za-z0-9])")
106
+ for pat in pats:
107
+ found = [c for c in re.findall(pat, s) if c in letters]
108
+ if found:
109
+ return found[0] if first else found[-1]
110
+ return ""
111
+
112
+
113
+ def _match_choice_text(s, letters, choices):
114
+ """Letter of the option whose text is s (exact after normalising), else ''."""
115
+ ns = _norm_text(s)
116
+ for l, c in zip(letters, choices):
117
+ if ns and ns == _norm_text(c):
118
+ return l
119
+ return ""
120
+
121
+
122
+ def _mc(t, ex):
123
+ letters, choices = _letters(ex), ex.get("choices") or []
124
+ # 1. last \boxed{...}
125
+ box = _boxed(t)
126
+ if box:
127
+ b = _strip_latex(box[-1])
128
+ if b.strip().strip("()") in letters:
129
+ return b.strip().strip("()")
130
+ l = _match_choice_text(b, letters, choices) or _letter_in(b, letters)
131
+ if l:
132
+ return l
133
+ t = _strip_latex(t)
134
+ # 2. after the last answer marker (or the last line)
135
+ seg, marked = _final_segment(t, with_flag=True)
136
+ bare = re.fullmatch(r"\(?([A-Z])\)?[.:]?", seg.strip(" *"))
137
+ if bare and bare.group(1) in letters:
138
+ return bare.group(1)
139
+ l = _match_choice_text(seg.strip(" .*"), letters, choices) or _letter_in(seg, letters)
140
+ if l:
141
+ return l
142
+ # option text inside the final segment (longest option that appears)
143
+ low = seg.lower()
144
+ hits = sorted(((len(str(c)), l) for l, c in zip(letters, choices)
145
+ if str(c).strip() and str(c).strip().lower() in low), reverse=True)
146
+ if hits:
147
+ return hits[0][1]
148
+ # 3. explicit statements anywhere ("the answer is C", "选 C"), last one wins
149
+ found = [m.group(1) for m in re.finditer(MARKER_RE + r"\(?([A-Z])(?![A-Za-z0-9])", t, re.I)
150
+ if m.group(1) in letters]
151
+ if found:
152
+ return found[-1]
153
+ # 4. last mention of an option's text, then last standalone letter
154
+ best, pos = "", -1
155
+ low = t.lower()
156
+ for l, c in zip(letters, choices):
157
+ p = low.rfind(str(c).strip().lower())
158
+ if len(str(c).strip()) > 2 and p > pos:
159
+ best, pos = l, p
160
+ return best or _letter_in(t, letters, first=False)
161
+
162
+
163
+ def extract_answer(response, ex):
164
+ t = _clean(response)
165
+ if not t.strip():
166
+ return ""
167
+ qt, at = ex.get("question_type"), ex.get("answer_type")
168
+
169
+ if qt == "multi_choice":
170
+ return _mc(t, ex)
171
+
172
+ box = _boxed(t)
173
+ if at == "list":
174
+ src = _strip_latex(box[-1]) if box else _strip_latex(t)
175
+ m = re.findall(r"\[[^\[\]]*\]", src)
176
+ return m[-1] if m else ""
177
+
178
+ if at in ("integer", "float"):
179
+ if box:
180
+ nums = re.findall(NUM_RE, _strip_latex(box[-1]))
181
+ if nums:
182
+ return nums[-1].replace(",", "")
183
+ t = _strip_latex(t)
184
+ lines = [l for l in t.splitlines() if l.strip()]
185
+ m = list(re.finditer(MARKER_RE, t, re.I))
186
+ after = t[m[-1].end():].strip() if m else ""
187
+ first = next((l for l in after.splitlines() if l.strip()), "")
188
+ # after a marker: its first line, then the rest of it -> first number;
189
+ # no marker (or nothing numeric after it): the last line -> last number
190
+ for seg, use_first in ((first, True), (after, True), (lines[-1] if lines else "", False)):
191
+ if "=" in seg: # "78 - 59 = 19" -> the result after the last "="
192
+ seg = seg.rsplit("=", 1)[1]
193
+ nums = re.findall(NUM_RE, seg)
194
+ if nums:
195
+ return (nums[0] if use_first else nums[-1]).replace(",", "")
196
+ all_nums = _nums(t) if not re.search(r"\d", t) else re.findall(NUM_RE, t)
197
+ if not all_nums and lines:
198
+ all_nums = _nums(lines[-1])
199
+ word = _nums(lines[-1]) if lines else []
200
+ if word and not re.search(r"\d", lines[-1]):
201
+ return word[0] # "Only one year satisfies the condition."
202
+ return all_nums[-1].replace(",", "") if all_nums else ""
203
+
204
+ if box:
205
+ return _strip_latex(box[-1])
206
+ return _final_segment(_strip_latex(t)).strip().strip(".")
207
+
208
+
209
+ def _to_float(x):
210
+ return float(str(x).replace(",", "").replace("%", "").strip())
211
+
212
+
213
+ def is_correct(pred, ex):
214
+ if pred is None or str(pred).strip() == "":
215
+ return False
216
+ gold, at = ex["answer"], ex.get("answer_type")
217
+ try:
218
+ if ex.get("question_type") == "multi_choice":
219
+ if ex.get("answer_is_letter"):
220
+ return str(pred).strip().upper() == str(gold).strip().upper()
221
+ letters, choices = _letters(ex), ex.get("choices") or []
222
+ text = choices[letters.index(pred)] if pred in letters else pred
223
+ return _norm_text(text) == _norm_text(ex.get("answer_raw", gold))
224
+ if at == "integer":
225
+ return int(round(_to_float(pred))) == int(round(_to_float(gold)))
226
+ if at == "float":
227
+ prec = int(ex.get("precision") or 2)
228
+ return round(_to_float(pred), prec) == round(_to_float(gold), prec)
229
+ if at == "list":
230
+ p, g = ast.literal_eval(str(pred)), ast.literal_eval(str(gold))
231
+ return len(p) == len(g) and all(abs(_to_float(a) - _to_float(b)) < 1e-6 for a, b in zip(p, g))
232
+ except Exception:
233
+ return False
234
+ unit = ex.get("unit") or ""
235
+ return _norm_text(pred, unit) == _norm_text(gold, unit)