File size: 10,794 Bytes
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Taxonomy-relaxed metrics driven by a frozen semantic-pair policy."""

from __future__ import annotations

from collections import defaultdict
from dataclasses import dataclass

from metrics._f_beta import ViolationCounts, aggregate_summary, summarise_counts
from metrics._labels import to_use_case_id
from metrics.localisation import _compute_iou, maximum_match_pairs
from schemas.ground_truth import GoldRecord
from schemas.inference import InferenceResponse


@dataclass(frozen=True)
class SemanticPolicy:
    """A symmetric class-pair acceptance matrix with similarity provenance."""

    class_ids: tuple[str, ...]
    similarities: tuple[tuple[float, ...], ...]
    accepted: tuple[tuple[int, ...], ...]

    @classmethod
    def from_dict(cls, payload: dict) -> "SemanticPolicy":
        return cls(
            class_ids=tuple(payload["class_ids"]),
            similarities=tuple(tuple(row) for row in payload["cosine_matrix"]),
            accepted=tuple(tuple(row) for row in payload["accepted_matrix"]),
        )

    def _indices(self, predicted: str, gold: str) -> tuple[int, int] | None:
        try:
            return self.class_ids.index(predicted), self.class_ids.index(gold)
        except ValueError:
            return None

    def allows(self, predicted: str, gold: str) -> bool:
        indices = self._indices(predicted, gold)
        return bool(indices and self.accepted[indices[0]][indices[1]])

    def similarity(self, predicted: str, gold: str) -> float:
        indices = self._indices(predicted, gold)
        return self.similarities[indices[0]][indices[1]] if indices else 0.0


def _maximum_semantic_pairs(
    predicted: list[str], gold: list[str], policy: SemanticPolicy
) -> list[tuple[int, int]]:
    """Maximum-cardinality deterministic matching for non-exact class pairs."""
    candidates = [
        sorted(
            (j for j, gold_id in enumerate(gold) if pred_id != gold_id and policy.allows(pred_id, gold_id)),
            key=lambda j: (-policy.similarity(pred_id, gold[j]), j),
        )
        for pred_id in predicted
    ]
    gold_owner: dict[int, int] = {}

    def assign(pred_index: int, seen: set[int]) -> bool:
        for gold_index in candidates[pred_index]:
            if gold_index in seen:
                continue
            seen.add(gold_index)
            owner = gold_owner.get(gold_index)
            if owner is None or assign(owner, seen):
                gold_owner[gold_index] = pred_index
                return True
        return False

    for pred_index in sorted(
        range(len(predicted)),
        key=lambda i: (-max((policy.similarity(predicted[i], gold[j]) for j in candidates[i]), default=0.0), i),
    ):
        assign(pred_index, set())
    return sorted((pred_index, gold_index) for gold_index, pred_index in gold_owner.items())


def _negative_fields(prediction_labels: set[str], record: GoldRecord, totals: dict) -> None:
    if record.gold.no_violation_detected:
        totals["negative_images"] += 1
        if prediction_labels:
            totals["false_positive_images"] += 1
        else:
            totals["true_negative_images"] += 1


def compute_semantic_classification_metrics(
    predictions: list[InferenceResponse],
    ground_truths: list[GoldRecord],
    policy: SemanticPolicy,
) -> dict:
    """Score unique class sets with exact-first, one-to-one semantic matching."""
    gt_by_id = {record.image_id: record for record in ground_truths}
    counts: dict[str, ViolationCounts] = defaultdict(ViolationCounts)
    totals = {"negative_images": 0, "true_negative_images": 0, "false_positive_images": 0}
    credited = []
    evaluated = 0
    for prediction in predictions:
        record = gt_by_id.get(prediction.image_id)
        if record is None or record.gold.reported:
            continue
        evaluated += 1
        gt_labels = {item.use_case_id for item in record.gold.violations}
        pred_labels = {to_use_case_id(item.category_id) for item in prediction.detections}
        exact = gt_labels & pred_labels
        for label in exact:
            counts[label].tp += 1
        unmatched_pred = sorted(pred_labels - exact)
        unmatched_gt = sorted(gt_labels - exact)
        pairs = _maximum_semantic_pairs(unmatched_pred, unmatched_gt, policy)
        matched_pred = {pred_index for pred_index, _ in pairs}
        matched_gt = {gold_index for _, gold_index in pairs}
        for pred_index, gold_index in pairs:
            predicted_id, gold_id = unmatched_pred[pred_index], unmatched_gt[gold_index]
            counts[gold_id].tp += 1
            credited.append({
                "image_id": prediction.image_id,
                "predicted_class": predicted_id,
                "gold_class": gold_id,
                "similarity": round(policy.similarity(predicted_id, gold_id), 6),
            })
        for index, label in enumerate(unmatched_pred):
            if index not in matched_pred:
                counts[label].fp += 1
        for index, label in enumerate(unmatched_gt):
            if index not in matched_gt:
                counts[label].fn += 1
        _negative_fields(pred_labels, record, totals)
    negatives = totals["negative_images"]
    return {
        "per_violation": summarise_counts(counts),
        "summary": aggregate_summary(counts),
        "n_images": evaluated,
        **totals,
        "negative_false_positive_rate": round(totals["false_positive_images"] / negatives, 4) if negatives else None,
        "credited_matches": credited,
    }


def _maximum_semantic_box_pairs(predictions: list[dict], gold: list[dict], policy: SemanticPolicy, threshold: float) -> list[tuple[int, int, float]]:
    candidates = [
        sorted(
            (
                j for j, target in enumerate(gold)
                if item["label"] != target["label"]
                and policy.allows(item["label"], target["label"])
                and _compute_iou(item["bbox"], target["bbox"]) >= threshold
            ),
            key=lambda j: (
                -policy.similarity(item["label"], gold[j]["label"]),
                -_compute_iou(item["bbox"], gold[j]["bbox"]),
                gold[j]["index"],
            ),
        )
        for item in predictions
    ]
    gold_owner: dict[int, int] = {}

    def assign(pred_index: int, seen: set[int]) -> bool:
        for gold_index in candidates[pred_index]:
            if gold_index in seen:
                continue
            seen.add(gold_index)
            owner = gold_owner.get(gold_index)
            if owner is None or assign(owner, seen):
                gold_owner[gold_index] = pred_index
                return True
        return False

    for pred_index in sorted(range(len(predictions)), key=lambda i: predictions[i]["index"]):
        assign(pred_index, set())
    return sorted(
        (
            pred_index,
            gold_index,
            _compute_iou(predictions[pred_index]["bbox"], gold[gold_index]["bbox"]),
        )
        for gold_index, pred_index in gold_owner.items()
    )


def compute_semantic_localisation_metrics(
    predictions: list[InferenceResponse],
    ground_truths: list[GoldRecord],
    policy: SemanticPolicy,
    iou_threshold: float = 0.50,
) -> dict:
    """Score boxes with exact-label matches first, then accepted class pairs."""
    gt_by_id = {record.image_id: record for record in ground_truths}
    counts: dict[str, ViolationCounts] = defaultdict(ViolationCounts)
    totals = {"negative_images": 0, "true_negative_images": 0, "false_positive_images": 0}
    credited = []
    evaluated = n_predictions = n_gt_boxes = 0
    for prediction in predictions:
        record = gt_by_id.get(prediction.image_id)
        if record is None or record.gold.reported:
            continue
        evaluated += 1
        pred_items = [
            {"index": i, "label": to_use_case_id(item.category_id), "bbox": item.bbox}
            for i, item in enumerate(prediction.detections)
        ]
        gt_items = [
            {"index": i, "label": item.use_case_id, "bbox": item.bbox}
            for i, item in enumerate(record.gold.violations)
        ]
        n_predictions += len(pred_items)
        n_gt_boxes += len(gt_items)
        matched_pred: set[int] = set()
        matched_gt: set[int] = set()
        labels = {item["label"] for item in pred_items + gt_items}
        for label in sorted(labels):
            preds = [item for item in pred_items if item["label"] == label]
            golds = [item for item in gt_items if item["label"] == label]
            for local_pred, local_gt, _ in maximum_match_pairs(
                [item["bbox"] for item in preds], [item["bbox"] for item in golds], iou_threshold
            ):
                matched_pred.add(preds[local_pred]["index"])
                matched_gt.add(golds[local_gt]["index"])
                counts[label].tp += 1
        remaining_pred = [item for item in pred_items if item["index"] not in matched_pred]
        remaining_gt = [item for item in gt_items if item["index"] not in matched_gt]
        semantic_pairs = _maximum_semantic_box_pairs(remaining_pred, remaining_gt, policy, iou_threshold)
        semantic_pred = {pred_index for pred_index, _, _ in semantic_pairs}
        semantic_gt = {gold_index for _, gold_index, _ in semantic_pairs}
        for pred_index, gold_index, iou in semantic_pairs:
            pred_item, gold_item = remaining_pred[pred_index], remaining_gt[gold_index]
            counts[gold_item["label"]].tp += 1
            credited.append({
                "image_id": prediction.image_id,
                "prediction_index": pred_item["index"],
                "gold_index": gold_item["index"],
                "predicted_class": pred_item["label"],
                "gold_class": gold_item["label"],
                "similarity": round(policy.similarity(pred_item["label"], gold_item["label"]), 6),
                "iou": round(iou, 6),
            })
        for index, item in enumerate(remaining_pred):
            if index not in semantic_pred:
                counts[item["label"]].fp += 1
        for index, item in enumerate(remaining_gt):
            if index not in semantic_gt:
                counts[item["label"]].fn += 1
        _negative_fields({item["label"] for item in pred_items}, record, totals)
    negatives = totals["negative_images"]
    return {
        "per_violation": summarise_counts(counts),
        "summary": aggregate_summary(counts),
        "iou_threshold": iou_threshold,
        "n_images": evaluated,
        "n_predictions": n_predictions,
        "n_gt_boxes": n_gt_boxes,
        **totals,
        "negative_false_positive_rate": round(totals["false_positive_images"] / negatives, 4) if negatives else None,
        "credited_matches": credited,
    }