File size: 8,744 Bytes
58bd51a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Нормализатор ответов. Две ветки: numeric (с tolerance) и categorical
(lower/trim/remove_punct).

VERSION 2 (Week 4 update):
- Categorical bidirectional matching: засчитываем как gold ⊆ pred,
  так и pred ⊆ gold (для случаев когда модель отвечает короче gold).
- Compound detection: если gold содержит маркеры "и"/"или"/"and"/"or",
  bidirectional НЕ применяется — требуется полное совпадение или
  gold ⊆ pred (одностороннее), чтобы "март" не засчитывался за
  "март и декабрь".
"""
import re
import unicodedata


# Маркеры составных ответов — если есть в gold, bidirectional не применяется
COMPOUND_MARKERS = [
    " и ", " или ",
    " and ", " or ",
    "; ",  # точка с запятой как разделитель
    ", ",  # запятая в gold длиной более 4 слов — обычно перечисление
]


def _strip_accents(s: str) -> str:
    return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))


def extract_all_numbers(text: str):
    """
    Найти ВСЕ числа в строке. Обрабатывает:
      - "примерно 150", "около 200", "approximately 150"
      - "1,234.5" (en) и "1 234,5" (ru)
    Возвращает список float (может быть пустой).
    """
    if text is None:
        return []
    s = str(text).strip()
    # Убираем пробелы-разделители тысяч между цифрами: "1 234" -> "1234"
    s = re.sub(r"(?<=\d)[ \u00A0\u2009](?=\d{3}\b)", "", s)

    nums = []
    for m in re.finditer(r"-?\d+(?:[.,]\d+)?", s):
        num_str = m.group(0)
        if "." in num_str and "," in num_str:
            if num_str.rfind(",") > num_str.rfind("."):
                num_str = num_str.replace(".", "").replace(",", ".")
            else:
                num_str = num_str.replace(",", "")
        else:
            num_str = num_str.replace(",", ".")
        try:
            nums.append(float(num_str))
        except ValueError:
            pass
    return nums


def extract_number(text: str):
    """
    Вытащить одно число. Возвращает ПОСЛЕДНЕЕ число из строки — эвристика:
    в verbose reasoning ответах финальное значение обычно в конце
    ("...is approximately 530 million rubles.").
    """
    nums = extract_all_numbers(text)
    return nums[-1] if nums else None


def normalize_categorical(text: str) -> str:
    """Lower + strip + drop punct + collapse whitespace. Для сравнения категорий."""
    if text is None:
        return ""
    s = str(text).lower().strip()
    # Убираем пунктуацию и кавычки
    s = re.sub(r"[«»\"'`.,;:!?()\[\]{}]", " ", s)
    s = re.sub(r"\s+", " ", s).strip()
    return s


def is_compound_gold(gold: str) -> bool:
    """
    Проверка содержит ли gold compound маркеры. Используем оригинальный gold
    с пробелами вокруг (нормализатор убирает пунктуацию).
    """
    if gold is None:
        return False
    g = str(gold).lower()
    # Маркеры с пробелами вокруг — это слова "и", "или", "and", "or" а не
    # части других слов. Кроме того ", " и "; " как разделители.
    for marker in COMPOUND_MARKERS:
        if marker in g:
            return True
    return False


def normalize_answer(pred: str, gold: str, answer_type: str,
                     gold_numeric=None, tol: float = 0.05,
                     bidirectional: bool = True) -> bool:
    """
    answer_type: 'numeric' | 'categorical'
    Для numeric использует gold_numeric если передано, иначе парсит gold.
    tol=0.05 -> 5% относительная толерантность (convention из ChartQA,
    Masry et al. 2022 — стандарт для bar charts без value labels).

    Для numeric: если в pred несколько чисел (например, "2 квартал имеет
    значение 530 миллионов"), выбираем то, которое ближе всего к gold.

    Для categorical:
        - all-lower, no punct
        - exact match → True
        - gold ⊆ pred (token или substring) → True (модель может вернуть
          "Апрель." или "The answer is April")
        - если bidirectional=True И gold не compound:
              pred ⊆ gold → True (модель ответила короче чем gold,
              например gold='март 2025' pred='март')

    bidirectional: bool — включить ли pred ⊆ gold matching. По умолчанию True
        для совместимости с Week 4 update. Передай False для baseline-сравнения.
    """
    if answer_type == "numeric":
        gold_val = gold_numeric if gold_numeric is not None else extract_number(gold)
        if gold_val is None:
            return False
        nums = extract_all_numbers(pred)
        if not nums:
            return False
        # Среди всех чисел берём ближайшее к gold (по абсолютной разнице)
        closest = min(nums, key=lambda x: abs(x - gold_val))
        if gold_val == 0:
            return abs(closest) < 1e-9
        # Year-as-numeric special case: если gold выглядит как год
        # (целое 1900-2100), требуем exact match. Это защита от false positive
        # вида gold=2024, pred=2025 (разница 0.05% < 5% tolerance, но это
        # не "почти угадал", это другой год).
        is_year = (gold_val == int(gold_val) and 1900 <= gold_val <= 2100)
        if is_year:
            return any(int(n) == int(gold_val) for n in nums if n == int(n))
        return abs(closest - gold_val) / abs(gold_val) <= tol

    # categorical
    p = normalize_categorical(pred)
    g = normalize_categorical(gold)
    if not g or not p:
        return False

    # Direction 1 (всегда работает): exact или gold ⊆ pred
    if p == g:
        return True
    if g in p.split() or g in p:
        return True

    # Direction 2 (bidirectional): pred ⊆ gold, только если gold не compound
    if bidirectional and not is_compound_gold(gold):
        # pred непустой, и pred — короткая часть gold (минимум 3 символа,
        # чтобы избежать совпадений по предлогам)
        if len(p) >= 3 and (p in g.split() or p in g):
            return True

    return False


# Self-test когда запускаем как скрипт
if __name__ == "__main__":
    cases = [
        # (pred, gold, answer_type, expected_old, expected_new)
        ("Апрель", "Апрель", "categorical", True, True),
        ("Апрель.", "Апрель", "categorical", True, True),
        ("The answer is April", "April", "categorical", True, True),
        # Bidirectional case: pred ⊂ gold
        ("март", "март 2025", "categorical", False, True),
        ("март 2025", "март 2025", "categorical", True, True),
        # Compound: pred = "март" не должен матчить gold = "март и декабрь"
        ("март", "март и декабрь 2025", "categorical", False, False),
        ("март и декабрь 2025", "март и декабрь 2025", "categorical", True, True),
        # Compound с запятой
        ("работниками", "работниками, выполнявшими работы по договорам", "categorical", False, False),
        # Numeric
        ("530", "530", "numeric", True, True),
        ("approximately 530", "530", "numeric", True, True),
    ]
    print("Testing normalize_answer:")
    all_pass = True
    for pred, gold, atype, exp_old, exp_new in cases:
        result = normalize_answer(pred, gold, atype, bidirectional=True)
        status = "✓" if result == exp_new else "✗"
        if result != exp_new:
            all_pass = False
        print(f"  {status} normalize({pred!r}, {gold!r}, {atype!r}) = {result} (expected {exp_new})")
    if all_pass:
        print("\nAll tests passed.")
    else:
        print("\n!!! Some tests FAILED")