File size: 15,871 Bytes
6b45f1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""MPBench scoring: rule-based, with wiggle room. Same output, same score, on any machine.

Task fields, by `type`:
  text    answers=[accepted wordings], reject=[wrong options] (optional), exact=true where spelling is the task
                                                              not_typos=[real words that look like an answer]
  ideas   ideas=[[phrasings of idea 1], [phrasings of idea 2], ...], need=N (default: all)
  number  answer="3/4", tolerance=absolute and/or relative_tolerance=share (both optional)
  html    checks=[...], see html_check.py
  tool    call={"name": ..., "arguments": {key: value or {"any": [values]}}}, optional=[argument names]
"""
from __future__ import annotations

VERSION = "1.1"  # 1.0 was used to check the tasks; 1.1 closes holes found in the scored answers

import ast
import json
import re
import unicodedata
from fractions import Fraction

UNITS = {w: 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".split())}
TENS = {w: 10 * (i + 2) for i, w in enumerate("twenty thirty forty fifty sixty seventy eighty ninety".split())}
SCALE = {"thousand": 10**3, "million": 10**6, "billion": 10**9, "trillion": 10**12}
PARTS = {"half": 2, "halves": 2, "third": 3, "thirds": 3, "quarter": 4, "quarters": 4, "fifth": 5, "fifths": 5,
         "eighth": 8, "eighths": 8, "tenth": 10, "tenths": 10}
NEGATIONS = {"not", "never", "isnt", "wasnt", "arent", "werent", "doesnt", "didnt", "cannot", "cant", "dont"}
CLAUSE_END = {"but", "it", "its", "rather", "instead"}


ONE_AFTER = {"the", "this", "that", "which", "each", "every", "any", "no", "another", "other", "someone", "anyone"}
NOT_ADJ = {"number", "answer", "total", "result", "value", "is", "was", "equals", "of", "and", "or", "to", "by"}


def pronoun_one(words: list, i: int) -> bool:
    """'the bigger one', 'which one', 'each one': a word, not the number 1."""
    prev = words[i - 1].lower() if i >= 1 else ""
    prev2 = words[i - 2].lower() if i >= 2 else ""
    return prev in ONE_AFTER or (prev2 in ("the", "this", "that") and prev.isalpha() and prev not in NOT_ADJ
                                 and prev not in UNITS and prev not in TENS)


def number_words(text: str) -> str:
    """'twenty-three' -> '23', 'one half' -> '1/2', 'two thousand and six' -> '2006'."""
    toks = re.split(r"(\W+)", text)
    words, gaps = toks[0::2], toks[1::2] + [""]
    out, i = [], 0
    while i < len(words):
        w = words[i].lower()
        if w == "one" and pronoun_one(words, i):
            out.append(words[i] + gaps[i]); i += 1
            continue
        if w in UNITS or w in TENS:
            total, cur, j, last = 0, 0, i, None
            while j < len(words):
                t = words[j].lower()
                if j > i and gaps[j - 1].strip() not in ("", "-"):
                    break
                if t in UNITS and last not in ("unit",) and not (last == "ten" and not 0 < UNITS[t] < 10):
                    cur += UNITS[t]; last = "unit"
                elif t in TENS and last not in ("unit", "ten"):
                    cur += TENS[t]; last = "ten"
                elif t == "hundred" and last in ("unit", "ten"):
                    cur *= 100; last = "scale"
                elif t in SCALE and last is not None:
                    total += cur * SCALE[t]; cur = 0; last = "scale"
                elif (t == "and" and last == "scale" and j + 1 < len(words)
                      and (words[j + 1].lower() in UNITS or words[j + 1].lower() in TENS)):
                    pass
                else:
                    break
                j += 1
            value = str(total + cur)
            if j < len(words) and gaps[j - 1].strip() in ("", "-") and words[j].lower() in PARTS and last == "unit":
                value += f"/{PARTS[words[j].lower()]}"; j += 1
            out += [value, gaps[j - 1]]
            i = j
        else:
            out += [words[i], gaps[i]]
            i += 1
    return "".join(out)


def words_of(text: str) -> list:
    t = unicodedata.normalize("NFKD", str(text))
    t = "".join(c for c in t if not unicodedata.combining(c)).lower().replace("’", "'").replace("&", " and ")
    t = re.sub(r"(?<=\d),(?=\d{3}\b)", "", number_words(t)).replace("'s ", " ").replace("'", "")
    t = re.sub(r"(?<!\d)\.|\.(?!\d)", " ", t)
    return [w for w in re.findall(r"[^\W_]+(?:[./][0-9]+)?", t) if w not in ("a", "an", "the")]


def edits(a: str, b: str, limit: int) -> int:
    """Edit distance with swapped neighbours counted once, capped at limit + 1."""
    if abs(len(a) - len(b)) > limit:
        return limit + 1
    prev2, prev = None, list(range(len(b) + 1))
    for i, x in enumerate(a, 1):
        cur = [i]
        for j, y in enumerate(b, 1):
            v = min(prev[j] + 1, cur[-1] + 1, prev[j - 1] + (x != y))
            if i > 1 and j > 1 and x == b[j - 2] and a[i - 2] == y:
                v = min(v, prev2[j - 2] + 1)
            cur.append(v)
        prev2, prev = prev, cur
    return min(prev[-1], limit + 1)


def same_word(said: str, want: str, known=frozenset()) -> bool:
    """Equal, or a typo that cannot be read as another answer of the section."""
    if said == want:
        return True
    if any(c.isdigit() for c in said + want) or said[:1] != want[:1] or said in known:
        return False
    if len(want) >= 5 and said in (want + "s", want + "es"):
        return True
    n = min(len(said), len(want))
    limit = 2 if n >= 9 else 1 if n >= 6 else 0
    return bool(limit) and edits(said, want, limit) <= limit


def find(words: list, phrase: str, known=frozenset(), negatable=True) -> list:
    """Positions of a phrase, leaving out negated ones."""
    p = words_of(phrase)
    hits = []
    if not p:
        return hits
    for i in range(len(words) - len(p) + 1):
        if all(same_word(words[i + k], p[k], known) for k in range(len(p))):
            before = words[max(0, i - 3):i]
            for k in range(len(before) - 1, -1, -1):
                if before[k] in CLAUSE_END:
                    before = before[k + 1:]
                    break
            if not negatable or not NEGATIONS & set(before):
                hits.append(i)
    return hits


def score_text(out: str, task: dict, known=frozenset()) -> float:
    w = words_of(out)[:80]
    wanted = [words_of(a) for a in task["answers"]]
    numeric = [a for a in wanted if a and all(x.isdigit() for x in a)]
    if numeric and in_number_list(number_words(out), {x for a in numeric for x in a}, GUESSES):
        return 0.0                      # a run of guesses is not an answer
    # where spelling is the task, only the exact word will do
    allowed = frozenset(w) | known if task.get("exact") else known
    good = [i for a in task["answers"] for i in find(w, a, allowed)]
    if not good:
        return 0.0
    # a wrong option counts only as an exact word, so a typo of the answer is never read as the wrong option
    everything = frozenset(w) | known
    bad = {r: h for r in task.get("reject", []) if (h := find(w, r, everything))}
    if len(bad) >= 2 or any(min(h) < min(good) for h in bad.values()):
        return 0.0
    if any("or" in w[min(g, b):max(g, b)] and abs(g - b) <= 4 for g in good for h in bad.values() for b in h):
        return 0.0                      # naming both options is not choosing
    return 1.0


def looping(words: list) -> bool:
    """The same six words three times over."""
    seen = {}
    for i in range(len(words) - 5):
        k = tuple(words[i:i + 6])
        seen[k] = seen.get(k, 0) + 1
        if seen[k] >= 3:
            return True
    return False


def score_ideas(out: str, task: dict, known=frozenset()) -> float:
    w = words_of(out)[:160]
    if looping(w):
        return 0.0
    if task.get("exact"):
        known = frozenset(w) | known
    got = sum(1 for idea in task["ideas"] if any(find(w, p, known, negatable=False) for p in idea))
    return float(got >= task.get("need", len(task["ideas"])))


NUMBER = re.compile(r"(?<![\w.])[-−]?(?:\d+\s+\d+/\d+|\d+/\d+|\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)")


def value(token: str):
    t = token.replace(",", "").replace("−", "-")
    if len(t) > 60 or re.search(r"[eE][-+]?[\d_]{3,}", t):
        return None
    try:
        if " " in t:
            whole, part = t.split()
            return Fraction(whole) + (-1 if t.startswith("-") else 1) * Fraction(part)
        return Fraction(t)
    except (ValueError, ZeroDivisionError):
        return None


def numbers(text: str) -> list:
    return [(m.group(), v) for m in NUMBER.finditer(number_words(text)) if (v := value(m.group())) is not None]


EQUATION = re.compile(r"(?<![a-z])\d*\s*[xyz](?![a-z])", re.I)


def is_equation(side: str) -> bool:
    """'= -5x + 9' still has the unknown in it, so it is not a stated value."""
    return bool(EQUATION.search(re.split(r"\n|(?<=\w)\.\s|[!?;,]", side, maxsplit=1)[0]))


def final_number(out: str):
    """The stated answer if there is one, else the number after the last '=', else the last number."""
    said = re.split(r"(?i)(?:\banswer(?:\s+is|\s*:)|####|\\boxed\{)", out)
    if len(said) > 1 and (n := numbers(said[-1])):
        sentence = re.split(r"\n|(?<=\w)\.\s|[!?;]", said[-1].lstrip(), maxsplit=1)[0]
        if "=" in sentence:
            side = sentence.rsplit("=", 1)[1]
            if is_equation(side):
                return None
            if after := numbers(side):
                return after[0]
        return n[0]
    if "=" in out:
        side = out.rsplit("=", 1)[1]
        if is_equation(side):
            return None
        if n := numbers(side):
            return n[0]
    n = numbers(out)
    return n[-1] if n else None


LIST = re.compile(r"(?<![\w.])[-−]?\d(?:[\d./]|,(?=\d))*(?:(?:\s*(?:,|;|\bor\b|\band\b|[x×*+]|\s)\s*)[-−]?\d(?:[\d./]|,(?=\d))*){2,}")
GUESSES = re.compile(r"(?<![\w.])[-−]?\d(?:[\d./]|,(?=\d))*(?:(?:\s*(?:,|;|\bor\b|\band\b)\s*)[-−]?\d(?:[\d./]|,(?=\d))*){2,}")


def in_number_list(text: str, wanted=None, pattern=LIST) -> bool:
    """Three or more numbers in a row with nothing but commas, 'or', 'and' (and, for maths, spaces or ×) between them."""
    for m in pattern.finditer(text):
        items = re.findall(r"[-−]?\d(?:[\d./]|,(?=\d))*", m.group())
        items = [x.rstrip(",.") for x in items]
        if len(items) >= 3 and (wanted is None or set(items) & set(wanted)):
            return True
    return False


def score_number(out: str, task: dict) -> float:
    out = re.sub(r"(?<=\d) / (?=\d)", "/", out)
    if not re.search(r"=|answer|####|\\boxed", out, re.I):
        said = number_words(out)
        if in_number_list(said):
            last = numbers(said)
            if last and LIST.search(said[max(0, said.rfind(last[-1][0]) - 200):]):
                return 0.0              # a list of numbers, not an answer
    got = final_number(out)
    want = value(str(task["answer"]))
    if got is None or want is None:
        return 0.0
    token, v = got
    allow = Fraction(str(task.get("tolerance", 0)))
    allow = max(allow, abs(want) * Fraction(str(task.get("relative_tolerance", 0))))
    if abs(v - want) <= allow:
        return 1.0
    if want.denominator != 1 and "." in token:          # a correctly rounded decimal: 0.33 for 1/3
        places = len(token.split(".")[1])
        if places >= 2 and abs(v - want) <= Fraction(1, 2 * 10**places):
            return 1.0
    return 0.0


def parse_calls(out: str) -> list:
    """Every tool call in the text: JSON in the usual shapes, or name(key=value)."""
    calls, dec, i = [], json.JSONDecoder(), 0
    while (i := out.find("{", i)) >= 0:
        try:
            obj, end = dec.raw_decode(out, i)
        except (ValueError, RecursionError):
            i += 1
            continue
        i = end
        c = obj.get("tool_call") or obj.get("function") or obj
        if isinstance(c, str):
            c = {**obj, "name": c}
        if not isinstance(c, dict):
            continue
        name = c.get("name") or c.get("tool")
        args = next((c[k] for k in ("arguments", "args", "parameters", "input") if k in c), {})
        if isinstance(args, str):
            try:
                args = json.loads(args)
            except ValueError:
                continue
        if isinstance(name, str) and isinstance(args, dict):
            calls.append((name, args))
    if not calls:
        for m in re.finditer(r"\b[A-Za-z_]\w*\([^()\n]*\)", out):
            try:
                node = ast.parse(m.group(), mode="eval").body
                if node.args:
                    continue
                calls.append((node.func.id, {k.arg: ast.literal_eval(k.value) for k in node.keywords}))
            except (ValueError, TypeError, SyntaxError, AttributeError, MemoryError, RecursionError):
                continue
    return calls


def expression(x) -> str:
    """An arithmetic expression with spacing and operator glyphs evened out."""
    t = re.sub(r"\s+", "", str(x)).replace(",", "").replace("×", "*").replace("÷", "/").replace("−", "-")
    return re.sub(r"(?<=\d)[xX](?=\d)", "*", t).rstrip("=")


def same_value(said, want) -> bool:
    if isinstance(want, dict) and "any" in want:
        return any(same_value(said, w) for w in want["any"])
    if isinstance(want, bool) or isinstance(said, bool):
        return str(said).strip().lower() == str(want).strip().lower()
    if isinstance(want, list):
        return isinstance(said, list) and len(said) == len(want) and all(map(same_value, said, want))
    if isinstance(want, dict):
        return isinstance(said, dict) and said.keys() == want.keys() and all(same_value(said[k], want[k]) for k in want)
    if said is None or isinstance(said, (dict, list)):
        return said == want
    if re.fullmatch(r"\d+(?:\.\d+)?(?:[-+*/]\d+(?:\.\d+)?)+", expression(want)) and isinstance(want, str):
        return expression(said) == expression(want)
    a, b = value(str(said).strip().rstrip("%")), value(str(want).strip().rstrip("%"))
    if a is not None or b is not None:
        return a == b
    x, y = words_of(said), words_of(want)
    return x == y and bool(x)


def score_tool(out: str, task: dict) -> float:
    calls = parse_calls(out)
    if len(calls) != 1:
        return 0.0
    name, args = calls[0]
    key = lambda s: re.sub(r"[^a-z0-9]", "", str(s).lower())
    want = {key(k): v for k, v in task["call"].get("arguments", {}).items()}
    said = {key(k): v for k, v in args.items()}
    extra = said.keys() - want.keys() - {key(k) for k in task.get("optional", [])}
    ok = key(name) == key(task["call"]["name"]) and not extra
    return float(ok and all(k in said and same_value(said[k], v) for k, v in want.items()))


def known_words(tasks: list) -> frozenset:
    """Answer, option and look-alike words of a section: never accepted as typos of an answer."""
    return frozenset(w for t in tasks for a in t.get("answers", []) + t.get("reject", []) + t.get("not_typos", []) for w in words_of(a))


def score(out: str, task: dict, known=frozenset()) -> float:
    kind = task["type"]
    asked = task.get("question", "").strip()
    if len(asked.split()) >= 3 and kind != "tool":          # repeating the question is not answering it
        echo = r"[\W_]+".join(map(re.escape, re.findall(r"[^\W_]+", asked)))
        out = re.sub(r"(?<![^\W_])" + echo + r"(?![^\W_])", " ", out, flags=re.I)
    if kind == "text":
        return score_text(out, task, known)
    if kind == "ideas":
        return score_ideas(out, task, known)
    if kind == "number":
        return score_number(out, task)
    if kind == "tool":
        return score_tool(out, task)
    if kind == "html":
        from .html_check import score_html
        return score_html(out, task)
    raise ValueError(f"unknown task type {kind}")