r4d-bench-qa / scripts /_derive_expected_targets.py
LiYacheng's picture
Fill unannotated_visible gaps: every query/frame has GT masks (part 24)
aa7e82c verified
Raw History Blame Contribute Delete
9.89 kB
"""Independently derive expected target_track_ids from query text + track catalog.
Compare to *_queries.json. Human-readable flags for mismatches / ambiguities.
"""
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 = []
warns = []
oks = []
def load(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 by_cat(tracks, *substrs):
out = []
for tid, t in tracks.items():
blob = (t["category"] or "").lower()
if any(s.lower() in blob for s in substrs):
out.append(tid)
return out
def static_ids(tracks):
return [tid for tid, t in tracks.items() if t.get("is_static")]
def hand_ids(tracks):
return by_cat(tracks, "hand", "arm")
def left_hand(tracks):
for tid, t in tracks.items():
zh = t.get("description_zh") or ""
en = (t.get("description_en") or "").lower()
cat = (t.get("category") or "").lower()
if "hand" not in cat and "arm" not in cat:
continue
if "左手" in zh or "左侧" in zh or re.search(r"\bleft\b", en):
return tid
return None
def right_hand(tracks):
for tid, t in tracks.items():
zh = t.get("description_zh") or ""
en = (t.get("description_en") or "").lower()
cat = (t.get("category") or "").lower()
if "hand" not in cat and "arm" not in cat:
continue
if "右手" in zh or "右侧" in zh or re.search(r"\bright\b", en):
return tid
return None
def expect_for(q, tracks):
"""Return (expected_ids or None if skip, note). None expected means cannot auto-derive."""
qtype = q.get("query_type")
en = q.get("text_en") or ""
zh = q.get("text_zh") or ""
low = en.lower()
all_ids = sorted(tracks.keys())
if qtype == "C":
return [], "distractor"
# except
if "everything except" in low or ("除了" in zh and "之外" in zh):
excl = set()
rules = [
(("dog", "狗"), ["dog"]),
(("glass window", "玻璃窗"), ["window"]),
(("green book", "绿色书"), ["green book", "book"]),
(("shutter", "百叶窗"), ["shutter"]),
(("shirt", "衬衫"), ["shirt"]),
(("wooden board", "木板"), ["wooden 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"]),
]
for (ek, zk), kws in rules:
hit = False
if ek == "hands":
hit = "except the hands" in low or "除了手" in zh
elif ek == "metal cup":
hit = ("metal cup" in low and "except" in low) or (
"金属杯" in zh and "除了" in zh
)
elif ek == "beef steak":
hit = "beef steak" in low or ("牛排" in zh and "除了" in zh)
elif ek == "wooden board":
# "on the wooden board except" — board is surface, not excluded object
if "on the wooden board" in low:
hit = False
else:
hit = ek in low or zk in zh
else:
hit = ek in low or zk in zh
if not hit:
continue
for tid, t in tracks.items():
cat = (t["category"] or "").lower()
if any(k in cat for k in kws):
excl.add(tid)
# keyboard special: on board except hands — also exclude board itself (not "on" board)
if "on the wooden board except" in low:
for tid in by_cat(tracks, "wooden board") + hand_ids(tracks):
excl.add(tid)
return sorted(set(all_ids) - excl), f"except excl={sorted(excl)}"
# motionless / static
if any(
p in low
for p in (
"never move",
"motionless",
"stationary",
"do not change position",
"remain completely still",
"remain physically",
"completely still",
"completely motionless",
"stay still",
)
) or ("静止" in zh and ("所有" in zh or "保持" in zh)):
# americano_q9: specific objects
if "coaster" in low or "杯垫" in zh:
ids = by_cat(tracks, "coaster") + by_cat(tracks, "tray")
return sorted(set(ids)), "coaster+tray still"
return sorted(static_ids(tracks)), "all static"
# left / right hand
if "left hand" in low or "左手" in zh:
lh = left_hand(tracks)
return ([lh] if lh else None), "left hand"
if "right hand" in low or "右手" in zh:
rh = right_hand(tracks)
return ([rh] if rh else None), "right hand"
# both hands
if "both hands" in low or "两只手" in zh:
return sorted(hand_ids(tracks)), "both hands"
# "The hands and the knife that are moving"
if "hands and the knife" in low or ("手和刀" in zh and "移动" in zh):
# moving hands + knife: non-static hands + knife
ids = [t for t in hand_ids(tracks) if not tracks[t].get("is_static")]
ids += by_cat(tracks, "knife")
return sorted(set(ids)), "moving hands+knife"
# all involved in cutting
if "involved in the cutting" in low or "参与切割" in zh:
ids = hand_ids(tracks) + by_cat(tracks, "knife", "lemon", "beef")
# exclude board
ids = [i for i in ids if "board" not in (tracks[i]["category"] or "").lower()]
return sorted(set(ids)), "cutting participants"
# single-object heuristics (type A)
mapping = [
(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"]),
(r"martini|马提尼", ["martini"]),
(r"metal cup|金属杯", ["metal cup"]),
(r"electronic scale|电子秤", ["scale", "Electronic"]),
(r"pot with beef steak|装有牛排的锅", ["Pot with beef steak"]),
(r"\bsalmon\b|三文鱼", ["salmon"]),
(r"beef steak before|牛排", ["beef steak"]),
(r"\bchef\b|厨师", ["chef"]),
(r"man who|man wearing|穿围裙的人", ["man", "chef", "apron"]),
(r"hands that are pouring|倾倒咖啡的手", ["hand"]),
(r"coaster|杯垫", ["coaster"]),
(r"tray|托盘", ["tray"]),
]
for pat, kws in mapping:
if re.search(pat, en, re.I) or re.search(pat, zh):
# avoid matching secondary nouns: prefer primary subject
# "pot with beef" before "beef steak"
ids = []
for tid, t in tracks.items():
cat = t["category"] or ""
if any(k.lower() in cat.lower() for k in kws):
ids.append(tid)
if ids:
# if multiple and query is singular type A, take best
if q.get("query_type") == "A" and len(ids) > 1:
# prefer exact-ish
return [ids[0]], f"heuristic {pat} (multi={ids})"
return sorted(ids), f"heuristic {pat}"
return None, "no_rule"
def main():
for cfg in SCENES_CONFIG:
qs, tracks = load(cfg)
print(f"\n=== {cfg['folder']} ===")
for q in qs:
qid = q["query_id"]
actual = list(q.get("target_track_ids") or [])
exp, note = expect_for(q, tracks)
if exp is None:
warns.append((qid, note, actual))
print(f" ? {qid}: cannot derive ({note}) actual={actual}")
continue
if sorted(actual) != sorted(exp):
errors.append((qid, note, actual, exp))
print(f" ERR {qid}: {note}")
print(f" actual={actual}")
print(f" expect={exp}")
# categories
print(
f" actual_cats={[tracks[t]['category'] for t in actual if t in tracks]}"
)
print(
f" expect_cats={[tracks[t]['category'] for t in exp if t in tracks]}"
)
else:
oks.append(qid)
print(f" OK {qid}: {note}")
print(f"\nOK={len(oks)} ERR={len(errors)} WARN={len(warns)}")
for e in errors:
print("ERR", e[0], e[1])
out = ROOT / "assets" / "gt_audit" / "expected_vs_actual.json"
out.write_text(
json.dumps({"ok": oks, "errors": errors, "warns": warns}, ensure_ascii=False, indent=2),
encoding="utf-8",
)
if __name__ == "__main__":
main()