File size: 12,919 Bytes
f1d615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
979f3c3
f1d615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
979f3c3
f1d615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2bea75
f1d615d
a2bea75
f1d615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
979f3c3
f1d615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
979f3c3
f1d615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests Sprint 42 โ€” exposition des token_confidences + cรขblage runner.

Le runner peut maintenant calculer des mรฉtriques de calibration
(ECE / MCE / reliability) dรจs qu'un moteur expose des
``token_confidences`` sur l'``EngineResult``.

Couvre :

1. ``EngineResult.token_confidences`` accepte ``None`` (rรฉtrocompat
   stricte) ou une liste de dicts.
2. ``DocumentResult.calibration_metrics`` est sรฉrialisรฉ via ``as_dict``
   uniquement quand renseignรฉ, libรฉrรฉ par ``compact()``.
3. ``EngineReport.aggregated_calibration`` apparaรฎt dans ``as_dict``
   quand renseignรฉ.
4. ``_calibration_from_engine_result`` :
   - Aligne en bag-of-words avec multiplicitรฉ (proxy oracle)
   - Normalise les confidences en pourcentage (>1) ร  [0, 1]
   - Ignore les confidences nรฉgatives (Tesseract -1 pour non-mots)
   - Retourne ``None`` sur entrรฉe vide / ``None``
5. ``_aggregate_calibration`` :
   - Combine les bins de plusieurs documents en somme pondรฉrรฉe
   - Recalcule ECE/MCE micro ร  partir des sommes
   - Retourne ``None`` si aucun doc n'a de calibration
6. Rรฉtrocompat : sans token_confidences sur l'EngineResult, aucun
   calcul calibration ; ``aggregated_calibration = None``.
"""

from __future__ import annotations

import pytest

from picarones.measurements.runner import (
    _aggregate_calibration,
    _calibration_from_engine_result,
)
from picarones.core.results import DocumentResult, EngineReport
from picarones.engines.base import EngineResult


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 1. EngineResult.token_confidences
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


class TestEngineResultExtension:
    def test_default_is_none(self) -> None:
        r = EngineResult("e", "/tmp/x.png", "hello", 1.0)
        assert r.token_confidences is None

    def test_accepts_list_of_dicts(self) -> None:
        confs = [{"token": "hello", "confidence": 0.95}]
        r = EngineResult("e", "/tmp/x.png", "hello", 1.0, token_confidences=confs)
        assert r.token_confidences == confs


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 2-3. Modรจles : sรฉrialisation et compact
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


def _make_dr(calibration_metrics: dict | None = None) -> DocumentResult:
    from picarones.measurements.metrics import MetricsResult

    return DocumentResult(
        doc_id="d1", image_path="/tmp/x.png",
        ground_truth="a b c", hypothesis="a b c",
        metrics=MetricsResult(
            cer=0.0, cer_nfc=0.0, cer_caseless=0.0,
            wer=0.0, wer_normalized=0.0, mer=0.0, wil=0.0,
            reference_length=5, hypothesis_length=5,
        ),
        duration_seconds=0.1,
        calibration_metrics=calibration_metrics,
    )


class TestModelsSerialization:
    def test_calibration_metrics_omitted_when_none(self) -> None:
        d = _make_dr(None).as_dict()
        assert "calibration_metrics" not in d

    def test_calibration_metrics_present_when_set(self) -> None:
        d = _make_dr({"ece": 0.05, "mce": 0.1}).as_dict()
        assert d["calibration_metrics"] == {"ece": 0.05, "mce": 0.1}

    def test_compact_clears_calibration(self) -> None:
        # Sprint A14-S1 โ€” ``compact()`` est dรฉsormais opt-in.
        dr = _make_dr({"ece": 0.05})
        dr.compact(drop_analyses=True)
        assert dr.calibration_metrics is None

    def test_engine_report_aggregated_calibration_omitted_when_none(self) -> None:
        rep = EngineReport(
            engine_name="t", engine_version="1", engine_config={},
            document_results=[_make_dr()],
        )
        assert "aggregated_calibration" not in rep.as_dict()

    def test_engine_report_aggregated_calibration_included_when_set(self) -> None:
        rep = EngineReport(
            engine_name="t", engine_version="1", engine_config={},
            document_results=[_make_dr()],
            aggregated_calibration={"ece": 0.05, "n_predictions": 100},
        )
        assert rep.as_dict()["aggregated_calibration"] == {
            "ece": 0.05, "n_predictions": 100,
        }


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 4. Helper d'alignement
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


class TestCalibrationFromEngineResult:
    def test_returns_none_for_empty_inputs(self) -> None:
        assert _calibration_from_engine_result("text", None) is None
        assert _calibration_from_engine_result("text", []) is None

    def test_perfect_calibration_when_conf_matches_accuracy(self) -> None:
        gt = "a b c d e f g h i j"
        # 7 tokens dans la GT ร  conf=0.7, 3 hors de la GT ร  conf=0.7 โ†’ ECE = 0
        tcs = (
            [{"token": c, "confidence": 0.7} for c in "abcdefg"]
            + [{"token": c, "confidence": 0.7} for c in ["X", "Y", "Z"]]
        )
        m = _calibration_from_engine_result(gt, tcs)
        assert m is not None
        assert m["ece"] == pytest.approx(0.0, abs=1e-9)
        assert m["overall_accuracy"] == pytest.approx(0.7)
        assert m["n_predictions"] == 10

    def test_normalizes_percentage_confidences(self) -> None:
        """Conf > 1 est interprรฉtรฉe en pourcentage et divisรฉe par 100."""
        m = _calibration_from_engine_result(
            "hello", [{"token": "hello", "confidence": 95.0}],
        )
        assert m is not None
        # 95/100 = 0.95
        assert m["overall_confidence"] == 0.95

    def test_skips_negative_confidences(self) -> None:
        """Tesseract met -1 pour les non-mots ; on les ignore."""
        m = _calibration_from_engine_result(
            "hello", [
                {"token": "hello", "confidence": 0.9},
                {"token": ".", "confidence": -1.0},
            ],
        )
        assert m is not None
        assert m["n_predictions"] == 1

    def test_bag_of_words_with_multiplicity(self) -> None:
        # GT contient deux 'le'. L'hypothรจse en a trois โ†’ 2 corrects, 1 incorrect.
        gt = "le chat le chien"
        tcs = [
            {"token": "le", "confidence": 0.9},
            {"token": "le", "confidence": 0.9},
            {"token": "le", "confidence": 0.9},  # 3e 'le' : pas dans la GT
            {"token": "chat", "confidence": 0.9},
            {"token": "chien", "confidence": 0.9},
        ]
        m = _calibration_from_engine_result(gt, tcs)
        # 4 corrects sur 5
        assert m["overall_accuracy"] == 0.8
        assert m["n_predictions"] == 5

    def test_skips_invalid_entries(self) -> None:
        m = _calibration_from_engine_result(
            "hello", [
                "not a dict",
                {"no_token": True, "confidence": 0.5},
                {"token": "hello"},  # pas de confidence
                {"token": "hello", "confidence": "abc"},  # conf non numรฉrique
                {"token": "hello", "confidence": 0.9},  # valide
            ],
        )
        assert m is not None
        assert m["n_predictions"] == 1


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 5. Agrรฉgateur
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


class TestAggregateCalibration:
    def test_returns_none_when_no_doc_has_calibration(self) -> None:
        drs = [_make_dr(None), _make_dr(None)]
        assert _aggregate_calibration(drs) is None

    def test_combines_bins_across_docs(self) -> None:
        # Doc 1 : bin [0.5, 0.6) avec 10 prรฉdictions, conf=0.55, acc=0.5
        # Doc 2 : bin [0.5, 0.6) avec 20 prรฉdictions, conf=0.55, acc=0.7
        # Agrรฉgat attendu : 30 prรฉdictions dans ce bin, conf moy = 0.55,
        # acc moy pondรฉrรฉe = (10*0.5 + 20*0.7) / 30 = 19/30 โ‰ˆ 0.633
        empty_bin = lambda lo, hi: {  # noqa: E731
            "bin_low": lo, "bin_high": hi,
            "avg_confidence": None, "accuracy": None,
            "count": 0, "gap": None,
        }
        bins1 = [empty_bin(k / 10, (k + 1) / 10) for k in range(10)]
        bins1[5] = {
            "bin_low": 0.5, "bin_high": 0.6,
            "avg_confidence": 0.55, "accuracy": 0.5,
            "count": 10, "gap": 0.05,
        }
        m1 = {
            "ece": 0.05, "mce": 0.05, "n_bins": 10, "n_predictions": 10,
            "overall_accuracy": 0.5, "overall_confidence": 0.55, "bins": bins1,
        }
        bins2 = [empty_bin(k / 10, (k + 1) / 10) for k in range(10)]
        bins2[5] = {
            "bin_low": 0.5, "bin_high": 0.6,
            "avg_confidence": 0.55, "accuracy": 0.7,
            "count": 20, "gap": 0.15,
        }
        m2 = {
            "ece": 0.15, "mce": 0.15, "n_bins": 10, "n_predictions": 20,
            "overall_accuracy": 0.7, "overall_confidence": 0.55, "bins": bins2,
        }
        drs = [_make_dr(m1), _make_dr(m2)]
        agg = _aggregate_calibration(drs)
        assert agg is not None
        assert agg["n_predictions"] == 30
        assert agg["doc_count"] == 2
        # Accuracy combinรฉe = (10*0.5 + 20*0.7) / 30
        assert agg["overall_accuracy"] == (10 * 0.5 + 20 * 0.7) / 30
        # Confidence combinรฉe = 0.55 (constante)
        assert abs(agg["overall_confidence"] - 0.55) < 1e-9
        # ECE micro : seul bin non vide (bin 5), avec count=30,
        # avg_conf=0.55, accuracy=19/30 โ‰ˆ 0.633, gap = |0.55 - 0.633|
        expected_ece = abs(0.55 - 19 / 30)
        assert abs(agg["ece"] - expected_ece) < 1e-9
        assert agg["mce"] == agg["ece"]  # un seul bin non vide โ†’ MCE = ECE


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 6. Rรฉtrocompat : sans token_confidences, rien ne change
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€


class TestBackwardCompat:
    def test_engine_result_default_no_calibration(self) -> None:
        # Un EngineResult sans token_confidences โ†’ calibration_metrics
        # ne doit pas รชtre calculรฉe.
        from picarones.measurements.runner import _compute_document_result
        ocr = EngineResult(
            engine_name="e",
            image_path="/tmp/x.png",
            text="a b c",
            duration_seconds=0.1,
            token_confidences=None,
        )
        dr = _compute_document_result(
            doc_id="d1", image_path="/tmp/x.png",
            ground_truth="a b c",
            ocr_result=ocr,
            char_exclude=None,
        )
        assert dr.calibration_metrics is None

    def test_engine_result_with_confs_triggers_calibration(self) -> None:
        from picarones.measurements.runner import _compute_document_result
        ocr = EngineResult(
            engine_name="e",
            image_path="/tmp/x.png",
            text="a b c",
            duration_seconds=0.1,
            token_confidences=[
                {"token": "a", "confidence": 0.9},
                {"token": "b", "confidence": 0.9},
                {"token": "c", "confidence": 0.9},
            ],
        )
        dr = _compute_document_result(
            doc_id="d1", image_path="/tmp/x.png",
            ground_truth="a b c",
            ocr_result=ocr,
            char_exclude=None,
        )
        assert dr.calibration_metrics is not None
        # 3 tokens, tous corrects, conf 0.9 โ†’ accuracy = 1, conf = 0.9
        assert dr.calibration_metrics["overall_accuracy"] == 1.0
        assert dr.calibration_metrics["overall_confidence"] == 0.9