File size: 13,075 Bytes
15d1f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Final prompt-annotation causal-isolation repair layered on RC5J-final.

RC5K changes exactly one formal component: prompt-scoped annotation.  The
offline full-GT annotation component, the other five components in both
scopes, the full-GT reward, geometry matching, anti-hack gates, and benchmark
remain RC5J-final.

Prompt native dimensions are partitioned with one joint lexicographic
assignment: maximise selected matches, then neutralise as many unselected GT
matches as possible, then minimise pair cost.  Neutral matches are neither
precision credit nor spam.  Remaining native dimensions and every
dimension-like TEXT/MTEXT entity are spam.  This removes full-GT inventory
leakage while preserving the intended neutral treatment of correct dimensions
outside the prompt mask.
"""

from __future__ import annotations

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

import numpy as np

try:
    from . import eval_geometric052_rc5j_final as RC5J
    from . import prompt_annotation_precision_candidate_v2 as PRECISION
except ImportError:  # direct evaluator import
    import eval_geometric052_rc5j_final as RC5J
    import prompt_annotation_precision_candidate_v2 as PRECISION


METRIC_VERSION = "v5.2-rc5k-final"
SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc5k-final"
ENGINEERING_THRESHOLDS = dict(RC5J.ENGINEERING_THRESHOLDS)
PHYSICAL_SUPPORTED_SEMANTICS = RC5J.PHYSICAL_SUPPORTED_SEMANTICS
MAX_MATCHED_OFFSET_DISPERSION_FRACTION = (
    RC5J.MAX_MATCHED_OFFSET_DISPERSION_FRACTION
)

RC3 = RC5J.RC3
BASE = RC5J.BASE


def _prompt_annotation_component(
    context: Mapping[str, Any],
    sidecar: Mapping[str, Any] | None,
) -> dict[str, Any]:
    """Score prompt targets with causally isolated native-DIM precision."""

    contract, selected_contract = RC3._scope_contract(sidecar, "prompt")
    mask = selected_contract.get("annotation_mask", [])
    if not selected_contract.get("annotation_eligible"):
        return BASE._component(
            None,
            False,
            "prompt_annotation_mask_ineligible",
            scope="prompt",
            contract_errors=contract.get("errors", []),
            reason_codes=selected_contract.get("reason_codes", []),
        )

    targets = RC3._dimension_targets(context, sidecar, contract)
    selected_spec_indices = {
        index for index, selected in enumerate(mask) if selected
    }
    selected_target_mask = [
        target["spec_index"] in selected_spec_indices for target in targets
    ]
    selected_targets = [
        target
        for target, selected in zip(targets, selected_target_mask)
        if selected
    ]
    if not selected_targets:
        return BASE._component(
            None,
            False,
            "no_valid_masked_target_dimensions",
            scope="prompt",
        )

    pred_dims = list((context.get("raw_pred") or {}).get("dims", []))
    details: dict[tuple[int, int], dict[str, Any]] = {}
    pair_matrix: list[list[dict[str, Any]]] = []
    for pred_index, pred_dim in enumerate(pred_dims):
        row: list[dict[str, Any]] = []
        for target_index, target in enumerate(targets):
            detail = RC3._dimension_pair_detail(context, pred_dim, target)
            details[(pred_index, target_index)] = detail
            row.append(
                {
                    "family_ok": detail.get("family_ok"),
                    "binding_distance_fraction": detail.get(
                        "binding_distance_fraction"
                    ),
                    "predicted_value": detail.get("predicted_value"),
                }
            )
        pair_matrix.append(row)

    pred_meta = context.get("pred_meta", {})
    pred_text = int(pred_meta.get("dimension_like_text", 0) or 0)
    try:
        precision = PRECISION.prompt_annotation_precision_candidate_v2(
            pair_matrix,
            selected_target_mask=selected_target_mask,
            target_values=[abs(float(target["spec"]["value"])) for target in targets],
            target_ids=[str(target["spec"]["id"]) for target in targets],
            predicted_text_count=pred_text,
            max_binding_fraction=RC3.MAX_DIMENSION_BINDING_FRACTION,
            max_value_log_error=RC3.MAX_DIMENSION_VALUE_LOG_ERROR,
        )
    except (KeyError, TypeError, ValueError) as exc:
        return BASE._component(
            None,
            False,
            "prompt_annotation_precision_contract_invalid",
            scope="prompt",
            contract_error=f"{type(exc).__name__}: {exc}",
            precision_policy=PRECISION.POLICY_VERSION,
        )
    if not precision.get("eligible"):
        return BASE._component(
            None,
            False,
            str(precision.get("reason") or "prompt_annotation_precision_ineligible"),
            scope="prompt",
            precision_policy=PRECISION.POLICY_VERSION,
            precision_diagnostics=precision,
        )

    selected_pair_by_target = {
        int(pair["target_index"]): int(pair["pred_index"])
        for pair in precision["selected_pairs"]
    }
    target_position = {
        target["spec_index"]: index for index, target in enumerate(targets)
    }
    item_rows: list[dict[str, Any]] = []
    item_scores: list[float] = []
    presence_values: list[float] = []
    type_values: list[float] = []
    value_values: list[float] = []
    binding_values: list[float] = []
    for target in selected_targets:
        position = target_position[target["spec_index"]]
        pred_index = selected_pair_by_target.get(position)
        spec = target["spec"]
        if pred_index is None:
            item_scores.append(0.0)
            presence_values.append(0.0)
            type_values.append(0.0)
            value_values.append(0.0)
            binding_values.append(0.0)
            item_rows.append(
                {
                    "id": spec["id"],
                    "gt_dimension_index": target["gt_index"],
                    "pred_dimension_index": None,
                    "role": target.get("role"),
                    "presence": 0.0,
                    "type": 0.0,
                    "display_value": 0.0,
                    "binding": 0.0,
                    "score": 0.0,
                    "reason": "missing_or_semantically_incompatible_dimension",
                }
            )
            continue

        detail = details[(pred_index, position)]
        value_log_error = float(detail["value_log_error"])
        binding_distance = float(detail["binding_distance_fraction"])
        value_quality = math.exp(-value_log_error / 0.10)
        binding_quality = math.exp(-binding_distance / 0.03)
        item_score = 0.35 + 0.20 + 0.30 * value_quality + 0.15 * binding_quality
        item_scores.append(item_score)
        presence_values.append(1.0)
        type_values.append(1.0)
        value_values.append(value_quality)
        binding_values.append(binding_quality)
        item_rows.append(
            {
                "id": spec["id"],
                "gt_dimension_index": target["gt_index"],
                "pred_dimension_index": pred_index,
                "role": target.get("role"),
                "presence": 1.0,
                "type": 1.0,
                "display_value": BASE._round(value_quality),
                "binding": BASE._round(binding_quality),
                "target_display_value": BASE._round(detail["target_value"]),
                "predicted_display_value": BASE._round(detail["predicted_value"]),
                "display_value_source": detail["value_source"],
                "display_value_relative_error": BASE._round(
                    detail["value_relative_error"]
                ),
                "binding_distance_fraction": BASE._round(binding_distance),
                "score": BASE._round(item_score),
                "reason": (
                    "ok" if item_score >= 0.90 else "annotation_field_mismatch"
                ),
            }
        )

    target_macro = float(np.mean(item_scores))
    target_worst = min(item_scores)
    target_quality = 0.50 * target_macro + 0.50 * target_worst
    predicted_precision = float(precision["precision"])
    score = BASE._harmonic(target_quality, predicted_precision)
    selected_count = int(precision["n_selected_matched_native"])
    neutral_count = int(precision["n_neutralized_unselected_native"])
    unmatched_count = int(precision["n_unmatched_predicted_native"])
    return BASE._component(
        score,
        True,
        (
            "ok"
            if score >= ENGINEERING_THRESHOLDS["annotation"]
            else "annotation_recall_precision_or_field_mismatch"
        ),
        scope="prompt",
        n_selected_target=len(selected_targets),
        n_total_gt_dimension_targets=len(targets),
        n_predicted_native=len(pred_dims),
        n_predicted_dimension_like_text=pred_text,
        n_selected_matched_native=selected_count,
        n_neutralized_unselected_native=neutral_count,
        n_unmatched_predicted_native=unmatched_count,
        n_matched_predicted_native=selected_count + neutral_count,
        predicted_precision=BASE._round(predicted_precision),
        effective_predicted_inventory=int(
            precision["effective_predicted_inventory"]
        ),
        empty_effective_inventory=bool(precision["empty_effective_inventory"]),
        presence_recall=BASE._round(float(np.mean(presence_values))),
        type_macro=BASE._round(float(np.mean(type_values))),
        display_value_macro=BASE._round(float(np.mean(value_values))),
        binding_macro=BASE._round(float(np.mean(binding_values))),
        target_quality=BASE._round(target_quality),
        item_macro=BASE._round(target_macro),
        item_worst=BASE._round(target_worst),
        items=item_rows,
        matching_policy=PRECISION.POLICY_VERSION,
        selected_targets_have_lexicographic_priority=True,
        unselected_gt_dimensions_are_precision_neutral=True,
        unselected_matches_are_neither_credit_nor_spam=True,
        dimension_like_text_policy="always_unmatched_without_item_level_verifier",
        reads_actual_geometry=False,
    )


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]:
    """Run RC5J-final with only its prompt annotation callback replaced."""

    # Reuse RC5J's RLock so concurrent RC5J/RC5K calls cannot observe a
    # half-patched RC3 module. RC5J re-enters this lock during its own wrapper.
    with RC5J._PATCH_LOCK:
        original_annotation = RC3._annotation_component

        def scoped_annotation(
            context: Mapping[str, Any],
            candidate_sidecar: Mapping[str, Any] | None,
            *,
            scope: str,
        ) -> dict[str, Any]:
            if scope == "prompt":
                return _prompt_annotation_component(context, candidate_sidecar)
            return original_annotation(
                context,
                candidate_sidecar,
                scope=scope,
            )

        RC3._annotation_component = scoped_annotation
        try:
            result = RC5J.score_dxf_pair(
                pred,
                gt,
                sidecar=sidecar,
                category=category,
                **kwargs,
            )
        finally:
            RC3._annotation_component = original_annotation

    result["schema_version"] = SCHEMA_VERSION
    result["metric_version"] = METRIC_VERSION
    result.setdefault("metric_definition", {})[
        "prompt_annotation_precision_policy"
    ] = {
        "policy_version": PRECISION.POLICY_VERSION,
        "changed_scope": "online_reward_prompt_masked.annotation_only",
        "assignment_objective": [
            "maximise_selected_matches",
            "maximise_unselected_neutral_matches",
            "minimise_pair_cost",
        ],
        "precision": "S/(S+X+Q)",
        "unselected_native_matches": "neutral",
        "dimension_like_text": "unmatched_without_item_level_verifier",
        "zero_unselected_value": "absolute_tolerance_neutralisation",
        "zero_selected_value": "fail_closed_ineligible",
        "full_gt_scope_changed": False,
        "other_component_definitions_changed": False,
    }
    result.setdefault("diagnostics", {})["rc5k_prompt_annotation_precision"] = {
        "applied": True,
        "policy_version": PRECISION.POLICY_VERSION,
        "changed_scope": "prompt_annotation_and_dependent_prompt_reward_only",
        "full_gt_scope_changed": False,
        "other_five_components_changed": False,
    }
    release = result.get("diagnostics", {}).get("release_status")
    if isinstance(release, dict):
        release["candidate"] = METRIC_VERSION
    return result


__all__ = [
    "ENGINEERING_THRESHOLDS",
    "MAX_MATCHED_OFFSET_DISPERSION_FRACTION",
    "METRIC_VERSION",
    "PHYSICAL_SUPPORTED_SEMANTICS",
    "SCHEMA_VERSION",
    "_prompt_annotation_component",
    "score_dxf_pair",
]