"""Evaluation runner for mask-aware PVR case_bank predictions.""" from __future__ import annotations from pathlib import Path from typing import Any from pvr_eval.checks import aggregate_dimension_scores, evaluate_atomic_check from pvr_eval.image_metrics import masked_rgb_metrics, validate_image from pvr_eval.io_utils import load_json from pvr_eval.schema import EvalSpec, normalize_observations def weighted_overall_score(dimension_scores: dict[str, float], weights: dict[str, float]) -> float: total = 0.0 used_weight = 0.0 for dimension, weight in weights.items(): if weight <= 0: continue score = dimension_scores.get(dimension) if score is None: continue total += float(score) * float(weight) used_weight += float(weight) if used_weight == 0: return 0.0 return max(0.0, min(1.0, total / used_weight)) def apply_score_caps( *, overall_score: float, primary_task_score: float, dimension_scores: dict[str, float], check_results: list[dict[str, Any]], spec: EvalSpec, ) -> tuple[float, float, list[str], str | None]: failure_tags: list[str] = [] failure_stage: str | None = None hard_failed = [result for result in check_results if result.get("hard_fail") and result.get("status") == "fail"] if hard_failed: primary_cap = float(spec.thresholds.get("hard_fail_primary_cap", 0.3)) overall_cap = float(spec.thresholds.get("hard_fail_overall_cap", 0.5)) primary_task_score = min(primary_task_score, primary_cap) overall_score = min(overall_score, overall_cap) failure_tags.append("hard_check_failed") failure_stage = "task_correctness" instruction_threshold = float(spec.thresholds.get("instruction_min_threshold", 0.0)) instruction_cap = float(spec.thresholds.get("low_instruction_overall_cap", 0.5)) instruction_score = dimension_scores.get("instruction") if instruction_threshold > 0 and instruction_score is not None and instruction_score < instruction_threshold: overall_score = min(overall_score, instruction_cap) failure_tags.append("low_instruction_score") failure_stage = failure_stage or "task_correctness" uncertain_count = sum(1 for result in check_results if result.get("status") == "uncertain") if uncertain_count: failure_tags.append("uncertain_checks") task_dimensions = {"instruction", "spatial", "attribute"} if not any(dimension in dimension_scores for dimension in task_dimensions): failure_tags.append("insufficient_task_evidence") return overall_score, primary_task_score, failure_tags, failure_stage def apply_observation_failure_caps( *, overall_score: float, primary_task_score: float, observations: dict[str, Any], failure_tags: list[str], failure_stage: str | None, ) -> tuple[float, float, list[str], str | None]: detected_failures = observations.get("detected_failures") or [] if not isinstance(detected_failures, list): return overall_score, primary_task_score, failure_tags, failure_stage severities = { str(item.get("severity", "")).lower() for item in detected_failures if isinstance(item, dict) } hard_cap_sources = {"detector_signal_expectation", "structured_checker", "manual_observation"} hard_cap_severities = { str(item.get("severity", "")).lower() for item in detected_failures if isinstance(item, dict) and str(item.get("source", "")).lower() in hard_cap_sources } if "critical" in hard_cap_severities: overall_score = min(overall_score, 0.3) primary_task_score = min(primary_task_score, 0.2) failure_tags.append("critical_failure") failure_stage = failure_stage or "task_correctness" elif "major" in hard_cap_severities: failure_tags.append("major_failure") elif "critical" in severities: failure_tags.append("vlm_critical_advisory") elif "major" in severities: failure_tags.append("vlm_major_failure") return overall_score, primary_task_score, failure_tags, failure_stage def evaluate_case( *, eval_spec_path: str | Path, pred_image_path: str | Path, observations_path: str | Path | None = None, model_id: str = "unknown_model", run_id: str = "manual_eval", ) -> dict[str, Any]: spec = EvalSpec.from_dict(load_json(eval_spec_path), eval_spec_path) pred_image = Path(pred_image_path) observations = normalize_observations(load_json(observations_path) if observations_path else None) validity = validate_image(pred_image) if not validity["ok"]: return { "case_id": spec.case_id, "task_family": spec.task_family, "model_id": model_id, "run_id": run_id, "eval_type": spec.eval_type, "hard_fail": True, "overall_score": 0.0, "primary_task_score": 0.0, "visual_integrity_score": 0.0, "dimension_scores": {}, "failure_stage": validity.get("failure_stage", "format"), "failure_tags": [validity.get("error", "invalid_image")], "needs_human_review": True, "confidence": 0.0, "details": { "validity": validity, "atomic_checks": [], }, } check_results = [evaluate_atomic_check(check, observations) for check in spec.atomic_checks] dimension_scores = aggregate_dimension_scores(check_results, observations.get("dimension_scores")) invariant_metrics = None invariant_mask = spec.mask_paths.get("invariant") input_image = spec.resolve(spec.input_image) if invariant_mask and input_image and input_image.is_file(): mask_path = spec.resolve(invariant_mask) if mask_path and mask_path.is_file(): invariant_metrics = masked_rgb_metrics(input_image, pred_image, mask_path) if invariant_metrics.get("available") and "invariant" not in dimension_scores: dimension_scores["invariant"] = float(invariant_metrics["score"]) if observations.get("visual_quality") is not None and "visual_quality" not in dimension_scores: dimension_scores["visual_quality"] = max(0.0, min(1.0, float(observations["visual_quality"]))) primary_dimensions = ["instruction", "spatial", "attribute"] primary_weights = {key: spec.scoring_weights.get(key, 0.0) for key in primary_dimensions} primary_task_score = weighted_overall_score(dimension_scores, primary_weights) visual_integrity_score = weighted_overall_score( dimension_scores, { "invariant": spec.scoring_weights.get("invariant", 0.0), "visual_quality": spec.scoring_weights.get("visual_quality", 0.0), }, ) overall_score = weighted_overall_score(dimension_scores, spec.scoring_weights) overall_score, primary_task_score, failure_tags, failure_stage = apply_score_caps( overall_score=overall_score, primary_task_score=primary_task_score, dimension_scores=dimension_scores, check_results=check_results, spec=spec, ) overall_score, primary_task_score, failure_tags, failure_stage = apply_observation_failure_caps( overall_score=overall_score, primary_task_score=primary_task_score, observations=observations, failure_tags=failure_tags, failure_stage=failure_stage, ) confidence_values = [float(result["confidence"]) for result in check_results] if invariant_metrics and invariant_metrics.get("available"): confidence_values.append(1.0) confidence = sum(confidence_values) / len(confidence_values) if confidence_values else 0.0 needs_human_review = False if "low_confidence" in spec.human_review_triggers and confidence < float(spec.thresholds.get("confidence_min", 0.65)): needs_human_review = True if "hard_check_uncertain" in spec.human_review_triggers and any( result.get("hard_fail") and result.get("status") == "uncertain" for result in check_results ): needs_human_review = True if "uncertain_checks" in failure_tags or "insufficient_task_evidence" in failure_tags: needs_human_review = True if any(tag in failure_tags for tag in ["vlm_major_failure", "vlm_critical_advisory", "major_failure", "critical_failure"]): needs_human_review = True return { "case_id": spec.case_id, "task_family": spec.task_family, "model_id": model_id, "run_id": run_id, "eval_type": spec.eval_type, "hard_fail": bool(failure_stage == "format" or "hard_check_failed" in failure_tags), "overall_score": round(overall_score, 6), "primary_task_score": round(primary_task_score, 6), "visual_integrity_score": round(visual_integrity_score, 6), "dimension_scores": {key: round(value, 6) for key, value in sorted(dimension_scores.items())}, "failure_stage": failure_stage, "failure_tags": failure_tags, "needs_human_review": needs_human_review, "confidence": round(confidence, 6), "details": { "validity": validity, "invariant_metrics": invariant_metrics, "atomic_checks": check_results, "observations_notes": observations.get("notes"), }, }