File size: 6,448 Bytes
d18d6b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
from __future__ import annotations

import re
import unicodedata

_SINGLE_LETTER_RE = re.compile(r"^[A-Za-z]$")
_OPTION_LINE_RE = re.compile(r"(?im)(?:^|[\n\r])\s*([A-Z])\s*[\)\.\::、]")
_OPTION_LIST_RE = re.compile(
    r"\b[A-Z]\b(?:\s*(?:,|,|/|、|&|\band\b|\bor\b)\s*\b[A-Z]\b)+",
    flags=re.IGNORECASE,
)
_OPTION_RANGE_RE = re.compile(r"\b([A-Z])\s*-\s*([A-Z])\b", flags=re.IGNORECASE)


def detect_task_type(answer: str) -> str:
    answer_text = str(answer or "").strip()
    if _SINGLE_LETTER_RE.fullmatch(answer_text):
        return "mcq"
    return "fill_blank"


def parse_valid_options(question: str) -> set[str]:
    text = str(question or "")
    options: set[str] = set()

    for match in _OPTION_LINE_RE.finditer(text):
        options.add(match.group(1).upper())

    list_text = re.sub(r"(?i)\s*,?\s*(?:and|or)\s*", ", ", text)
    for match in _OPTION_LIST_RE.finditer(list_text):
        letters = [letter.upper() for letter in re.findall(r"\b([A-Z])\b", match.group(0), flags=re.IGNORECASE)]
        if len(letters) >= 2:
            options.update(letters)

    for match in _OPTION_RANGE_RE.finditer(text):
        start = ord(match.group(1).upper())
        end = ord(match.group(2).upper())
        if start > end:
            start, end = end, start
        if 0 <= (end - start) <= 25:
            for code in range(start, end + 1):
                options.add(chr(code))

    options = {ch for ch in options if "A" <= ch <= "Z"}
    if not options:
        return {chr(code) for code in range(ord("A"), ord("Z") + 1)}
    return options


def _last_valid_match(response_text: str, pattern: str, valid_options: set[str]) -> str:
    matches = list(re.finditer(pattern, response_text, flags=re.IGNORECASE | re.MULTILINE))
    for match in reversed(matches):
        candidate = match.group(1).upper()
        if candidate in valid_options:
            return candidate.lower()
    return ""


def extract_mcq_pred(response_text: str, valid_options: set[str]) -> str:
    text = str(response_text or "")
    if not text:
        return ""

    patterns = [
        r"\*\*\s*(?:final\s+answer|answer|option|choice)?\s*[::]?\s*([A-Z])\s*\*\*",
        r"(?:^|\b)(?:final\s+answer|answer|option|choice)\s*(?:is|:|:)\s*(?:\*\*)?\s*([A-Z])\s*(?:\*\*)?",
        r"(?:^|\b)(?:answer|option|choice)\s+([A-Z])\b",
        r"(?:^|\b)(?:i\s+(?:choose|pick)|my\s+answer\s+is)\s*[::]?\s*(?:\*\*)?\s*([A-Z])\s*(?:\*\*)?",
        r"^\s*(?:\*\*)?\s*([A-Z])\s*(?:\*\*)?\s*$",
        r"^\s*[\(\[]?\s*(?:\*\*)?\s*([A-Z])\s*(?:\*\*)?\s*[\)\].,:;!\s]*$",
    ]

    for pattern in patterns:
        pred = _last_valid_match(text, pattern, valid_options)
        if pred:
            return pred

    tail_matches = list(
        re.finditer(
            r"(?:\*\*)?\b([A-Z])\b(?:\*\*)?[\)\].,:;!?\s]*$",
            text.strip(),
            flags=re.IGNORECASE | re.MULTILINE,
        )
    )
    for match in reversed(tail_matches):
        candidate = match.group(1).upper()
        if candidate in valid_options:
            return candidate.lower()
    return ""


def _is_edge_punct(ch: str) -> bool:
    return unicodedata.category(ch).startswith("P")


def strip_edge_punctuation(text: str) -> str:
    value = str(text or "")
    start = 0
    end = len(value)
    while start < end and _is_edge_punct(value[start]):
        start += 1
    while end > start and _is_edge_punct(value[end - 1]):
        end -= 1
    return value[start:end]


def _strip_markdown_wrappers(text: str) -> str:
    value = str(text or "").strip()
    while value:
        changed = False
        for left, right in (("**", "**"), ("__", "__"), ("`", "`")):
            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
        if not changed:
            break
    return value


def clean_fill_candidate(text: str) -> str:
    value = _strip_markdown_wrappers(str(text or "").strip())
    value = value.strip()
    value = strip_edge_punctuation(value).strip()
    return value


def extract_fill_pred(response_text: str) -> str:
    text = str(response_text or "")
    if not text:
        return ""

    patterns = [
        r"\*\*\s*(?:final\s+answer|answer|答案)\s*[::]\s*(.*?)\s*\*\*",
        r"(?:^|[\n\r])\s*(?:final\s+answer|answer|答案)\s*[::]\s*(.+)$",
    ]
    for pattern in patterns:
        matches = list(re.finditer(pattern, text, flags=re.IGNORECASE | re.MULTILINE))
        for match in reversed(matches):
            candidate = clean_fill_candidate(match.group(1))
            if candidate:
                return candidate

    lines = [line.strip() for line in text.splitlines() if line.strip()]
    if not lines:
        return ""

    candidate = lines[-1]
    candidate = re.sub(r"^(?:[-*•>]+)\s*", "", candidate)
    candidate = re.sub(r"^(?:final\s+answer|answer|答案)\s*[::]\s*", "", candidate, flags=re.IGNORECASE)
    return clean_fill_candidate(candidate)


def normalize_fill_text(text: str) -> str:
    value = unicodedata.normalize("NFKC", str(text or ""))
    value = value.casefold()
    value = re.sub(r"\s+", " ", value).strip()
    value = strip_edge_punctuation(value).strip()
    value = re.sub(r"\s+", " ", value).strip()
    return value


def grade_response(question: str, answer: str, response_text: str) -> dict:
    answer_text = str(answer or "").strip()
    task_type = detect_task_type(answer_text)

    if task_type == "mcq":
        valid_options = parse_valid_options(question)
        pred_raw = extract_mcq_pred(response_text, valid_options)
        pred_norm = pred_raw.lower() if pred_raw else ""
        answer_norm = answer_text.lower()
        extract_ok = bool(pred_norm)
        correct = bool(answer_norm) and pred_norm == answer_norm
        pred = pred_norm
    else:
        pred_raw = extract_fill_pred(response_text)
        pred_norm = normalize_fill_text(pred_raw)
        answer_norm = normalize_fill_text(answer_text)
        extract_ok = bool(pred_norm)
        correct = bool(answer_norm) and pred_norm == answer_norm
        pred = pred_raw

    return {
        "task_type": task_type,
        "pred": pred,
        "pred_raw": pred_raw,
        "pred_norm": pred_norm,
        "answer_norm": answer_norm,
        "extract_ok": extract_ok,
        "correct": correct,
    }