scanquorum 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {scanquorum-0.2.0/scanquorum.egg-info → scanquorum-0.2.1}/PKG-INFO +39 -3
  2. {scanquorum-0.2.0 → scanquorum-0.2.1}/README.md +38 -2
  3. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/__init__.py +1 -1
  4. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/vote.py +4 -2
  5. {scanquorum-0.2.0 → scanquorum-0.2.1/scanquorum.egg-info}/PKG-INFO +39 -3
  6. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum.egg-info/SOURCES.txt +1 -0
  7. scanquorum-0.2.1/tests/test_riskcov.py +223 -0
  8. {scanquorum-0.2.0 → scanquorum-0.2.1}/LICENSE +0 -0
  9. {scanquorum-0.2.0 → scanquorum-0.2.1}/pyproject.toml +0 -0
  10. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/__main__.py +0 -0
  11. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/build.py +0 -0
  12. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/doctor.py +0 -0
  13. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/engines/__init__.py +0 -0
  14. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/engines/rapidocr_en.py +0 -0
  15. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/engines/rapidocr_multi.py +0 -0
  16. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/engines/tesseract.py +0 -0
  17. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/layout.py +0 -0
  18. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum/verify_ai.py +0 -0
  19. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum.egg-info/dependency_links.txt +0 -0
  20. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum.egg-info/entry_points.txt +0 -0
  21. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum.egg-info/requires.txt +0 -0
  22. {scanquorum-0.2.0 → scanquorum-0.2.1}/scanquorum.egg-info/top_level.txt +0 -0
  23. {scanquorum-0.2.0 → scanquorum-0.2.1}/setup.cfg +0 -0
  24. {scanquorum-0.2.0 → scanquorum-0.2.1}/tests/test_doctor.py +0 -0
  25. {scanquorum-0.2.0 → scanquorum-0.2.1}/tests/test_goldset.py +0 -0
  26. {scanquorum-0.2.0 → scanquorum-0.2.1}/tests/test_safety.py +0 -0
  27. {scanquorum-0.2.0 → scanquorum-0.2.1}/tests/test_vote_parity.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scanquorum
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Read a scanned page with several independent OCR engines and accept a word only when they agree. No language model in the transcription path.
5
5
  Author: Igor Saevets
6
6
  License-Expression: MIT
@@ -181,6 +181,36 @@ with three engines and 99.15 % with four**. Read the two warnings below before u
181
181
  > this sample cannot distinguish from luck. It is reported because it was measured, not
182
182
  > because it is proven.
183
183
 
184
+ ### The curve, not one point
185
+
186
+ Every reviewer of the accompanying paper asked for the same two measurements, so both are now
187
+ in the repository and recomputable by a stranger: vary the acceptance rule and plot
188
+ accepted-token accuracy against coverage, and threshold the best single engine on its own
189
+ confidence to the same coverage. `python tests/test_riskcov.py` recomputes every point from a
190
+ shipped fixture of cross-tabulations; no engine, no network.
191
+
192
+ Three cells of that table earn their space here. Accepting only full unanimity (the
193
+ `VOTE4/4 only` policy) keeps 77.3 % of the document with zero errors observed in its gold
194
+ crops — which is 0 in 7, an unweighted Wilson floor of 64.6 %, and must not be read as
195
+ "100 %". The default cascade reaches 98.9 % coverage at an estimated 99.3 % accepted-token
196
+ accuracy on the sampled strata (Manski band [97.7, 99.3] once the 1.9 % of tokens in
197
+ never-sampled strata are allowed to be anything). And `rapidocr_multi`, thresholded on its
198
+ own confidence — which is line-level, so every word inherits its line's score — barely sorts
199
+ its own errors: 95.9 % accurate at 99 % coverage, 97.4 % at 14 %. Separately, the ensemble's
200
+ point estimate is above that baseline at all fourteen policies, matched at nearest coverage
201
+ in both directions, and the **paired** per-resample difference excludes zero at every point —
202
+ while the fair word-level challenger, Tesseract's per-word confidence, is statistically
203
+ indistinguishable from the ensemble at the coverages it can reach (≤ 83 %) and cannot reach
204
+ the 95–99 % coverage where a quotation tool operates.
205
+
206
+ The same three warnings that wrap the headline number above wrap this table too: the curve is
207
+ an upper bound (the reference standard cannot see a wrong frame — and unanimity is exactly
208
+ where frame errors hide; counted as errors, the four known ones cost the full-coverage point
209
+ half a percentage point and the unanimity point nothing), it is one document, and its
210
+ accuracy axis rests on 56 crops re-used across rounds. `testing/TESTED.md` round 4 carries
211
+ every number in this paragraph with its interval, sensitivity, and the two crops that are the
212
+ entire observed error set.
213
+
184
214
  Everything above is reproducible from this repository: `samples/` contains all five documents,
185
215
  `testing/` records what was tried and what was rejected.
186
216
 
@@ -264,6 +294,11 @@ the two RapidOCR voters share a detector.
264
294
  **If you are handing this to an AI coding agent,** point it at [AGENTS.md](AGENTS.md). It is
265
295
  written to be executed and it lists the five things that will otherwise mislead it.
266
296
 
297
+ **How this was built:** substantial AI assistance (Anthropic's Claude) wrote code and prose
298
+ throughout, under human direction and review — the commit trailers say so on every commit, and
299
+ the paper's final section reports it as arXiv policy requires. Every published number is
300
+ recomputed from shipped fixtures by the test suites regardless of who typed the code.
301
+
267
302
  No account and no API key: `build`, the vote engine and both test suites run entirely
268
303
  offline. (One optional command, `verify-ai`, does send a crop to a model API — it refuses to
269
304
  run without a key, and you never need it. See [SECURITY.md](SECURITY.md).) Tesseract is optional — it is the fourth
@@ -362,8 +397,9 @@ survey (*IEEE SMC* 1998) had already laid out the taxonomy.
362
397
  **Abstention is older still, and better formalised elsewhere.** Chow (1957, and *IEEE Trans.
363
398
  Inf. Theory* 1970) is the reject option, with an optimal threshold derived from a cost model.
364
399
  Modern selective prediction (El-Yaniv and Wiener, *JMLR* 2010; Geifman and El-Yaniv, *NeurIPS*
365
- 2017) reports a **risk-coverage curve**. We report one point on that curve and we have no
366
- calibrated confidence at all. Conformal prediction would give distribution-free coverage
400
+ 2017) reports a **risk-coverage curve**. As of round 4 we report that curve too
401
+ (`python tests/test_riskcov.py`); what we still lack is calibrated confidence.
402
+ Conformal prediction would give distribution-free coverage
367
403
  guarantees for the set of readings we already produce; we do not currently make that claim.
368
404
 
369
405
  **Voting inside one engine is a live alternative.** Calamari (Wick, Reul and Puppe, 2018) votes
@@ -143,6 +143,36 @@ with three engines and 99.15 % with four**. Read the two warnings below before u
143
143
  > this sample cannot distinguish from luck. It is reported because it was measured, not
144
144
  > because it is proven.
145
145
 
146
+ ### The curve, not one point
147
+
148
+ Every reviewer of the accompanying paper asked for the same two measurements, so both are now
149
+ in the repository and recomputable by a stranger: vary the acceptance rule and plot
150
+ accepted-token accuracy against coverage, and threshold the best single engine on its own
151
+ confidence to the same coverage. `python tests/test_riskcov.py` recomputes every point from a
152
+ shipped fixture of cross-tabulations; no engine, no network.
153
+
154
+ Three cells of that table earn their space here. Accepting only full unanimity (the
155
+ `VOTE4/4 only` policy) keeps 77.3 % of the document with zero errors observed in its gold
156
+ crops — which is 0 in 7, an unweighted Wilson floor of 64.6 %, and must not be read as
157
+ "100 %". The default cascade reaches 98.9 % coverage at an estimated 99.3 % accepted-token
158
+ accuracy on the sampled strata (Manski band [97.7, 99.3] once the 1.9 % of tokens in
159
+ never-sampled strata are allowed to be anything). And `rapidocr_multi`, thresholded on its
160
+ own confidence — which is line-level, so every word inherits its line's score — barely sorts
161
+ its own errors: 95.9 % accurate at 99 % coverage, 97.4 % at 14 %. Separately, the ensemble's
162
+ point estimate is above that baseline at all fourteen policies, matched at nearest coverage
163
+ in both directions, and the **paired** per-resample difference excludes zero at every point —
164
+ while the fair word-level challenger, Tesseract's per-word confidence, is statistically
165
+ indistinguishable from the ensemble at the coverages it can reach (≤ 83 %) and cannot reach
166
+ the 95–99 % coverage where a quotation tool operates.
167
+
168
+ The same three warnings that wrap the headline number above wrap this table too: the curve is
169
+ an upper bound (the reference standard cannot see a wrong frame — and unanimity is exactly
170
+ where frame errors hide; counted as errors, the four known ones cost the full-coverage point
171
+ half a percentage point and the unanimity point nothing), it is one document, and its
172
+ accuracy axis rests on 56 crops re-used across rounds. `testing/TESTED.md` round 4 carries
173
+ every number in this paragraph with its interval, sensitivity, and the two crops that are the
174
+ entire observed error set.
175
+
146
176
  Everything above is reproducible from this repository: `samples/` contains all five documents,
147
177
  `testing/` records what was tried and what was rejected.
148
178
 
@@ -226,6 +256,11 @@ the two RapidOCR voters share a detector.
226
256
  **If you are handing this to an AI coding agent,** point it at [AGENTS.md](AGENTS.md). It is
227
257
  written to be executed and it lists the five things that will otherwise mislead it.
228
258
 
259
+ **How this was built:** substantial AI assistance (Anthropic's Claude) wrote code and prose
260
+ throughout, under human direction and review — the commit trailers say so on every commit, and
261
+ the paper's final section reports it as arXiv policy requires. Every published number is
262
+ recomputed from shipped fixtures by the test suites regardless of who typed the code.
263
+
229
264
  No account and no API key: `build`, the vote engine and both test suites run entirely
230
265
  offline. (One optional command, `verify-ai`, does send a crop to a model API — it refuses to
231
266
  run without a key, and you never need it. See [SECURITY.md](SECURITY.md).) Tesseract is optional — it is the fourth
@@ -324,8 +359,9 @@ survey (*IEEE SMC* 1998) had already laid out the taxonomy.
324
359
  **Abstention is older still, and better formalised elsewhere.** Chow (1957, and *IEEE Trans.
325
360
  Inf. Theory* 1970) is the reject option, with an optimal threshold derived from a cost model.
326
361
  Modern selective prediction (El-Yaniv and Wiener, *JMLR* 2010; Geifman and El-Yaniv, *NeurIPS*
327
- 2017) reports a **risk-coverage curve**. We report one point on that curve and we have no
328
- calibrated confidence at all. Conformal prediction would give distribution-free coverage
362
+ 2017) reports a **risk-coverage curve**. As of round 4 we report that curve too
363
+ (`python tests/test_riskcov.py`); what we still lack is calibrated confidence.
364
+ Conformal prediction would give distribution-free coverage
329
365
  guarantees for the set of readings we already produce; we do not currently make that claim.
330
366
 
331
367
  **Voting inside one engine is a live alternative.** Calamari (Wick, Reul and Puppe, 2018) votes
@@ -3,7 +3,7 @@ engines agree, and show you the ones they do not.
3
3
 
4
4
  No language model is involved in transcription. See README.md.
5
5
  """
6
- __version__ = "0.2.0"
6
+ __version__ = "0.2.1"
7
7
 
8
8
  # A Windows console defaults to a legacy code page (cp1251, cp866, cp1252...) and
9
9
  # raises UnicodeEncodeError the first time anything prints a character outside it.
@@ -16,8 +16,10 @@
16
16
  # The cascade is ordered by how much evidence each rule requires, most first.
17
17
  # A rule only runs when every rule above it has declined.
18
18
  #
19
- # PARITY: tests/test_vote_parity.py replays 29,853 real decisions recorded from
20
- # the measured run and asserts this file reproduces every one of them. If you
19
+ # PARITY: tests/test_vote_parity.py replays the 11,780 DISTINCT candidate sets
20
+ # recorded from the measured run (they cover all 29,853 decisions; the fixture was
21
+ # recorded by importing the ORIGINAL lab module, not this file, so the replay is
22
+ # not circular) and asserts this file reproduces every order-independent one. If you
21
23
  # change anything here and that test still passes, you changed nothing that
22
24
  # matters; if it fails, you changed the measured behaviour and the numbers in
23
25
  # README.md no longer describe this code.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scanquorum
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Read a scanned page with several independent OCR engines and accept a word only when they agree. No language model in the transcription path.
5
5
  Author: Igor Saevets
6
6
  License-Expression: MIT
@@ -181,6 +181,36 @@ with three engines and 99.15 % with four**. Read the two warnings below before u
181
181
  > this sample cannot distinguish from luck. It is reported because it was measured, not
182
182
  > because it is proven.
183
183
 
184
+ ### The curve, not one point
185
+
186
+ Every reviewer of the accompanying paper asked for the same two measurements, so both are now
187
+ in the repository and recomputable by a stranger: vary the acceptance rule and plot
188
+ accepted-token accuracy against coverage, and threshold the best single engine on its own
189
+ confidence to the same coverage. `python tests/test_riskcov.py` recomputes every point from a
190
+ shipped fixture of cross-tabulations; no engine, no network.
191
+
192
+ Three cells of that table earn their space here. Accepting only full unanimity (the
193
+ `VOTE4/4 only` policy) keeps 77.3 % of the document with zero errors observed in its gold
194
+ crops — which is 0 in 7, an unweighted Wilson floor of 64.6 %, and must not be read as
195
+ "100 %". The default cascade reaches 98.9 % coverage at an estimated 99.3 % accepted-token
196
+ accuracy on the sampled strata (Manski band [97.7, 99.3] once the 1.9 % of tokens in
197
+ never-sampled strata are allowed to be anything). And `rapidocr_multi`, thresholded on its
198
+ own confidence — which is line-level, so every word inherits its line's score — barely sorts
199
+ its own errors: 95.9 % accurate at 99 % coverage, 97.4 % at 14 %. Separately, the ensemble's
200
+ point estimate is above that baseline at all fourteen policies, matched at nearest coverage
201
+ in both directions, and the **paired** per-resample difference excludes zero at every point —
202
+ while the fair word-level challenger, Tesseract's per-word confidence, is statistically
203
+ indistinguishable from the ensemble at the coverages it can reach (≤ 83 %) and cannot reach
204
+ the 95–99 % coverage where a quotation tool operates.
205
+
206
+ The same three warnings that wrap the headline number above wrap this table too: the curve is
207
+ an upper bound (the reference standard cannot see a wrong frame — and unanimity is exactly
208
+ where frame errors hide; counted as errors, the four known ones cost the full-coverage point
209
+ half a percentage point and the unanimity point nothing), it is one document, and its
210
+ accuracy axis rests on 56 crops re-used across rounds. `testing/TESTED.md` round 4 carries
211
+ every number in this paragraph with its interval, sensitivity, and the two crops that are the
212
+ entire observed error set.
213
+
184
214
  Everything above is reproducible from this repository: `samples/` contains all five documents,
185
215
  `testing/` records what was tried and what was rejected.
186
216
 
@@ -264,6 +294,11 @@ the two RapidOCR voters share a detector.
264
294
  **If you are handing this to an AI coding agent,** point it at [AGENTS.md](AGENTS.md). It is
265
295
  written to be executed and it lists the five things that will otherwise mislead it.
266
296
 
297
+ **How this was built:** substantial AI assistance (Anthropic's Claude) wrote code and prose
298
+ throughout, under human direction and review — the commit trailers say so on every commit, and
299
+ the paper's final section reports it as arXiv policy requires. Every published number is
300
+ recomputed from shipped fixtures by the test suites regardless of who typed the code.
301
+
267
302
  No account and no API key: `build`, the vote engine and both test suites run entirely
268
303
  offline. (One optional command, `verify-ai`, does send a crop to a model API — it refuses to
269
304
  run without a key, and you never need it. See [SECURITY.md](SECURITY.md).) Tesseract is optional — it is the fourth
@@ -362,8 +397,9 @@ survey (*IEEE SMC* 1998) had already laid out the taxonomy.
362
397
  **Abstention is older still, and better formalised elsewhere.** Chow (1957, and *IEEE Trans.
363
398
  Inf. Theory* 1970) is the reject option, with an optimal threshold derived from a cost model.
364
399
  Modern selective prediction (El-Yaniv and Wiener, *JMLR* 2010; Geifman and El-Yaniv, *NeurIPS*
365
- 2017) reports a **risk-coverage curve**. We report one point on that curve and we have no
366
- calibrated confidence at all. Conformal prediction would give distribution-free coverage
400
+ 2017) reports a **risk-coverage curve**. As of round 4 we report that curve too
401
+ (`python tests/test_riskcov.py`); what we still lack is calibrated confidence.
402
+ Conformal prediction would give distribution-free coverage
367
403
  guarantees for the set of readings we already produce; we do not currently make that claim.
368
404
 
369
405
  **Voting inside one engine is a live alternative.** Calamari (Wick, Reul and Puppe, 2018) votes
@@ -20,5 +20,6 @@ scanquorum/engines/rapidocr_multi.py
20
20
  scanquorum/engines/tesseract.py
21
21
  tests/test_doctor.py
22
22
  tests/test_goldset.py
23
+ tests/test_riskcov.py
23
24
  tests/test_safety.py
24
25
  tests/test_vote_parity.py
@@ -0,0 +1,223 @@
1
+ # tests/test_riskcov.py v1.0
2
+ #
3
+ # THE RISK-COVERAGE CURVE AND THE SINGLE-ENGINE BASELINE, RECOMPUTABLE BY A STRANGER.
4
+ #
5
+ # Every external reviewer of the paper asked for the same two measurements, in almost
6
+ # the same words: (1) vary the acceptance rule and plot accepted-token accuracy against
7
+ # coverage instead of reporting one operating point; (2) threshold a single engine on
8
+ # its own confidence to the same coverage, because -- as one reviewer put it -- if the
9
+ # ensemble does not beat that curve, the premise collapses.
10
+ #
11
+ # Both were measured on 2026-08-09 (testing/TESTED.md, round 4). This test recomputes
12
+ # every published point from `tests/fixtures/index_census.json`, which carries only
13
+ # aggregate cross-tabulations of the 41-page EOIR index evidence plus the 56 scored
14
+ # gold crops -- no lab files, no OCR engine, no network.
15
+ #
16
+ # WHAT THIS TEST PROVES, AND WHAT IT CANNOT (round-3 reviewer point, kept verbatim
17
+ # because it is right): the expected values below were transcribed from the same run
18
+ # that produced the fixture, so parts 1-2 prove the shipped fixture and the published
19
+ # numbers are one consistent object -- they do NOT independently verify the estimator.
20
+ # A wrong estimator would pass here forever. The estimator's own audit lives in
21
+ # testing/TESTED.md round 4, where three external channels attacked it.
22
+ #
23
+ # WHAT THE ESTIMATOR IS, in one paragraph, so nobody has to reverse-engineer it:
24
+ # coverage is EXACT (a census of which tokens each policy accepts); accuracy among
25
+ # accepted tokens is a Hájek ratio -- Horvitz-Thompson totals for "correct and
26
+ # accepted" over "accepted", both estimated from the same stratified gold crops with
27
+ # post-stratification weights N_h/n_h by the three-voice rule stratum each crop's
28
+ # token belongs to. The first version of the measuring script divided the estimated
29
+ # numerator by the EXACT accepted count instead, and printed 143 % accuracy: the
30
+ # dominant stratum has 23,585 tokens behind 8 crops, and which of those crops land
31
+ # inside a policy is sampling noise that only cancels if numerator and denominator
32
+ # come from the same sample. The ratio form cannot leave [0, 1]. That defect is kept
33
+ # in the lab script's header the same way every other rejected instrument is kept.
34
+ #
35
+ # Run: python tests/test_riskcov.py Exit: 0 pass, 1 fail.
36
+ import sys
37
+ import json
38
+ import pathlib
39
+
40
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
41
+ ROOT = pathlib.Path(__file__).resolve().parent.parent
42
+ FX = ROOT / "tests" / "fixtures" / "index_census.json"
43
+
44
+ TOTAL = 29853
45
+
46
+ # Published points (testing/riskcov_results.json, riskcov.py v1.1, seed 20260809).
47
+ # coverage is exact and must match EXACTLY; accuracy is a deterministic ratio and
48
+ # must match to 1e-6.
49
+ E1_EXPECT = {
50
+ "VOTE4/4 only": (0.773289, 1.000000),
51
+ "VOTE4/4 only +SEP/NUM": (0.879744, 1.000000),
52
+ "VOTE4/4 only +LEX/PATTERN": (0.777074, 1.000000),
53
+ "VOTE4/4 only +SEP/NUM +LEX/PATTERN": (0.883529, 1.000000),
54
+ "VOTE>=3": (0.846414, 0.993013),
55
+ "VOTE>=3 +SEP/NUM": (0.952869, 0.993788),
56
+ "VOTE>=3 +LEX/PATTERN": (0.850199, 0.993040),
57
+ "VOTE>=3 +SEP/NUM +LEX/PATTERN": (0.956654, 0.993809),
58
+ "VOTE>=2": (0.865776, 0.993129),
59
+ "VOTE>=2 +SEP/NUM": (0.972231, 0.993879),
60
+ "VOTE>=2 +LEX/PATTERN": (0.869561, 0.993155),
61
+ "VOTE>=2 +SEP/NUM +LEX/PATTERN": (0.976016, 0.993900),
62
+ "all present agree (VOTEk/k)": (0.775500, 1.000000),
63
+ "everything emitted (+flags)": (0.989314, 0.992664),
64
+ }
65
+ E2_EXPECT = [ # (tau, coverage, accuracy)
66
+ (0.0, 0.989884, 0.958992), (0.5, 0.989884, 0.958992), (0.7, 0.989247, 0.960177),
67
+ (0.8, 0.988879, 0.960177), (0.85, 0.988778, 0.960177), (0.9, 0.987740, 0.960177),
68
+ (0.925, 0.983620, 0.970804), (0.95, 0.968780, 0.970114), (0.96, 0.951998, 0.969940),
69
+ (0.97, 0.912471, 0.970124), (0.975, 0.869695, 0.972912), (0.98, 0.808160, 0.972211),
70
+ (0.985, 0.710180, 0.971375), (0.99, 0.564700, 0.972897), (0.9925, 0.467960, 0.978377),
71
+ (0.995, 0.370482, 0.986882), (0.9975, 0.275651, 0.982429), (0.999, 0.189696, 0.974148),
72
+ (0.9995, 0.143001, 0.973995),
73
+ ]
74
+
75
+ S_RULES = {"SEP", "SEP=", "NUM"}
76
+ R_RULES = {"LEX", "PATTERN"}
77
+ FLAG_RULES = {"ONLY_ONE", "MEDOID_FLAG"}
78
+
79
+
80
+ def votes_k(rule):
81
+ return int(rule[4:].split("/")[0]) if rule.startswith("VOTE") else None
82
+
83
+
84
+ def unanimous(rule):
85
+ if not rule.startswith("VOTE"):
86
+ return False
87
+ k, m = rule[4:].split("/")
88
+ return k == m
89
+
90
+
91
+ def accepted(rule, kmin, s, rr, flags=False, unan=False):
92
+ k = votes_k(rule)
93
+ if k is not None:
94
+ return unanimous(rule) if unan else k >= kmin
95
+ return (s and rule in S_RULES) or (rr and rule in R_RULES) or (flags and rule in FLAG_RULES)
96
+
97
+
98
+ POLICIES = []
99
+ for kmin, kl in ((4, "VOTE4/4 only"), (3, "VOTE>=3"), (2, "VOTE>=2")):
100
+ for s, rr, sl in ((0, 0, ""), (1, 0, " +SEP/NUM"), (0, 1, " +LEX/PATTERN"),
101
+ (1, 1, " +SEP/NUM +LEX/PATTERN")):
102
+ POLICIES.append((kl + sl, dict(kmin=kmin, s=s, rr=rr)))
103
+ POLICIES.append(("all present agree (VOTEk/k)", dict(kmin=99, unan=True)))
104
+ POLICIES.append(("everything emitted (+flags)", dict(kmin=2, s=1, rr=1, flags=True)))
105
+
106
+
107
+ def main():
108
+ fx = json.loads(FX.read_text(encoding="utf-8"))
109
+ fails = []
110
+
111
+ # ---- 0. the fixture must account for every token, twice over ------------
112
+ census = fx["shipped_rule_census"]
113
+ old = fx["old_stratum_census"]
114
+ assert sum(census.values()) == TOTAL and sum(old.values()) == TOTAL
115
+ from collections import Counter
116
+ m_rule = Counter()
117
+ m_old = Counter()
118
+ for h, rl, c in fx["cross_old_by_shipped_rule"]:
119
+ m_rule[rl] += c
120
+ m_old[h] += c
121
+ assert dict(m_rule) == census, "cross table does not marginalise to the rule census"
122
+ assert dict(m_old) == old, "cross table does not marginalise to the stratum census"
123
+ rows = fx["gold_rows"]
124
+ assert len(rows) == 56, "expected 56 scored gold crops"
125
+ H = set(fx["covered_strata"])
126
+ nh = Counter(r["h"] for r in rows)
127
+ assert set(nh) == H
128
+ print("fixture accounts for every one of %d tokens, both ways; 56 gold crops in %d strata"
129
+ % (TOTAL, len(H)))
130
+
131
+ def hajek(y_num_key, acc_fn):
132
+ tn = td = 0.0
133
+ for h in H:
134
+ w = old[h] / nh[h]
135
+ for r in rows:
136
+ if r["h"] != h or not acc_fn(r):
137
+ continue
138
+ tn += w * r[y_num_key]
139
+ td += w
140
+ return tn / td if td else 0.0
141
+
142
+ # ---- 1. the risk-coverage curve -----------------------------------------
143
+ print("\nPART 1 -- accepted-token accuracy vs coverage, every published point recomputed")
144
+ for label, kw in POLICIES:
145
+ cov = sum(c for rl, c in census.items()
146
+ if accepted(rl, kw.get("kmin", 2), kw.get("s", 0), kw.get("rr", 0),
147
+ kw.get("flags", False), kw.get("unan", False))) / TOTAL
148
+ acc = hajek("ens_ok", lambda r: accepted(
149
+ r["rule"], kw.get("kmin", 2), kw.get("s", 0), kw.get("rr", 0),
150
+ kw.get("flags", False), kw.get("unan", False)))
151
+ ecov, eacc = E1_EXPECT[label]
152
+ ok = abs(cov - ecov) < 5e-7 and abs(acc - eacc) < 1e-6
153
+ print(" %-36s cov %7.2f%% acc %7.2f%% %s"
154
+ % (label, 100 * cov, 100 * acc, "ok" if ok else "MISMATCH"))
155
+ if not ok:
156
+ fails.append("E1 %r: got (%.6f, %.6f), published (%.6f, %.6f)"
157
+ % (label, cov, acc, ecov, eacc))
158
+
159
+ # ---- 2. the single-engine confidence baseline ---------------------------
160
+ print("\nPART 2 -- rapidocr_multi alone, thresholded on its own line confidence")
161
+ grid = fx["conf_grid"]
162
+ bins = Counter()
163
+ for h, b, c in fx["cross_old_by_conf_bin"]:
164
+ bins[b] += c
165
+ for tau, ecov, eacc in E2_EXPECT:
166
+ cov = sum(c for b, c in bins.items()
167
+ if b not in ("none", "<0") and float(b) >= tau - 1e-12) / TOTAL
168
+ acc = hajek("multi_ok", lambda r: r["conf_mu"] is not None and r["conf_mu"] >= tau)
169
+ ok = abs(cov - ecov) < 5e-7 and abs(acc - eacc) < 1e-6
170
+ print(" tau %-7s cov %7.2f%% acc %7.2f%% %s"
171
+ % (("%.4f" % tau).rstrip("0").rstrip("."), 100 * cov, 100 * acc,
172
+ "ok" if ok else "MISMATCH"))
173
+ if not ok:
174
+ fails.append("E2 tau=%s: got (%.6f, %.6f), published (%.6f, %.6f)"
175
+ % (tau, cov, acc, ecov, eacc))
176
+ assert grid == sorted(grid)
177
+
178
+ # ---- 3. the comparative claim, which is the one that matters ------------
179
+ # Round 3 correction: v1.0 of this part matched the baseline only at coverage
180
+ # >= the policy's, which forces extra low-confidence tokens on it and flatters
181
+ # the ensemble. Both directions are now checked. The statistical form of the
182
+ # claim -- the PAIRED per-resample difference, which excludes zero at every
183
+ # point in both directions -- lives in testing/riskcov_results.json and
184
+ # TESTED.md round 4; this part checks only the point estimates.
185
+ print("\nPART 3 -- at every policy's coverage, the ensemble vs the single engine,")
186
+ print(" baseline matched at nearest coverage above AND below")
187
+ e2pts = sorted(((c, a) for _, c, a in E2_EXPECT))
188
+ below = 0
189
+ for label, _ in POLICIES:
190
+ cov, acc = E1_EXPECT[label]
191
+ for tag, cand in (("above", [(c, a) for c, a in e2pts if c >= cov - 1e-9]),
192
+ ("below", [(c, a) for c, a in e2pts if c <= cov + 1e-9])):
193
+ if not cand:
194
+ continue
195
+ mcov, macc = min(cand) if tag == "above" else max(cand)
196
+ if acc <= macc:
197
+ below += 1
198
+ print(" %-36s ensemble %6.2f%% <= single %6.2f%% (matched %s)"
199
+ % (label, 100 * acc, 100 * macc, tag))
200
+ if below:
201
+ fails.append("the ensemble fails to beat the single-engine baseline at %d "
202
+ "direction-matched point(s)" % below)
203
+ else:
204
+ print(" point estimates: the ensemble is above the single-engine curve at all")
205
+ print(" %d policies, matched in both directions. Marginal per-point intervals"
206
+ % len(POLICIES))
207
+ print(" overlap; the PAIRED difference excludes zero everywhere -- TESTED.md")
208
+ print(" round 4 states both, with the caveats.")
209
+
210
+ print()
211
+ if fails:
212
+ print("FAILED (%d):" % len(fails))
213
+ for f in fails:
214
+ print(" - %s" % f)
215
+ return 1
216
+ print("RISK-COVERAGE OK.")
217
+ print(" Every published point on both curves is recomputed from the shipped fixture,")
218
+ print(" and the comparative claim holds at every matched coverage.")
219
+ return 0
220
+
221
+
222
+ if __name__ == "__main__":
223
+ sys.exit(main())
File without changes
File without changes
File without changes