"""Compile resolved PVR contracts into executable eval contracts and plans.""" from __future__ import annotations from collections import Counter, defaultdict from dataclasses import dataclass from pathlib import Path from typing import Any from pvr_eval.checkers.base import CheckerRegistry CHECKER_ALIASES = { "color_blob_parser": "color_classifier", "grid_slot_parser": "grid_state_parser", "image_similarity_guard": "input_output_similarity_guard", "object_zone_checker+preservation_checker": "object_zone_checker|preservation_checker", } MODEL_BACKEND_BY_PROPOSAL = { "dino_box": "dino_or_yolo_detector", "yolo_box": "yolo_world_or_yoloe_detector", "sam_mask": "sam_mask_refiner", "vlm_box": "vlm_region_proposer", "ocr_layout": "ocr_layout_engine", "route_mask": "route_mask_parser", "cv_segmentation": "cv_segmentation_parser", "grid_parser": "grid_layout_parser", "color_blob_parser": "color_blob_parser", } @dataclass(frozen=True) class CompileArtifacts: """Payloads produced for one resolved case.""" compiled_contract: dict[str, Any] observation_plan: dict[str, Any] compile_report: dict[str, Any] def compile_resolved_case( *, source_contract: dict[str, Any], resolved_contract: dict[str, Any], source_contract_path: str | Path, resolved_contract_path: str | Path, registry: CheckerRegistry | None = None, ) -> CompileArtifacts: """Compile one PPAPI-resolved contract into package-native structures. The resolver emits human-readable ``resolved_checks``. The formal runner consumes ``atomic_checks``. This bridge preserves the resolver evidence plan while converting each check into the stable schema used by :class:`pvr_eval.runners.case_runner.EvaluationRunner`. """ case_id = str(resolved_contract.get("case_id") or source_contract.get("case_id") or "").strip() if not case_id: raise ValueError("resolved/source contract is missing case_id") case_dir = Path(source_contract_path).parent original_questions = _index_original_questions(source_contract) resolved_checks = [item for item in resolved_contract.get("resolved_checks", []) if isinstance(item, dict)] atomic_checks = [ _compile_check(item, original_questions.get(str(item.get("id", "")), {})) for item in resolved_checks ] compiled_contract = { "case_id": case_id, "source": source_contract.get("source", ""), "top_level": source_contract.get("top_level", ""), "case_family": resolved_contract.get("case_family") or source_contract.get("case_family", ""), "task_family": source_contract.get("task_family", ""), "eval_type": "resolved_executable_contract_v1", "scoring_policy": source_contract.get("scoring_policy", "task_success_minus_penalty"), "instruction": source_contract.get("instruction", ""), "input_image": _resolve_case_path(case_dir, source_contract.get("input_image", "images/input.jpg")), "gt_image": _resolve_case_path(case_dir, source_contract.get("gt_image", source_contract.get("reference_image", ""))), "quality_gate": source_contract.get("quality_gate", {}), "manual_facts": { **dict(source_contract.get("manual_facts", {}) or {}), "resolved_intended_final_state": resolved_contract.get("intended_final_state", ""), }, "zones": source_contract.get("zones", {}), "metadata": { "source_contract_path": str(source_contract_path), "resolved_contract_path": str(resolved_contract_path), "resolver_version": resolved_contract.get("resolver_version", ""), "resolver_readiness": resolved_contract.get("readiness", ""), "global_annotation_needs": resolved_contract.get("global_annotation_needs", []), "global_auto_region_proposals": resolved_contract.get("global_auto_region_proposals", []), "audit_notes": resolved_contract.get("audit_notes", []), }, "atomic_checks": atomic_checks, } observation_plan = build_observation_plan( compiled_contract=compiled_contract, resolved_contract=resolved_contract, source_contract_path=source_contract_path, ) compile_report = build_compile_report( compiled_contract=compiled_contract, resolved_contract=resolved_contract, observation_plan=observation_plan, registry=registry, ) return CompileArtifacts( compiled_contract=compiled_contract, observation_plan=observation_plan, compile_report=compile_report, ) def build_observation_plan( *, compiled_contract: dict[str, Any], resolved_contract: dict[str, Any], source_contract_path: str | Path, ) -> dict[str, Any]: """Build model/parser jobs required before scoring can run.""" case_id = compiled_contract["case_id"] source_contract_path = Path(source_contract_path) case_dir = source_contract_path.parent global_regions = _normalize_region_jobs( resolved_contract.get("global_auto_region_proposals", []), source="global_auto_region_proposals", ) per_check_regions: list[dict[str, Any]] = [] checker_jobs: list[dict[str, Any]] = [] for check in compiled_contract.get("atomic_checks", []): params = dict(check.get("params", {}) or {}) check_regions = _normalize_region_jobs( params.get("auto_region_proposals", []), source=f"check:{check.get('id', '')}", used_by=[check.get("id", "")], ) per_check_regions.extend(check_regions) checker_jobs.append({ "check_id": check.get("id", ""), "role": check.get("role", "reward"), "dimension": check.get("dimension", ""), "checker": check.get("checker", ""), "original_recommended_checker": params.get("recommended_checker", ""), "fallback_checker": params.get("fallback_checker", ""), "region_ids": sorted(_region_ids_for_check(check, check_regions, global_regions)), "required_evidence": params.get("evidence_required", []), "decision_rule": params.get("decision_rule", ""), "params": params.get("checker_params", {}), }) all_region_jobs = _dedupe_region_jobs(global_regions + per_check_regions) by_method: dict[str, list[dict[str, Any]]] = defaultdict(list) for job in all_region_jobs: by_method[str(job.get("proposal_method", "unknown"))].append(job) return { "case_id": case_id, "readiness": resolved_contract.get("readiness", ""), "case_family": compiled_contract.get("case_family", ""), "instruction": compiled_contract.get("instruction", ""), "case_dir": str(case_dir), "input_image": _resolve_case_path(case_dir, compiled_contract.get("input_image", "")), "reference_image": _resolve_case_path(case_dir, compiled_contract.get("gt_image", "")), "region_jobs": all_region_jobs, "region_jobs_by_method": dict(sorted(by_method.items())), "checker_jobs": checker_jobs, "backend_requirements": _backend_requirements(all_region_jobs, checker_jobs), "human_annotation_needs": resolved_contract.get("global_annotation_needs", []), "notes": [ "This plan does not contain model observations yet.", "Run detector/OCR/SAM/parser backends to materialize observations, then execute compiled_eval_contract.json.", ], } def build_compile_report( *, compiled_contract: dict[str, Any], resolved_contract: dict[str, Any], observation_plan: dict[str, Any], registry: CheckerRegistry | None = None, ) -> dict[str, Any]: """Summarize compile health and execution gaps.""" checker_counts = Counter(str(item.get("checker", "")) for item in compiled_contract.get("atomic_checks", [])) registered: dict[str, bool] = {} selected: dict[str, str] = {} if registry is not None: for checker in checker_counts: selected_checker = _select_registered_checker(checker, registry) selected[checker] = selected_checker or "" registered[checker] = bool(selected_checker) missing = [checker for checker, ok in registered.items() if not ok] method_counts = Counter(str(item.get("proposal_method", "unknown")) for item in observation_plan.get("region_jobs", [])) annotation_needs = resolved_contract.get("global_annotation_needs", []) or [] status = "compiled" if not compiled_contract.get("atomic_checks"): status = "skipped_no_resolved_checks" elif missing: status = "compiled_with_missing_checker" elif annotation_needs: status = "compiled_needs_human_annotation" return { "case_id": compiled_contract.get("case_id", ""), "status": status, "resolver_readiness": resolved_contract.get("readiness", ""), "atomic_check_count": len(compiled_contract.get("atomic_checks", [])), "reward_check_count": sum(1 for item in compiled_contract.get("atomic_checks", []) if item.get("role") != "penalty"), "penalty_check_count": sum(1 for item in compiled_contract.get("atomic_checks", []) if item.get("role") == "penalty"), "checker_counts": dict(sorted(checker_counts.items())), "checker_registered": registered, "checker_selected": selected, "missing_checkers": missing, "region_job_count": len(observation_plan.get("region_jobs", [])), "region_job_method_counts": dict(sorted(method_counts.items())), "backend_requirements": observation_plan.get("backend_requirements", {}), "human_annotation_need_count": len(annotation_needs), "human_annotation_needs": annotation_needs, "audit_notes": resolved_contract.get("audit_notes", []), } def _compile_check(resolved_check: dict[str, Any], original: dict[str, Any]) -> dict[str, Any]: check_id = str(resolved_check.get("id") or original.get("id") or "").strip() if not check_id: raise ValueError("resolved check is missing id") role = "penalty" if str(resolved_check.get("role") or original.get("role") or "").lower() == "penalty" else "reward" score_key = "max_deduct" if role == "penalty" else "points" raw_weight = resolved_check.get("weight_or_max_deduct", original.get(score_key, original.get("weight", 1.0))) checker = _normalize_checker(str(resolved_check.get("recommended_checker") or original.get("checker") or "observation")) checker_params = dict(resolved_check.get("params", {}) or {}) return { "id": check_id, "role": role, "dimension": str(resolved_check.get("dimension") or original.get("dimension") or "target_completion"), score_key: float(raw_weight), "checker": checker, "question": original.get("question", ""), "description": original.get("question") or resolved_check.get("decision_rule", ""), "pass_criteria": original.get("pass_criteria", ""), "partial_criteria": original.get("partial_criteria", ""), "fail_criteria": original.get("fail_criteria", ""), "hard_fail": bool(original.get("hard_fail", False)), "params": { "checker_params": checker_params, **checker_params, "original_checker": resolved_check.get("original_checker", original.get("checker", "")), "recommended_checker": resolved_check.get("recommended_checker", ""), "normalized_checker": checker, "fallback_checker": resolved_check.get("fallback_checker", ""), "region_resolution": resolved_check.get("region_resolution", ""), "auto_region_proposals": resolved_check.get("auto_region_proposals", []), "annotation_needs": resolved_check.get("annotation_needs", []), "needs_annotation": bool(resolved_check.get("needs_annotation", False)), "decision_rule": resolved_check.get("decision_rule", ""), "evidence_required": resolved_check.get("evidence_required", []), "resolver_confidence": resolved_check.get("confidence", None), }, } def _index_original_questions(source_contract: dict[str, Any]) -> dict[str, dict[str, Any]]: out: dict[str, dict[str, Any]] = {} for role, key in (("reward", "reward_questions"), ("penalty", "penalty_questions")): for item in source_contract.get(key, []) or []: if not isinstance(item, dict): continue check_id = str(item.get("id", "")).strip() if check_id: out[check_id] = {"role": role, **item} for item in source_contract.get("atomic_checks", []) or []: if not isinstance(item, dict): continue check_id = str(item.get("id") or item.get("check_id") or "").strip() if check_id and check_id not in out: out[check_id] = dict(item) return out def _normalize_checker(checker: str) -> str: checker = checker.strip() or "observation" return CHECKER_ALIASES.get(checker, checker) def _normalize_region_jobs( proposals: Any, *, source: str, used_by: list[str] | None = None, ) -> list[dict[str, Any]]: if not isinstance(proposals, list): return [] jobs: list[dict[str, Any]] = [] for item in proposals: if not isinstance(item, dict): continue region_id = str(item.get("region_id") or item.get("id") or "").strip() method = str(item.get("proposal_method") or "unknown").strip() query = str(item.get("query_or_rule") or item.get("query") or "").strip() description = str(item.get("description") or "").strip() job_used_by = item.get("used_by", used_by or []) if isinstance(job_used_by, str): job_used_by = [job_used_by] if not region_id: region_id = _stable_region_id(method, description, query) jobs.append({ "region_id": region_id, "proposal_method": method, "backend": MODEL_BACKEND_BY_PROPOSAL.get(method, "custom_or_vlm_backend"), "image_scope": _infer_image_scope(region_id, description, query), "description": description, "query_or_rule": query, "used_by": [str(value) for value in (job_used_by or [])], "source": source, }) return jobs def _dedupe_region_jobs(jobs: list[dict[str, Any]]) -> list[dict[str, Any]]: merged: dict[tuple[str, str], dict[str, Any]] = {} for job in jobs: key = (str(job.get("region_id", "")), str(job.get("proposal_method", ""))) if key not in merged: merged[key] = dict(job) continue existing = merged[key] existing["used_by"] = sorted(set(existing.get("used_by", [])) | set(job.get("used_by", []))) if not existing.get("query_or_rule") and job.get("query_or_rule"): existing["query_or_rule"] = job["query_or_rule"] if not existing.get("description") and job.get("description"): existing["description"] = job["description"] return sorted(merged.values(), key=lambda item: (str(item.get("proposal_method", "")), str(item.get("region_id", "")))) def _region_ids_for_check( check: dict[str, Any], check_regions: list[dict[str, Any]], global_regions: list[dict[str, Any]], ) -> set[str]: check_id = str(check.get("id", "")) out = {str(job.get("region_id", "")) for job in check_regions if job.get("region_id")} for job in global_regions: used_by = {str(item) for item in job.get("used_by", []) or []} if check_id in used_by: out.add(str(job.get("region_id", ""))) params = check.get("params", {}) or {} for key, value in params.items(): if key.endswith("_zone") or key.endswith("_region") or key.endswith("_mask") or key in {"slot", "zones", "target_zone"}: if isinstance(value, str): out.add(value) elif isinstance(value, list): out.update(str(item) for item in value if isinstance(item, str)) return {item for item in out if item} def _backend_requirements(region_jobs: list[dict[str, Any]], checker_jobs: list[dict[str, Any]]) -> dict[str, Any]: proposal_counts = Counter(str(item.get("proposal_method", "unknown")) for item in region_jobs) backend_counts = Counter(str(item.get("backend", "unknown")) for item in region_jobs) checker_counts = Counter(str(item.get("checker", "unknown")) for item in checker_jobs) return { "proposal_method_counts": dict(sorted(proposal_counts.items())), "backend_counts": dict(sorted(backend_counts.items())), "checker_counts": dict(sorted(checker_counts.items())), } def _select_registered_checker(checker_spec: str, registry: CheckerRegistry) -> str | None: for candidate in [part.strip() for part in str(checker_spec).split("|") if part.strip()]: if registry.get(candidate) is not None: return candidate base = candidate.split(":", 1)[0].strip() if registry.get(base) is not None: return base return checker_spec if registry.get(checker_spec) is not None else None def _infer_image_scope(region_id: str, description: str, query: str) -> str: text = f"{region_id} {description} {query}".lower() has_input = any(token in text for token in ("input", "source", "original", "before edit")) has_output = any(token in text for token in ("output", "newly", "drawn", "after edit", "prediction")) if has_input and has_output: return "input_and_output" if has_input: return "input" if has_output: return "output" return "output_or_input_context" def _stable_region_id(method: str, description: str, query: str) -> str: text = "_".join((method, description, query)).lower() chars = [ch if ch.isalnum() else "_" for ch in text] token = "_".join("".join(chars).split("_")[:8]).strip("_") return token or "unnamed_region" def _resolve_case_path(case_dir: Path, path_text: str) -> str: if not path_text: return "" path = Path(path_text) if path.is_absolute(): return str(path) candidate = case_dir / path if candidate.exists(): return str(candidate.resolve()) image_candidate = case_dir / "images" / path.name if image_candidate.exists(): return str(image_candidate.resolve()) return str(candidate.resolve())