r4d-bench-qa / scripts /_audit_all_query_semantics_v2.py
LiYacheng's picture
Fill unannotated_visible gaps: every query/frame has GT masks (part 24)
aa7e82c verified
Raw History Blame Contribute Delete
13.5 kB
"""Full audit: every query's target_track_ids vs category / except / static / L-R cues.
Also diffs scene queries.json ↔ evaluation/R4D-Bench_queries.json ↔
evaluation/R4D-Bench_predictions.json.
"""
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 # noqa: E402
errors: list[str] = []
warnings: list[str] = []
def load_queries(path: Path):
data = json.loads(path.read_text(encoding="utf-8"))
if isinstance(data, dict):
data = data.get("queries", data)
return data
def tracks_map(cfg):
scene = ROOT / "data" / "scenes" / cfg["folder"]
tracks = json.loads((scene / cfg["track_file"]).read_text(encoding="utf-8"))["tracks"]
return {t["track_id"]: t for t in tracks}
def cat_blob(tracks, tids):
return " | ".join(
f"{t}:{(tracks[t]['category'] if t in tracks else 'MISSING')}" for t in tids
)
def must_have_kw(qid, tids, tracks, kws, where="targets"):
blob = " ".join(
(tracks[t]["category"] if t in tracks else "").lower() for t in tids
)
if not any(k.lower() in blob for k in kws):
errors.append(f"{qid}: {where} lack {kws}; got [{cat_blob(tracks, tids)}]")
def must_lack_kw(qid, tids, tracks, kws, where="targets"):
blob = " ".join(
(tracks[t]["category"] if t in tracks else "").lower() for t in tids
)
for k in kws:
if k.lower() in blob:
errors.append(
f"{qid}: {where} still contain '{k}'; got [{cat_blob(tracks, tids)}]"
)
def audit_one(q, tracks, all_ids):
qid = q["query_id"]
tids = list(q.get("target_track_ids") or [])
en = q.get("text_en") or ""
zh = q.get("text_zh") or ""
low = en.lower()
qtype = q.get("query_type")
for t in tids:
if t not in tracks:
errors.append(f"{qid}: unknown track_id {t}")
if qtype == "C":
if tids:
errors.append(f"{qid}: type C nonempty targets {tids}")
return
if qtype in ("A", "B") and not tids:
errors.append(f"{qid}: type {qtype} empty targets")
# EXCEPT
if "everything except" in low or ("除了" in zh and "之外" in zh):
excl = sorted(all_ids - set(tids))
pairs = [
(("dog", "狗"), ["dog"]),
(("glass window", "玻璃窗"), ["window"]),
(("green book", "绿色书"), ["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", "bowl"]),
(("spinach", "菠菜"), ["spinach"]),
(("green bottle", "绿色瓶"), ["green bottle"]),
(("hands", "手"), ["hand", "arm"]),
]
for (en_k, zh_k), kws in pairs:
mentioned = en_k in low or zh_k in zh
# "hands" alone in except — careful with "except the hands and the metal cup"
if en_k == "hands":
mentioned = ("except the hands" in low) or ("除了手" in zh)
if en_k == "beef steak":
mentioned = "beef steak" in low or ("牛排" in zh and "除了" in zh)
if en_k == "metal cup":
mentioned = ("metal cup" in low and "except" in low) or (
"金属杯" in zh and "除了" in zh
)
if not mentioned:
continue
# excluded set must contain keyword; targets must not
excl_blob = " ".join(
(tracks[t]["category"] if t in tracks else "").lower() for t in excl
)
tgt_blob = " ".join(
(tracks[t]["category"] if t in tracks else "").lower() for t in tids
)
if not any(k in excl_blob for k in kws):
# wooden board exception: "on the wooden board except hands" may exclude board from targets by phrasing
if en_k == "wooden board" and "on the wooden board" in low:
# keyboard_q6 style — board is surface, not necessarily excluded as object
continue
errors.append(
f"{qid}: except-clause '{en_k}' not in excluded set "
f"[{cat_blob(tracks, excl)}]"
)
if any(k in tgt_blob for k in kws):
# "hands" substring in "bare hands" etc.
if en_k == "hands" and 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 but hand still in targets "
f"[{cat_blob(tracks, tids)}]"
)
elif en_k != "hands":
errors.append(
f"{qid}: except '{en_k}' still in targets "
f"[{cat_blob(tracks, tids)}]"
)
return
# STATIC / MOTIONLESS
static_phrases = (
"never move",
"motionless",
"stationary",
"do not change position",
"remain completely still",
"remain physically",
"completely still",
"completely motionless",
"stay still",
)
if any(p in low for p in static_phrases) or ("静止" in zh and ("所有" in zh or "保持" in zh)):
for t in tids:
if t in tracks and not tracks[t].get("is_static", False):
errors.append(
f"{qid}: static-query includes non-static {t} "
f"({tracks[t]['category']})"
)
return
# LEFT / RIGHT HAND — check track description side labels if present
if "left hand" in low or "左手" in zh:
if len(tids) != 1:
errors.append(f"{qid}: left-hand expects 1 id, got {tids}")
else:
t = tracks.get(tids[0], {})
zh_d = str(t.get("description_zh") or "")
en_d = str(t.get("description_en") or "").lower()
if "右手" in zh_d or re.search(r"\bright\b", en_d):
errors.append(
f"{qid}: left-hand query points to right-labeled track {tids[0]} "
f"zh={zh_d!r} en={en_d!r}"
)
cat = (t.get("category") or "").lower()
if "hand" not in cat and "arm" not in cat:
errors.append(f"{qid}: left-hand target not hand/arm: {t.get('category')}")
return
if "right hand" in low or "右手" in zh:
if len(tids) != 1:
errors.append(f"{qid}: right-hand expects 1 id, got {tids}")
else:
t = tracks.get(tids[0], {})
zh_d = str(t.get("description_zh") or "")
en_d = str(t.get("description_en") or "").lower()
if "左手" in zh_d or re.search(r"\bleft\b", en_d):
errors.append(
f"{qid}: right-hand query points to left-labeled track {tids[0]} "
f"zh={zh_d!r} en={en_d!r}"
)
cat = (t.get("category") or "").lower()
if "hand" not in cat and "arm" not in cat:
errors.append(f"{qid}: right-hand target not hand/arm: {t.get('category')}")
return
# BOTH HANDS
if "both hands" in low or "两只手" in zh:
if len(tids) < 2:
errors.append(f"{qid}: both-hands expects >=2, got {tids}")
must_have_kw(qid, tids, tracks, ["hand", "arm"])
return
# Type-A object keyword checks
if qtype != "A" or not tids:
return
rules = [
(r"\bknife\b|刀", ["knife"]),
(r"\blemons?\b|柠檬", ["lemon"]),
(r"\btongs\b|夹子", ["tongs"]),
(r"\btorch\b|喷枪", ["torch"]),
(r"\bchocolate\b|巧克力", ["chocolate"]),
(r"\bcookie\b|曲奇", ["cookie"]),
(r"glass cup|玻璃杯", ["glass cup", "glass"]),
(r"martini|马提尼", ["martini"]),
(r"metal cup|金属杯", ["metal cup"]),
(r"electronic scale|电子秤", ["scale"]),
(r"pot with beef steak|装有牛排的锅", ["pot with beef steak"]),
(r"\bsalmon\b|三文鱼", ["salmon"]),
(r"beef steak|牛排", ["beef", "steak", "pot"]),
(r"\bchef\b|厨师|man who|man wearing", ["chef", "man", "apron"]),
(r"hands that are pouring|倾倒咖啡的手", ["hand"]),
(r"coaster|杯垫", ["coaster"]),
(r"wooden tray|木质托盘", ["tray"]),
(r"\btray\b that stay", ["tray"]),
(r"liquid in the glass|液体", ["glass"]),
(r"spinach", ["spinach"]),
]
blob = " ".join((tracks[t]["category"] if t in tracks else "").lower() for t in tids)
hit = False
for pat, kws in rules:
if re.search(pat, en, re.I) or re.search(pat, zh):
hit = True
if not any(k in blob for k in kws):
errors.append(
f"{qid}: text~/{pat}/ but categories lack {kws}: [{cat_blob(tracks, tids)}]"
)
break
if not hit:
# hands pouring etc.
if "hand" in low or "手" in zh:
if "hand" not in blob and "arm" not in blob:
warnings.append(f"{qid}: hand-ish text but cats=[{cat_blob(tracks, tids)}]")
else:
warnings.append(f"{qid}: no A-rule matched: {en[:70]}")
def sync_eval():
"""Compare scene queries vs evaluation JSON files."""
eval_q_path = ROOT / "evaluation" / "R4D-Bench_queries.json"
eval_p_path = ROOT / "evaluation" / "R4D-Bench_predictions.json"
eval_qs = {q["query_id"]: q for q in load_queries(eval_q_path)}
eval_pred = json.loads(eval_p_path.read_text(encoding="utf-8"))
scene_qs = {}
for cfg in SCENES_CONFIG:
scene = ROOT / "data" / "scenes" / cfg["folder"]
for q in load_queries(scene / cfg["query_file"]):
scene_qs[q["query_id"]] = q
print(f"scene queries: {len(scene_qs)} eval queries: {len(eval_qs)} pred keys: {len(eval_pred)}")
only_scene = sorted(set(scene_qs) - set(eval_qs))
only_eval = sorted(set(eval_qs) - set(scene_qs))
if only_scene:
warnings.append(f"in scene not eval: {only_scene}")
if only_eval:
warnings.append(f"in eval not scene: {only_eval}")
for qid, sq in sorted(scene_qs.items()):
eq = eval_qs.get(qid)
if not eq:
continue
s_ids = list(sq.get("target_track_ids") or [])
e_ids = list(eq.get("target_track_ids") or [])
if s_ids != e_ids:
errors.append(
f"SYNC eval_queries {qid}: scene={s_ids} vs eval={e_ids}"
)
p_ids = list(eval_pred.get(qid, []))
if s_ids != p_ids:
errors.append(
f"SYNC eval_predictions {qid}: scene={s_ids} vs pred={p_ids}"
)
# text sync
if (sq.get("text_en") or "") != (eq.get("text_en") or ""):
warnings.append(f"SYNC text_en differs {qid}")
if (sq.get("text_zh") or "") != (eq.get("text_zh") or ""):
warnings.append(f"SYNC text_zh differs {qid}")
def main():
sync_eval()
n = 0
for cfg in SCENES_CONFIG:
tracks = tracks_map(cfg)
all_ids = set(tracks)
scene = ROOT / "data" / "scenes" / cfg["folder"]
qs = load_queries(scene / cfg["query_file"])
print(f"\n=== {cfg['folder']} ({len(qs)} queries, {len(tracks)} tracks) ===")
for tid, t in sorted(tracks.items()):
print(
f" {tid}: {t['category']} static={t.get('is_static')} "
f"zh={(t.get('description_zh') or '')[:40]}"
)
for q in qs:
n += 1
audit_one(q, tracks, all_ids)
# print compact
tids = q.get("target_track_ids") or []
print(
f" {q['query_id']} [{q.get('query_type')}] "
f"{cat_blob(tracks, tids) if tids else '(empty)'} | {q.get('text_en','')[:60]}"
)
print(f"\n========== Audited {n} scene queries ==========")
print(f"ERRORS ({len(errors)}):")
for e in errors:
print(" ERR", e)
print(f"WARNINGS ({len(warnings)}):")
for w in warnings:
print(" WARN", w)
out = ROOT / "assets" / "gt_audit" / "semantics_v2_report.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(
json.dumps({"errors": errors, "warnings": warnings}, ensure_ascii=False, indent=2),
encoding="utf-8",
)
print(f"Wrote {out}")
if __name__ == "__main__":
main()