Datasets:
File size: 7,576 Bytes
b8ea052 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | """Checker protocol and registry."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Protocol
from pvr_eval.core.schema import AtomicCheckSpec, CheckResult, EvalContract
from pvr_eval.core.scoring import clamp01, score_to_status
@dataclass(frozen=True)
class CheckerContext:
"""Runtime inputs shared by all checkers."""
contract: EvalContract
input_image: Path | None
pred_image: Path
observations: dict[str, Any] = field(default_factory=dict)
work_dir: Path | None = None
class Checker(Protocol):
name: str
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
"""Run a single atomic check."""
class CheckerRegistry:
"""Simple in-process checker registry."""
def __init__(self) -> None:
self._checkers: dict[str, Checker] = {}
def register(self, checker: Checker) -> None:
self._checkers[checker.name] = checker
def get(self, name: str) -> Checker | None:
return self._checkers.get(name)
def require(self, name: str) -> Checker:
checker = self.get(name)
if checker is None:
raise KeyError(f"checker is not registered: {name}")
return checker
def result_from_observation(spec: AtomicCheckSpec, observed: Any, *, checker_name: str) -> CheckResult:
if observed is None:
if bool(getattr(spec, "params", {}).get("audit_only", False)):
score = 0.0 if spec.role == "penalty" else 0.0
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=checker_name,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status="clean" if spec.role == "penalty" else "uncertain",
score=score,
confidence=0.0,
evidence={
"reason": "audit_only_observation_missing",
"audit_only": True,
"note": getattr(spec, "params", {}).get("reason", ""),
},
)
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=checker_name,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status="uncertain",
score=0.0,
confidence=0.0,
evidence={"reason": "missing_observation"},
)
if isinstance(observed, bool):
score = 1.0 if observed else 0.0
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=checker_name,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status=score_to_status(score),
score=score,
confidence=1.0,
evidence={"source": "boolean_observation"},
)
if isinstance(observed, (int, float)):
score = clamp01(float(observed))
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=checker_name,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status=score_to_status(score),
score=score,
confidence=1.0,
evidence={"source": "numeric_observation"},
)
if isinstance(observed, dict):
raw_score = observed.get("score", 0.0)
requested_status = str(observed.get("status") or "").strip().lower()
evidence = dict(observed.get("evidence", {}))
if raw_score is None:
# Contract metrics use ``score: null`` to represent an explicit
# abstention. Do not feed it through ``float`` (which raises) or
# infer a numeric fail. Malformed conclusive statuses with no
# score also fail closed.
status = (
requested_status
if requested_status in {"unknown", "uncertain", "error", "abstain"}
else "uncertain"
)
score = 0.0
confidence = 0.0
evidence.setdefault("reason", "observation_score_missing")
else:
score = clamp01(float(raw_score))
status = requested_status or score_to_status(score)
confidence = clamp01(
float(observed.get("confidence", 1.0 if status not in {"unknown", "uncertain", "error", "abstain"} else 0.0))
)
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=checker_name,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status=status,
score=score,
confidence=confidence,
evidence=evidence,
)
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=checker_name,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status="uncertain",
score=0.0,
confidence=0.0,
evidence={"reason": f"unsupported_observation_type:{type(observed).__name__}"},
)
class ObservationChecker:
"""Compatibility checker that reads precomputed atomic observations."""
name = "observation"
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
observed = context.observations.get("atomic_checks", {}).get(spec.check_id)
return result_from_observation(spec, observed, checker_name=self.name)
class ObservationAliasChecker:
"""Read precomputed observations while preserving the intended checker name.
This is useful for smoke tests and migration dashboards where the contract
already names the future objective checker, but the current run only has
cached atomic observations. It should be registered explicitly by the caller;
the production default registry intentionally does not alias unknown
checkers to observations.
"""
def __init__(self, name: str) -> None:
self.name = name
def run(self, context: CheckerContext, spec: AtomicCheckSpec) -> CheckResult:
observed = context.observations.get("atomic_checks", {}).get(spec.check_id)
return result_from_observation(spec, observed, checker_name=self.name)
def register_observation_aliases(
registry: CheckerRegistry,
names: list[str] | tuple[str, ...] | set[str],
*,
overwrite: bool = False,
) -> None:
for name in sorted({str(item).strip() for item in names if str(item).strip()}):
if overwrite or registry.get(name) is None:
registry.register(ObservationAliasChecker(name))
def default_registry() -> CheckerRegistry:
registry = CheckerRegistry()
registry.register(ObservationChecker())
from pvr_eval.checkers.object import register_object_checkers
from pvr_eval.checkers.state import register_state_checkers
from pvr_eval.checkers.text_symbol import register_text_symbol_checkers
from pvr_eval.checkers.vision import register_lightweight_vision_checkers
from pvr_eval.checkers.vlm import register_vlm_checkers
register_lightweight_vision_checkers(registry)
register_object_checkers(registry)
register_text_symbol_checkers(registry)
register_state_checkers(registry)
register_vlm_checkers(registry)
return registry
|