File size: 13,435 Bytes
aa7e82c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
"""Complete correctness pass for all 89 queries.



Checks from every angle:

- track_id exists

- type A/B/C cardinality

- target_count

- category keywords vs primary referent

- fused Pot/Scale naming in text

- except-set correctness

- static-set vs is_static

- L/R hand vs track description

- EN/ZH both name same referent family

- eval queries + predictions sync

"""
from __future__ import annotations

import json
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from scripts.predictions_ground_truth import SCENES_CONFIG

errors: list[str] = []
ok_n = 0


def load_scene(cfg):
    scene = ROOT / "data" / "scenes" / cfg["folder"]
    tracks = {
        t["track_id"]: t
        for t in json.loads((scene / cfg["track_file"]).read_text(encoding="utf-8"))["tracks"]
    }
    qs = json.loads((scene / cfg["query_file"]).read_text(encoding="utf-8"))
    if isinstance(qs, dict):
        qs = qs["queries"]
    return qs, tracks


def left_hand(tracks):
    for tid, t in tracks.items():
        c = (t.get("category") or "").lower()
        if "hand" not in c and "arm" not in c:
            continue
        if t.get("image_side") == "image_left":
            return tid
        zh, en = t.get("description_zh") or "", (t.get("description_en") or "").lower()
        if "图像左侧" in zh or "left side of the image" in en:
            return tid
    return None


def right_hand(tracks):
    for tid, t in tracks.items():
        c = (t.get("category") or "").lower()
        if "hand" not in c and "arm" not in c:
            continue
        if t.get("image_side") == "image_right":
            return tid
        zh, en = t.get("description_zh") or "", (t.get("description_en") or "").lower()
        if "图像右侧" in zh or "right side of the image" in en:
            return tid
    return None


def check_query(q, tracks):
    qid = q["query_id"]
    en, zh = q.get("text_en") or "", q.get("text_zh") or ""
    qtype = q.get("query_type")
    tids = list(q.get("target_track_ids") or [])
    low = en.lower()
    cats = [(t, tracks[t]["category"] if t in tracks else None) for t in tids]
    cat_blob = " ".join((c or "") for _, c in cats).lower()

    for t in tids:
        if t not in tracks:
            errors.append(f"{qid}: unknown track {t}")

    if q.get("target_count") is not None and int(q["target_count"]) != len(tids):
        errors.append(f"{qid}: target_count {q['target_count']} != {len(tids)}")

    # --- C ---
    if qtype == "C":
        if tids:
            errors.append(f"{qid}: C must be empty")
        return

    # --- A ---
    if qtype == "A":
        if len(tids) != 1:
            errors.append(f"{qid}: A must have exactly 1 id, got {tids}")
            return
        tid = tids[0]
        cat = (tracks[tid]["category"] or "").lower()

        # fused pot
        if cat.startswith("pot with"):
            if "pot" not in low and "锅" not in zh:
                errors.append(f"{qid}: fused pot GT but text omits pot/锅")
            content = cat.replace("pot with", "").strip()
            # content word should appear
            token = content.split()[0]
            zh_map = {"beef": "牛排", "salmon": "三文鱼", "spinach": "菠菜"}
            ok_content = token in low or any(
                zh_map[k] in zh for k in zh_map if k in content
            )
            if not ok_content:
                errors.append(f"{qid}: pot-with text missing content '{content}'")

        # image left/right hand (viewer coordinates)
        if (
            "left side of the image" in low
            or "左手" in zh
            or ("图像左侧" in zh and "手" in zh)
        ):
            lh = left_hand(tracks)
            if lh and tid != lh:
                errors.append(f"{qid}: image-left hand query -> {tid} but left track is {lh}")
            if "hand" not in cat and "arm" not in cat:
                errors.append(f"{qid}: image-left hand query but cat={cat}")
        if (
            "right side of the image" in low
            or "右手" in zh
            or ("图像右侧" in zh and "手" in zh)
        ):
            rh = right_hand(tracks)
            if rh and tid != rh:
                errors.append(f"{qid}: image-right hand query -> {tid} but right track is {rh}")

        # Primary referent = EN head NP after The/A (ignore relative clauses).
        # ZH is checked only for fused-pot / L-R above.
        m = re.match(
            r"^(?:The|A|An)\s+(.+?)(?:\s+while|\s+before|\s+after|\s+that|\s+who|\s+whose|\s+as\b|\s+at\b|\s+during|\s+when|\s+between|\s+\(|$)",
            en.strip(),
            re.I,
        )
        head = (m.group(1) if m else en[:50]).lower()
        head_rules = [
            (r"\bknife\b", ["knife"]),
            (r"\btongs\b", ["tongs"]),
            (r"\btorch\b", ["torch"]),
            (r"\blemons?\b", ["lemon"]),
            (r"\bcookie\b", ["cookie"]),
            (r"\bchocolate\b", ["chocolate"]),
            (r"glass cup", ["glass"]),
            (r"metal cup", ["metal cup"]),
            (r"martini", ["martini"]),
            (r"electronic scale", ["scale"]),
            (r"pot with", ["pot"]),
            (r"beef steak", ["beef", "steak"]),
            (r"\bchef\b|\bman\b", ["chef", "man", "apron"]),
            (r"\bhands?\b|bare arms", ["hand", "arm"]),
        ]
        hit = False
        for pat, reqs in head_rules:
            if re.search(pat, head, re.I):
                hit = True
                if not any(r in cat for r in reqs):
                    errors.append(
                        f"{qid}: EN head '{head}'~/{pat}/ but category '{cat}' lacks {reqs}"
                    )
                break
        if not hit:
            errors.append(f"{qid}: no EN-head rule matched: head={head!r} en={en}")

    # --- B ---
    if qtype == "B":
        if not tids:
            errors.append(f"{qid}: B empty targets")
        # except
        if "everything except" in low or ("除了" in zh and "之外" in zh):
            all_ids = set(tracks)
            excl = sorted(all_ids - set(tids))
            pairs = [
                (("dog", "狗"), ["dog"]),
                (("window", "窗"), ["window"]),
                (("green book", "书"), ["book"]),
                (("shutter", "百叶窗"), ["shutter"]),
                (("shirt", "衬衫"), ["shirt"]),
                (("wooden board", "木板"), ["wooden board", "board"]),
                (("white bottle", "白色瓶"), ["white bottle"]),
                (("metal cup", "金属杯"), ["metal cup"]),
                (("kitchen rolls", "厨房纸"), ["kitchen rolls", "kitchen roll"]),
                (("beef steak", "牛排"), ["beef steak"]),
                (("black kettle", "水壶"), ["kettle"]),
                (("wooden bowl", "木碗"), ["wooden bowl"]),
                (("spinach", "菠菜"), ["spinach"]),
                (("green bottle", "绿色瓶"), ["green bottle"]),
                (("hands", "手"), ["hand", "arm"]),
                (("bare arms", "手臂"), ["arm", "hand"]),
            ]
            for (ek, zk), kws in pairs:
                if ek == "hands":
                    mentioned = "except the hands" in low or (
                        "除了手" in zh and "手臂" not in zh
                    )
                elif ek == "bare arms":
                    mentioned = "bare arms" in low or "手臂" in zh
                elif ek == "wooden board":
                    if "on the wooden board except" in low:
                        # exclude board+hands from targets by design
                        for tid in list(tracks):
                            c = (tracks[tid]["category"] or "").lower()
                            if "board" in c or "hand" in c or "arm" in c:
                                if tid in tids:
                                    errors.append(
                                        f"{qid}: on-board-except-hands should not include {tid}"
                                    )
                        continue
                    mentioned = ek in low or zk in zh
                elif ek == "window":
                    # avoid matching 百叶窗 via 窗 alone — require window/窗户/玻璃窗
                    mentioned = (
                        "window" in low
                        or "玻璃窗" in zh
                        or "窗户" in zh
                        or ("窗" in zh and "百叶窗" not in zh)
                    )
                elif ek == "green bottle":
                    mentioned = "green bottle" in low or "绿色瓶" in zh
                elif ek == "beef steak":
                    mentioned = "beef steak" in low or (
                        "牛排" in zh and "除了" in zh
                    )
                else:
                    mentioned = ek in low or zk in zh
                if not mentioned:
                    continue
                excl_blob = " ".join(
                    (tracks[t]["category"] or "").lower() for t in excl
                )
                tgt_blob = " ".join(
                    (tracks[t]["category"] or "").lower() for t in tids
                )
                if not any(k in excl_blob for k in kws):
                    errors.append(
                        f"{qid}: except '{ek}' not in excluded [{excl_blob}]"
                    )
                if any(k in tgt_blob for k in kws):
                    if ek in ("hands", "bare arms"):
                        if any(
                            "hand" in (tracks[t]["category"] or "").lower()
                            or "arm" in (tracks[t]["category"] or "").lower()
                            for t in tids
                        ):
                            errors.append(f"{qid}: except hands/arms still in targets")
                    else:
                        errors.append(
                            f"{qid}: except '{ek}' still in targets [{tgt_blob}]"
                        )

        # static
        if any(
            p in low
            for p in (
                "never move",
                "motionless",
                "stationary",
                "completely still",
                "do not change position",
                "remain physically",
                "remain completely",
            )
        ) or ("静止" in zh and ("所有" in zh or "保持" in zh)):
            # intentional exclusions noted in query notes (cookie / martini glass)
            for t in tids:
                if t in tracks and not tracks[t].get("is_static", False):
                    errors.append(
                        f"{qid}: static query has non-static {t} ({tracks[t]['category']})"
                    )

        # both hands / bare arms
        if "both hands" in low or "both bare arms" in low or "两只手" in zh or "两只裸露手臂" in zh:
            if len(tids) < 2:
                errors.append(f"{qid}: both-hands expects >=2")
            if "arm" not in cat_blob and "hand" not in cat_blob:
                errors.append(f"{qid}: both-hands cats={cat_blob}")


def main():
    global ok_n
    all_q = {}
    for cfg in SCENES_CONFIG:
        qs, tracks = load_scene(cfg)
        print(f"=== {cfg['folder']} ({len(qs)} q, {len(tracks)} tracks) ===")
        for q in qs:
            before = len(errors)
            check_query(q, tracks)
            all_q[q["query_id"]] = q
            if len(errors) == before:
                ok_n += 1
                print(f"  OK {q['query_id']} [{q.get('query_type')}] {q.get('target_track_ids')}")
            else:
                print(f"  FAIL {q['query_id']}")

    # eval sync
    eval_q = {
        q["query_id"]: q
        for q in json.loads(
            (ROOT / "evaluation" / "R4D-Bench_queries.json").read_text(encoding="utf-8")
        )
    }
    eval_p = json.loads(
        (ROOT / "evaluation" / "R4D-Bench_predictions.json").read_text(encoding="utf-8")
    )
    for qid, q in all_q.items():
        a = list(q.get("target_track_ids") or [])
        eq = eval_q.get(qid)
        if not eq:
            errors.append(f"eval missing {qid}")
            continue
        if sorted(eq.get("target_track_ids") or []) != sorted(a):
            errors.append(f"eval ids {qid}")
        if sorted(eval_p.get(qid) or []) != sorted(a):
            errors.append(f"eval pred {qid}")
        if (eq.get("text_en") or "") != (q.get("text_en") or ""):
            errors.append(f"eval en {qid}: {eq.get('text_en')!r} vs {q.get('text_en')!r}")
        if (eq.get("text_zh") or "") != (q.get("text_zh") or ""):
            errors.append(f"eval zh {qid}")

    print(f"\nOK queries (local checks)={ok_n}/89")
    print(f"ERRORS={len(errors)}")
    for e in errors:
        print(" ", e)

    out = ROOT / "assets" / "gt_audit" / "complete_correctness.json"
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps({"errors": errors, "ok": ok_n}, ensure_ascii=False, indent=2), encoding="utf-8")
    return len(errors)


if __name__ == "__main__":
    sys.exit(main())