File size: 9,443 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
214
215
216
217
218
219
220
"""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"),
        },
    }