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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Prompt-observable v5.1 wrapper around the frozen geometric-v5 evaluator.

The expensive and representation-sensitive geometry implementation remains in
``eval_geometric05``.  This module changes only the supervision contract:

* online physical/annotation scores consume explicit v5.1 sidecar masks;
* unmasked GT dimensions are unknown, never model errors;
* full-GT reconstruction is retained as a diagnostic;
* the strict ``engineering_success`` alias refers only to the certified scope.

There is deliberately no fallback to the legacy ``fmfs.eligible`` field.  A
missing or malformed v5.1 manifest masks physical and annotation supervision.
"""

from __future__ import annotations

import copy
import math
from pathlib import Path
from typing import Any, Mapping, Sequence

import numpy as np

try:
    from . import eval_geometric05 as EV5
except ImportError:  # direct evaluator import
    import eval_geometric05 as EV5


METRIC_VERSION = "v5.1"
FMFS_VERSION = "fmfs-v5.1"
ENGINEERING_THRESHOLDS = dict(EV5.ENGINEERING_THRESHOLDS)
_SCOPE_NAMES = ("prompt", "full_gt", "certified")


def _unknown_component(reason: str, *, scope: str, **details: Any) -> dict[str, Any]:
    return EV5._component(None, False, reason, scope=scope, **details)


def _zero_component(reason: str, *, scope: str, **details: Any) -> dict[str, Any]:
    return EV5._component(0.0, True, reason, scope=scope, **details)


def _bool_mask(value: Any, length: int) -> list[bool] | None:
    if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
        return None
    if len(value) != length or any(type(item) is not bool for item in value):
        return None
    return list(value)


def _dimension_specs(sidecar: Mapping[str, Any] | None) -> tuple[list[dict[str, Any]], list[str]]:
    errors: list[str] = []
    dimensions = sidecar.get("dimensions") if isinstance(sidecar, Mapping) else None
    raw_items = dimensions.get("items") if isinstance(dimensions, Mapping) else None
    if not isinstance(raw_items, Sequence) or isinstance(raw_items, (str, bytes)):
        return [], ["missing_dimensions_items"]
    specs: list[dict[str, Any]] = []
    for position, raw in enumerate(raw_items):
        if not isinstance(raw, Mapping):
            errors.append(f"invalid_dimension_item:{position}")
            continue
        try:
            gt_index = int(raw.get("index", raw.get("gt_dimension_index")))
            value = float(raw.get("display_value", raw.get("value")))
        except (TypeError, ValueError):
            errors.append(f"invalid_dimension_value_or_index:{position}")
            continue
        family = str(raw.get("family") or "").lower()
        if family not in EV5.DIMENSION_FAMILIES or not math.isfinite(value):
            errors.append(f"invalid_dimension_family_or_value:{position}")
            continue
        specs.append(
            {
                "position": position,
                "id": str(raw.get("id") or f"d{position:03d}"),
                "gt_dimension_index": gt_index,
                "family": family,
                "value": abs(value),
                "reliable": bool(raw.get("reliable", True)),
            }
        )
    if len(specs) != len(raw_items):
        errors.append("dimension_inventory_not_total")
    return specs, errors


def _scope_contracts(sidecar: Mapping[str, Any] | None) -> dict[str, Any]:
    """Fail-closed parser for the v5.1 item-mask contract."""

    specs, errors = _dimension_specs(sidecar)
    length = len(specs)
    fmfs = sidecar.get("fmfs") if isinstance(sidecar, Mapping) else None
    valid_version = isinstance(fmfs, Mapping) and fmfs.get("version") == FMFS_VERSION
    if not valid_version:
        errors.append("missing_or_legacy_fmfs_contract")
    prompt = fmfs.get("prompt") if valid_version else None
    certified = fmfs.get("certified") if valid_version else None

    def parsed_mask(container: Any, key: str) -> list[bool] | None:
        return _bool_mask(container.get(key), length) if isinstance(container, Mapping) else None

    prompt_physical = parsed_mask(prompt, "physical_item_mask")
    prompt_annotation = parsed_mask(prompt, "annotation_item_mask")
    certified_physical = parsed_mask(certified, "physical_item_mask")
    certified_annotation = parsed_mask(certified, "annotation_item_mask")
    full_mask = [True] * length
    dimensions = sidecar.get("dimensions") if isinstance(sidecar, Mapping) else None
    full_eligible = bool(
        valid_version
        and specs
        and not errors
        and all(item["reliable"] for item in specs)
        and (
            not isinstance(dimensions, Mapping)
            or int(dimensions.get("reliable_count", length)) == length
        )
    )
    prompt_physical_eligible = bool(
        isinstance(prompt, Mapping)
        and prompt.get("physical_eligible")
        and prompt_physical is not None
        and any(prompt_physical)
        and not errors
    )
    prompt_annotation_eligible = bool(
        isinstance(prompt, Mapping)
        and prompt.get("annotation_eligible")
        and prompt_annotation is not None
        and any(prompt_annotation)
        and not errors
    )
    certified_eligible = bool(
        isinstance(certified, Mapping)
        and certified.get("eligible")
        and certified.get("status") == "certified"
        and certified_physical is not None
        and certified_annotation is not None
        and any(certified_physical)
        and any(certified_annotation)
        and not errors
    )
    return {
        "valid": valid_version and not errors,
        "errors": errors,
        "n_dimension_items": length,
        "specs": specs,
        "prompt": {
            "physical_eligible": prompt_physical_eligible,
            "annotation_eligible": prompt_annotation_eligible,
            "physical_mask": prompt_physical or [False] * length,
            "annotation_mask": prompt_annotation or [False] * length,
            "reason_codes": list(prompt.get("reason_codes", [])) if isinstance(prompt, Mapping) else [],
        },
        "full_gt": {
            "physical_eligible": full_eligible,
            "annotation_eligible": full_eligible,
            "physical_mask": full_mask if full_eligible else [False] * length,
            "annotation_mask": full_mask if full_eligible else [False] * length,
            "reason_codes": [] if full_eligible else ["full_gt_dimension_inventory_ineligible"],
        },
        "certified": {
            "physical_eligible": certified_eligible,
            "annotation_eligible": certified_eligible,
            "physical_mask": certified_physical or [False] * length,
            "annotation_mask": certified_annotation or [False] * length,
            "status": certified.get("status", "unknown") if isinstance(certified, Mapping) else "unknown",
            "reason_codes": list(certified.get("reason_codes", [])) if isinstance(certified, Mapping) else [],
        },
    }


def _pair_context(pred: str | Path, gt: str | Path) -> dict[str, Any]:
    pred_path, gt_path = Path(pred), Path(gt)
    pred_meta, gt_meta = EV5._read_structure(pred_path), EV5._read_structure(gt_path)
    raw_gt = EV5._extract_entities(gt_path) if gt_meta.get("readable") else None
    target_valid = bool(
        raw_gt is not None
        and EV5._n_geometry(raw_gt) > 0
        and EV5._safe_bbox(raw_gt) is not None
    )
    raw_pred = EV5._extract_entities(pred_path) if pred_meta.get("readable") else None
    prediction_valid = bool(
        raw_pred is not None
        and EV5._n_geometry(raw_pred) > 0
        and EV5._safe_bbox(raw_pred) is not None
    )
    context: dict[str, Any] = {
        "target_valid": target_valid,
        "prediction_valid": prediction_valid,
        "pred_meta": pred_meta,
        "gt_meta": gt_meta,
        "raw_pred": raw_pred,
        "raw_gt": raw_gt,
    }
    if not target_valid or not prediction_valid:
        return context
    canonical_pred = EV5.EV4.canonicalize_entities(raw_pred)
    canonical_gt = EV5.EV4.canonicalize_entities(raw_gt)
    source_center, target_center, global_scale = EV5.EV3.shared_alignment(
        canonical_pred, canonical_gt
    )
    context.update(
        {
            "canonical_pred": canonical_pred,
            "canonical_gt": canonical_gt,
            "source_center": source_center,
            "target_center": target_center,
            "global_scale": global_scale,
        }
    )
    return context


def _selected_specs(contract: Mapping[str, Any], mask: Sequence[bool]) -> list[dict[str, Any]]:
    return [dict(spec) for spec, selected in zip(contract.get("specs", []), mask) if selected]


def _masked_component(
    context: Mapping[str, Any],
    contract: Mapping[str, Any],
    mask: Sequence[bool],
    *,
    eligible: bool,
    scope: str,
    component_name: str,
) -> dict[str, Any]:
    selected = _selected_specs(contract, mask)
    item_ids = [item["id"] for item in selected]
    if not context.get("target_valid"):
        return _unknown_component(
            "target_dxf_unreadable_or_degenerate", scope=scope, item_ids=item_ids
        )
    if not eligible or not selected:
        return _unknown_component(
            "sidecar_item_mask_ineligible",
            scope=scope,
            item_ids=item_ids,
            contract_errors=list(contract.get("errors", [])),
        )
    if not context.get("prediction_valid"):
        return _zero_component(
            "prediction_dxf_unreadable_or_degenerate", scope=scope, item_ids=item_ids
        )

    raw_gt = context["raw_gt"]
    gt_dims = list(raw_gt.get("dims", []))
    selected_dims: list[Any] = []
    local_specs: list[dict[str, Any]] = []
    for local_index, spec in enumerate(selected):
        gt_index = int(spec["gt_dimension_index"])
        if not 0 <= gt_index < len(gt_dims):
            return _unknown_component(
                "sidecar_gt_dimension_index_out_of_range",
                scope=scope,
                item_ids=item_ids,
                bad_gt_dimension_index=gt_index,
            )
        selected_dims.append(gt_dims[gt_index])
        local = dict(spec)
        local["gt_dimension_index"] = local_index
        local_specs.append(local)

    target_subset = dict(raw_gt)
    target_subset["dims"] = selected_dims
    _annotation, annotation_diagnostics = EV5._annotation_component(
        context["raw_pred"],
        target_subset,
        np.asarray(context["source_center"]),
        np.asarray(context["target_center"]),
        float(context["global_scale"]),
        context["pred_meta"],
    )
    raw_fmfs = EV5._fmfs_diagnostics(
        {
            "fmfs": {
                "eligible": True,
                "fully_derivable": scope == "certified",
                "items": local_specs,
            }
        },
        context["canonical_pred"],
        annotation_diagnostics,
    )
    rows = list(raw_fmfs.get("items", []))
    item_scores: list[dict[str, Any]] = []
    qualities: list[float] = []
    for position, spec in enumerate(selected):
        row = rows[position] if position < len(rows) and isinstance(rows[position], Mapping) else {}
        value_quality = float(row.get("value_quality", 0.0) or 0.0)
        type_quality = float(row.get("type_quality", 0.0) or 0.0)
        binding_quality = float(row.get("binding_quality", 0.0) or 0.0)
        internal_binding = float(row.get("internal_binding_quality", 0.0) or 0.0)
        scale_quality = float(row.get("scale_quality", 0.0) or 0.0)
        physical_quality = value_quality * binding_quality * internal_binding * scale_quality
        annotation_quality = type_quality * value_quality * binding_quality * internal_binding * scale_quality
        quality = physical_quality if component_name == "physical" else annotation_quality
        quality = max(0.0, min(1.0, quality))
        qualities.append(quality)
        item_scores.append(
            {
                "id": spec["id"],
                "gt_dimension_index": spec["gt_dimension_index"],
                "score": EV5._round(quality),
                "physical_quality": EV5._round(physical_quality),
                "annotation_quality": EV5._round(annotation_quality),
                "raw": dict(row),
            }
        )
    score = float(np.mean(qualities)) if qualities else 0.0
    return EV5._component(
        score,
        True,
        "ok" if score >= ENGINEERING_THRESHOLDS[component_name] else f"masked_{component_name}_mismatch",
        scope=scope,
        item_ids=item_ids,
        n_items=len(item_ids),
        items=item_scores,
        raw_fmfs=raw_fmfs,
        unmasked_prediction_dimensions_ignored=True,
    )


def _scope_components(
    context: Mapping[str, Any], contract: Mapping[str, Any], scope: str
) -> dict[str, dict[str, Any]]:
    scope_contract = contract[scope]
    return {
        "physical": _masked_component(
            context,
            contract,
            scope_contract["physical_mask"],
            eligible=bool(scope_contract["physical_eligible"]),
            scope=scope,
            component_name="physical",
        ),
        "annotation": _masked_component(
            context,
            contract,
            scope_contract["annotation_mask"],
            eligible=bool(scope_contract["annotation_eligible"]),
            scope=scope,
            component_name="annotation",
        ),
    }


def _pass(component: Mapping[str, Any], name: str) -> bool | None:
    if not component.get("eligible") or not isinstance(component.get("score"), (int, float)):
        return None
    return bool(float(component["score"]) >= ENGINEERING_THRESHOLDS[name])


def _tri_and(states: Sequence[bool | None]) -> bool | None:
    if any(value is False for value in states):
        return False
    if states and all(value is True for value in states):
        return True
    return None


def _benchmark_scope(
    base_benchmark: Mapping[str, Any],
    scope_components: Mapping[str, Mapping[str, Any]],
    *,
    target_eligible: bool,
) -> dict[str, Any]:
    physical_pass = _pass(scope_components["physical"], "physical") if target_eligible else None
    annotation_pass = _pass(scope_components["annotation"], "annotation") if target_eligible else None
    states = {
        "three_views": base_benchmark.get("three_views"),
        "geometry_pass": base_benchmark.get("geometry_pass"),
        "physical_pass": physical_pass,
        "annotation_pass": annotation_pass,
        "layout_pass": base_benchmark.get("layout_pass"),
        "structure_pass": base_benchmark.get("structure_pass"),
    }
    success = _tri_and(list(states.values())) if target_eligible else None
    return {
        **states,
        "target_eligible": bool(target_eligible),
        "fully_evaluable": bool(target_eligible and all(value is not None for value in states.values())),
        "engineering_success": success,
    }


def score_dxf_pair(
    pred: str | Path,
    gt: str | Path,
    sidecar: Mapping[str, Any] | None = None,
    category: str | None = None,
    **_kwargs: Any,
) -> dict[str, Any]:
    """Score a pair with prompt-masked online P/A and certified strict success."""

    base = EV5.score_dxf_pair(pred, gt, sidecar=sidecar, category=category)
    result = copy.deepcopy(base)
    contract = _scope_contracts(sidecar)
    context = _pair_context(pred, gt)

    # Prompt masking intentionally ignores dimensions outside the observable
    # contract, but it must not make arbitrary detached DIMENSION/TEXT spam
    # free. Preserve the frozen v5 duplicate diagnostics and expose the
    # broader unmatched count through the same capped anti-hack channel.
    annotation_details = (
        base.get("components", {}).get("annotation", {}).get("details", {})
    )
    if not isinstance(annotation_details, Mapping):
        annotation_details = {}
    try:
        predicted_dimension_count = max(
            0,
            int(annotation_details.get("n_pred_native", 0) or 0)
            + int(annotation_details.get("n_pred_text_only", 0) or 0),
        )
        matched_dimension_count = max(
            0, int(annotation_details.get("matched_by_binding", 0) or 0)
        )
    except (TypeError, ValueError):
        predicted_dimension_count = 0
        matched_dimension_count = 0
    unmatched_dimension_count = max(
        0, predicted_dimension_count - matched_dimension_count
    )
    anti_hack = result.get("anti_hack")
    if not isinstance(anti_hack, dict):
        anti_hack = {}
        result["anti_hack"] = anti_hack
    true_duplicate_count = float(
        anti_hack.get("duplicate_dimension_count", 0.0) or 0.0
    )
    true_duplicate_ratio = float(
        anti_hack.get("duplicate_dimension_ratio", 0.0) or 0.0
    )
    unmatched_ratio = unmatched_dimension_count / max(predicted_dimension_count, 1)
    anti_hack["true_duplicate_dimension_count"] = true_duplicate_count
    anti_hack["true_duplicate_dimension_ratio"] = true_duplicate_ratio
    anti_hack["unmatched_dimension_count"] = unmatched_dimension_count
    anti_hack["unmatched_dimension_ratio"] = unmatched_ratio
    anti_hack["dimension_spam_count"] = max(true_duplicate_count, unmatched_dimension_count)
    anti_hack["dimension_spam_ratio"] = max(true_duplicate_ratio, unmatched_ratio)
    anti_hack["duplicate_dimension_count"] = anti_hack["dimension_spam_count"]
    anti_hack["duplicate_dimension_ratio"] = anti_hack["dimension_spam_ratio"]
    if unmatched_dimension_count:
        flags = anti_hack.setdefault("flags", [])
        if "unmatched_dimension_entities" not in flags:
            flags.append("unmatched_dimension_entities")

    scopes = {
        name: _scope_components(context, contract, name) for name in _SCOPE_NAMES
    }

    prompt = scopes["prompt"]
    result["metric_version"] = METRIC_VERSION
    result["components"]["physical"] = prompt["physical"]
    result["components"]["annotation"] = prompt["annotation"]
    result["online_reward"] = {
        "scope": "prompt",
        "components": {
            name: result["components"][name]
            for name in ("view", "geometry", "physical", "annotation", "layout", "structure")
        },
    }

    base_benchmark = dict(base.get("benchmark", {}))
    view_count_ok = bool(
        isinstance(sidecar, Mapping)
        and isinstance(sidecar.get("views"), Mapping)
        and sidecar["views"].get("candidate_count") == EV5.VIEW_TARGET_COUNT
    )
    target_valid = bool(context.get("target_valid"))
    scope_benchmarks: dict[str, Any] = {}
    for name in _SCOPE_NAMES:
        scope_contract = contract[name]
        target_eligible = bool(
            target_valid
            and view_count_ok
            and scope_contract["physical_eligible"]
            and scope_contract["annotation_eligible"]
        )
        scope_benchmarks[name] = _benchmark_scope(
            base_benchmark, scopes[name], target_eligible=target_eligible
        )

    certified = scope_benchmarks["certified"]
    benchmark = dict(base_benchmark)
    benchmark.update(
        {
            "physical_pass": certified["physical_pass"],
            "annotation_pass": certified["annotation_pass"],
            "engineering_eligible": certified["target_eligible"],
            "engineering_success": certified["engineering_success"],
            "cad_pass": certified["engineering_success"],
            "strict_scope": "certified",
            "scopes": scope_benchmarks,
            "thresholds": dict(ENGINEERING_THRESHOLDS),
        }
    )
    result["benchmark"] = benchmark
    result["engineering_eligible"] = certified["target_eligible"]
    result["engineering_success"] = certified["engineering_success"]
    result["diagnostics"]["v5_base_physical"] = base["components"]["physical"]
    result["diagnostics"]["v5_base_annotation"] = base["components"]["annotation"]
    result["diagnostics"]["fmfs_v51"] = {
        "contract": {
            key: value
            for key, value in contract.items()
            if key != "specs"
        },
        "scopes": scopes,
        "strict_scope": "certified",
        "legacy_fmfs_fallback": False,
    }
    return result


__all__ = [
    "ENGINEERING_THRESHOLDS",
    "FMFS_VERSION",
    "METRIC_VERSION",
    "score_dxf_pair",
]