File size: 4,205 Bytes
1138ff6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Answer parts and their scoring. Reward is the mean score over parts."""

import math
import re
from dataclasses import dataclass
from typing import Any

_NUMBER_RE = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?")


def parse_number(value: Any) -> float | None:
    if isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        return float(value) if math.isfinite(value) else None
    if isinstance(value, str):
        match = _NUMBER_RE.search(value.replace(",", "").replace("−", "-"))
        if match:
            return float(match.group())
    return None


def parse_int(value: Any) -> int | None:
    """Whole numbers only: 1234, "1,234", "1234.0"; anything else is not an integer answer."""
    if isinstance(value, bool):
        return None
    if isinstance(value, int):
        return value
    if isinstance(value, float):
        return int(value) if value.is_integer() else None
    if isinstance(value, str):
        text = value.strip().replace(",", "").replace(" ", "")
        if re.fullmatch(r"[-+]?\d+(\.0*)?", text):
            return int(float(text)) if abs(float(text)) < 2**53 else int(text.split(".")[0])
    return None


def parse_items(value: Any) -> list[str] | None:
    if isinstance(value, list):
        items = [str(v) for v in value]
    elif isinstance(value, str):
        if value.strip().lower() in {"", "none", "[]"}:
            return []
        items = re.split(r"[,;\s]+", value.strip().strip("[]"))
    elif isinstance(value, (int, float)) and not isinstance(value, bool):
        items = [str(value)]
    else:
        return None
    return [normalize_text(i) for i in items if normalize_text(i)]


def normalize_text(value: Any) -> str:
    text = str(value).strip().strip("\"'").strip()
    return re.sub(r"\s+", " ", text).lower()


@dataclass(frozen=True)
class Part:
    key: str
    kind: str  # number | int | text | items | rule | timecode
    expected: Any
    hint: str
    abs_tol: float = 0.0
    rel_tol: float = 0.0

    def score(self, given: Any) -> float:
        if given is None:
            return 0.0
        if self.kind == "number":
            value = parse_number(given)
            if value is None:
                return 0.0
            tol = max(self.abs_tol, self.rel_tol * abs(self.expected))
            return 1.0 if abs(value - self.expected) <= tol + 1e-12 else 0.0
        if self.kind == "int":
            value = parse_int(given)
            return 1.0 if value is not None and value == self.expected else 0.0
        if self.kind == "text":
            return 1.0 if normalize_text(given) == normalize_text(self.expected) else 0.0
        if self.kind == "rule":
            if self.expected == "default":
                text = normalize_text(given).rstrip(".")
                return 1.0 if text in {"default", "default deny", "no match", "none", "no rule"} else 0.0
            text = re.sub(r"^rule\s*", "", normalize_text(given)).rstrip(".")
            return 1.0 if parse_int(text) == int(self.expected) else 0.0
        if self.kind == "timecode":
            text = normalize_text(given).replace(";", ":").replace(".", ":")
            return 1.0 if text == normalize_text(self.expected) else 0.0
        if self.kind == "items":
            items = parse_items(given)
            if items is None:
                return 0.0
            got = set(items)
            want = {normalize_text(i) for i in self.expected}
            if got == want:
                return 1.0
            union = got | want
            # Near misses earn a little, so groups of rollouts still differ.
            return 0.5 * len(got & want) / len(union) if union else 0.0
        raise ValueError(f"unknown part kind {self.kind}")


def grade(parts: list[Part], answer: dict[str, Any]) -> tuple[float, list[float]]:
    lowered = {normalize_text(k): v for k, v in answer.items()} if isinstance(answer, dict) else {}
    scores = [p.score(lowered.get(normalize_text(p.key))) for p in parts]
    return (sum(scores) / len(scores) if scores else 0.0), scores


def answer_template(parts: list[Part]) -> str:
    return "{" + ", ".join(f'"{p.key}": {p.hint}' for p in parts) + "}"