"""Structured state checkers for grid/slot/parser-style tasks. State parsers should emit compact observations such as per-cell occupancy, slot colors, gauge values, watch date/time, or kanban column counts. This module scores those states against case contracts and includes a few stable image proxies used by existing PVR contracts. """ from __future__ import annotations from dataclasses import dataclass import math from pathlib import Path from typing import Any import numpy as np from PIL import Image, ImageChops 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 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 _lookup_path(payload: Any, path: str) -> Any: cur = payload for part in path.split("."): if isinstance(cur, dict): cur = cur.get(part) elif isinstance(cur, list) and part.isdigit(): idx = int(part) cur = cur[idx] if idx < len(cur) else None else: return None return cur def _ocr_items_from_observations(context: CheckerContext, check_id: str | None = None) -> 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("pred"), list): return [item for item in bucket["pred"] if isinstance(item, dict)] raw = context.observations.get("ocr", {}) if isinstance(raw, dict): items = raw.get("items", []) if isinstance(items, list): return [item for item in items if isinstance(item, dict)] if isinstance(raw, list): return [item for item in raw if isinstance(item, dict)] return [] def _ocr_bbox(item: dict[str, Any]) -> tuple[float, float, float, float] | None: box = item.get("box") or item.get("bbox") or item.get("bbox_xyxy") if isinstance(box, dict) and "bbox" in box: box = box.get("bbox") if isinstance(box, list) and box and isinstance(box[0], list): xs = [] ys = [] for pt in box: if not isinstance(pt, (list, tuple)) or len(pt) < 2: continue xs.append(float(pt[0])) ys.append(float(pt[1])) if xs and ys: return min(xs), min(ys), max(xs), max(ys) if isinstance(box, (list, tuple)) and len(box) == 4: try: return float(box[0]), float(box[1]), float(box[2]), float(box[3]) except Exception: return None return None def _ocr_text(item: dict[str, Any]) -> str: return str(item.get("text", "")).strip() def _rect_to_pixels(rect: Any, *, width: int, height: int) -> tuple[int, int, int, int] | None: if isinstance(rect, dict): if rect.get("type") == "rect_ratio": values = [rect.get("x0"), rect.get("y0"), rect.get("x1"), rect.get("y1")] elif {"x0", "y0", "x1", "y1"} <= set(rect): values = [rect.get("x0"), rect.get("y0"), rect.get("x1"), rect.get("y1")] elif "bbox" in rect: values = rect.get("bbox") elif "rect" in rect: values = rect.get("rect") else: return None else: values = rect if not isinstance(values, (list, tuple)) or len(values) != 4: return None try: x0, y0, x1, y1 = [float(value) for value in values] except Exception: return None if max(abs(x0), abs(y0), abs(x1), abs(y1)) <= 1.0: x0, x1 = x0 * width, x1 * width y0, y1 = y0 * height, y1 * height px0 = max(0, min(width, int(round(x0)))) py0 = max(0, min(height, int(round(y0)))) px1 = max(0, min(width, int(round(x1)))) py1 = max(0, min(height, int(round(y1)))) return min(px0, px1), min(py0, py1), max(px0, px1), max(py0, py1) def _crop(image: Image.Image, roi: Any | None) -> Image.Image: if roi is None: return image rect = _rect_to_pixels(roi, width=image.size[0], height=image.size[1]) if rect is None: return image return image.crop(rect) def _diff_metrics(a_path: Path, b_path: Path, roi: Any | None = None, size: int = 256) -> dict[str, float]: with Image.open(a_path).convert("RGB") as a, Image.open(b_path).convert("RGB") as b: aa = _crop(a, roi).resize((size, size)) bb = _crop(b, roi).resize((size, size)) diff = ImageChops.difference(aa, bb).convert("L") arr = np.array(diff, dtype=np.float32) return { "mae": float(arr.mean() / 255.0), "changed_24": float((arr >= 24).mean()), "changed_48": float((arr >= 48).mean()), } def _zone_rect_from_context(context: CheckerContext, zone_id: str) -> dict[str, Any] | None: zones = context.observations.get("zones") zone = zones.get(zone_id) if isinstance(zones, dict) else None if zone is None and isinstance(context.contract.zones, dict): candidate = context.contract.zones.get(zone_id) if candidate and not (isinstance(candidate, str) and candidate.startswith("TODO")): zone = candidate return zone if isinstance(zone, dict) else None def _mask_from_zone(image_shape: tuple[int, int], zone: dict[str, Any]) -> np.ndarray: height, width = image_shape mask = Image.new("L", (width, height), 0) from PIL import ImageDraw draw = ImageDraw.Draw(mask) points = zone.get("points") if isinstance(points, list) and points: pts = [] for point in points: if isinstance(point, (list, tuple)) and len(point) == 2: pts.append((int(round(float(point[0]))), int(round(float(point[1]))))) if zone.get("shape") == "bbox" and len(pts) >= 2: draw.rectangle([pts[0], pts[1]], fill=255) elif len(pts) >= 3: draw.polygon(pts, fill=255) elif len(pts) >= 2: draw.rectangle([pts[0], pts[1]], fill=255) else: rect = _rect_to_pixels(zone, width=width, height=height) if rect is not None: draw.rectangle(rect, fill=255) return np.asarray(mask, dtype=np.uint8) > 0 def _hsv_mask(rgb: np.ndarray, color: str) -> 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) active = diff > 1e-6 rmax = active & (mx == r) gmax = active & (mx == g) bmax = active & (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 *= 30.0 s = np.zeros_like(mx) nz = mx > 1e-6 s[nz] = diff[nz] / mx[nz] * 255.0 v = mx * 255.0 color = color.lower().strip() if color == "yellow": return (h >= 17) & (h <= 38) & (s >= 50) & (v >= 50) if color == "green": return (h >= 36) & (h <= 86) & (s >= 35) & (v >= 35) if color == "blue": return (h >= 88) & (h <= 130) & (s >= 45) & (v >= 35) if color in {"gray", "grey"}: return (s <= 55) & (v >= 45) & (v <= 190) return np.zeros(rgb.shape[:2], dtype=bool) def _component_meta(mask: np.ndarray, min_area: int = 20) -> tuple[np.ndarray, dict[str, Any]]: from scipy import ndimage labels, count = ndimage.label(mask) if count <= 0: return np.zeros_like(mask, dtype=bool), {"area": 0, "bbox": None, "centroid": None} slices = ndimage.find_objects(labels) areas = np.array([(labels == idx).sum() for idx in range(1, count + 1)]) best = int(np.argmax(areas)) + 1 area = int(areas[best - 1]) if area < min_area: return np.zeros_like(mask, dtype=bool), {"area": area, "bbox": None, "centroid": None} comp = labels == best sl = slices[best - 1] ys, xs = np.where(comp) return comp, { "area": area, "bbox": [int(sl[1].start), int(sl[0].start), int(sl[1].stop), int(sl[0].stop)], "centroid": [float(xs.mean()), float(ys.mean())], } def _min_distance(mask_a: np.ndarray, mask_b: np.ndarray) -> float: pts_a = np.column_stack(np.where(mask_a)) pts_b = np.column_stack(np.where(mask_b)) if len(pts_a) == 0 or len(pts_b) == 0: return float("inf") pts_a = pts_a[:: max(1, len(pts_a) // 700)] pts_b = pts_b[:: max(1, len(pts_b) // 700)] dist = np.sqrt(((pts_a[:, None, :] - pts_b[None, :, :]) ** 2).sum(axis=2)) return float(dist.min()) def _mask_overlap_fraction(mask: np.ndarray, zone_mask: np.ndarray) -> float: total = int(mask.sum()) if total <= 0: return 0.0 return float((mask & zone_mask).sum() / total) def _parse_bbox(raw: Any) -> list[float] | 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 _open_gray(path: Path) -> np.ndarray: return np.asarray(Image.open(path).convert("L"), dtype=np.float32) def _best_dark_line_angle( gray: np.ndarray, center: tuple[float, float], angle_min: float, angle_max: float, r0: float, r1: float, *, width: int = 1, darkness_thr: float = 120.0, step: float = 1.0, ) -> tuple[float, float]: darkness = np.clip((darkness_thr - gray) / max(darkness_thr, 1.0), 0.0, 1.0) h, w = darkness.shape best_angle = angle_min best_score = -1.0 sample_count = max(8, int((r1 - r0) * 1.4)) for angle in np.arange(angle_min, angle_max + 1e-6, step): rad = math.radians(angle) dx = math.cos(rad) dy = math.sin(rad) px = -dy py = dx values: list[float] = [] for radius in np.linspace(r0, r1, sample_count): x = center[0] + dx * radius y = center[1] + dy * radius for offset in range(-width, width + 1): xx = int(round(x + px * offset)) yy = int(round(y + py * offset)) if 0 <= xx < w and 0 <= yy < h: values.append(float(darkness[yy, xx])) score = float(np.mean(values)) if values else -1.0 if score > best_score: best_angle = float(angle) best_score = score return best_angle, best_score 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 _detector_filters(params: dict[str, Any]) -> tuple[set[str], set[str]]: backend = params.get("detector_backend") or params.get("detector_backends") source = params.get("source_image") or params.get("source_images") def values(raw: Any) -> set[str]: 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()} return values(backend), values(source) def _detector_candidates(context: CheckerContext, params: dict[str, Any]) -> list[dict[str, Any]]: key = str(params.get("detections_key", "detections")) raw = context.observations.get(key, []) if isinstance(raw, dict): raw = raw.get("items", []) if not isinstance(raw, list): return [] labels = [str(item) for item in params.get("detector_labels", params.get("labels", [])) if str(item).strip()] min_score = float(params.get("detector_min_score", params.get("min_detector_score", params.get("min_score", 0.0)))) backend_filter, source_filter = _detector_filters(params) candidates: list[dict[str, Any]] = [] for item in raw: if not isinstance(item, dict): continue bbox = _parse_bbox(item.get("bbox") or item.get("bbox_xyxy")) if bbox is None: continue label = str(item.get("label", "")) query = str(item.get("query_text", "")) backend = str(item.get("backend") or item.get("detector_backend") or "").lower() source = str(item.get("source_image") or item.get("source") or "").lower() try: score = float(item.get("score", 0.0)) except Exception: score = 0.0 if backend_filter and backend not in backend_filter: continue if source_filter and source not in source_filter: continue if score < min_score: continue if labels and not (_label_matches(label, labels) or _label_matches(query, labels)): continue candidates.append( { "label": label, "query_text": query, "score": score, "bbox": bbox, "backend": backend, "source_image": source, } ) candidates.sort(key=lambda item: item["score"], reverse=True) return candidates def _bbox_mask(shape: tuple[int, int], bbox: list[float], *, pad_px: float = 0.0) -> np.ndarray: height, width = shape x0 = max(0, min(width, int(round(bbox[0] - pad_px)))) y0 = max(0, min(height, int(round(bbox[1] - pad_px)))) x1 = max(0, min(width, int(round(bbox[2] + pad_px)))) y1 = max(0, min(height, int(round(bbox[3] + pad_px)))) mask = np.zeros(shape, dtype=bool) if x1 > x0 and y1 > y0: mask[y0:y1, x0:x1] = True return mask def _candidate_union_mask(shape: tuple[int, int], candidates: list[dict[str, Any]], *, pad_px: float) -> np.ndarray: mask = np.zeros(shape, dtype=bool) for item in candidates: bbox = item.get("bbox") if isinstance(bbox, list): mask |= _bbox_mask(shape, bbox, pad_px=pad_px) return mask def _color_ok(pixel: tuple[int, int, int], color: str) -> bool: r, g, b = pixel if color == "blue": return b > 70 and b > r * 1.15 and b > g * 1.02 if color == "yellow": return r > 110 and g > 80 and b < 140 and r >= g * 0.75 if color == "red": return r > 85 and r > g * 1.25 and r > b * 1.15 if color == "green": return g > 60 and g > r * 1.05 and g > b * 0.95 if color == "black": return r < 80 and g < 80 and b < 80 if color == "white": return r > 180 and g > 180 and b > 180 return False def _color_area_stats(image: Image.Image, roi: Any, color: str) -> dict[str, float]: crop = _crop(image.convert("RGB"), roi) pixels = list(crop.getdata()) if not pixels: return {"fraction": 0.0, "vertical_span_ratio": 0.0, "horizontal_span_ratio": 0.0} width, height = crop.size xs: list[int] = [] ys: list[int] = [] for index, pixel in enumerate(pixels): if _color_ok(pixel, color): xs.append(index % width) ys.append(index // width) if not xs: return {"fraction": 0.0, "vertical_span_ratio": 0.0, "horizontal_span_ratio": 0.0} return { "fraction": len(xs) / float(len(pixels)), "vertical_span_ratio": (max(ys) - min(ys) + 1) / float(height), "horizontal_span_ratio": (max(xs) - min(xs) + 1) / float(width), } def _cell_roi(board_roi: dict[str, Any], rows: int, cols: int, cell: str) -> dict[str, float | str]: col = ord(cell[0].upper()) - ord("A") row_from_bottom = int(cell[1:]) - 1 row_from_top = rows - 1 - row_from_bottom x0 = float(board_roi["x0"]) + (float(board_roi["x1"]) - float(board_roi["x0"])) * col / cols x1 = float(board_roi["x0"]) + (float(board_roi["x1"]) - float(board_roi["x0"])) * (col + 1) / cols y0 = float(board_roi["y0"]) + (float(board_roi["y1"]) - float(board_roi["y0"])) * row_from_top / rows y1 = float(board_roi["y0"]) + (float(board_roi["y1"]) - float(board_roi["y0"])) * (row_from_top + 1) / rows pad_x = (x1 - x0) * 0.12 pad_y = (y1 - y0) * 0.12 return {"type": "rect_ratio", "x0": x0 + pad_x, "y0": y0 + pad_y, "x1": x1 - pad_x, "y1": y1 - pad_y} @dataclass class StructuredStateChecker: """Compare parser-emitted state observations with expected state.""" name: str = "state_checker" def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult: params = dict(spec.params) relation = str(params.get("relation", "state_equals")) state_key = str(params.get("state_key", "state")) state = context.observations.get(state_key, {}) evidence: dict[str, Any] = {"relation": relation, "state_key": state_key} if not isinstance(state, dict): return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_state_observation"}) if relation in {"state_equals", "state_fields_match"}: expected = params.get("expected", {}) if not isinstance(expected, dict) or not expected: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_expected_state"}) details = [] matched = 0 for path, expected_value in expected.items(): actual = _lookup_path(state, str(path)) ok = actual == expected_value matched += int(ok) details.append({"path": path, "expected": expected_value, "actual": actual, "ok": ok}) score = matched / len(details) if details else 0.0 return _make_result(spec, score=score, confidence=float(params.get("confidence", 0.85)), checker=self.name, evidence={**evidence, "fields": details}) if relation == "ocr_terms_in_roi_zones": zones = params.get("zones", []) if not isinstance(zones, list) or not zones: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_zones"}) items = _ocr_items_from_observations(context, spec.check_id) if not items: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_ocr_items"}) with Image.open(context.pred_image).convert("RGB") as pred_image: pred_width, pred_height = pred_image.size matched_zones = 0 details = [] for zone in zones: zone_id = str(zone.get("id", "zone")) expected_all = [str(value).lower() for value in zone.get("expected_all", []) if value] expected_any = [str(value).lower() for value in zone.get("expected_any", []) if value] rect = zone if {"x0", "y0", "x1", "y1"} <= set(zone) else None if rect is None: continue rect_px = _rect_to_pixels(rect, width=pred_width, height=pred_height) if rect_px is None: continue x0, y0, x1, y1 = rect_px zone_hits = [] matched_terms: list[str] = [] for item in items: bbox = _ocr_bbox(item) if bbox is None: continue cx = (bbox[0] + bbox[2]) / 2.0 cy = (bbox[1] + bbox[3]) / 2.0 if not (x0 <= cx <= x1 and y0 <= cy <= y1): continue text = _ocr_text(item).lower() hits = [term for term in expected_all or expected_any if term and term in text] if hits: matched_terms.extend(hits) zone_hits.append({"text": _ocr_text(item), "bbox": [round(v, 1) for v in bbox], "matched_terms": hits}) required_terms = expected_all or expected_any ok = bool(required_terms and matched_terms) matched_zones += int(ok) details.append({"zone_id": zone_id, "expected_terms": required_terms, "matched_terms": sorted(set(matched_terms)), "ok": ok, "hits": zone_hits}) min_zones_matched = int(params.get("min_zones_matched", len(zones))) score = 1.0 if matched_zones >= min_zones_matched else 0.5 if matched_zones else 0.0 return _make_result( spec, score=score, confidence=float(params.get("confidence", 0.80)), checker=self.name, evidence={**evidence, "zones": details, "matched_zones": matched_zones, "min_zones_matched": min_zones_matched}, ) if relation == "forbidden_pairs_absent": groups = state.get(str(params.get("groups_key", "groups")), {}) forbidden_pairs = params.get("forbidden_pairs", []) violations = [] if isinstance(groups, dict): for pair in forbidden_pairs: if not isinstance(pair, (list, tuple)) or len(pair) != 2: continue a, b = pair for group_id, members in groups.items(): if isinstance(members, list) and a in members and b in members: violations.append({"pair": [a, b], "group": group_id}) score = 1.0 if not violations else 0.0 return _make_result(spec, score=score, confidence=float(params.get("confidence", 0.85)), checker=self.name, evidence={**evidence, "violations": violations}) return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": f"unsupported_relation:{relation}"}) @dataclass class StateImageProxyChecker: """Stable image proxies for state tasks when parser output is unavailable.""" name: str = "state_image_proxy_checker" def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult: params = dict(spec.params) relation = str(params.get("relation", "roi_must_change_from_input")) evidence: dict[str, Any] = {"relation": relation} if relation == "roi_must_change_from_input": if context.input_image is None: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_input_image"}) metrics = _diff_metrics(context.input_image, context.pred_image, params.get("roi")) min_changed = float(params.get("min_changed_24", 0.01)) score = 1.0 if metrics["changed_24"] >= min_changed else 0.0 return _make_result( spec, score=score, confidence=float(params.get("confidence", 0.70)), checker=self.name, evidence={**evidence, "roi": params.get("roi"), "metrics": {k: round(v, 6) for k, v in metrics.items()}, "min_changed_24": min_changed}, ) if relation == "gt_state_patch_matches_reference": gt_path = params.get("reference_image") or context.observations.get("reference_image") if not gt_path: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_reference_image"}) ref = Path(gt_path) if not ref.is_absolute() and context.contract.case_dir is not None: ref = context.contract.case_dir / ref if not ref.is_file(): return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "reference_image_not_found", "path": str(ref)}) metrics = _diff_metrics(ref, context.pred_image, params.get("roi")) max_mae = float(params.get("max_mae_vs_gt", 0.08)) partial_mae = float(params.get("partial_mae_vs_gt", 0.14)) score = 1.0 if metrics["mae"] <= max_mae else 0.5 if metrics["mae"] <= partial_mae else 0.0 return _make_result( spec, score=score, confidence=float(params.get("confidence", 0.75)), checker=self.name, evidence={**evidence, "roi": params.get("roi"), "reference_image": str(ref), "metrics": {k: round(v, 6) for k, v in metrics.items()}, "max_mae_vs_gt": max_mae, "partial_mae_vs_gt": partial_mae}, ) if relation == "board_piece_cells_match": with Image.open(context.pred_image).convert("RGB") as image: expected = params.get("expected", []) details = [] matched = 0 for item in expected: roi = _cell_roi(params["board_roi"], int(params["rows"]), int(params["cols"]), str(item["cell"])) color = str(item["color"]) stats = _color_area_stats(image, roi, color) threshold = float(params.get("min_dark_fraction" if color == "black" else "min_colored_fraction", 0.02)) ok = stats["fraction"] >= threshold matched += int(ok) details.append({"cell": item["cell"], "color": color, "fraction": round(stats["fraction"], 6), "threshold": threshold, "ok": ok}) score = matched / len(details) if details else 0.0 return _make_result(spec, score=score, confidence=float(params.get("confidence", 0.78)), checker=self.name, evidence={**evidence, "cells": details}) if relation == "slot_color_presence": with Image.open(context.pred_image).convert("RGB") as image: expected = params.get("expected", []) details = [] matched = 0 for item in expected: color = str(item["color"]) stats = _color_area_stats(image, item["roi"], color) frac_threshold = float(params.get("min_colored_fraction", 0.04)) span_threshold = float(params.get("min_vertical_span_ratio", 0.0)) ok = stats["fraction"] >= frac_threshold and stats["vertical_span_ratio"] >= span_threshold matched += int(ok) details.append({"name": item.get("name", ""), "color": color, **{k: round(v, 6) for k, v in stats.items()}, "ok": ok}) min_pass = int(params.get("min_pass_count", len(details))) score = 1.0 if matched >= min_pass else 0.5 if matched else 0.0 return _make_result(spec, score=score, confidence=float(params.get("confidence", 0.76)), checker=self.name, evidence={**evidence, "matched": matched, "min_pass_count": min_pass, "items": details}) if relation == "forbid_loose_colored_keys": with Image.open(context.pred_image).convert("RGB") as image: roi = params.get("roi") crop = _crop(image, roi) pixels = list(crop.getdata()) if not pixels: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "empty_roi"}) colors = [str(item).lower() for item in params.get("colors", [])] fractions: dict[str, float] = {} for color in colors: hits = sum(1 for pixel in pixels if _color_ok(pixel, color)) fractions[color] = hits / len(pixels) max_fraction = max(fractions.values()) if fractions else 1.0 pass_at = float(params.get("max_color_fraction", 0.012)) partial_at = float(params.get("partial_color_fraction", pass_at * 2)) score = 1.0 if max_fraction <= pass_at else 0.5 if max_fraction <= partial_at else 0.0 return _make_result( spec, score=score, confidence=float(params.get("confidence", 0.75)), checker=self.name, evidence={**evidence, "roi": roi, "fractions": {k: round(v, 6) for k, v in fractions.items()}, "max_fraction": round(max_fraction, 6), "pass_max_color_fraction": pass_at, "partial_max_color_fraction": partial_at}, ) return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": f"unsupported_relation:{relation}"}) @dataclass class WatchHandAngleChecker: """Estimate hour/minute hand angles for watch-style time-update cases.""" name: str = "watch_hand_angle_parser" def _geometry(self, context: CheckerContext, params: dict[str, Any]) -> dict[str, Any]: pivot = params.get("pivot") or params.get("center") or params.get("watch_center") if isinstance(pivot, dict): pivot = pivot.get("xy") or pivot.get("point") or pivot.get("center") if isinstance(pivot, (list, tuple)) and len(pivot) == 2: pivot = (float(pivot[0]), float(pivot[1])) else: pivot = None if pivot is None and "watch_time_delta" in str(getattr(context.contract, "case_id", "")): pivot = (501.5, 546.0) hour_range = params.get("hour_angle_range") or params.get("hour_range") or [170, 270] minute_range = params.get("minute_angle_range") or params.get("minute_range") or [-20, 60] return { "pivot": pivot, "hour_angle_range": hour_range, "minute_angle_range": minute_range, "hour_r0": float(params.get("hour_r0", 35)), "hour_r1": float(params.get("hour_r1", 170)), "minute_r0": float(params.get("minute_r0", 70)), "minute_r1": float(params.get("minute_r1", 230)), "hour_width": int(params.get("hour_width", 1)), "minute_width": int(params.get("minute_width", 2)), } @staticmethod def _angle_delta_deg(a: float, b: float) -> float: return float((float(b) - float(a) + 180.0) % 360.0 - 180.0) def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult: params = dict(spec.params) evidence: dict[str, Any] = {"checker_scope": "watch hour/minute hand angle estimation from dark-line proxy"} if context.input_image is None: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_input_image"}) geometry = self._geometry(context, params) pivot = geometry["pivot"] if pivot is None: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_watch_geometry"}) input_gray = _open_gray(context.input_image) pred_gray = _open_gray(context.pred_image) hour_in, hour_strength_in = _best_dark_line_angle( input_gray, pivot, float(geometry["hour_angle_range"][0]), float(geometry["hour_angle_range"][1]), float(geometry["hour_r0"]), float(geometry["hour_r1"]), width=int(geometry["hour_width"]), ) hour_pr, hour_strength_pr = _best_dark_line_angle( pred_gray, pivot, float(geometry["hour_angle_range"][0]), float(geometry["hour_angle_range"][1]), float(geometry["hour_r0"]), float(geometry["hour_r1"]), width=int(geometry["hour_width"]), ) minute_in, minute_strength_in = _best_dark_line_angle( input_gray, pivot, float(geometry["minute_angle_range"][0]), float(geometry["minute_angle_range"][1]), float(geometry["minute_r0"]), float(geometry["minute_r1"]), width=int(geometry["minute_width"]), ) minute_pr, minute_strength_pr = _best_dark_line_angle( pred_gray, pivot, float(geometry["minute_angle_range"][0]), float(geometry["minute_angle_range"][1]), float(geometry["minute_r0"]), float(geometry["minute_r1"]), width=int(geometry["minute_width"]), ) hour_delta = self._angle_delta_deg(hour_in, hour_pr) minute_delta = self._angle_delta_deg(minute_in, minute_pr) abs_hour_delta = abs(hour_delta) abs_minute_delta = abs(minute_delta) if "hour" in spec.check_id: score = 1.0 if 45.0 <= abs_hour_delta <= 75.0 else 0.5 if 30.0 <= abs_hour_delta < 45.0 or 75.0 < abs_hour_delta <= 90.0 else 0.0 confidence = 0.60 evidence.update( { "kind": "hour_hand", "expected_delta_deg": 60.0, "input_angle_deg": round(hour_in, 1), "pred_angle_deg": round(hour_pr, 1), "angle_delta_deg": round(hour_delta, 1), "input_strength": round(hour_strength_in, 3), "pred_strength": round(hour_strength_pr, 3), "pivot": [round(pivot[0], 1), round(pivot[1], 1)], } ) elif "minute" in spec.check_id: score = 1.0 if abs_minute_delta <= 3.0 else 0.5 if abs_minute_delta <= 8.0 else 0.0 confidence = 0.80 evidence.update( { "kind": "minute_hand", "input_angle_deg": round(minute_in, 1), "pred_angle_deg": round(minute_pr, 1), "angle_delta_deg": round(minute_delta, 1), "input_strength": round(minute_strength_in, 3), "pred_strength": round(minute_strength_pr, 3), "pivot": [round(pivot[0], 1), round(pivot[1], 1)], } ) else: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "unsupported_watch_check_id"}) return _make_result(spec, score=score, confidence=confidence, checker=self.name, evidence=evidence) @dataclass class WireConnectivityChecker: """Check colored wire presence, endpoints, corridor, and forbidden pads.""" name: str = "line_connectivity_checker" def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult: params = dict(spec.params) relation = str(params.get("relation", "auto")) color = str(params.get("line_color", params.get("wire_color", "yellow"))) rgb = np.asarray(Image.open(context.pred_image).convert("RGB")) mask = _hsv_mask(rgb, color) candidates = _detector_candidates(context, params) require_detector = bool(params.get("require_detector", params.get("detector_gate", False))) candidate_pad_px = float(params.get("candidate_pad_px", 8.0)) candidate_mask = _candidate_union_mask(mask.shape, candidates, pad_px=candidate_pad_px) if candidates and bool(params.get("restrict_to_detector_candidates", True)): mask &= candidate_mask board_zone = _zone_rect_from_context(context, str(params.get("target_region", "protected_board_and_labels"))) if board_zone is not None: mask &= _mask_from_zone(mask.shape, board_zone) for pad in params.get("exclude_zones", ["pad_P1", "pad_P2", "pad_P3", "pad_P4"]): zone = _zone_rect_from_context(context, str(pad)) if zone is not None: mask &= ~_mask_from_zone(mask.shape, zone) comp, meta = _component_meta(mask, min_area=int(params.get("min_component_area", 20))) area = int(comp.sum()) bbox = meta.get("bbox") aspect = 0.0 if isinstance(bbox, list): width = max(1, bbox[2] - bbox[0]) height = max(1, bbox[3] - bbox[1]) aspect = width / height evidence: dict[str, Any] = { "relation": relation, "line_color": color, "detector_gate": require_detector, "detector_candidate_count": len(candidates), "detector_candidates": [ { "label": item["label"], "query_text": item["query_text"], "score": round(float(item["score"]), 6), "bbox_xyxy": [round(float(value), 1) for value in item["bbox"]], "backend": item.get("backend", ""), "source_image": item.get("source_image", ""), } for item in candidates[:8] ], "restricted_to_detector_candidates": bool(candidates and params.get("restrict_to_detector_candidates", True)), "candidate_pad_px": candidate_pad_px, "component": meta, "area_px": area, "aspect_ratio": round(aspect, 6), } if require_detector and not candidates: return _make_result( spec, score=0.0, confidence=float(params.get("missing_detector_confidence", 0.35)), checker=self.name, evidence={**evidence, "reason": "required_detector_candidate_missing"}, ) if relation in {"auto", "wire_present_on_board", "must_exist"}: min_area = int(params.get("min_area_px", 80)) min_aspect = float(params.get("min_aspect_ratio", 2.0)) present_score = 1.0 if area >= min_area and aspect >= min_aspect else 0.5 if area >= min_area else 0.0 score = 1.0 - present_score if spec.role == "penalty" else present_score evidence.update({"min_area_px": min_area, "min_aspect_ratio": min_aspect}) return _make_result(spec, score=score, confidence=float(params.get("confidence", 0.78)), checker=self.name, evidence=evidence) if relation in {"auto", "endpoint_touches"} or spec.check_id.startswith("wire_endpoint_contacts_"): pad = str(params.get("required_endpoint") or params.get("source") or params.get("target") or "") if spec.check_id.endswith("_P1"): pad = "pad_P1" elif spec.check_id.endswith("_P3"): pad = "pad_P3" zone = _zone_rect_from_context(context, pad) if zone is None: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_pad_zone", "pad": pad}) dist = _min_distance(comp, _mask_from_zone(comp.shape, zone)) pass_px = float(params.get("max_endpoint_distance_px", 12)) partial_px = float(params.get("partial_endpoint_distance_px", pass_px * 1.8)) score = 1.0 if dist <= pass_px else 0.5 if dist <= partial_px else 0.0 evidence.update({"pad": pad, "min_distance_px": None if np.isinf(dist) else round(dist, 6), "pass_threshold_px": pass_px, "partial_threshold_px": partial_px}) return _make_result(spec, score=score, confidence=float(params.get("confidence", 0.78)), checker=self.name, evidence=evidence) if relation in {"auto", "continuous_between"} or spec.check_id == "wire_continuous_between_P1_P3": corridor = _zone_rect_from_context(context, str(params.get("corridor", "expected_wire_corridor_P1_P3"))) if corridor is None: return _make_result(spec, score=0.0, confidence=0.0, checker=self.name, evidence={**evidence, "reason": "missing_corridor_zone"}) corridor_fraction = _mask_overlap_fraction(comp, _mask_from_zone(comp.shape, corridor)) min_area = int(params.get("min_area_px", 80)) pass_fraction = float(params.get("pass_min_corridor_fraction", 0.60)) partial_fraction = float(params.get("partial_min_corridor_fraction", 0.25)) score = 1.0 if area >= min_area and corridor_fraction >= pass_fraction else 0.5 if area >= min_area and corridor_fraction >= partial_fraction else 0.0 evidence.update({"corridor": "expected_wire_corridor_P1_P3", "corridor_fraction": round(corridor_fraction, 6), "min_area_px": min_area, "pass_min_corridor_fraction": pass_fraction, "partial_min_corridor_fraction": partial_fraction}) return _make_result(spec, score=score, confidence=float(params.get("confidence", 0.78)), checker=self.name, evidence=evidence) forbidden = [str(item) for item in params.get("forbidden_pads", ["pad_P2", "pad_P4"])] wrong_distances: dict[str, float | None] = {} for pad in forbidden: zone = _zone_rect_from_context(context, pad) if zone is None: wrong_distances[pad] = None continue dist = _min_distance(comp, _mask_from_zone(comp.shape, zone)) wrong_distances[pad] = None if np.isinf(dist) else round(dist, 6) contact_px = float(params.get("forbidden_contact_threshold_px", 8)) any_wrong = any(value is not None and value <= contact_px for value in wrong_distances.values()) if spec.role == "penalty": score = 1.0 if any_wrong else 0.0 else: corridor = _zone_rect_from_context(context, str(params.get("corridor", "expected_wire_corridor_P1_P3"))) corridor_fraction = _mask_overlap_fraction(comp, _mask_from_zone(comp.shape, corridor)) if corridor is not None else 0.0 pass_fraction = float(params.get("pass_min_corridor_fraction", 0.60)) partial_fraction = float(params.get("partial_min_corridor_fraction", 0.25)) score = ( 1.0 if area > 0 and corridor_fraction >= pass_fraction and not any_wrong else 0.5 if area > 0 and corridor_fraction >= partial_fraction and not any_wrong else 0.0 ) evidence["corridor_fraction"] = round(corridor_fraction, 6) evidence["pass_min_corridor_fraction"] = pass_fraction evidence["partial_min_corridor_fraction"] = partial_fraction evidence.update({"forbidden_pads": forbidden, "wrong_pad_min_distances": wrong_distances, "forbidden_contact_threshold_px": contact_px}) return _make_result(spec, score=score, confidence=float(params.get("confidence", 0.78)), checker=self.name, evidence=evidence) def register_state_checkers(registry: Any) -> None: state = StructuredStateChecker() proxy = StateImageProxyChecker() watch = WatchHandAngleChecker() wire = WireConnectivityChecker() registry.register(state) registry.register(proxy) registry.register(watch) registry.register(wire) for alias in ["state_parser", "state_parser_checker", "grid_state_parser", "slot_state_parser", "kanban_state_parser"]: registry.register(StructuredStateChecker(name=alias)) for alias in ["board_state_parser", "board_piece_parser", "lock_state_parser", "gauge_state_parser", "watch_state_parser"]: registry.register(StateImageProxyChecker(name=alias)) for alias in ["watch_hand_angle_parser", "watch_hand_angle_checker", "clock_hand_angle_parser"]: registry.register(WatchHandAngleChecker(name=alias)) registry.register(StateImageProxyChecker(name="gt_state_or_reference_checker")) for alias in [ "wire_endpoint_checker", "wire_endpoint_checker|line_connectivity_checker", "line_connectivity_checker|color_skeleton_checker", "wire_corridor_checker", "wire_corridor_checker|forbidden_pad_checker", "forbidden_pad_checker", "forbidden_pad_checker|line_connectivity_checker", "wire_presence_checker:color_mask+DINO+SAM", ]: registry.register(WireConnectivityChecker(name=alias))