"""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