Datasets:
File size: 76,172 Bytes
b8ea052 | 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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 | """Object presence, zone, and preservation checkers.
The checker consumes precomputed detector evidence from observations. Model
execution stays outside the scorer so DINO/SAM/API backends can change without
changing case scoring semantics.
"""
from __future__ import annotations
import base64
import zlib
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
from PIL import Image
from pvr_eval.checkers.base import CheckerContext
from pvr_eval.core.schema import AtomicCheckSpec, CheckResult
from pvr_eval.core.scoring import clamp01, score_to_status
BBox = list[float]
CHECK_ID_DEFAULT_ZONE_REFS = {
"tool_tip_target_alignment": "auto_container_opening",
"white_container_unmoved": "auto_container_body",
"constraint_violation_outside_slots": "basketball_gray_slots",
}
def _bbox_area(box: BBox) -> float:
return max(0.0, box[2] - box[0]) * max(0.0, box[3] - box[1])
def _bbox_center(box: BBox) -> tuple[float, float]:
return (box[0] + box[2]) / 2.0, (box[1] + box[3]) / 2.0
def _bbox_mask(shape: tuple[int, int], box: BBox) -> np.ndarray:
h, w = shape
mask = np.zeros((h, w), dtype=bool)
x0 = max(0, min(w, int(round(box[0]))))
y0 = max(0, min(h, int(round(box[1]))))
x1 = max(0, min(w, int(round(box[2]))))
y1 = max(0, min(h, int(round(box[3]))))
if x1 > x0 and y1 > y0:
mask[y0:y1, x0:x1] = True
return mask
def _intersection_area(a: BBox, b: BBox) -> float:
x0, y0 = max(a[0], b[0]), max(a[1], b[1])
x1, y1 = min(a[2], b[2]), min(a[3], b[3])
return max(0.0, x1 - x0) * max(0.0, y1 - y0)
def _bbox_iou(a: BBox, b: BBox) -> float:
inter = _intersection_area(a, b)
union = _bbox_area(a) + _bbox_area(b) - inter
return 0.0 if union <= 0 else inter / union
def _containment(inner: BBox, outer: BBox) -> float:
area = _bbox_area(inner)
return 0.0 if area <= 0 else _intersection_area(inner, outer) / area
def _point_in_box(point: tuple[float, float], box: BBox) -> bool:
return box[0] <= point[0] <= box[2] and box[1] <= point[1] <= box[3]
def _label_matches(label: str, labels: list[str]) -> bool:
text = label.lower().strip()
return any(candidate.lower().strip() in text or text in candidate.lower().strip() for candidate in labels if candidate)
def _labels_from_params(params: dict[str, Any]) -> list[str]:
labels = [str(item) for item in params.get("labels", []) if str(item).strip()]
raw_objects = params.get("objects") or params.get("forbidden_objects") or params.get("entities")
if not labels:
if isinstance(raw_objects, str):
labels.extend([item.strip() for item in raw_objects.split("|") if item.strip()])
elif isinstance(raw_objects, (list, tuple, set)):
labels.extend([str(item).replace("_", " ").strip() for item in raw_objects if str(item).strip()])
expected_color = str(params.get("expected_color", "")).strip()
expected_object = str(params.get("object", "")).replace("_", " ").strip()
if expected_color:
labels.extend([f"{expected_color} car", expected_color])
if expected_object:
labels.append(expected_object)
return _expand_label_aliases(labels)
def _expand_label_aliases(labels: list[str]) -> list[str]:
"""Add conservative detector-query aliases for common PVR entities."""
out: list[str] = []
for label in labels:
text = str(label).strip()
if not text:
continue
out.append(text)
low = text.lower()
if "pvc" in low and "pipe" in low:
out.extend(["PVC pipe", "gray PVC pipe", "plastic pipe", "pipe", "pipes", "gray pipes", "construction pipes", "cylindrical pipes", "gray tubes"])
elif "pipe" in low:
out.extend(["pipe", "pipes", "cylindrical pipes", "tube", "tubes"])
if "yellow" in low and ("wire" in low or "cable" in low):
out.extend(["yellow wire", "yellow cable", "yellow electrical wire", "thin yellow wire", "jumper wire"])
deduped: list[str] = []
seen: set[str] = set()
for item in out:
key = item.lower().strip()
if key and key not in seen:
seen.add(key)
deduped.append(item)
return deduped
def _vlm_item_for_check(context: CheckerContext, check_id: str, params: dict[str, Any]) -> dict[str, Any] | None:
raw = context.observations.get(str(params.get("vlm_key", "vlm_checks")), [])
if isinstance(raw, dict):
raw = raw.get("items", [])
if not isinstance(raw, list):
return None
matches = [item for item in raw if isinstance(item, dict) and str(item.get("check_id", "")) == check_id]
return matches[-1] if matches else None
def _vlm_score_for_role(item: dict[str, Any], role: str) -> float:
status = str(item.get("status", "uncertain")).lower()
try:
numeric_score = clamp01(float(item.get("score")))
except Exception:
numeric_score = None
if role == "penalty":
if status == "pass":
return 0.0
if status == "partial":
return numeric_score if numeric_score not in {None, 0.0, 1.0} else 0.5
if status == "fail":
return numeric_score if numeric_score not in {None, 0.0} else 1.0
return 0.0
if numeric_score is not None:
return numeric_score
return 1.0 if status == "pass" else 0.5 if status == "partial" else 0.0
def _normalize_color_name(color: str) -> str:
color = color.lower().strip()
return "gray" if color == "grey" else color
def _color_query_matches(expected_color: str, text: str) -> bool:
expected = _normalize_color_name(expected_color)
normalized = text.lower().replace("grey", "gray")
return bool(expected and expected in normalized)
def _parse_bbox(raw: Any) -> BBox | None:
if isinstance(raw, (list, tuple)) and len(raw) == 4:
try:
return [float(value) for value in raw]
except Exception:
return None
if isinstance(raw, str):
try:
values = [float(value) for value in raw.split(",")]
except Exception:
return None
return values if len(values) == 4 else None
return None
def _normalize_detection(item: dict[str, Any]) -> dict[str, Any] | None:
bbox = _parse_bbox(item.get("bbox") or item.get("bbox_xyxy"))
if bbox is None:
return None
try:
score = float(item.get("score", 0.0))
except Exception:
score = 0.0
backend = str(item.get("backend") or item.get("detector_backend") or item.get("source_backend") or "")
source = str(item.get("source") or item.get("source_image") or "")
try:
rank = int(float(item.get("rank", 0)))
except Exception:
rank = 0
return {
"label": str(item.get("label", "")),
"query_text": str(item.get("query_text", "")),
"score": score,
"bbox": bbox,
"bbox_xyxy": [round(value, 1) for value in bbox],
"center": [round(value, 1) for value in _bbox_center(bbox)],
"source": source,
"source_image": source,
"backend": backend,
"detector_backend": backend,
"rank": rank,
"raw": {key: value for key, value in item.items() if key not in {"bbox", "bbox_xyxy"}},
}
def _detections_from_observations(context: CheckerContext, key: str, check_id: str | None = None) -> list[dict[str, Any]]:
raw = None
if check_id:
scoped = context.observations.get("detections_by_check", {})
if isinstance(scoped, dict):
check_bucket = scoped.get(check_id)
if isinstance(check_bucket, dict):
role = "input" if key.startswith("input") else "pred"
if role in check_bucket:
raw = check_bucket.get(role, [])
if raw is None:
raw = context.observations.get(key, [])
if isinstance(raw, dict):
raw = raw.get("items", [])
if not isinstance(raw, list):
return []
out = []
for item in raw:
if isinstance(item, dict):
det = _normalize_detection(item)
if det is not None:
out.append(det)
return out
def _values_from_param(params: dict[str, Any], singular: str, plural: str) -> set[str]:
raw = params.get(plural)
if raw is None:
raw = params.get(singular)
if raw is None or raw == "":
return set()
if isinstance(raw, str):
return {item.strip().lower() for item in raw.split("|") if item.strip()}
if isinstance(raw, (list, tuple, set)):
return {str(item).strip().lower() for item in raw if str(item).strip()}
return {str(raw).strip().lower()}
def _filter_detections_by_params(
detections: list[dict[str, Any]],
params: dict[str, Any],
*,
default_source: str | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Filter detector candidates by provenance requested in a contract.
This keeps model evidence composable: a single observations file may hold
GroundingDINO, YOLO-World, and other detector rows, while each atomic check
can choose the source it considers reliable.
"""
backends = _values_from_param(params, "detector_backend", "detector_backends")
sources = _values_from_param(params, "source_image", "source_images")
if not sources and default_source and bool(params.get("use_default_source_filter", False)):
sources = {default_source.lower()}
before = len(detections)
out = []
for det in detections:
backend = str(det.get("backend") or det.get("detector_backend") or "").lower()
source = str(det.get("source_image") or det.get("source") or "").lower()
if backends and backend not in backends:
continue
if sources and source not in sources:
continue
out.append(det)
return out, {
"detector_backend_filter": sorted(backends),
"source_image_filter": sorted(sources),
"detection_count_before_filter": before,
"detection_count_after_filter": len(out),
}
def _decode_mask(encoded: dict[str, Any] | None) -> np.ndarray | None:
if not encoded:
return None
try:
h, w = [int(value) for value in encoded.get("shape", [])]
raw = zlib.decompress(base64.b64decode(str(encoded.get("packbits_zlib_b64", ""))))
flat = np.unpackbits(np.frombuffer(raw, dtype=np.uint8))[: h * w]
return flat.reshape((h, w)).astype(bool)
except Exception:
return None
def _sam_items_from_observations(context: CheckerContext, key: str = "sam_masks", check_id: str | None = None) -> list[dict[str, Any]]:
raw = None
if check_id:
scoped = context.observations.get("sam_masks_by_check", {})
if isinstance(scoped, dict):
check_bucket = scoped.get(check_id)
if isinstance(check_bucket, dict):
role = "input" if key.startswith("input") else "pred"
if role in check_bucket:
raw = check_bucket.get(role, [])
if raw is None:
raw = context.observations.get(key, [])
if isinstance(raw, dict):
raw = raw.get("items", [])
if not isinstance(raw, list):
return []
items = []
for item in raw:
if not isinstance(item, dict):
continue
bbox = _parse_bbox(item.get("bbox") or item.get("dino_bbox") or item.get("bbox_xyxy"))
if bbox is None:
continue
decoded = _decode_mask(item.get("encoded_mask") if isinstance(item.get("encoded_mask"), dict) else None)
items.append({**item, "bbox": bbox, "decoded_mask": decoded})
return items
def _match_sam_for_detection(det: dict[str, Any], masks: list[dict[str, Any]], min_iou: float = 0.35) -> dict[str, Any] | None:
best = None
best_iou = 0.0
for item in masks:
iou = _bbox_iou(det["bbox"], item["bbox"])
if iou > best_iou:
best = item
best_iou = iou
if best is None or best_iou < min_iou:
return None
return {**best, "dino_sam_bbox_iou": best_iou}
def _sam_is_usable(sam: dict[str, Any] | None, *, min_match_iou: float = 0.5, require_encoded_mask: bool = True) -> bool:
if not sam:
return False
if require_encoded_mask and sam.get("decoded_mask") is None:
return False
try:
iou = float(sam.get("matched_iou", sam.get("dino_sam_bbox_iou", 0.0)))
except Exception:
iou = 0.0
return iou >= min_match_iou
def _mask_containment(mask: np.ndarray | None, zone: BBox) -> float | None:
if mask is None:
return None
total = int(mask.sum())
if total <= 0:
return None
h, w = mask.shape
x0 = max(0, min(w, int(round(zone[0]))))
y0 = max(0, min(h, int(round(zone[1]))))
x1 = max(0, min(w, int(round(zone[2]))))
y1 = max(0, min(h, int(round(zone[3]))))
if x1 <= x0 or y1 <= y0:
return 0.0
return float(mask[y0:y1, x0:x1].sum()) / float(total)
def _matched_detections(detections: list[dict[str, Any]], labels: list[str], min_score: float) -> list[dict[str, Any]]:
return [
det
for det in detections
if det["score"] >= min_score
and (_label_matches(det["label"], labels) or _label_matches(det.get("query_text", ""), labels))
]
def _expand_box(box: BBox, pad: float, width: int | None, height: int | None) -> BBox:
x0, y0, x1, y1 = box[0] - pad, box[1] - pad, box[2] + pad, box[3] + pad
if width is not None:
x0, x1 = max(0.0, x0), min(float(width), x1)
if height is not None:
y0, y1 = max(0.0, y0), min(float(height), y1)
return [x0, y0, x1, y1]
def _zone_rect(zone: Any, width: int | None, height: int | None) -> BBox | None:
if isinstance(zone, dict):
if {"x0", "y0", "x1", "y1"} <= set(zone):
vals = [float(zone["x0"]), float(zone["y0"]), float(zone["x1"]), float(zone["y1"])]
elif "bbox" in zone:
vals = _parse_bbox(zone["bbox"])
if vals is None:
return None
elif "rect" in zone:
vals = _parse_bbox(zone["rect"])
if vals is None:
return None
elif "points" in zone and isinstance(zone.get("points"), list):
points = []
for point in zone.get("points", []):
if isinstance(point, (list, tuple)) and len(point) == 2:
try:
points.append((float(point[0]), float(point[1])))
except Exception:
continue
if not points:
return None
xs = [point[0] for point in points]
ys = [point[1] for point in points]
vals = [min(xs), min(ys), max(xs), max(ys)]
else:
return None
else:
vals = _parse_bbox(zone)
if vals is None:
return None
if max(abs(v) for v in vals) <= 1.0 and width and height:
return [vals[0] * width, vals[1] * height, vals[2] * width, vals[3] * height]
return vals
def _image_size(context: CheckerContext) -> tuple[int | None, int | None]:
evidence = context.quality if hasattr(context, "quality") else None
_ = evidence
size = context.observations.get("image_size") or context.observations.get("pred_image_size")
if isinstance(size, dict):
width = size.get("width")
height = size.get("height")
if isinstance(width, int) and isinstance(height, int):
return width, height
try:
with Image.open(context.pred_image) as image:
return image.size
except Exception:
pass
return None, None
def _zones_from_context_or_params(context: CheckerContext, params: dict[str, Any], check_id: str = "") -> Any:
zones = params.get("zones") or params.get("target_zones")
slots = _requested_zone_refs_from_params(params)
resolved: dict[str, Any] = {}
if isinstance(zones, dict):
resolved.update({key: value for key, value in zones.items() if isinstance(value, dict)})
elif isinstance(zones, list):
for index, value in enumerate(zones):
if isinstance(value, dict):
resolved[str(value.get("id") or value.get("zone_id") or index)] = value
if slots and isinstance(context.contract.zones, dict):
for slot in slots:
zone_value = context.contract.zones.get(str(slot))
if zone_value and not (isinstance(zone_value, str) and zone_value.startswith("TODO")):
resolved[str(slot)] = zone_value
zone_observations = context.observations.get("zones")
if slots and isinstance(zone_observations, dict):
for slot in slots:
zone_value = zone_observations.get(str(slot))
if zone_value:
resolved[str(slot)] = zone_value
if slots and isinstance(zone_observations, list):
for zone in zone_observations:
if not isinstance(zone, dict):
continue
zone_id = str(zone.get("zone_id", ""))
if zone_id in slots:
resolved[zone_id] = zone
scoped = context.observations.get("zones_by_check", {})
if check_id and isinstance(scoped, dict) and isinstance(scoped.get(check_id), dict):
resolved.update(scoped[check_id])
zone_annotations = _zones_from_manual_annotation(context)
if slots and zone_annotations:
for slot in slots:
zone_value = zone_annotations.get(str(slot))
if zone_value:
resolved[str(slot)] = zone_value
if slots:
requested = {str(slot): resolved[str(slot)] for slot in slots if str(slot) in resolved}
if requested:
return requested
if resolved:
return resolved
return zones
def _requested_zone_reference(params: dict[str, Any]) -> str:
refs = _requested_zone_refs_from_params(params)
return refs[0] if refs else ""
def _requested_zone_refs_from_params(params: dict[str, Any]) -> list[str]:
slot = (
params.get("slot")
or params.get("target_region")
or params.get("target_zone")
or params.get("forbidden_zone")
or params.get("forbidden_zones")
or params.get("source_zone")
or params.get("zone")
)
refs: list[str] = []
if isinstance(slot, str) and slot.strip():
refs.append(slot.strip())
elif isinstance(slot, (list, tuple, set)):
refs.extend(str(item).strip() for item in slot if str(item).strip())
for key, value in params.items():
if not str(key).startswith("zone_"):
continue
if isinstance(value, str) and value.strip():
refs.append(value.strip())
out: list[str] = []
seen: set[str] = set()
for ref in refs:
if ref in seen:
continue
seen.add(ref)
out.append(ref)
return out
def _zone_params_with_check_defaults(spec: AtomicCheckSpec, params: dict[str, Any]) -> dict[str, Any]:
out = dict(params)
if spec.check_id == "constraint_violation_outside_slots":
out.setdefault("relation", "count_outside_min")
out.setdefault("min_count", 1)
if _requested_zone_refs_from_params(out):
return out
default_zone = CHECK_ID_DEFAULT_ZONE_REFS.get(spec.check_id)
if not default_zone:
return out
if spec.check_id == "constraint_violation_outside_slots":
return {**out, "target_zone": default_zone}
return {**out, "target_zone": default_zone}
def _available_zone_ids(context: CheckerContext) -> list[str]:
ids: set[str] = set()
if isinstance(context.contract.zones, dict):
ids.update(str(key) for key in context.contract.zones)
zones = context.observations.get("zones")
if isinstance(zones, dict):
ids.update(str(key) for key in zones)
annotations = context.observations.get("zone_annotations")
if isinstance(annotations, dict):
ids.update(str(key) for key in annotations)
return sorted(ids)
def _zone_resolution_failure_reason(context: CheckerContext, params: dict[str, Any]) -> dict[str, Any]:
"""Classify why a zone-like reference could not be resolved.
Human-drawn zones are only needed for semantic regions that are hard to
infer. Structured layouts such as shelves, boards, baskets, medicine boxes,
and parking slots should be handled by parser/resolver checkers. Reporting
all of those as ``missing_zones`` incorrectly asks the annotation workflow
to solve a checker-routing problem.
"""
task_family = str(getattr(context.contract, "task_family", "") or "").lower()
zone_keys = set(_available_zone_ids(context))
requested = _requested_zone_reference(params)
has_todo_structured_zone = any(
key in zone_keys
for key in {
"slot_polygons",
"target_object_zone_mapping",
"target_symbol_regions",
"protected_text_regions",
"endpoint_zones",
"expected_region_states",
}
)
has_route_geometry = any(
key in zone_keys
for key in {
"start_zone_polygon",
"end_zone_polygon",
"required_waypoint_polygons",
"forbidden_region_polygons",
}
)
structured_terms = (
"slot",
"grid",
"shelf",
"basket",
"organizer",
"compartment",
"cell",
"cubby",
"parking",
"board",
"ocr",
)
route_terms = ("route", "path", "trail")
if has_route_geometry or any(term in task_family for term in route_terms):
reason = "missing_route_geometry_resolver"
elif has_todo_structured_zone or any(term in task_family for term in structured_terms):
reason = "missing_structured_slot_resolver"
else:
reason = "missing_concrete_zone"
return {
"reason": reason,
"requested_zone": requested,
"available_zone_ids": sorted(zone_keys),
"task_family": task_family,
"annotation_semantics": (
"manual zones are for hard semantic regions; structured slots/grids should be generated by parser/resolver"
),
}
def _zones_from_manual_annotation(context: CheckerContext) -> dict[str, Any]:
"""Return zone annotations supplied as observations or copied contract data."""
zones = context.observations.get("zones")
if isinstance(zones, dict):
return zones
raw = context.observations.get("zone_annotations")
if isinstance(raw, dict):
return raw
return {}
def _zones_from_contract_or_manual(context: CheckerContext) -> dict[str, Any]:
zones = _zones_from_manual_annotation(context)
if zones:
return zones
return context.contract.zones if isinstance(context.contract.zones, dict) else {}
def _public_sam(sam: dict[str, Any] | None) -> dict[str, Any] | None:
if not sam:
return None
return {
"mask_backend": sam.get("mask_backend", ""),
"mask_bbox": sam.get("mask_bbox"),
"mask_area": sam.get("mask_area"),
"sam_score": sam.get("sam_score"),
"dino_sam_bbox_iou": round(float(sam.get("dino_sam_bbox_iou", 0.0)), 6),
"matched_iou": sam.get("matched_iou"),
"fastsam_box": sam.get("fastsam_box"),
}
def _read_rgb(path: Path) -> np.ndarray | None:
try:
return np.asarray(Image.open(path).convert("RGB"))
except Exception:
return None
def _rgb_to_hsv_np(rgb: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
arr = rgb.astype(np.float32) / 255.0
r, g, b = arr[..., 0], arr[..., 1], arr[..., 2]
mx = np.max(arr, axis=2)
mn = np.min(arr, axis=2)
diff = mx - mn
h = np.zeros_like(mx)
mask = diff > 1e-6
rmax = mask & (mx == r)
gmax = mask & (mx == g)
bmax = mask & (mx == b)
h[rmax] = ((g[rmax] - b[rmax]) / diff[rmax]) % 6
h[gmax] = ((b[gmax] - r[gmax]) / diff[gmax]) + 2
h[bmax] = ((r[bmax] - g[bmax]) / diff[bmax]) + 4
h = h * 30.0
s = np.zeros_like(mx)
nonzero = mx > 1e-6
s[nonzero] = diff[nonzero] / mx[nonzero] * 255.0
v = mx * 255.0
return h, s, v
def _hsv_between(h: np.ndarray, s: np.ndarray, v: np.ndarray, lo: tuple[int, int, int], hi: tuple[int, int, int]) -> np.ndarray:
return (h >= lo[0]) & (h <= hi[0]) & (s >= lo[1]) & (s <= hi[1]) & (v >= lo[2]) & (v <= hi[2])
def _color_mask(rgb: np.ndarray, color: str) -> np.ndarray:
h, s, v = _rgb_to_hsv_np(rgb)
color = color.lower().strip()
if color == "blue":
return _hsv_between(h, s, v, (88, 45, 35), (130, 255, 255))
if color == "green":
return _hsv_between(h, s, v, (36, 35, 35), (86, 255, 255))
if color == "yellow":
return _hsv_between(h, s, v, (17, 50, 50), (38, 255, 255))
if color in {"gray", "grey"}:
return _hsv_between(h, s, v, (0, 0, 45), (180, 55, 190))
if color == "cyan":
return _hsv_between(h, s, v, (78, 35, 35), (100, 255, 255))
return np.zeros(rgb.shape[:2], dtype=bool)
def _mask_area(mask: np.ndarray | None, fallback_box: BBox | None = None) -> float:
if mask is not None:
return float(mask.sum())
if fallback_box is not None:
return _bbox_area(fallback_box)
return 0.0
def _dedupe_vehicle_candidates(candidates: list[dict[str, Any]], min_iou: float) -> list[dict[str, Any]]:
"""Collapse overlapping DINO phrases that refer to the same visual vehicle."""
deduped: list[dict[str, Any]] = []
for item in candidates:
bbox = item.get("_bbox")
if not isinstance(bbox, list):
deduped.append(item)
continue
duplicate = False
for kept in deduped:
kept_bbox = kept.get("_bbox")
if isinstance(kept_bbox, list) and _bbox_iou(bbox, kept_bbox) >= min_iou:
duplicate = True
break
if not duplicate:
deduped.append(item)
return deduped
def _vehicle_color_candidates(
context: CheckerContext,
*,
expected_color: str,
min_score: float,
min_area: float,
min_color_ratio: float,
detections_key: str = "detections",
sam_key: str = "sam_masks",
labels: list[str] | None = None,
params: dict[str, Any] | None = None,
check_id: str | None = None,
) -> list[dict[str, Any]]:
rgb = _read_rgb(context.pred_image)
if rgb is None:
return []
color_mask = _color_mask(rgb, expected_color)
detections = _detections_from_observations(context, detections_key, check_id)
detections, _ = _filter_detections_by_params(detections, params or {}, default_source="pred")
sam_items = _sam_items_from_observations(context, sam_key, check_id)
min_sam_match_iou = float((params or {}).get("min_sam_match_iou", (params or {}).get("min_dino_sam_iou", 0.5)))
labels = labels or [f"{expected_color} car", expected_color, "car", "vehicle"]
candidates = []
for det in detections:
if det["score"] < min_score or not _label_matches(det["label"], labels):
continue
sam = _match_sam_for_detection(det, sam_items, min_iou=0.35)
usable_sam = _sam_is_usable(sam, min_match_iou=min_sam_match_iou)
det_mask = sam.get("decoded_mask") if usable_sam and sam and sam.get("decoded_mask") is not None else _bbox_mask(rgb.shape[:2], det["bbox"])
area = _mask_area(det_mask, det["bbox"])
color_pixels = int((det_mask & color_mask).sum()) if det_mask is not None else 0
color_ratio = float(color_pixels / area) if area > 0 else 0.0
is_vehicle_like = area >= min_area and color_ratio >= min_color_ratio
color_query_match = _color_query_matches(expected_color, f"{det.get('label', '')} {det.get('query_text', '')}")
candidates.append(
{
**_public_det(det),
"area_px": round(area, 1),
"expected_color": expected_color,
"color_pixels": color_pixels,
"color_ratio": round(color_ratio, 6),
"color_query_match": color_query_match,
"is_vehicle_like": is_vehicle_like,
"sam": _public_sam(sam),
"sam_usable": usable_sam,
"sam_min_match_iou": min_sam_match_iou,
"mask_source": "sam" if usable_sam else "bbox_fallback",
"_bbox": det["bbox"],
"_mask": det_mask,
}
)
candidates.sort(key=lambda item: (item["is_vehicle_like"], item["color_query_match"], item["area_px"], item["color_ratio"]), reverse=True)
return _dedupe_vehicle_candidates(candidates, min_iou=0.55)
def _public_det(det: dict[str, Any]) -> dict[str, Any]:
return {
"label": det["label"],
"query_text": det.get("query_text", ""),
"score": round(float(det["score"]), 4),
"bbox_xyxy": det["bbox_xyxy"],
"center": det["center"],
"backend": det.get("backend", ""),
"source_image": det.get("source_image") or det.get("source", ""),
"rank": det.get("rank", 0),
}
def _make_result(spec: AtomicCheckSpec, *, score: float, confidence: float, checker: str, evidence: dict[str, Any]) -> CheckResult:
score = clamp01(score)
status = score_to_status(score)
if spec.role == "penalty":
status = "triggered" if score >= 0.85 else "partial_trigger" if score >= 0.35 else "clean"
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=checker,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status=status,
score=score,
confidence=clamp01(confidence),
evidence=evidence,
)
def _make_uncertain_result(spec: AtomicCheckSpec, *, checker: str, evidence: dict[str, Any]) -> CheckResult:
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=checker,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status="uncertain",
score=0.0,
confidence=0.0,
evidence=evidence,
)
@dataclass
class ObjectPresenceChecker:
"""Check output object presence by detector labels/counts."""
name: str = "object_presence_checker"
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
params = _zone_params_with_check_defaults(spec, dict(spec.params))
labels = _labels_from_params(params)
if not labels:
return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={"reason": "missing_labels"})
min_score = float(params.get("min_score", 0.0))
min_count = int(params.get("min_count", params.get("min_output_count", 1)))
detections = _detections_from_observations(context, str(params.get("detections_key", "detections")), spec.check_id)
detections, provenance = _filter_detections_by_params(detections, params, default_source="pred")
hits = _matched_detections(detections, labels, min_score)
score = 1.0 if len(hits) >= min_count else 0.5 if hits else 0.0
return _make_result(
spec,
score=score,
confidence=float(params.get("confidence", 0.75)),
checker=self.name,
evidence={
"labels": labels,
"min_score": min_score,
"min_count": min_count,
"matched_count": len(hits),
"matched": [_public_det(det) for det in hits[:12]],
"detection_count": len(detections),
**provenance,
},
)
@dataclass
class ObjectZoneChecker:
"""Check detected objects inside/outside target or forbidden zones."""
name: str = "object_zone_checker"
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
params = _zone_params_with_check_defaults(spec, dict(spec.params))
labels = _labels_from_params(params)
if not labels:
return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={"reason": "missing_labels"})
zones = _zones_from_context_or_params(context, params, spec.check_id)
if not zones:
if "source_vacated" in spec.check_id or "source_empty" in spec.check_id:
return SourceVacatedChecker(name=self.name).run(context, spec)
failure = _zone_resolution_failure_reason(context, params)
if failure.get("reason") == "missing_structured_slot_resolver" and bool(params.get("allow_vlm_fallback", True)):
vlm_item = _vlm_item_for_check(context, spec.check_id, params)
if vlm_item is not None:
return _make_result(
spec,
score=_vlm_score_for_role(vlm_item, spec.role),
confidence=float(vlm_item.get("confidence", 0.55) or 0.0),
checker=f"{self.name}:vlm_fallback",
evidence={
**failure,
"reason": "structured_slot_resolver_vlm_fallback",
"vlm_status": vlm_item.get("status", ""),
"vlm_score": vlm_item.get("score"),
"vlm_answer": vlm_item.get("answer", ""),
"vlm_evidence": vlm_item.get("evidence", ""),
"fallback_policy": "Structured spatial relation is not yet parser-resolved; used saved targeted VLM evidence for this atomic check.",
},
)
return _make_result(
spec,
score=0.0,
confidence=0.0,
checker=self.name,
evidence=failure,
)
min_score = float(params.get("min_score", 0.0))
min_count = int(params.get("min_count", 1))
relation = str(params.get("relation", "inside_any"))
min_bbox_containment = float(params.get("min_bbox_containment", 0.15))
min_mask_containment = float(params.get("min_mask_containment", min_bbox_containment))
width, height = _image_size(context)
image_area = float(width * height) if width and height else 0.0
max_area_fraction = params.get("max_area_fraction")
max_area_fraction = float(max_area_fraction) if max_area_fraction is not None else None
min_aspect_ratio = params.get("min_aspect_ratio")
min_aspect_ratio = float(min_aspect_ratio) if min_aspect_ratio is not None else None
max_aspect_ratio = params.get("max_aspect_ratio")
max_aspect_ratio = float(max_aspect_ratio) if max_aspect_ratio is not None else None
zone_items = zones.items() if isinstance(zones, dict) else [(f"zone_{idx}", zone) for idx, zone in enumerate(zones)]
zone_rects = []
for zone_id, zone in zone_items:
components = zone.get("components", []) if isinstance(zone, dict) else []
component_items = components if isinstance(components, list) and components else [zone]
for component_index, component in enumerate(component_items):
rect = _zone_rect(component, width, height)
if rect is None:
continue
component_id = str(zone_id) if len(component_items) == 1 else f"{zone_id}::component_{component_index + 1:02d}"
zone_rect = {"id": component_id, "parent_region_id": str(zone_id), "bbox": rect}
if isinstance(component, dict):
for key in (
"zone_type", "auto_resolver", "confidence", "source", "source_image", "call_id",
"proposal_call_id", "query_text", "score", "backend", "supporting_backends",
):
if key in component:
zone_rect[key] = component[key]
zone_rects.append(zone_rect)
detections = _detections_from_observations(context, str(params.get("detections_key", "detections")), spec.check_id)
detections, provenance = _filter_detections_by_params(detections, params, default_source="pred")
sam_items = _sam_items_from_observations(context, str(params.get("sam_key", "sam_masks")), spec.check_id)
hits = _matched_detections(detections, labels, min_score)
matched_for_relation = 0
evaluated = []
rejected = []
for det in hits:
bbox_area = _bbox_area(det["bbox"])
bbox_w = max(1e-6, det["bbox"][2] - det["bbox"][0])
bbox_h = max(1e-6, det["bbox"][3] - det["bbox"][1])
aspect_ratio = bbox_w / bbox_h
area_fraction = bbox_area / image_area if image_area > 0 else None
reject_reasons = []
if max_area_fraction is not None and area_fraction is not None and area_fraction > max_area_fraction:
reject_reasons.append("bbox_too_large")
if min_aspect_ratio is not None and aspect_ratio < min_aspect_ratio:
reject_reasons.append("aspect_ratio_too_low")
if max_aspect_ratio is not None and aspect_ratio > max_aspect_ratio:
reject_reasons.append("aspect_ratio_too_high")
if reject_reasons:
rejected.append(
{
**_public_det(det),
"bbox_area": round(bbox_area, 1),
"area_fraction": round(area_fraction, 6) if area_fraction is not None else None,
"aspect_ratio": round(aspect_ratio, 6),
"reject_reasons": reject_reasons,
}
)
continue
sam = _match_sam_for_detection(det, sam_items, min_iou=float(params.get("min_dino_sam_iou", 0.35)))
zone_hits = []
inside_any = False
for zone in zone_rects:
bbox_containment = _containment(det["bbox"], zone["bbox"])
m_containment = _mask_containment(sam.get("decoded_mask"), zone["bbox"]) if sam else None
containment = m_containment if m_containment is not None else bbox_containment
center_inside = _point_in_box(_bbox_center(det["bbox"]), zone["bbox"])
threshold = min_mask_containment if m_containment is not None else min_bbox_containment
ok = center_inside or containment >= threshold
inside_any = inside_any or ok
zone_hits.append(
{
"zone_id": zone["id"],
"center_inside": center_inside,
"bbox_containment": round(bbox_containment, 6),
"mask_containment": round(m_containment, 6) if m_containment is not None else None,
"containment_used": round(containment, 6),
"threshold_used": threshold,
"mask_backend": sam.get("mask_backend", "missing") if sam else "missing",
"ok": ok,
}
)
if relation in {"inside_any", "count_inside_min", "overlap_any"} and inside_any:
matched_for_relation += 1
elif relation == "count_outside_min" and not inside_any:
matched_for_relation += 1
evaluated.append(
{
**_public_det(det),
"bbox_area": round(bbox_area, 1),
"area_fraction": round(area_fraction, 6) if area_fraction is not None else None,
"aspect_ratio": round(aspect_ratio, 6),
"zone_hits": zone_hits,
"sam": _public_sam(sam),
}
)
if relation == "must_exist":
score = 1.0 if len(hits) >= min_count else 0.5 if hits else 0.0
else:
score = 1.0 if matched_for_relation >= min_count else 0.5 if matched_for_relation > 0 else 0.0
return _make_result(
spec,
score=score,
confidence=float(params.get("confidence", 0.72)),
checker=self.name,
evidence={
"relation": relation,
"labels": labels,
"min_score": min_score,
"min_count": min_count,
"min_bbox_containment": min_bbox_containment,
"min_mask_containment": min_mask_containment,
"max_area_fraction": max_area_fraction,
"min_aspect_ratio": min_aspect_ratio,
"max_aspect_ratio": max_aspect_ratio,
"matched_count": len(hits),
"matched_count_for_relation": matched_for_relation,
"zones": [
{
"id": zone["id"],
"bbox_xyxy": [round(value, 1) for value in zone["bbox"]],
**{key: zone[key] for key in ("zone_type", "auto_resolver", "confidence") if key in zone},
}
for zone in zone_rects
],
"matched": evaluated[:12],
"rejected": rejected[:12],
"sam_mask_count": len(sam_items),
"image_size": {"width": width, "height": height},
**provenance,
},
)
@dataclass
class ObjectDistanceChecker:
"""Check whether two detected objects are close enough in the output."""
name: str = "distance_checker"
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
params = dict(spec.params)
subject_labels = _labels_from_params(
{
"labels": params.get("subject_labels")
or params.get("object_labels")
or ([params.get("object")] if params.get("object") else []),
}
)
reference_labels = _labels_from_params(
{
"labels": params.get("reference_labels")
or params.get("reference_object_labels")
or ([params.get("reference_object") or params.get("reference")] if params.get("reference_object") or params.get("reference") else []),
}
)
if not subject_labels or not reference_labels:
labels = _labels_from_params(params)
subject_labels = subject_labels or labels[:1]
reference_labels = reference_labels or labels[1:2]
if not subject_labels or not reference_labels:
return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={"reason": "missing_subject_or_reference_labels"})
min_score = float(params.get("min_score", 0.0))
detections = _detections_from_observations(context, str(params.get("detections_key", "detections")), spec.check_id)
detections, provenance = _filter_detections_by_params(detections, params, default_source="pred")
subjects = _matched_detections(detections, subject_labels, min_score)
references = _matched_detections(detections, reference_labels, min_score)
width, height = _image_size(context)
diag = float(((width or 1) ** 2 + (height or 1) ** 2) ** 0.5)
pass_dist = float(params.get("pass_max_edge_distance_px", params.get("pass_max_center_distance_px", diag * 0.22)))
partial_dist = float(params.get("partial_max_edge_distance_px", params.get("partial_max_center_distance_px", pass_dist * 1.75)))
metric = str(params.get("distance_metric", "edge")).lower()
pairs = []
best_dist = float("inf")
best_pair = None
for sub in subjects:
for ref in references:
if metric == "center":
sx, sy = _bbox_center(sub["bbox"])
rx, ry = _bbox_center(ref["bbox"])
dist = ((sx - rx) ** 2 + (sy - ry) ** 2) ** 0.5
else:
dx = max(ref["bbox"][0] - sub["bbox"][2], sub["bbox"][0] - ref["bbox"][2], 0.0)
dy = max(ref["bbox"][1] - sub["bbox"][3], sub["bbox"][1] - ref["bbox"][3], 0.0)
dist = (dx * dx + dy * dy) ** 0.5
pair = {"subject": _public_det(sub), "reference": _public_det(ref), "distance_px": round(dist, 3)}
pairs.append(pair)
if dist < best_dist:
best_dist = dist
best_pair = pair
if not subjects or not references:
score = 0.0
reason = "subject_or_reference_not_detected"
else:
score = 1.0 if best_dist <= pass_dist else 0.5 if best_dist <= partial_dist else 0.0
reason = "distance_evaluated"
return _make_result(
spec,
score=score,
confidence=float(params.get("confidence", 0.72 if subjects and references else 0.25)),
checker=self.name,
evidence={
"reason": reason,
"subject_labels": subject_labels,
"reference_labels": reference_labels,
"min_score": min_score,
"distance_metric": metric,
"pass_max_distance_px": round(pass_dist, 3),
"partial_max_distance_px": round(partial_dist, 3),
"best_distance_px": None if best_pair is None else best_pair["distance_px"],
"best_pair": best_pair,
"subject_count": len(subjects),
"reference_count": len(references),
"pairs": pairs[:12],
**provenance,
},
)
@dataclass
class SourceVacatedChecker:
"""Check that an object/text disappeared from its original source area.
This fills the common slot/shelf pattern where the source location can be
inferred from input OCR/detections rather than manually annotated.
"""
name: str = "source_vacated_checker"
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
params = dict(spec.params)
terms = [str(item).strip() for item in params.get("ocr_terms", []) if str(item).strip()]
if not terms:
labels = _labels_from_params(params)
terms = [item for item in labels if item]
source_rect = self._source_rect_from_ocr(context, terms, params, spec.check_id)
if source_rect is None:
source_rect = self._source_rect_from_input_detection(context, params, spec.check_id)
if source_rect is None:
return _make_result(
spec,
score=0.0,
confidence=0.0,
checker=self.name,
evidence={"reason": "source_region_not_inferred", "terms": terms, "labels": _labels_from_params(params)},
)
pred_ocr_hits = self._ocr_hits_in_rect(context, source_rect, terms, spec.check_id)
output_hits = self._output_detection_hits_in_rect(context, source_rect, params, spec.check_id)
min_clear = int(params.get("max_allowed_hits", 0))
remaining = len(pred_ocr_hits) + len(output_hits)
score = 1.0 if remaining <= min_clear else 0.5 if remaining <= int(params.get("partial_max_allowed_hits", 1)) else 0.0
return _make_result(
spec,
score=score,
confidence=float(params.get("confidence", 0.68)),
checker=self.name,
evidence={
"source_rect_xyxy": [round(v, 1) for v in source_rect],
"terms": terms,
"remaining_hit_count": remaining,
"max_allowed_hits": min_clear,
"pred_ocr_hits": pred_ocr_hits[:12],
"output_detection_hits": output_hits[:12],
},
)
@staticmethod
def _ocr_items(context: CheckerContext, check_id: str | None = None, role: str = "pred") -> list[dict[str, Any]]:
if check_id:
scoped = context.observations.get("ocr_by_check", {})
if isinstance(scoped, dict):
bucket = scoped.get(check_id)
if isinstance(bucket, dict) and isinstance(bucket.get(role), list):
return [item for item in bucket[role] if isinstance(item, dict)]
raw = context.observations.get("input_ocr" if role == "input" else "ocr", {})
if isinstance(raw, dict):
raw = raw.get("items", [])
return [item for item in raw if isinstance(item, dict)] if isinstance(raw, list) else []
@staticmethod
def _ocr_text(item: dict[str, Any]) -> str:
return str(item.get("text") or "").strip()
def _source_rect_from_ocr(self, context: CheckerContext, terms: list[str], params: dict[str, Any], check_id: str) -> BBox | None:
items = self._ocr_items(context, check_id, "input")
if not items:
return None
norm_terms = [_normalize_term(term) for term in terms]
matches = []
for item in items:
text = _normalize_term(self._ocr_text(item))
if not text:
continue
if any(term and (term in text or text in term) for term in norm_terms):
bbox = _parse_ocr_bbox(item)
if bbox is not None:
matches.append({"text": self._ocr_text(item), "bbox": bbox})
if not matches:
# Shelf case: HDX is more reliable than full brand phrase.
for item in items:
text = _normalize_term(self._ocr_text(item))
if any(token in text for token in ("hdx", "essolub")):
bbox = _parse_ocr_bbox(item)
if bbox is not None:
matches.append({"text": self._ocr_text(item), "bbox": bbox})
if not matches:
return None
# Use the rightmost matching label for source-vacated shelf cases.
match = max(matches, key=lambda item: (item["bbox"][0] + item["bbox"][2]) / 2.0)
box = match["bbox"]
width, height = _image_size(context)
pad_x = float(params.get("source_pad_x_px", 95.0))
pad_y = float(params.get("source_pad_y_px", 90.0))
return _expand_box(box, max(pad_x, pad_y), width, height)
def _source_rect_from_input_detection(self, context: CheckerContext, params: dict[str, Any], check_id: str) -> BBox | None:
labels = _labels_from_params(params)
detections = _detections_from_observations(context, str(params.get("input_detections_key", "input_detections")), check_id)
detections, _ = _filter_detections_by_params(detections, params, default_source="input")
hits = _matched_detections(detections, labels, float(params.get("min_score", 0.0)))
if not hits:
return None
box = max(hits, key=lambda det: det["score"])["bbox"]
width, height = _image_size(context)
return _expand_box(box, float(params.get("source_pad_px", 24.0)), width, height)
def _ocr_hits_in_rect(self, context: CheckerContext, rect: BBox, terms: list[str], check_id: str) -> list[dict[str, Any]]:
out = []
norm_terms = [_normalize_term(term) for term in terms] + ["hdx", "essolub"]
for item in self._ocr_items(context, check_id, "pred"):
bbox = _parse_ocr_bbox(item)
if bbox is None or _intersection_area(bbox, rect) <= 0:
continue
text = _normalize_term(self._ocr_text(item))
if any(term and (term in text or text in term) for term in norm_terms):
out.append({"text": self._ocr_text(item), "bbox_xyxy": [round(v, 1) for v in bbox]})
return out
def _output_detection_hits_in_rect(self, context: CheckerContext, rect: BBox, params: dict[str, Any], check_id: str) -> list[dict[str, Any]]:
labels = _labels_from_params(params)
if not labels:
return []
detections = _detections_from_observations(context, str(params.get("detections_key", "detections")), check_id)
detections, _ = _filter_detections_by_params(detections, params, default_source="pred")
hits = _matched_detections(detections, labels, float(params.get("min_score", 0.0)))
return [_public_det(det) for det in hits if _intersection_area(det["bbox"], rect) > 0]
def _normalize_term(text: str) -> str:
return "".join(ch for ch in text.lower() if ch.isalnum())
def _parse_ocr_bbox(item: dict[str, Any]) -> BBox | None:
raw = item.get("box") or item.get("bbox") or item.get("bbox_xyxy")
if isinstance(raw, list) and raw and isinstance(raw[0], list):
xs = []
ys = []
for point in raw:
if isinstance(point, (list, tuple)) and len(point) >= 2:
try:
xs.append(float(point[0]))
ys.append(float(point[1]))
except Exception:
continue
return [min(xs), min(ys), max(xs), max(ys)] if xs and ys else None
return _parse_bbox(raw)
@dataclass
class VehicleSlotChecker:
"""Check colored vehicle assignment with DINO candidates plus color evidence.
This is deliberately stricter than generic object-zone matching. Parking
cases often contain colored icons or markings that DINO may label as
``green car``. A candidate only passes when it is large enough, overlaps
the target slot, and has enough expected-color pixels within its mask/box.
"""
name: str = "vehicle_slot_checker"
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
params = dict(spec.params)
expected_color = str(params.get("expected_color", "")).strip().lower()
slot = str(params.get("slot", "")).strip()
if not expected_color:
return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={"reason": "missing_expected_color"})
if not slot:
return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={"reason": "missing_slot"})
zones = _zones_from_context_or_params(context, params, spec.check_id)
if not zones:
return _make_result(
spec,
score=0.0,
confidence=0.0,
checker=self.name,
evidence=_zone_resolution_failure_reason(context, params),
)
width, height = _image_size(context)
zone = zones.get(slot) if isinstance(zones, dict) else None
zone_rect = _zone_rect(zone, width, height) if zone is not None else None
if zone_rect is None:
return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={"reason": "missing_slot_zone", "slot": slot})
min_score = float(params.get("min_score", 0.18))
min_area = float(params.get("min_vehicle_area_px", 1800.0))
min_color_ratio = float(params.get("min_color_ratio", 0.10))
min_containment = float(params.get("min_mask_containment", params.get("min_bbox_containment", 0.85)))
slot_expand_px = float(params.get("slot_expand_px", 24.0))
detector_labels = [str(item) for item in params.get("detector_labels", []) if str(item).strip()]
if not detector_labels:
detector_labels = [f"{expected_color} car", expected_color, "car", "vehicle"]
detections = _detections_from_observations(context, str(params.get("detections_key", "detections")), spec.check_id)
filtered_detections, provenance = _filter_detections_by_params(detections, params, default_source="pred")
sam_items = _sam_items_from_observations(context, str(params.get("sam_key", "sam_masks")), spec.check_id)
scoped_zone = _expand_box(zone_rect, slot_expand_px, width, height)
candidates = []
raw_candidates = _vehicle_color_candidates(
context,
expected_color=expected_color,
min_score=min_score,
min_area=min_area,
min_color_ratio=min_color_ratio,
detections_key=str(params.get("detections_key", "detections")),
sam_key=str(params.get("sam_key", "sam_masks")),
labels=detector_labels,
params=params,
check_id=spec.check_id,
)
rejected_outside_slot = 0
for item in raw_candidates:
det_mask = item.get("_mask")
bbox = item.get("_bbox")
if not isinstance(bbox, list):
continue
bbox_near_slot = _intersection_area(bbox, scoped_zone) > 0 or _point_in_box(_bbox_center(bbox), scoped_zone)
if bool(params.get("slot_scoped", True)) and not bbox_near_slot:
rejected_outside_slot += 1
continue
mask_cont = _mask_containment(det_mask, zone_rect) if isinstance(det_mask, np.ndarray) else None
bbox_cont = _containment(bbox, zone_rect)
containment_source = "sam_mask" if item.get("mask_source") == "sam" and mask_cont is not None else "bbox"
containment = mask_cont if containment_source == "sam_mask" else bbox_cont
center_inside = _point_in_box(_bbox_center(bbox), zone_rect)
candidate_score = 0.0
weak_color_identity = bool(item.get("color_query_match")) and item.get("area_px", 0.0) >= min_area
if item["is_vehicle_like"] and containment >= min_containment:
candidate_score = 1.0
elif (item["is_vehicle_like"] or weak_color_identity) and (containment >= min_containment * 0.5 or center_inside):
candidate_score = 0.5
public_item = {key: value for key, value in item.items() if key not in {"_bbox", "_mask"}}
candidates.append(
{
**public_item,
"candidate_score": candidate_score,
"mask_containment": round(mask_cont, 6) if mask_cont is not None else None,
"bbox_containment": round(bbox_cont, 6),
"containment_used": round(containment, 6),
"containment_source": containment_source,
"center_inside": center_inside,
}
)
best = max(
candidates,
key=lambda item: (
item["candidate_score"],
bool(item.get("color_query_match")),
item["containment_used"],
item["color_ratio"],
),
default=None,
)
score = float(best["candidate_score"]) if best else 0.0
return _make_result(
spec,
score=score,
confidence=float(params.get("confidence", 0.78 if best else 0.35)),
checker=self.name,
evidence={
"slot": slot,
"expected_color": expected_color,
"zone": {"id": slot, "bbox_xyxy": [round(value, 1) for value in zone_rect]},
"thresholds": {
"min_detector_score": min_score,
"min_vehicle_area_px": min_area,
"min_color_ratio": min_color_ratio,
"min_containment": min_containment,
"slot_expand_px": slot_expand_px,
"min_sam_match_iou": float(params.get("min_sam_match_iou", params.get("min_dino_sam_iou", 0.5))),
},
"detector_labels": detector_labels,
"slot_scoped": bool(params.get("slot_scoped", True)),
"rejected_outside_slot_count": rejected_outside_slot,
"best_candidate": best,
"candidates": candidates[:12],
"detection_count": len(filtered_detections),
**provenance,
"sam_mask_count": len(sam_items),
},
)
@dataclass
class VehiclePenaltyChecker:
"""Penalty checks for colored vehicle assignment cases.
Penalty score follows the global convention: ``1.0`` means the bad thing is
triggered; ``0.0`` means clean.
"""
name: str = "vehicle_penalty_checker"
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
params = dict(spec.params)
check_id = spec.check_id
mapping = context.contract.manual_facts.get("expected_slot_mapping", {})
if not isinstance(mapping, dict) or not mapping:
return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={"reason": "missing_expected_slot_mapping"})
min_score = float(params.get("min_score", 0.18))
min_area = float(params.get("min_vehicle_area_px", 1800.0))
min_color_ratio = float(params.get("min_color_ratio", 0.10))
min_containment = float(params.get("min_mask_containment", params.get("min_bbox_containment", 0.85)))
slot_expand_px = float(params.get("slot_expand_px", 28.0))
zones = _zones_from_contract_or_manual(context)
width, height = _image_size(context)
all_detections = _detections_from_observations(context, str(params.get("detections_key", "detections")), spec.check_id)
_, provenance = _filter_detections_by_params(all_detections, params, default_source="pred")
details = []
missing_or_duplicate = []
boundary_violations = []
for slot, expected in mapping.items():
expected_color = str(expected.get("vehicle_color", "") if isinstance(expected, dict) else "").strip().lower()
if not expected_color:
continue
zone_value = zones.get(str(slot))
zone_rect = _zone_rect(zone_value, width, height) if zone_value is not None else None
scoped_zone = _expand_box(zone_rect, slot_expand_px, width, height) if zone_rect is not None else None
candidates = _vehicle_color_candidates(
context,
expected_color=expected_color,
min_score=min_score,
min_area=min_area,
min_color_ratio=min_color_ratio,
labels=[f"{expected_color} car", f"{expected_color} vehicle", "car", "vehicle"],
params=params,
check_id=spec.check_id,
)
# Missing/duplicate penalties should answer a different question
# from slot containment. A required color can exist in the output
# but still be parked badly; that is a boundary/slot violation, not
# an entity-missing violation.
global_identity_hits = [
item
for item in candidates
if item.get("is_vehicle_like")
or (item.get("color_query_match") and float(item.get("area_px", 0.0)) >= min_area)
]
scoped_candidates = []
for item in candidates:
bbox = item.get("_bbox")
if not isinstance(bbox, list):
continue
if scoped_zone is None or _intersection_area(bbox, scoped_zone) > 0 or _point_in_box(_bbox_center(bbox), scoped_zone):
scoped_candidates.append(item)
vehicle_like = [item for item in scoped_candidates if item.get("is_vehicle_like")]
containment = None
scored_candidates = []
for item in scoped_candidates:
mask = item.get("_mask")
bbox = item.get("_bbox")
item_containment = None
if zone_rect is not None:
item_containment = _mask_containment(mask, zone_rect) if isinstance(mask, np.ndarray) else None
if item.get("mask_source") != "sam" and isinstance(bbox, list):
item_containment = _containment(bbox, zone_rect)
elif item_containment is None and isinstance(bbox, list):
item_containment = _containment(bbox, zone_rect)
scored_candidates.append((item_containment if item_containment is not None else 0.0, item))
scored_candidates.sort(
key=lambda pair: (
bool(pair[1].get("color_query_match")),
pair[0],
pair[1].get("color_ratio", 0.0),
pair[1].get("area_px", 0.0),
),
reverse=True,
)
best = scored_candidates[0][1] if scored_candidates else None
containment = scored_candidates[0][0] if scored_candidates else None
slot_pass = bool(best and best.get("is_vehicle_like") and containment is not None and containment >= min_containment)
if not global_identity_hits:
missing_or_duplicate.append(
{
"slot": slot,
"expected_color": expected_color,
"global_identity_count": 0,
"slot_vehicle_like_count": len(vehicle_like),
"reason": "expected_vehicle_identity_missing",
}
)
elif bool(params.get("trigger_duplicate_identity", False)) and len(global_identity_hits) > int(params.get("expected_count_per_color", 1)):
missing_or_duplicate.append(
{
"slot": slot,
"expected_color": expected_color,
"global_identity_count": len(global_identity_hits),
"slot_vehicle_like_count": len(vehicle_like),
"reason": "expected_vehicle_identity_duplicated",
"matched": [
{key: value for key, value in item.items() if key not in {"_bbox", "_mask"}}
for item in global_identity_hits[:8]
],
}
)
if best and best.get("is_vehicle_like") and containment is not None and containment < min_containment:
boundary_violations.append(
{
"slot": slot,
"expected_color": expected_color,
"containment": round(containment, 6),
"threshold": min_containment,
}
)
public_best = None
if best:
public_best = {key: value for key, value in best.items() if key not in {"_bbox", "_mask"}}
public_best["containment"] = round(containment, 6) if containment is not None else None
details.append(
{
"slot": slot,
"expected_color": expected_color,
"best": public_best,
"candidate_count": len(candidates),
"global_identity_count": len(global_identity_hits),
"scoped_candidate_count": len(scoped_candidates),
"slot_pass": slot_pass,
}
)
if "missing_or_duplicated" in check_id or "count" in self.name:
triggered = bool(missing_or_duplicate)
evidence = {"violations": missing_or_duplicate, "slots": details}
else:
triggered = bool(boundary_violations)
evidence = {"violations": boundary_violations, "slots": details}
return _make_result(
spec,
score=1.0 if triggered else 0.0,
confidence=float(params.get("confidence", 0.76)),
checker=self.name,
evidence={
**evidence,
"thresholds": {
"min_detector_score": min_score,
"min_vehicle_area_px": min_area,
"min_color_ratio": min_color_ratio,
"min_containment": min_containment,
"slot_expand_px": slot_expand_px,
},
**provenance,
},
)
@dataclass
class ObjectPreservationChecker:
"""Check that important input objects are still detected in output."""
name: str = "object_preservation_checker"
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
params = dict(spec.params)
labels = _labels_from_params(params)
if not labels:
return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={"reason": "missing_labels"})
min_score = float(params.get("min_score", 0.0))
min_input_count = int(params.get("min_input_count", 1))
min_output_count = int(params.get("min_output_count", 1))
input_detections = _detections_from_observations(context, str(params.get("input_detections_key", "input_detections")), spec.check_id)
output_detections = _detections_from_observations(context, str(params.get("detections_key", "detections")), spec.check_id)
input_detections, input_provenance = _filter_detections_by_params(input_detections, params, default_source="input")
output_detections, output_provenance = _filter_detections_by_params(output_detections, params, default_source="pred")
input_hits = _matched_detections(input_detections, labels, min_score)
output_hits = _matched_detections(output_detections, labels, min_score)
matched_pairs = []
used: set[int] = set()
matched_count = 0
min_iou = float(params.get("min_match_iou", 0.08))
for inp in input_hits:
best_idx = -1
best_iou = 0.0
for idx, out in enumerate(output_hits):
if idx in used:
continue
iou = _bbox_iou(inp["bbox"], out["bbox"])
if iou > best_iou:
best_idx = idx
best_iou = iou
if best_idx >= 0 and best_iou >= min_iou:
used.add(best_idx)
matched_count += 1
matched_pairs.append({"input": _public_det(inp), "output": _public_det(output_hits[best_idx]), "iou": round(best_iou, 6)})
else:
matched_pairs.append({"input": _public_det(inp), "output": None, "iou": round(best_iou, 6)})
if len(input_hits) < min_input_count:
return _make_uncertain_result(
spec,
checker=self.name,
evidence={
"labels": labels,
"min_score": min_score,
"min_input_count": min_input_count,
"min_output_count": min_output_count,
"input_count": len(input_hits),
"output_count": len(output_hits),
"spatially_matched_count": matched_count,
"min_match_iou": min_iou,
"reason": "input_object_not_detected",
"input_hits": [_public_det(det) for det in input_hits[:12]],
"output_hits": [_public_det(det) for det in output_hits[:12]],
"matched_pairs": matched_pairs[:12],
"input_provenance": input_provenance,
"output_provenance": output_provenance,
"evidence_semantics": "The preservation/disappearance check is not scored because the required object was not reliably detected in the input evidence.",
},
)
elif len(output_hits) >= min_output_count:
score = 1.0
confidence = float(params.get("confidence", 0.70))
reason = "output_object_detected"
elif output_hits:
score = 0.5
confidence = float(params.get("confidence", 0.70))
reason = "partial_output_object_detected"
else:
score = 0.0
confidence = float(params.get("confidence", 0.70))
reason = "input_detected_but_output_missing"
return _make_result(
spec,
score=score,
confidence=confidence,
checker=self.name,
evidence={
"labels": labels,
"min_score": min_score,
"min_input_count": min_input_count,
"min_output_count": min_output_count,
"input_count": len(input_hits),
"output_count": len(output_hits),
"spatially_matched_count": matched_count,
"min_match_iou": min_iou,
"reason": reason,
"input_hits": [_public_det(det) for det in input_hits[:12]],
"output_hits": [_public_det(det) for det in output_hits[:12]],
"matched_pairs": matched_pairs[:12],
"input_provenance": input_provenance,
"output_provenance": output_provenance,
},
)
def register_object_checkers(registry: Any) -> None:
presence = ObjectPresenceChecker()
zone = ObjectZoneChecker()
distance = ObjectDistanceChecker()
source_vacated = SourceVacatedChecker()
preservation = ObjectPreservationChecker()
vehicle = VehicleSlotChecker()
vehicle_penalty = VehiclePenaltyChecker()
for checker in [presence, zone, distance, source_vacated, preservation, vehicle, vehicle_penalty]:
registry.register(checker)
for alias in [
"DINO_SAM_presence",
"dino_presence_checker",
"object_detector_presence",
"object_detector",
"object_detector:bottle_count",
"object_count_checker:DINO+SAM",
"count_checker:DINO+SAM",
]:
registry.register(ObjectPresenceChecker(name=alias))
for alias in [
"object_zone_checker:DINO+SAM",
"object_zone_checker:VLM",
"object_zone_checker:VLM_audit",
"object_intersection_checker:DINO+SAM",
"object_detector:DINO+SAM",
"object_position_checker",
"DINO_SAM",
"DINO+SAM",
"object_zone",
"zone_contract_checker",
"vehicle_detector",
"lane_region_checker",
"animal_detector",
]:
registry.register(ObjectZoneChecker(name=alias))
for alias in ["distance_checker:DINO+SAM", "relative_distance_checker", "near_object_checker"]:
registry.register(ObjectDistanceChecker(name=alias))
for alias in ["source_vacated_checker:DINO+SAM", "source_vacated_checker:OCR", "source_empty_checker"]:
registry.register(SourceVacatedChecker(name=alias))
for alias in [
"vehicle_slot_checker:DINO+SAM+color",
"vehicle_slot_checker:DINO+SAM+color+symbol",
]:
registry.register(VehicleSlotChecker(name=alias))
for alias in [
"vehicle_slot_containment_checker:DINO+SAM",
"vehicle_count_and_color_checker:DINO+SAM+color",
]:
registry.register(VehiclePenaltyChecker(name=alias))
for alias in [
"disappearance_checker",
"disappearance_checker:DINO+SAM",
"disappearance_checker:VLM_audit",
"disappearance_checker:vlm_audit",
"disappearance_checker:vlm+differencing",
"object_absence_checker:DINO+SAM",
"visual_absence_checker:DINO+SAM",
"disappearance_checker|wire_presence_checker",
"preservation_checker:DINO+SAM",
"preservation_checker:image_similarity",
"preservation_checker|disappearance_checker:DINO+SAM",
"DINO_SAM_preservation",
"invariant_checker:DINO+SAM",
"entity_integrity_checker:DINO+SAM",
"appearance_checker:DINO+SAM",
"patch_similarity:DINO+SAM",
"overedit_checker:DINO+SAM",
"object_disappearance_checker",
"input_output_disappearance",
"object_delta_checker",
"wire_presence_checker:color_mask+DINO+SAM",
]:
registry.register(ObjectPreservationChecker(name=alias))
|