Datasets:
Download code/src/pvr_eval/checkers/object.py from wenjieshu/solveedit_benchmark_2728: direct link, hf CLI and curl.
- Browser
- Download file 76.2 kB
-
https://huggingface.co/datasets/wenjieshu/solveedit_benchmark_2728/resolve/main/code/src/pvr_eval/checkers/object.py
- Command line
-
hf download hf://datasets/wenjieshu/solveedit_benchmark_2728/code/src/pvr_eval/checkers/object.py
-
curl -L -o object.py https://huggingface.co/datasets/wenjieshu/solveedit_benchmark_2728/resolve/main/code/src/pvr_eval/checkers/object.py
76.2 kB
"""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))
"""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: