File size: 9,102 Bytes
47abdb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import math
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from structured import STRUCT_TYPES, score_struct


def num(x):
    if isinstance(x, bool):
        return None
    if isinstance(x, (int, float)):
        return float(x)
    if isinstance(x, str):
        s = x.strip().replace(",", "")
        for tok in s.split():
            try:
                return float(tok)
            except ValueError:
                pass
        try:
            return float(s)
        except ValueError:
            return None
    if isinstance(x, dict) and len(x) == 1:
        return num(next(iter(x.values())))
    if isinstance(x, list) and len(x) == 1:
        return num(x[0])
    return None


def nkey(k):
    return str(k).strip().strip("'\"").strip().lower()


def get_key(d, k):
    if not isinstance(d, dict):
        return None
    if k in d:
        return d[k]
    return next((d[q] for q in d if nkey(q) == nkey(k)), None)


SCORE_MODE = os.environ.get("SCI_SCORE_MODE", "binary")


def s_of_e(e):
    if e is None or math.isnan(e):
        return 0.0
    if e <= 1:
        return 1.0
    if SCORE_MODE == "binary":
        return 0.0
    return max(0.0, 1 - (e - 1) / 2)


def exact_eq(p, y):
    if isinstance(y, bool) or isinstance(p, bool):
        return p == y
    if isinstance(y, (int, float)):
        q = num(p)
        return q is not None and abs(q - float(y)) < 1e-9
    if isinstance(y, str):
        return isinstance(p, str) and p.strip().lower() == y.strip().lower()
    if isinstance(y, list):
        return isinstance(p, list) and len(p) == len(y) and all(exact_eq(a, b) for a, b in zip(p, y))
    if isinstance(y, dict):
        return isinstance(p, dict) and all(exact_eq(get_key(p, k), v) for k, v in y.items())
    return p == y


def err_scalar(pred, gt, tol):
    p, y = num(pred), num(gt)
    if p is None or y is None:
        return None
    t, v = tol.get("type", "rel"), float(tol.get("value", 0.1))
    if t == "abs":
        return abs(p - y) / max(v, 1e-12)
    if t == "rel":
        return abs(p - y) / max(abs(y) * v, 1e-12)
    if t == "log":
        if p <= 0 or y <= 0:
            return None
        return abs(math.log(p / y)) / math.log(1 + v)
    if t == "count":
        return abs(p - y) / (max(1.0, v * abs(y)) if v < 1 else v)
    return abs(p - y) / max(v, 1e-12)


def as_point(x):
    if isinstance(x, dict):
        ks = [k for k in ("x", "y", "z") if k in x]
        if len(ks) >= 2:
            return [num(x[k]) for k in ks]
        return None
    if isinstance(x, (list, tuple)) and x and all(isinstance(v, (int, float)) for v in x):
        return [float(v) for v in x]
    return None


def is_point_list(x):
    return isinstance(x, list) and x and all(as_point(p) is not None for p in x)


def match_f1(pred, gt, radius, scalars=False):
    import numpy as np
    from scipy.optimize import linear_sum_assignment
    if isinstance(pred, str):
        try:
            pred = json.loads(pred)
        except Exception:
            return 0.0
    gp = as_point(gt)
    if gp is not None and not scalars and not (isinstance(gt, list) and len(gt) > 3):
        pp = as_point(pred) if not is_point_list(pred) else as_point(pred[0])
        if pp is None or len(pp) < len(gp) or any(v is None for v in pp):
            return 0.0
        return s_of_e(math.dist(pp[:len(gp)], gp) / radius)
    if isinstance(gt, dict):
        if not isinstance(pred, dict):
            return 0.0
        tot = 0.0
        for k, g in gt.items():
            pk = get_key(pred, k)
            tot += match_f1(pk, g, radius) if pk is not None else 0.0
        return tot / max(1, len(gt))
    if isinstance(gt, list) and not isinstance(pred, list):
        return 0.0
    if isinstance(gt, list) and not gt:
        return 1.0 if len(pred) == 0 else 0.0
    if isinstance(gt, list) and gt and all(isinstance(v, (int, float)) for v in gt):
        G = [[float(v)] for v in gt]
        P = [[float(v)] for v in (pred or []) if isinstance(v, (int, float))] if isinstance(pred, list) else []
    else:
        G = [as_point(g) or [] for g in gt]
        P = [as_point(p) or [] for p in pred] if isinstance(pred, list) else []
    P = [p for p in P if p and all(v is not None for v in p)]
    if not P or not G:
        return 1.0 if not P and not G else 0.0
    d = np.array([[math.dist(p[:len(g)], g) if len(p) >= len(g) else 1e18 for g in G] for p in P])
    r, c = linear_sum_assignment(d)
    tp = int(sum(d[i, j] <= radius for i, j in zip(r, c)))
    if tp == 0:
        return 0.0
    pr, rc = tp / len(P), tp / len(G)
    return 2 * pr * rc / (pr + rc)


def iou(a, b):
    try:
        a, b = [float(v) for v in a], [float(v) for v in b]
    except Exception:
        return 0.0
    if len(a) != 4 or len(b) != 4:
        return 0.0
    ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
    iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
    inter = ix * iy
    u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    return inter / u if u > 0 else 0.0


def s_iou(p, g, thr):
    v = iou(p, g) if p is not None else 0.0
    return 1.0 if v >= thr else v / thr


def score(task, pred, pred_dir=None, gt_dir=None):
    gt, tol = task["answer"], task.get("tolerance", {"type": "rel", "value": 0.1})
    if tol.get("type") in STRUCT_TYPES:
        return score_struct(pred, gt, tol, pred_dir, gt_dir)
    if tol.get("type") == "exact":
        return (1.0 if exact_eq(pred, gt) else 0.0), {}
    if tol.get("type") == "f1_radius":
        return match_f1(pred, gt, float(tol["value"])), {}
    if isinstance(gt, dict):
        if not isinstance(pred, dict):
            try:
                pred = json.loads(pred) if isinstance(pred, str) else {}
            except Exception:
                pred = {}
        parts = {}
        if all(isinstance(tol.get(k), dict) and tol[k].get("type") == "iou" for k in gt) and len(gt) == 2 and isinstance(pred, dict):
            ks = list(gt)
            pv = [get_key(pred, k) for k in ks]
            th = [float(tol[k]["value"]) for k in ks]
            direct = (s_iou(pv[0], gt[ks[0]], th[0]) + s_iou(pv[1], gt[ks[1]], th[1])) / 2
            swap = (s_iou(pv[1], gt[ks[0]], th[0]) + s_iou(pv[0], gt[ks[1]], th[1])) / 2
            return max(direct, swap), {"direct": direct, "swapped": swap}
        for k, y in gt.items():
            tk = tol.get(k, tol) if isinstance(tol.get(k), dict) else tol
            pk = get_key(pred, k)
            if tk.get("type") == "exact":
                parts[k] = 1.0 if exact_eq(pk, y) else 0.0
            elif tk.get("type") in STRUCT_TYPES:
                parts[k] = score_struct(pk, y, tk, pred_dir, gt_dir)[0] if pk is not None else 0.0
            elif tk.get("type") == "iou":
                parts[k] = s_iou(pk, y, float(tk["value"]))
            elif tk.get("type") == "f1_radius":
                parts[k] = match_f1(pk, y, float(tk["value"]), scalars=isinstance(y, list) and all(isinstance(v, (int, float)) for v in y)) if pk is not None else 0.0
            elif isinstance(y, list):
                parts[k] = sum(s_of_e(err_scalar(a, b, tk)) for a, b in zip(pk or [], y)) / len(y) if isinstance(pk, list) else 0.0
            else:
                parts[k] = s_of_e(err_scalar(pk, y, tk))
        return sum(parts.values()) / len(parts), parts
    if isinstance(gt, list):
        if isinstance(pred, str):
            try:
                pred = json.loads(pred)
            except Exception:
                pred = None
        if not isinstance(pred, list) or len(pred) != len(gt):
            return 0.0, {}
        return sum(s_of_e(err_scalar(a, b, tol)) for a, b in zip(pred, gt)) / len(gt), {}
    return s_of_e(err_scalar(pred, gt, tol)), {}


def main(run_dir, items_dir):
    rows = []
    for iid in sorted(os.listdir(run_dir)):
        rp = os.path.join(run_dir, iid, "result.json")
        tp = os.path.join(items_dir, iid, "task.json")
        if not (os.path.exists(rp) and os.path.exists(tp)):
            continue
        r, t = json.load(open(rp)), json.load(open(tp))
        s, parts = score(t, r["answer"], os.path.join(run_dir, iid, "answer_files"), os.path.join(items_dir, iid)) if r["status"] in ("submitted", "submitted_forced") else (0.0, {})
        rows.append({"id": iid, "source_id": t["source_id"], "score": round(s, 3), "parts": parts, "pred": r["answer"],
                     "gt": t["answer"], "unit": t.get("unit", ""), "tolerance": t.get("tolerance"), "status": r["status"],
                     "tool_calls": r["tool_calls"], "seconds": r["seconds"]})
    json.dump(rows, open(os.path.join(run_dir, "scores.json"), "w"), ensure_ascii=False, indent=1)
    for x in rows:
        print(f'{x["id"]:<16} {x["score"]:.2f}  pred={json.dumps(x["pred"])[:50]:<52} gt={json.dumps(x["gt"])[:40]} {x["status"]}')
    if rows:
        print("mean", round(sum(x["score"] for x in rows) / len(rows), 3), "n", len(rows))


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else os.path.expanduser("~/sci_index/items"))