Datasets:
File size: 9,607 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 | """Contract-driven case evaluation runner."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from pvr_eval.checkers.base import CheckerContext, CheckerRegistry, default_registry, result_from_observation
from pvr_eval.checkers.quality import image_quality_gate
from pvr_eval.contracts.loader import load_contract
from pvr_eval.core.io import load_json
from pvr_eval.core.schema import CheckResult, EvalContract
from pvr_eval.core.scoring import aggregate_eval_result
from pvr_eval.resolvers.auto_zones import resolve_auto_zones
class EvaluationRunner:
"""Run one prediction against one eval contract."""
def __init__(self, registry: CheckerRegistry | None = None) -> None:
self.registry = registry or default_registry()
def run(
self,
*,
contract_path: str | Path,
pred_image: str | Path,
observations_path: str | Path | None = None,
work_dir: str | Path | None = None,
metadata: dict[str, Any] | None = None,
) -> dict[str, Any]:
contract = load_contract(contract_path)
observations = load_json(observations_path) if observations_path else {}
observations = self._merge_case_annotations(contract, observations)
observations = self._merge_auto_zones(contract, observations, pred_image)
quality = image_quality_gate(pred_image)
context = CheckerContext(
contract=contract,
input_image=self._resolve_input_image(contract),
pred_image=Path(pred_image),
observations=observations,
work_dir=Path(work_dir) if work_dir is not None else None,
)
checks = [self._run_check(context, spec) for spec in contract.atomic_checks]
result = aggregate_eval_result(
contract=contract,
quality_gate=quality,
checks=checks,
notes=str(observations.get("notes", "")),
metadata={"source": "pvr_eval.runners.EvaluationRunner", **dict(metadata or {})},
)
return result.to_dict()
def _run_check(self, context: CheckerContext, spec) -> CheckResult:
structured_observations = context.observations.get("structured_results_by_check", {})
if isinstance(structured_observations, dict) and spec.check_id in structured_observations:
return result_from_observation(
spec,
structured_observations[spec.check_id],
checker_name="structured_contract_parser",
)
metric_observations = context.observations.get("contract_metrics_by_check", {})
if isinstance(metric_observations, dict) and spec.check_id in metric_observations:
return result_from_observation(
spec,
metric_observations[spec.check_id],
checker_name="contract_metric_binding",
)
checker_name = self._select_checker_name(spec.checker, spec)
checker = self.registry.get(checker_name)
if checker is None:
return CheckResult(
check_id=spec.check_id,
dimension=spec.dimension,
checker=spec.checker,
weight=spec.weight,
role=spec.role,
hard_fail=spec.hard_fail,
status="uncertain",
score=0.0,
confidence=0.0,
evidence={"reason": "checker_not_registered", "checker": spec.checker},
)
try:
return checker.run(context, spec)
except Exception as exc:
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": "checker_exception",
"checker": checker_name,
"exception_type": type(exc).__name__,
"exception_message": str(exc),
},
)
def _select_checker_name(self, checker_spec: str, spec=None) -> str:
"""Resolve checker specs like ``path_checker|zone_checker``.
Existing contracts often keep a preferred checker and one or more
fallback/checker-family names in a pipe-separated string. The formal
runner dispatches one checker per atomic check, so choose the first
registered checker while preserving the original spec in the contract.
"""
if spec is not None:
params = getattr(spec, "params", {}) or {}
checker_text = str(checker_spec)
if "endpoint_checker" in checker_text and params.get("target_zone") and (
params.get("object") or params.get("labels")
):
return "object_zone_checker"
for candidate in [part.strip() for part in str(checker_spec).split("|") if part.strip()]:
base_name = candidate.split(":", 1)[0].strip()
if base_name and self.registry.get(base_name) is not None:
return base_name
if self.registry.get(candidate) is not None:
return candidate
return str(checker_spec)
def _merge_case_annotations(self, contract: EvalContract, observations: dict[str, Any]) -> dict[str, Any]:
"""Merge case-local annotation files into evaluator observations.
The canonical PVR case layout stores human or preconfirmed zones under
``case_dir/annotations/zones.json`` and lightweight facts under
``manual_facts.json``. The checker layer consumes these through the
normal observations object so every run can show exactly which zone
evidence was used.
"""
if contract.case_dir is None:
return observations
merged = dict(observations)
annotation_dir = contract.case_dir / "annotations"
zones = self._load_zone_annotations(annotation_dir / "zones.json")
if zones:
existing_zones = merged.get("zones") if isinstance(merged.get("zones"), dict) else {}
merged["zones"] = {**zones, **existing_zones}
existing_zone_annotations = (
merged.get("zone_annotations") if isinstance(merged.get("zone_annotations"), dict) else {}
)
merged["zone_annotations"] = {**zones, **existing_zone_annotations}
manual_facts_path = annotation_dir / "manual_facts.json"
if manual_facts_path.is_file():
manual_facts = load_json(manual_facts_path)
existing_manual_facts = merged.get("manual_facts") if isinstance(merged.get("manual_facts"), dict) else {}
merged["manual_facts"] = {**manual_facts, **existing_manual_facts}
sources = list(merged.get("observation_sources", [])) if isinstance(merged.get("observation_sources"), list) else []
if zones:
sources.append({"type": "case_annotations", "path": str(annotation_dir / "zones.json"), "zone_count": len(zones)})
if manual_facts_path.is_file():
sources.append({"type": "manual_facts", "path": str(manual_facts_path)})
if sources:
merged["observation_sources"] = sources
return merged
@staticmethod
def _merge_auto_zones(contract: EvalContract, observations: dict[str, Any], pred_image: str | Path) -> dict[str, Any]:
auto_zones = resolve_auto_zones(contract=contract, observations=observations, pred_image=pred_image)
if not auto_zones:
return observations
merged = dict(observations)
existing_zones = merged.get("zones") if isinstance(merged.get("zones"), dict) else {}
merged["zones"] = {**auto_zones, **existing_zones}
existing_auto = merged.get("auto_zones") if isinstance(merged.get("auto_zones"), dict) else {}
merged["auto_zones"] = {**existing_auto, **auto_zones}
sources = list(merged.get("observation_sources", [])) if isinstance(merged.get("observation_sources"), list) else []
sources.append({"type": "auto_zone_resolver", "zone_count": len(auto_zones), "zone_ids": sorted(auto_zones)})
merged["observation_sources"] = sources
return merged
@staticmethod
def _load_zone_annotations(path: Path) -> dict[str, Any]:
if not path.is_file():
return {}
payload = load_json(path)
raw_zones = payload.get("zones", [])
if isinstance(raw_zones, dict):
items = raw_zones.values()
elif isinstance(raw_zones, list):
items = raw_zones
else:
items = []
zones: dict[str, Any] = {}
for item in items:
if not isinstance(item, dict):
continue
zone_id = str(item.get("zone_id") or item.get("id") or "").strip()
if not zone_id:
continue
zone = dict(item)
if "bbox" not in zone and isinstance(zone.get("rect"), list) and len(zone["rect"]) == 4:
zone["bbox"] = zone["rect"]
zones[zone_id] = zone
return zones
@staticmethod
def _resolve_input_image(contract: EvalContract) -> Path | None:
if contract.case_dir is None:
return None
path = Path(contract.input_image)
if path.is_absolute():
return path
return contract.case_dir / path
|