File size: 12,611 Bytes
6a5714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import json
import os
import re
import unicodedata
from collections import defaultdict
from typing import Any, Dict, List, Tuple

# ---------- Text Normalization ----------
_PUNCT_MAP = str.maketrans("。、“”‘’()【】", ".,\"\"''()[]")

def norm_text(s: Any) -> str:
    if not s: return ""
    t = str(s)
    t = unicodedata.normalize('NFKC', t)
    t = t.translate(_PUNCT_MAP)
    t = re.sub(r'[\u200b\u200c\u200d\ufeff]+', '', t)
    return re.sub(r'\s+', ' ', t).strip()

# ---------- Core Algorithms ----------
def levenshtein(a: str, b: str) -> int:
    if a == b: return 0
    la, lb = len(a), len(b)
    if la == 0: return lb
    if lb == 0: return la
    if la < lb: a, b, la, lb = b, a, lb, la
    prev = list(range(lb + 1))
    cur = [0] * (lb + 1)
    for i in range(1, la + 1):
        cur[0] = i
        ca = a[i - 1]
        for j in range(1, lb + 1):
            cost = 0 if ca == b[j - 1] else 1
            cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost)
        prev, cur = cur, prev
    return prev[lb]

def iou_xyxy(a: List[float], b: List[float]) -> float:
    ax1, ay1, ax2, ay2 = float(a[0]), float(a[1]), float(a[2]), float(a[3])
    bx1, by1, bx2, by2 = float(b[0]), float(b[1]), float(b[2]), float(b[3])
    ix1, iy1 = max(ax1, bx1), max(ay1, by1)
    ix2, iy2 = min(ax2, bx2), min(ay2, by2)
    iw, ih = max(0, ix2 - ix1), max(0, iy2 - iy1)
    inter = iw * ih
    if inter <= 0: return 0.0
    union = max(0, ax2 - ax1) * max(0, ay2 - ay1) + max(0, bx2 - bx1) * max(0, by2 - by1) - inter
    return inter / union if union > 0 else 0.0

def greedy_match_iou(preds: List[List[float]], gts: List[List[float]], thr: float) -> Tuple[int, int, int]:
    pairs = []
    for i, pb in enumerate(preds):
        for j, gb in enumerate(gts):
            v = iou_xyxy(pb, gb)
            if v >= thr: pairs.append((v, i, j))
    pairs.sort(key=lambda x: x[0], reverse=True)
    used_p, used_g = set(), set()
    tp = 0
    for v, i, j in pairs:
        if i in used_p or j in used_g: continue
        used_p.add(i); used_g.add(j)
        tp += 1
    return tp, max(0, len(preds) - tp), max(0, len(gts) - tp)

# ---------- Parsing Logic ----------
def _extract_json_string(s: str) -> str:
    m = re.search(r"```(?:json)?\s*([\s\S]*?)```", s)
    return m.group(1).strip() if m else s.strip()

def parse_pred_text_for_r2t(raw: str) -> Tuple[str, bool]:
    if not raw or not isinstance(raw, str): return "", False
    raw_str = _extract_json_string(raw)
    
    # Recognize empty outputs as valid parsing
    if raw_str.strip() in ("[]", "{}", '""', "''"): 
        return "", True
        
    try:
        obj = json.loads(raw_str)
        while isinstance(obj, list) and len(obj) == 1: obj = obj[0]
        if isinstance(obj, list) and len(obj) == 0: return "", True
        if isinstance(obj, dict) and "text" in obj: return str(obj["text"]), True
        if isinstance(obj, list) and obj and isinstance(obj[0], dict) and "text" in obj[0]: return str(obj[0]["text"]), True
        if isinstance(obj, str): return obj, True
    except Exception: 
        pass
        
    m = re.search(r'"text"\s*:\s*(?:\[\s*)?(["\'])(.*?)(?:\1|(?=\})|(?=$))', raw_str, flags=re.DOTALL)
    if m: return str(m.group(2)), True
    return raw_str.strip(), False

def parse_bbox_list_from_t2r(raw: str) -> Tuple[List[List[float]], bool]:
    if not raw or not isinstance(raw, str): return [], False
    raw_str = _extract_json_string(raw)
    
    if raw_str.strip() in ("[]", "{}", '""', "''"): 
        return [], True
        
    out = []
    is_valid = False
    try:
        obj = json.loads(raw_str)
        is_valid = True  # Successfully parsed by json.loads
        while isinstance(obj, list) and len(obj) == 1: obj = obj[0]
        if isinstance(obj, dict):
            b = obj.get("bbox") or obj.get("bbox_2d") or obj.get("xyxy") or obj.get("box")
            if b and len(b) >= 4: out.append([float(x) for x in b[:4]])
        elif isinstance(obj, list):
            if len(obj) == 0: return [], True
            for item in obj:
                if isinstance(item, (list, tuple)) and len(item) >= 4:
                    out.append([float(x) for x in item[:4]])
                elif isinstance(item, dict):
                    b = item.get("bbox") or item.get("bbox_2d") or item.get("xyxy") or item.get("box")
                    if b and len(b) >= 4: out.append([float(x) for x in b[:4]])
        if out: return out, True
    except Exception: 
        pass
        
    boxes = re.findall(r'(?:"bbox_2d"|"bbox"|"xyxy"|"box")\s*:\s*\[\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\]', raw_str)
    if boxes: 
        out = [[float(x) for x in b] for b in boxes]
        return out, True
        
    return [], is_valid

# ---------- Evaluation Modules ----------
def eval_r2t(rows: List[dict]) -> Tuple[dict, dict, List[dict]]:
    n = exact = ed_leq1 = sum_ed = sum_len = macro_sum = macro_n = parse_errors = 0
    per_sample = []
    cat_stats = defaultdict(lambda: {"n": 0, "exact": 0, "sum_ed": 0, "sum_len": 0, "parse_errors": 0})
    
    for idx, r in enumerate(rows):
        gt = norm_text(r.get("GT") or r.get("answer") or "")
        pred_raw, is_valid = parse_pred_text_for_r2t(r.get("model_answer") or "")
        pred = norm_text(pred_raw)
        cat = r.get("category", "unknown")
        
        n += 1
        if not is_valid:
            parse_errors += 1
            cat_stats[cat]["parse_errors"] += 1
            
        ed = levenshtein(pred, gt)
        exact_i = 1 if pred == gt else 0
        ed_leq1_i = 1 if ed <= 1 else 0
        
        exact += exact_i; ed_leq1 += ed_leq1_i
        sum_ed += ed; sum_len += len(gt)
        macro = (ed / len(gt)) if len(gt) > 0 else (0.0 if len(pred) == 0 else 1.0)
        macro_sum += macro; macro_n += 1
        
        cat_stats[cat]["n"] += 1
        cat_stats[cat]["exact"] += exact_i
        cat_stats[cat]["sum_ed"] += ed
        cat_stats[cat]["sum_len"] += len(gt)
        
        per_sample.append({
            "idx": idx, "image_path": r.get("image_path"), "category": cat,
            "GT_text": gt, "parsed_pred_text": pred_raw, "parse_success": is_valid,
            "exact": exact_i, "ed": ed, "cer": round(macro, 6), "acc_ed_leq_1": ed_leq1_i,
        })
        
    summary = {
        "count": n, "parse_error_rate": round(parse_errors / n, 6) if n else 0.0,
        "exact_acc": round(exact / n, 6) if n else 0.0,
        "cer_micro": round(sum_ed / sum_len, 6) if sum_len > 0 else 0.0,
        "cer_macro": round(macro_sum / macro_n, 6) if macro_n > 0 else 0.0,
    }
    cat_summary = {k: {
        "count": v["n"], "parse_error_rate": round(v["parse_errors"] / v["n"], 6) if v["n"] else 0.0,
        "exact_acc": round(v["exact"] / v["n"], 6) if v["n"] else 0.0,
        "cer_micro": round(v["sum_ed"] / v["sum_len"], 6) if v["sum_len"] else 0.0
    } for k, v in cat_stats.items()}
    
    return summary, cat_summary, per_sample

def eval_t2r(rows: List[dict], iou_thr: float = 0.5, ks: Tuple[int, ...] = (1, 3)) -> Tuple[dict, dict, List[dict]]:
    clusters_total = TP = FP = FN = parse_errors = 0
    qsr_hits = {k: 0 for k in ks}
    per_sample = []
    cat_stats = defaultdict(lambda: {"clusters": 0, "tp": 0, "fp": 0, "fn": 0, "parse_errors": 0})
    
    for idx, r in enumerate(rows):
        gt_bboxes_raw = r.get("bbox")
        gts = []
        if isinstance(gt_bboxes_raw, list):
            if gt_bboxes_raw and isinstance(gt_bboxes_raw[0], (list, tuple)):
                gts = [[float(x) for x in b[:4]] for b in gt_bboxes_raw if len(b) >= 4]
            elif len(gt_bboxes_raw) >= 4:
                gts = [[float(x) for x in gt_bboxes_raw[:4]]]
                
        pred_boxes_raw, is_valid = parse_bbox_list_from_t2r(r.get("model_answer") or "")
        valid_pred_boxes = [b for b in pred_boxes_raw if len(b) == 4 and b[2] > b[0] and b[3] > b[1]]
        cat = r.get("category", "unknown")
        
        clusters_total += 1
        if not is_valid:
            parse_errors += 1
            cat_stats[cat]["parse_errors"] += 1
            
        qsr_at_k = {}
        for k in ks:
            top = valid_pred_boxes[:k]
            hit = any(any(iou_xyxy(pb, gb) >= iou_thr for gb in gts) for pb in top)
            qsr_at_k[k] = 1 if hit else 0
            if hit: qsr_hits[k] += 1
                
        tp, fp, fn = greedy_match_iou(valid_pred_boxes, gts, thr=iou_thr)
        TP += tp; FP += fp; FN += fn
        
        cat_stats[cat]["clusters"] += 1
        cat_stats[cat]["tp"] += tp; cat_stats[cat]["fp"] += fp; cat_stats[cat]["fn"] += fn
        
        prec_i = tp / (tp + fp) if (tp + fp) > 0 else 0.0
        rec_i = tp / (tp + fn) if (tp + fn) > 0 else 0.0
        
        per_sample.append({
            "idx": idx, "image_path": r.get("image_path"), "category": cat,
            "GT_boxes": gts, "parsed_pred_boxes": valid_pred_boxes, "parse_success": is_valid,
            "qsr_at_1": qsr_at_k.get(1, 0), "qsr_at_3": qsr_at_k.get(3, 0),
            "precision": round(prec_i, 6), "recall": round(rec_i, 6),
        })
        
    precision = TP / (TP + FP) if (TP + FP) > 0 else 0.0
    recall = TP / (TP + FN) if (TP + FN) > 0 else 0.0
    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
    
    summary = {
        "clusters_total": clusters_total, "iou_thr": iou_thr, "parse_error_rate": round(parse_errors / clusters_total, 6) if clusters_total else 0.0,
        "qsr": {f"QSR@{k}": round(qsr_hits[k] / clusters_total, 6) if clusters_total else 0.0 for k in ks},
        "precision": round(precision, 6), "recall": round(recall, 6), "f1": round(f1, 6),
    }
    cat_summary = {}
    for k, v in cat_stats.items():
        c_p = v["tp"] / (v["tp"] + v["fp"]) if (v["tp"] + v["fp"]) > 0 else 0.0
        c_r = v["tp"] / (v["tp"] + v["fn"]) if (v["tp"] + v["fn"]) > 0 else 0.0
        cat_summary[k] = {
            "clusters": v["clusters"], "parse_error_rate": round(v["parse_errors"] / v["clusters"], 6) if v["clusters"] else 0.0,
            "precision": round(c_p, 6), "recall": round(c_r, 6)
        }
        
    return summary, cat_summary, per_sample

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--pred", "-p", default="infer_output/TA-Bench-abs_with_predictions.jsonl")
    ap.add_argument("--iou-thr", type=float, default=0.5)
    ap.add_argument("--export-jsonl", default="case_analysis.jsonl", help="Export per-sample evaluation results")
    ap.add_argument("--output", default=None, help="Export summary report")
    args = ap.parse_args()

    if not os.path.isfile(args.pred):
        print(f"File not found: {args.pred}")
        return

    rows = []
    with open(args.pred, "r", encoding="utf-8") as f:
        for line in f:
            if line.strip(): rows.append(json.loads(line))
            
    r2t_rows = [r for r in rows if r.get("task_type") == "R2T"]
    t2r_rows = [r for r in rows if r.get("task_type") == "T2R"]
    ks = (1, 3)

    r2t_sum, r2t_cat, r2t_per = eval_r2t(r2t_rows) if r2t_rows else ({}, {}, [])
    t2r_sum, t2r_cat, t2r_per = eval_t2r(t2r_rows, args.iou_thr, ks) if t2r_rows else ({}, {}, [])

    # Compute core metrics
    r2t_acc = r2t_sum.get("exact_acc", 0.0)
    t2r_f1 = t2r_sum.get("f1", 0.0)
    overall = 0.5 * r2t_acc + 0.5 * t2r_f1

    report = {
        "Overall_Score": round(overall, 6),
        "R2T_Accuracy": round(r2t_acc, 6),
        "T2R_F1_Score": round(t2r_f1, 6),
        "R2T_Details": r2t_sum,
        "T2R_Details": t2r_sum,
        "R2T_Category": r2t_cat,
        "T2R_Category": t2r_cat
    }
    
    print("=" * 40)
    print(f"R2T Accuracy: {round(r2t_acc, 6)}")
    print(f"T2R F1 Score: {round(t2r_f1, 6)}")
    print(f"Overall Score (0.5*R2T + 0.5*T2R): {round(overall, 6)}")
    print("=" * 40)
    print(json.dumps(report, ensure_ascii=False, indent=2))
    
    if args.output:
        with open(args.output, "w", encoding="utf-8") as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
        print(f"\n✅ Report exported to {args.output}")

    if args.export_jsonl:
        with open(args.export_jsonl, "w", encoding="utf-8") as f:
            for typ, per in [("R2T", r2t_per), ("T2R", t2r_per)]:
                for s in per:
                    f.write(json.dumps({"task_type": typ, **s}, ensure_ascii=False) + "\n")
        print(f"\n✅ All cases exported to {args.export_jsonl}")

if __name__ == "__main__":
    main()