File size: 28,842 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
"""Conservative, check-scoped computer-vision evidence executors.

These helpers deliberately produce measurements, not check scores.  A tool
status of ``ok`` means that the stated measurement was available; it does not
mean that an atomic question passed.  When a generic parser request lacks the
structured facts needed to make an objective measurement, the executor emits
``unsupported`` or ``insufficient`` instead of guessing from prose.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Iterable, Mapping

import numpy as np
from PIL import Image

from pvr_eval.agent.human_pose_executor import run_human_pose_estimation
from pvr_eval.agent.preservation_local_correspondence import run_local_correspondence


CV_TOOL_TYPES = frozenset(
    {
        "image_registration",
        "change_analysis",
        "route_parser",
        "visual_attribute_parser",
        "state_parser",
        "human_pose_parser",
        "local_correspondence",
    }
)

_COLOR_KEYS = ("line_color", "wire_color", "route_color", "expected_color", "target_color", "color")
_SUPPORTED_COLORS = frozenset(
    {"red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink", "black", "white", "gray", "grey", "brown"}
)


def _json_value(value: Any, default: Any) -> Any:
    if value in (None, ""):
        return default
    if not isinstance(value, str):
        return value
    try:
        return json.loads(value)
    except (TypeError, ValueError):
        return default


def _strings(value: Any) -> list[str]:
    decoded = _json_value(value, value)
    if isinstance(decoded, str):
        return [item for item in decoded.split("|") if item]
    if isinstance(decoded, (list, tuple, set)):
        return [str(item) for item in decoded if str(item)]
    return []


def _base_payload(call: Mapping[str, Any], tool: str) -> dict[str, Any]:
    return {
        "call_id": str(call.get("call_id", "")),
        "cache_key": str(call.get("cache_key", "")),
        "case_key": str(call.get("case_key", "")),
        "check_ids": _strings(call.get("check_ids", [])),
        "image_role": str(call.get("image_role", "")),
        "tool": tool,
        "status": "unsupported",
        "backend": "pvr_cv_tools_v1",
        "metrics": {},
        "thresholds": {},
        "limitations": ["evidence_only_no_pass_fail_score"],
    }


def _result(
    call: Mapping[str, Any],
    *,
    tool: str,
    status: str,
    metrics: Mapping[str, Any] | None = None,
    thresholds: Mapping[str, Any] | None = None,
    limitations: Iterable[str] = (),
    backend: str = "pvr_cv_tools_v1",
) -> dict[str, Any]:
    payload = _base_payload(call, tool)
    payload.update(
        {
            "status": status,
            "backend": backend,
            "metrics": dict(metrics or {}),
            "thresholds": dict(thresholds or {}),
            "limitations": list(dict.fromkeys([*payload["limitations"], *limitations])),
        }
    )
    return payload


def error_payload(call: Mapping[str, Any], exc: Exception) -> dict[str, Any]:
    tool = str(call.get("tool", ""))
    payload = _result(call, tool=tool, status="error", limitations=("tool_execution_failed",))
    payload["error_type"] = type(exc).__name__
    payload["error_message"] = str(exc)
    return payload


def _params(call: Mapping[str, Any], check_params: Mapping[str, Any] | None) -> dict[str, Any]:
    direct = _json_value(call.get("params", {}), {})
    merged = dict(direct) if isinstance(direct, dict) else {}
    if isinstance(check_params, Mapping):
        merged.update(check_params)
    rule = merged.get("decision_rule")
    if isinstance(rule, Mapping) and isinstance(rule.get("parameters"), Mapping):
        # The resolved compiler stores thresholds here.  Keep top-level values
        # authoritative when an explicit adapter has already normalized them.
        merged = {**dict(rule["parameters"]), **merged}
    return merged


def _load_rgb(path: str | Path) -> np.ndarray:
    with Image.open(path) as image:
        return np.asarray(image.convert("RGB"), dtype=np.uint8)


def _resize_rgb(rgb: np.ndarray, size: tuple[int, int]) -> np.ndarray:
    return np.asarray(Image.fromarray(rgb).resize(size, Image.Resampling.BILINEAR), dtype=np.uint8)


def _pair_paths(call: Mapping[str, Any]) -> tuple[Path, Path]:
    if str(call.get("image_role", "")) != "input_pred":
        raise ValueError("paired CV tool requires image_role=input_pred")
    return Path(str(call["input"])), Path(str(call["pred"]))


def _single_path(call: Mapping[str, Any]) -> Path:
    role = str(call.get("image_role", "pred"))
    if role not in {"input", "pred"}:
        raise ValueError(f"single-image CV tool does not support image_role={role!r}")
    return Path(str(call[role]))


def _gray_features(rgb: np.ndarray) -> np.ndarray:
    gray = np.dot(rgb.astype(np.float32) / 255.0, np.array([0.299, 0.587, 0.114], dtype=np.float32))
    # Gradients reduce the influence of global color and brightness changes.
    gx = np.zeros_like(gray)
    gy = np.zeros_like(gray)
    gx[:, 1:] = np.diff(gray, axis=1)
    gy[1:, :] = np.diff(gray, axis=0)
    feature = np.hypot(gx, gy)
    feature -= float(feature.mean())
    return feature


def _phase_translation(reference: np.ndarray, moving: np.ndarray) -> tuple[float, float, dict[str, float]]:
    fa = np.fft.fft2(reference)
    fb = np.fft.fft2(moving)
    cross = fa * np.conj(fb)
    magnitude = np.abs(cross)
    cross /= np.maximum(magnitude, 1e-12)
    correlation = np.fft.ifft2(cross).real
    peak_y, peak_x = np.unravel_index(int(np.argmax(correlation)), correlation.shape)
    height, width = correlation.shape
    shift_y = float(peak_y - height if peak_y > height // 2 else peak_y)
    shift_x = float(peak_x - width if peak_x > width // 2 else peak_x)
    peak = float(correlation[peak_y, peak_x])
    exclusion = correlation.copy()
    radius = 3
    ys = [(peak_y + offset) % height for offset in range(-radius, radius + 1)]
    xs = [(peak_x + offset) % width for offset in range(-radius, radius + 1)]
    exclusion[np.ix_(ys, xs)] = -np.inf
    sidelobe = float(np.max(exclusion)) if np.isfinite(exclusion).any() else 0.0
    median = float(np.median(correlation))
    mad = float(np.median(np.abs(correlation - median)))
    robust_z = (peak - median) / max(1e-9, 1.4826 * mad)
    # Keep cache JSON standards-compliant even for a perfect impulse peak.
    peak_to_sidelobe = (peak + 1e-9) / (max(0.0, sidelobe) + 1e-9)
    return shift_x, shift_y, {
        "phase_peak": peak,
        "phase_sidelobe_peak": sidelobe,
        "peak_to_sidelobe_ratio": peak_to_sidelobe,
        "phase_peak_robust_z": robust_z,
    }


def run_image_registration(call: Mapping[str, Any], params: Mapping[str, Any]) -> dict[str, Any]:
    input_path, pred_path = _pair_paths(call)
    input_rgb, pred_rgb = _load_rgb(input_path), _load_rgb(pred_path)
    input_h, input_w = input_rgb.shape[:2]
    pred_h, pred_w = pred_rgb.shape[:2]
    input_aspect = input_w / max(1, input_h)
    pred_aspect = pred_w / max(1, pred_h)
    aspect_delta = abs(input_aspect - pred_aspect) / max(input_aspect, 1e-9)
    max_dimension = int(params.get("registration_max_dimension", 512))
    scale = min(1.0, max_dimension / max(input_h, input_w))
    work_w = max(32, int(round(input_w * scale)))
    work_h = max(32, int(round(input_h * scale)))
    ref = _gray_features(_resize_rgb(input_rgb, (work_w, work_h)))
    moving = _gray_features(_resize_rgb(pred_rgb, (work_w, work_h)))
    texture_std = min(float(ref.std()), float(moving.std()))
    thresholds = {
        "min_texture_gradient_std": float(params.get("min_texture_gradient_std", 0.015)),
        "min_peak_to_sidelobe_ratio": float(params.get("min_peak_to_sidelobe_ratio", 1.25)),
        "min_phase_peak_robust_z": float(params.get("min_phase_peak_robust_z", 8.0)),
        "min_overlap_fraction": float(params.get("min_registration_overlap", 0.70)),
        "max_aspect_ratio_relative_delta": float(params.get("max_aspect_ratio_relative_delta", 0.03)),
    }
    shift_x_work, shift_y_work, phase = _phase_translation(ref, moving)
    shift_x = shift_x_work / scale
    shift_y = shift_y_work / scale
    overlap = max(0.0, input_w - abs(shift_x)) * max(0.0, input_h - abs(shift_y)) / max(1.0, input_w * input_h)
    metrics: dict[str, Any] = {
        "input_size_wh": [input_w, input_h],
        "pred_size_wh": [pred_w, pred_h],
        "working_size_wh": [work_w, work_h],
        "aspect_ratio_relative_delta": aspect_delta,
        "texture_gradient_std": texture_std,
        "translation_pred_to_input_px": [shift_x, shift_y],
        "translation_matrix_pred_to_input": [[1.0, 0.0, shift_x], [0.0, 1.0, shift_y], [0.0, 0.0, 1.0]],
        "overlap_fraction": overlap,
        **phase,
    }
    limitations = ["translation_only_no_rotation_scale_or_homography"]
    supported_geometry = aspect_delta <= thresholds["max_aspect_ratio_relative_delta"]
    reliable = (
        supported_geometry
        and texture_std >= thresholds["min_texture_gradient_std"]
        and phase["peak_to_sidelobe_ratio"] >= thresholds["min_peak_to_sidelobe_ratio"]
        and phase["phase_peak_robust_z"] >= thresholds["min_phase_peak_robust_z"]
        and overlap >= thresholds["min_overlap_fraction"]
    )
    if not supported_geometry:
        limitations.append("aspect_ratio_mismatch_requires_non_translation_registration")
    if texture_std < thresholds["min_texture_gradient_std"]:
        limitations.append("insufficient_visual_texture_for_registration")
    if not reliable:
        limitations.append("registration_not_reliable_enough_for_automatic_scoring")
    return _result(
        call,
        tool="image_registration",
        status="ok" if reliable else "insufficient",
        metrics=metrics,
        thresholds=thresholds,
        limitations=limitations,
        backend="numpy_phase_correlation_translation_v1",
    )


def _rect_to_pixels(value: Any, width: int, height: int) -> tuple[int, int, int, int] | None:
    if isinstance(value, Mapping):
        if "geometry" in value:
            return _rect_to_pixels(value["geometry"], width, height)
        if "bbox" in value:
            return _rect_to_pixels(value["bbox"], width, height)
        if "rect" in value:
            return _rect_to_pixels(value["rect"], width, height)
        if {"x0", "y0", "x1", "y1"} <= set(value):
            value = [value["x0"], value["y0"], value["x1"], value["y1"]]
        elif {"x", "y", "width", "height"} <= set(value):
            value = [value["x"], value["y"], float(value["x"]) + float(value["width"]), float(value["y"]) + float(value["height"])]
        elif isinstance(value.get("points"), list) and value["points"]:
            points = value["points"]
            try:
                xs = [float(point[0]) for point in points]
                ys = [float(point[1]) for point in points]
            except (TypeError, ValueError, IndexError):
                return None
            value = [min(xs), min(ys), max(xs), max(ys)]
        else:
            return None
    if not isinstance(value, (list, tuple)) or len(value) != 4:
        return None
    try:
        x0, y0, x1, y1 = [float(item) for item in value]
    except (TypeError, ValueError):
        return None
    if max(abs(x0), abs(y0), abs(x1), abs(y1)) <= 1.0:
        x0, x1 = x0 * width, x1 * width
        y0, y1 = y0 * height, y1 * height
    x0, x1 = sorted((max(0, min(width, int(round(x0)))), max(0, min(width, int(round(x1))))))
    y0, y1 = sorted((max(0, min(height, int(round(y0)))), max(0, min(height, int(round(y1))))))
    return (x0, y0, x1, y1) if x1 > x0 and y1 > y0 else None


def _region_ids(call: Mapping[str, Any], params: Mapping[str, Any]) -> list[str]:
    result = _strings(call.get("region_ids", []))
    for key in ("zone", "zone_id", "target_zone", "source_zone", "forbidden_zone", "target_region", "corridor"):
        value = params.get(key)
        if isinstance(value, str) and value:
            result.append(value)
    for key in ("invariant_zones", "target_zones", "forbidden_zones", "exclude_zones", "required_nodes"):
        value = params.get(key)
        if isinstance(value, list):
            result.extend(str(item) for item in value if isinstance(item, (str, int)))
    return list(dict.fromkeys(result))


def _resolved_regions(
    call: Mapping[str, Any], params: Mapping[str, Any], regions: Mapping[str, Any] | None, width: int, height: int
) -> tuple[dict[str, tuple[int, int, int, int]], list[str]]:
    candidates: dict[str, Any] = dict(regions or {})
    planned = params.get("planned_regions", [])
    if isinstance(planned, list):
        for item in planned:
            if isinstance(item, Mapping):
                region_id = str(item.get("region_id") or item.get("id") or "")
                if region_id:
                    candidates.setdefault(region_id, item)
    resolved: dict[str, tuple[int, int, int, int]] = {}
    missing: list[str] = []
    for region_id in _region_ids(call, params):
        rect = _rect_to_pixels(candidates.get(region_id), width, height)
        if rect is None:
            missing.append(region_id)
        else:
            resolved[region_id] = rect
    return resolved, missing


def _translate_rgb(rgb: np.ndarray, shift_x: float, shift_y: float, output_shape: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]:
    from scipy import ndimage

    height, width = output_shape
    if rgb.shape[:2] != output_shape:
        rgb = _resize_rgb(rgb, (width, height))
    shifted = np.stack(
        [ndimage.shift(rgb[..., channel].astype(np.float32), shift=(shift_y, shift_x), order=1, mode="constant", cval=np.nan) for channel in range(3)],
        axis=2,
    )
    valid = np.isfinite(shifted).all(axis=2)
    return np.nan_to_num(shifted, nan=0.0), valid


def _change_metrics(input_rgb: np.ndarray, aligned_pred: np.ndarray, mask: np.ndarray, threshold: float) -> dict[str, Any]:
    pixels = int(mask.sum())
    if pixels <= 0:
        return {"pixel_count": 0}
    diff = np.abs(input_rgb.astype(np.float32) - aligned_pred.astype(np.float32)) / 255.0
    per_pixel = diff.mean(axis=2)[mask]
    return {
        "pixel_count": pixels,
        "rgb_mae": float(per_pixel.mean()),
        "rgb_rmse": float(np.sqrt(np.mean(per_pixel**2))),
        "changed_fraction": float((per_pixel >= threshold).mean()),
        "difference_p95": float(np.quantile(per_pixel, 0.95)),
    }


def run_change_analysis(
    call: Mapping[str, Any],
    params: Mapping[str, Any],
    regions: Mapping[str, Any] | None,
    dependencies: Mapping[str, Mapping[str, Any]],
) -> dict[str, Any]:
    input_path, pred_path = _pair_paths(call)
    input_rgb, pred_rgb = _load_rgb(input_path), _load_rgb(pred_path)
    height, width = input_rgb.shape[:2]
    dependency_ids = _strings(call.get("depends_on", []))
    registration = next((dependencies[item] for item in dependency_ids if item in dependencies), None)
    threshold = float(params.get("change_pixel_threshold", 24.0 / 255.0))
    thresholds = {"changed_pixel_mean_rgb_fraction": threshold, "registration_status_required": "ok"}
    limitations: list[str] = []
    shift_x = shift_y = 0.0
    registration_ok = False
    if isinstance(registration, Mapping):
        translation = registration.get("metrics", {}).get("translation_pred_to_input_px", [])
        if isinstance(translation, list) and len(translation) == 2:
            shift_x, shift_y = float(translation[0]), float(translation[1])
        registration_ok = registration.get("status") == "ok"
    else:
        limitations.append("missing_registration_dependency")
    if not registration_ok:
        limitations.append("change_metrics_not_safe_for_automatic_scoring_without_reliable_registration")
    aligned, valid = _translate_rgb(pred_rgb, shift_x, shift_y, (height, width))
    resolved, missing = _resolved_regions(call, params, regions, width, height)
    if missing:
        limitations.append("unresolved_regions:" + "|".join(missing))
    global_metrics = _change_metrics(input_rgb, aligned, valid, threshold)
    region_metrics: dict[str, Any] = {}
    for region_id, (x0, y0, x1, y1) in resolved.items():
        mask = np.zeros((height, width), dtype=bool)
        mask[y0:y1, x0:x1] = True
        region_metrics[region_id] = {"bbox_xyxy": [x0, y0, x1, y1], **_change_metrics(input_rgb, aligned, valid & mask, threshold)}
    if not resolved:
        limitations.append("no_resolved_regions_global_metrics_only")
    metrics = {
        "registration_call_id": str(registration.get("call_id", "")) if isinstance(registration, Mapping) else "",
        "applied_translation_pred_to_input_px": [shift_x, shift_y],
        "global": global_metrics,
        "regions": region_metrics,
    }
    status = "ok" if registration_ok and (resolved or not _region_ids(call, params)) else "insufficient"
    return _result(
        call,
        tool="change_analysis",
        status=status,
        metrics=metrics,
        thresholds=thresholds,
        limitations=limitations,
        backend="registered_rgb_difference_v1",
    )


def _explicit_colors(params: Mapping[str, Any]) -> list[str]:
    values: list[Any] = []
    for key in _COLOR_KEYS:
        if key in params:
            values.append(params[key])
    if "colors" in params:
        values.extend(params["colors"] if isinstance(params["colors"], list) else [params["colors"]])
    result = []
    for value in values:
        color = str(value).lower().strip()
        if color in _SUPPORTED_COLORS:
            result.append("gray" if color == "grey" else color)
    return list(dict.fromkeys(result))


def _rgb_to_hsv(rgb: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    arr = rgb.astype(np.float32) / 255.0
    r, g, b = arr[..., 0], arr[..., 1], arr[..., 2]
    maximum, minimum = arr.max(axis=2), arr.min(axis=2)
    delta = maximum - minimum
    hue = np.zeros_like(maximum)
    active = delta > 1e-6
    rmax, gmax, bmax = active & (maximum == r), active & (maximum == g), active & (maximum == b)
    hue[rmax] = (60.0 * ((g[rmax] - b[rmax]) / delta[rmax])) % 360.0
    hue[gmax] = 60.0 * ((b[gmax] - r[gmax]) / delta[gmax] + 2.0)
    hue[bmax] = 60.0 * ((r[bmax] - g[bmax]) / delta[bmax] + 4.0)
    saturation = np.zeros_like(maximum)
    nonzero = maximum > 1e-6
    saturation[nonzero] = delta[nonzero] / maximum[nonzero]
    return hue, saturation, maximum


def _color_mask(rgb: np.ndarray, color: str) -> tuple[np.ndarray, dict[str, Any]]:
    h, s, v = _rgb_to_hsv(rgb)
    ranges: dict[str, tuple[tuple[float, float], ...]] = {
        "red": ((345, 360), (0, 15)), "orange": ((15, 42),), "yellow": ((42, 72),),
        "green": ((72, 165),), "cyan": ((165, 205),), "blue": ((205, 260),),
        "purple": ((260, 300),), "pink": ((300, 345),), "brown": ((10, 45),),
    }
    if color == "black":
        return v <= 0.22, {"value_max": 0.22}
    if color == "white":
        return (s <= 0.18) & (v >= 0.78), {"saturation_max": 0.18, "value_min": 0.78}
    if color == "gray":
        return (s <= 0.20) & (v > 0.22) & (v < 0.78), {"saturation_max": 0.20, "value_range": [0.22, 0.78]}
    sat_min, val_min = (0.28, 0.12) if color == "brown" else (0.30, 0.20)
    hue_mask = np.zeros(h.shape, dtype=bool)
    for low, high in ranges[color]:
        hue_mask |= (h >= low) & (h <= high)
    mask = hue_mask & (s >= sat_min) & (v >= val_min)
    if color == "brown":
        mask &= v <= 0.65
    return mask, {"hue_ranges_degrees": [list(item) for item in ranges[color]], "saturation_min": sat_min, "value_min": val_min}


def _mask_stats(mask: np.ndarray, roi: tuple[int, int, int, int] | None = None) -> dict[str, Any]:
    from scipy import ndimage

    if roi is None:
        x0, y0, x1, y1 = 0, 0, mask.shape[1], mask.shape[0]
    else:
        x0, y0, x1, y1 = roi
    selected = np.zeros_like(mask, dtype=bool)
    selected[y0:y1, x0:x1] = True
    clipped = mask & selected
    labels, count = ndimage.label(clipped)
    areas = [int((labels == index).sum()) for index in range(1, count + 1)]
    area = int(clipped.sum())
    return {
        "bbox_xyxy": [x0, y0, x1, y1],
        "roi_pixel_count": int(selected.sum()),
        "mask_pixel_count": area,
        "mask_fraction": area / max(1, int(selected.sum())),
        "component_count": int(count),
        "largest_component_area_px": max(areas, default=0),
    }


def _color_region_metrics(
    rgb: np.ndarray, colors: list[str], resolved: Mapping[str, tuple[int, int, int, int]]
) -> tuple[dict[str, Any], dict[str, Any]]:
    metrics: dict[str, Any] = {}
    thresholds: dict[str, Any] = {}
    for color in colors:
        mask, color_thresholds = _color_mask(rgb, color)
        thresholds[color] = color_thresholds
        metrics[color] = {
            "global": _mask_stats(mask),
            "regions": {region_id: _mask_stats(mask, rect) for region_id, rect in resolved.items()},
        }
    return metrics, thresholds


def run_route_parser(
    call: Mapping[str, Any], params: Mapping[str, Any], regions: Mapping[str, Any] | None
) -> dict[str, Any]:
    rgb = _load_rgb(_single_path(call))
    height, width = rgb.shape[:2]
    colors = _explicit_colors(params)
    if not colors:
        return _result(
            call,
            tool="route_parser",
            status="unsupported",
            limitations=("route_color_or_typed_route_segmentation_model_not_specified", "semantic_route_identity_not_inferred_from_question_text"),
        )
    resolved, missing = _resolved_regions(call, params, regions, width, height)
    metrics, color_thresholds = _color_region_metrics(rgb, colors, resolved)
    limitations = ["color_mask_is_not_semantic_route_identity", "connectivity_and_endpoint_decisions_require_downstream_checker"]
    if missing:
        limitations.append("unresolved_regions:" + "|".join(missing))
    status = "ok" if not missing else "insufficient"
    return _result(
        call,
        tool="route_parser",
        status=status,
        metrics={"colors": metrics, "resolved_region_count": len(resolved)},
        thresholds={"color_masks": color_thresholds},
        limitations=limitations,
        backend="explicit_hsv_route_mask_v1",
    )


def run_visual_attribute_parser(
    call: Mapping[str, Any], params: Mapping[str, Any], regions: Mapping[str, Any] | None
) -> dict[str, Any]:
    rgb = _load_rgb(_single_path(call))
    height, width = rgb.shape[:2]
    colors = _explicit_colors(params)
    if not colors:
        return _result(
            call,
            tool="visual_attribute_parser",
            status="unsupported",
            limitations=("only_explicit_color_attributes_have_an_objective_parser", "symbols_glyphs_orientation_and_semantic_attributes_require_dedicated_models"),
        )
    resolved, missing = _resolved_regions(call, params, regions, width, height)
    metrics, color_thresholds = _color_region_metrics(rgb, colors, resolved)
    limitations = ["color_fraction_does_not_establish_object_identity"]
    if missing:
        limitations.append("unresolved_regions:" + "|".join(missing))
    if not resolved:
        limitations.append("no_resolved_region_global_color_statistics_only")
    status = "ok" if resolved and not missing else "insufficient"
    return _result(
        call,
        tool="visual_attribute_parser",
        status=status,
        metrics={"colors": metrics, "resolved_region_count": len(resolved)},
        thresholds={"color_masks": color_thresholds},
        limitations=limitations,
        backend="explicit_hsv_attribute_mask_v1",
    )


def _structured_cells(params: Mapping[str, Any]) -> list[dict[str, Any]]:
    for key in ("expected_cells", "cells", "slots", "expected_slots", "cell_states"):
        value = params.get(key)
        if isinstance(value, list) and all(isinstance(item, Mapping) for item in value):
            return [dict(item) for item in value]
    return []


def run_state_parser(
    call: Mapping[str, Any], params: Mapping[str, Any], regions: Mapping[str, Any] | None
) -> dict[str, Any]:
    rgb = _load_rgb(_single_path(call))
    height, width = rgb.shape[:2]
    cells = _structured_cells(params)
    if not cells:
        return _result(
            call,
            tool="state_parser",
            status="unsupported",
            limitations=("generic_visual_state_has_no_universal_parser", "requires_explicit_cells_with_geometry_and_objective_attribute_schema"),
        )
    external_regions = dict(regions or {})
    cell_metrics: list[dict[str, Any]] = []
    unresolved: list[str] = []
    color_thresholds: dict[str, Any] = {}
    for index, cell in enumerate(cells):
        cell_id = str(cell.get("cell") or cell.get("slot") or cell.get("id") or index)
        geometry = cell.get("roi") or cell.get("bbox") or cell.get("rect") or external_regions.get(cell_id)
        rect = _rect_to_pixels(geometry, width, height)
        color = str(cell.get("expected_color") or cell.get("color") or "").lower().strip()
        if color == "grey":
            color = "gray"
        if rect is None or color not in _SUPPORTED_COLORS:
            unresolved.append(cell_id)
            cell_metrics.append({"cell_id": cell_id, "status": "insufficient", "reason": "missing_geometry_or_supported_explicit_color"})
            continue
        mask, thresholds = _color_mask(rgb, color)
        color_thresholds[color] = thresholds
        cell_metrics.append({"cell_id": cell_id, "status": "measured", "expected_color": color, **_mask_stats(mask, rect)})
    limitations = ["cell_color_fraction_does_not_infer_semantic_occupancy_or_object_identity"]
    if unresolved:
        limitations.append("unresolved_cells:" + "|".join(unresolved))
    measured = len(cells) - len(unresolved)
    status = "ok" if measured == len(cells) else "insufficient"
    return _result(
        call,
        tool="state_parser",
        status=status,
        metrics={"cells": cell_metrics, "measured_cell_count": measured, "requested_cell_count": len(cells)},
        thresholds={"color_masks": color_thresholds},
        limitations=limitations,
        backend="explicit_cell_color_parser_v1",
    )


def execute_cv_call(
    call: Mapping[str, Any],
    *,
    check_params: Mapping[str, Any] | None = None,
    regions: Mapping[str, Any] | None = None,
    dependencies: Mapping[str, Mapping[str, Any]] | None = None,
    runtime_resources: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
    """Execute one typed CV call and return provenance-rich evidence only."""

    tool = str(call.get("tool", ""))
    if tool not in CV_TOOL_TYPES:
        raise ValueError(f"unsupported CV tool type: {tool}")
    parsed_params = _params(call, check_params)
    if tool == "image_registration":
        return run_image_registration(call, parsed_params)
    if tool == "change_analysis":
        return run_change_analysis(call, parsed_params, regions, dependencies or {})
    if tool == "route_parser":
        return run_route_parser(call, parsed_params, regions)
    if tool == "visual_attribute_parser":
        return run_visual_attribute_parser(call, parsed_params, regions)
    if tool == "human_pose_parser":
        result = run_human_pose_estimation(
            _single_path(call),
            params=parsed_params,
            weights_path=(runtime_resources or {}).get("human_pose_weights"),
        )
        return _result(
            call,
            tool=tool,
            status=str(result.get("status") or "error"),
            metrics=result.get("metrics") if isinstance(result.get("metrics"), Mapping) else {},
            thresholds=result.get("thresholds") if isinstance(result.get("thresholds"), Mapping) else {},
            limitations=result.get("limitations") if isinstance(result.get("limitations"), Iterable) else (),
            backend=str(result.get("backend") or "pvr.human_pose_executor.v1"),
        )
    if tool == "local_correspondence":
        input_path, pred_path = _pair_paths(call)
        result = run_local_correspondence(
            input_path,
            pred_path,
            params=parsed_params,
            dependencies=dependencies or {},
        )
        return _result(
            call,
            tool=tool,
            status=str(result.get("status") or "error"),
            metrics=result.get("metrics") if isinstance(result.get("metrics"), Mapping) else {},
            thresholds=result.get("thresholds") if isinstance(result.get("thresholds"), Mapping) else {},
            limitations=result.get("limitations") if isinstance(result.get("limitations"), Iterable) else (),
            backend=str(result.get("backend") or "pvr.local_correspondence_executor.v1"),
        )
    return run_state_parser(call, parsed_params, regions)