"""Final lockdown: every query target_track_ids vs tracks + query text intent. Outputs a per-query verdict sheet. No GT regeneration here — IDs only. """ 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 OUT = ROOT / "assets" / "gt_audit" / "final_id_lockdown" OUT.mkdir(parents=True, exist_ok=True) # Manual expected answers derived from query semantics (author intent). # If a query is listed here, actual MUST match exactly. # Format: query_id -> list of track_ids (or [] for C) # Built by reading every query + track file carefully. MANUAL_EXPECT: dict[str, list[str] | None] = {} # filled below after load def load_all(): data = {} for cfg in SCENES_CONFIG: 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"] data[cfg["folder"]] = {"cfg": cfg, "tracks": tracks, "queries": qs} return data def all_ids(tracks): return sorted(tracks.keys()) def cats(tracks, tids): return [(t, tracks[t]["category"] if t in tracks else "MISSING") for t in tids] def static_ids(tracks): return sorted(t for t, tr in tracks.items() if tr.get("is_static")) def find_by_cat(tracks, *needles): out = [] for tid, tr in tracks.items(): c = (tr["category"] or "").lower() if any(n.lower() in c for n in needles): out.append(tid) return out def left_hand_id(tracks): for tid, tr in tracks.items(): c = (tr["category"] or "").lower() if "hand" not in c and "arm" not in c: continue zh = tr.get("description_zh") or "" en = (tr.get("description_en") or "").lower() if "左手" in zh or "左侧" in zh or re.search(r"\bleft\b", en): return tid return None def right_hand_id(tracks): for tid, tr in tracks.items(): c = (tr["category"] or "").lower() if "hand" not in c and "arm" not in c: continue zh = tr.get("description_zh") or "" en = (tr.get("description_en") or "").lower() if "右手" in zh or "右侧" in zh or re.search(r"\bright\b", en): return tid return None def hand_ids(tracks): return find_by_cat(tracks, "hand", "arm") def except_targets(tracks, excl_needles): excl = set() for tid, tr in tracks.items(): c = (tr["category"] or "").lower() zh = (tr.get("description_zh") or "").lower() blob = c + " " + zh if any(n.lower() in blob or n.lower() in c for n in excl_needles): excl.add(tid) return sorted(set(all_ids(tracks)) - excl) def build_expected(folder, q, tracks): """Return expected target list or raise ValueError if cannot decide.""" qid = q["query_id"] qtype = q.get("query_type") en = q.get("text_en") or "" zh = q.get("text_zh") or "" low = en.lower() if qtype == "C": return [] # --- cut_lemon --- if qid == "cut_lemon_q1": return find_by_cat(tracks, "knife") if qid == "cut_lemon_q2": return find_by_cat(tracks, "lemon") if qid == "cut_lemon_q3": return [left_hand_id(tracks)] if qid == "cut_lemon_q4": return sorted( set(hand_ids(tracks) + find_by_cat(tracks, "knife", "lemon")) ) if qid == "cut_lemon_q5": # note: right hand static-hold excluded return sorted([left_hand_id(tracks)] + find_by_cat(tracks, "knife")) if qid == "cut_lemon_q6": return except_targets(tracks, ["wooden board"]) # --- espresso --- if qid in ("espresso_q1", "espresso_q2", "espresso_q3"): return find_by_cat(tracks, "glass cup") if qid == "espresso_q4": return static_ids(tracks) if qid == "espresso_q7": return find_by_cat(tracks, "scale", "Electronic") if qid == "espresso_q8": return except_targets(tracks, ["white bottle", "metal cup"]) # --- keyboard --- if qid == "keyboard_q1": return [left_hand_id(tracks)] if qid == "keyboard_q2": return sorted(hand_ids(tracks)) if qid == "keyboard_q3": return static_ids(tracks) if qid == "keyboard_q6": # on wooden board except hands — exclude board + hands return except_targets(tracks, ["hand", "arm", "wooden board"]) # --- torchchocolate --- if qid in ("torchchocolate_q1", "torchchocolate_q7"): return find_by_cat(tracks, "chocolate") if qid == "torchchocolate_q2": return sorted(hand_ids(tracks)) if qid == "torchchocolate_q3": return static_ids(tracks) if qid == "torchchocolate_q6": return except_targets(tracks, ["shirt", "wooden board"]) # --- cook-spinach --- if qid == "cook-spinach_q1": return find_by_cat(tracks, "tongs") if qid == "cook-spinach_q2": return [left_hand_id(tracks)] if qid == "cook-spinach_q3": return [right_hand_id(tracks)] if qid == "cook-spinach_q4": return static_ids(tracks) if qid == "cook-spinach_q7": return except_targets(tracks, ["beef steak", "kitchen rolls"]) # --- cut_roasted_beef --- if qid == "cut_roasted_beef_q1": return find_by_cat(tracks, "knife") if qid == "cut_roasted_beef_q2": return find_by_cat(tracks, "beef steak") if qid == "cut_roasted_beef_q3": return [left_hand_id(tracks)] if qid == "cut_roasted_beef_q4": return static_ids(tracks) if qid == "cut_roasted_beef_q7": return except_targets(tracks, ["dog", "window"]) # --- flame_salmon --- if qid == "flame_salmon_q1": return find_by_cat(tracks, "torch") if qid == "flame_salmon_q2": return find_by_cat(tracks, "salmon") if qid == "flame_salmon_q3": return [left_hand_id(tracks)] if qid == "flame_salmon_q4": return static_ids(tracks) if qid == "flame_salmon_q7": return except_targets(tracks, ["green book", "window"]) # --- sear_steak --- if qid == "sear_steak_q1": return find_by_cat(tracks, "tongs") if qid == "sear_steak_q2": # CRITICAL: pot with beef steak (治同 issue) return find_by_cat(tracks, "Pot with beef steak") if qid == "sear_steak_q3": return [left_hand_id(tracks)] if qid == "sear_steak_q4": return static_ids(tracks) if qid == "sear_steak_q7": return except_targets(tracks, ["green book", "shutter"]) # --- split_cookie --- if qid in ("split_cookie_q1", "split_cookie_q2", "split_cookie_q6"): return find_by_cat(tracks, "cookie") if qid == "split_cookie_q3": return sorted(hand_ids(tracks)) if qid == "split_cookie_q4": # note: cookie excluded (state change) — board + tablecloth only return sorted( find_by_cat(tracks, "Square Wooden Board", "board") + find_by_cat(tracks, "tablecloth") ) if qid == "split_cookie_q7": return except_targets(tracks, ["hand", "arm"]) # --- americano --- if qid in ("americano_q1", "americano_q2", "americano_q10"): return find_by_cat(tracks, "glass cup") if qid == "americano_q3": return find_by_cat(tracks, "hand") if qid == "americano_q4": return find_by_cat(tracks, "metal cup") if qid == "americano_q5": return static_ids(tracks) if qid == "americano_q6": return except_targets(tracks, ["hand", "metal cup"]) if qid == "americano_q9": return sorted(find_by_cat(tracks, "coaster") + find_by_cat(tracks, "tray")) # --- coffee_martini --- if qid == "coffee_martini_q1": return find_by_cat(tracks, "martini") if qid == "coffee_martini_q2": return find_by_cat(tracks, "metal cup") if qid == "coffee_martini_q3": return find_by_cat(tracks, "man", "chef", "apron") if qid == "coffee_martini_q4": # note: exclude martini glass (state change) despite is_static return sorted( find_by_cat(tracks, "Kettle") + find_by_cat(tracks, "shutter") + find_by_cat(tracks, "wooden bowl") ) if qid == "coffee_martini_q7": return except_targets(tracks, ["kettle", "wooden bowl"]) # --- flame_steak --- if qid == "flame_steak_q1": return find_by_cat(tracks, "torch") if qid == "flame_steak_q2": return [left_hand_id(tracks)] if qid == "flame_steak_q3": return find_by_cat(tracks, "chef") if qid == "flame_steak_q4": return static_ids(tracks) if qid == "flame_steak_q7": return except_targets(tracks, ["spinach", "green bottle"]) raise ValueError(f"No expected rule for {qid}: {en}") def text_object_traps(q, tracks, actual): """Flag dangerous text↔object mismatches like 治同's sear_steak case.""" flags = [] en = q.get("text_en") or "" zh = q.get("text_zh") or "" low = en.lower() actual_cats = " ".join( (tracks[t]["category"] if t in tracks else "") for t in actual ).lower() # steak text but pot GT without saying pot if ("steak" in low or "牛排" in zh) and "pot" in actual_cats: if "pot" not in low and "锅" not in zh: flags.append( "TRAP: text says steak/牛排 but targets are Pot — text must mention pot/锅" ) # tongs in text as main object vs wrong cat if q.get("query_type") == "A" and actual: # primary noun checks for classic traps if re.search(r"^The tongs\b", en) or en.startswith("The tongs"): if "tongs" not in actual_cats: flags.append("TRAP: tongs query but targets not tongs") if re.search(r"^The knife\b", en) or "正在切割" in zh and "刀" in zh: if "knife" in low or "刀" in zh: if q["query_id"].endswith("_q1") or "knife" in low: if "knife" not in actual_cats and "刀" in zh: if "knife" not in actual_cats: flags.append("TRAP: knife query but not knife") if "torch" in low[:40] or (zh.startswith("正在") and "喷枪" in zh): if "torch" in low and "torch" not in actual_cats and "喷枪" in zh: # only if torch is the subject if low.startswith("the torch") or zh.startswith("正在") and "喷枪" in zh[:10]: if "torch" not in actual_cats: flags.append("TRAP: torch subject but not torch target") return flags def main(): data = load_all() rows = [] errors = [] traps = [] type_counts = {"A": 0, "B": 0, "C": 0} for folder, pack in data.items(): tracks = pack["tracks"] for q in pack["queries"]: qid = q["query_id"] qtype = q.get("query_type") or "?" type_counts[qtype] = type_counts.get(qtype, 0) + 1 actual = list(q.get("target_track_ids") or []) # missing tracks for t in actual: if t not in tracks: errors.append(f"{qid}: unknown track {t}") try: expected = build_expected(folder, q, tracks) except ValueError as e: errors.append(str(e)) expected = None # normalize None in expected if expected is not None: expected = [e for e in expected if e is not None] if sorted(actual) != sorted(expected): errors.append( f"{qid}: actual={actual} expected={expected} " f"actual_cats={cats(tracks, actual)} " f"expected_cats={cats(tracks, expected)}" ) # type cardinality if qtype == "C" and actual: errors.append(f"{qid}: type C must be empty, got {actual}") if qtype == "A" and len(actual) != 1 and expected is not None: # A is usually single; allow only if expected says so if len(expected) == 1 and len(actual) != 1: errors.append(f"{qid}: type A should be single target") if qtype == "B" and len(actual) < 2 and expected is not None and len(expected) >= 2: errors.append(f"{qid}: type B multi expected") # 治同-style traps for f in text_object_traps(q, tracks, actual): traps.append(f"{qid}: {f}") # target_count field tc = q.get("target_count") if tc is not None and tc != len(actual): errors.append(f"{qid}: target_count={tc} != len(ids)={len(actual)}") rows.append( { "query_id": qid, "scene": folder, "query_type": qtype, "n_targets": len(actual), "text_en": q.get("text_en"), "text_zh": q.get("text_zh"), "actual": actual, "actual_cats": [c for _, c in cats(tracks, actual)], "expected": expected, "match": expected is not None and sorted(actual) == sorted(expected), "note": q.get("note"), } ) # 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 folder, pack in data.items(): for q in pack["queries"]: qid = q["query_id"] a = list(q.get("target_track_ids") or []) if qid not in eval_q: errors.append(f"eval queries missing {qid}") elif sorted(eval_q[qid].get("target_track_ids") or []) != sorted(a): errors.append(f"eval queries mismatch {qid}") if sorted(eval_p.get(qid) or []) != sorted(a): errors.append(f"eval predictions mismatch {qid}") # text sync for sear_steak_q2 especially if qid in eval_q: if (eval_q[qid].get("text_en") or "") != (q.get("text_en") or ""): errors.append(f"eval text_en mismatch {qid}") if (eval_q[qid].get("text_zh") or "") != (q.get("text_zh") or ""): errors.append(f"eval text_zh mismatch {qid}") # print sheet lines = ["# Final ID lockdown\n", f"types={type_counts} total={len(rows)}\n"] for r in rows: mark = "OK" if r["match"] else "FAIL" lines.append( f"- **{mark}** `{r['query_id']}` [{r['query_type']}] n={r['n_targets']} " f"| {r['actual_cats']} | {r['text_en'][:70]}" ) lines.append(f"\n## ERRORS ({len(errors)})\n") for e in errors: lines.append(f"- {e}") lines.append(f"\n## TEXT↔OBJECT TRAPS ({len(traps)})\n") for t in traps: lines.append(f"- {t}") (OUT / "report.md").write_text("\n".join(lines), encoding="utf-8") (OUT / "report.json").write_text( json.dumps( {"rows": rows, "errors": errors, "traps": traps, "type_counts": type_counts}, ensure_ascii=False, indent=2, ), encoding="utf-8", ) print(f"types={type_counts} queries={len(rows)}") print(f"ERRORS={len(errors)}") for e in errors: print(" ERR", e) print(f"TRAPS={len(traps)}") for t in traps: print(" TRAP", t) mismatches = [r for r in rows if not r["match"]] print(f"ID mismatches={len(mismatches)}") for r in mismatches: print(" MISMATCH", r["query_id"], "actual", r["actual"], "expected", r["expected"]) if __name__ == "__main__": main()