scanquorum 0.2.0__tar.gz → 0.2.2__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.
- {scanquorum-0.2.0/scanquorum.egg-info → scanquorum-0.2.2}/PKG-INFO +39 -3
- {scanquorum-0.2.0 → scanquorum-0.2.2}/README.md +38 -2
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/__init__.py +1 -1
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/build.py +133 -1
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/vote.py +4 -2
- {scanquorum-0.2.0 → scanquorum-0.2.2/scanquorum.egg-info}/PKG-INFO +39 -3
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum.egg-info/SOURCES.txt +2 -0
- scanquorum-0.2.2/tests/test_purescan.py +138 -0
- scanquorum-0.2.2/tests/test_riskcov.py +223 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/LICENSE +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/pyproject.toml +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/__main__.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/doctor.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/engines/__init__.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/engines/rapidocr_en.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/engines/rapidocr_multi.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/engines/tesseract.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/layout.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum/verify_ai.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum.egg-info/dependency_links.txt +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum.egg-info/entry_points.txt +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum.egg-info/requires.txt +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/scanquorum.egg-info/top_level.txt +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/setup.cfg +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/tests/test_doctor.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/tests/test_goldset.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/tests/test_safety.py +0 -0
- {scanquorum-0.2.0 → scanquorum-0.2.2}/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.
|
|
3
|
+
Version: 0.2.2
|
|
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**.
|
|
366
|
-
|
|
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**.
|
|
328
|
-
|
|
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.
|
|
6
|
+
__version__ = "0.2.2"
|
|
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.
|
|
@@ -33,7 +33,27 @@ from . import __version__
|
|
|
33
33
|
# Module version, bumped when this file's behaviour changes. Distinct from the
|
|
34
34
|
# package version above on purpose: the sidecar header records both, so a reader
|
|
35
35
|
# who finds an odd number can tell whether the pipeline or the packaging moved.
|
|
36
|
-
VERSION = "1.
|
|
36
|
+
VERSION = "1.2"
|
|
37
|
+
|
|
38
|
+
# When the PDF has no text layer at all (`pg.get_text("words") == []`), the
|
|
39
|
+
# word-anchored voting path below has nothing to iterate: `owner` is empty,
|
|
40
|
+
# every `for bi in order` loop does zero work, and the .md file comes back
|
|
41
|
+
# with a valid YAML header and an empty body while every OCR engine sits on
|
|
42
|
+
# a full page of boxes it has already read. Found on Igor's I-485 exhibit
|
|
43
|
+
# corpus on 2026-08-17: 5 of 5 pilot pure-scan documents emitted 0 rows,
|
|
44
|
+
# and 3 of them still emitted 10-19 rows -- but only because a stamp had been
|
|
45
|
+
# ADDED to the PDF layer by the packaging tool, so the "OCR output" was the
|
|
46
|
+
# stamp read three times, not the document read once. See CHANGELOG.md 0.2.2.
|
|
47
|
+
#
|
|
48
|
+
# The fix is a separate emission path (see `_emit_pure_scan_page` below) that
|
|
49
|
+
# runs when `words == []` AND at least one engine produced boxes. Voting is
|
|
50
|
+
# LINE-to-LINE rather than word-to-word, because there are no per-word anchors
|
|
51
|
+
# in the PDF to line up against. The IoU threshold below matches the one the
|
|
52
|
+
# workaround pilot (ocr_pilot_v2.py) settled on empirically: 0.30 lets slightly
|
|
53
|
+
# tilted engines agree without letting neighbouring lines masquerade as the
|
|
54
|
+
# same one. Tests in tests/test_purescan.py assert both that the .md is
|
|
55
|
+
# non-empty and that the header's `pure_scan_pages` counter incremented.
|
|
56
|
+
PURE_SCAN_IOU_THR = 0.30
|
|
37
57
|
|
|
38
58
|
# Which engine's line boxes define the page's layout, in order of preference.
|
|
39
59
|
# STATED, not alphabetical -- see the note at the frame selection below. The
|
|
@@ -69,6 +89,78 @@ def load_engines(names, pdf, dpi, progress):
|
|
|
69
89
|
return out, missing
|
|
70
90
|
|
|
71
91
|
|
|
92
|
+
def _emit_pure_scan_page(pi, frame, frame_engine, ocr, granularity, lex):
|
|
93
|
+
"""Line-level records for a page whose PDF has no text layer.
|
|
94
|
+
|
|
95
|
+
The word-anchored path in `build()` iterates over `pg.get_text("words")`. On a
|
|
96
|
+
pure scan that list is empty, and the whole voting loop does zero work: an .md
|
|
97
|
+
file is written with a valid YAML header and an empty body while every engine's
|
|
98
|
+
boxes are silently discarded. This function replaces that empty output.
|
|
99
|
+
|
|
100
|
+
Voting is LINE-to-LINE because the pipeline has no per-word anchors on this
|
|
101
|
+
page. For every line box the frame engine drew, the other engines' readings
|
|
102
|
+
are collected by IoU (for line-granularity engines) or by aggregating words
|
|
103
|
+
whose centres fall inside the frame box (for word engines like tesseract).
|
|
104
|
+
The same `vote.decide` cascade then runs on the candidate map, exactly as in
|
|
105
|
+
the word path -- so LEX still cannot promote a Capitalised token, PATTERN
|
|
106
|
+
still requires digit-match from at least one other engine, and MEDOID still
|
|
107
|
+
flags rather than accepts. Every rule tag is suffixed with "|NO_LAYER" so a
|
|
108
|
+
downstream reader can tell this row was decided without a PDF anchor.
|
|
109
|
+
|
|
110
|
+
Returns (rows, per_rule_counter). The rows have the same shape as the word
|
|
111
|
+
path's records so the outer pipeline's `classify` / bucket accounting and
|
|
112
|
+
the unconfirmed-index writer work unchanged.
|
|
113
|
+
"""
|
|
114
|
+
import collections
|
|
115
|
+
rows, stats = [], collections.Counter()
|
|
116
|
+
for fb in sorted(frame, key=lambda b: (round(b["b"][1], 1), b["b"][0])):
|
|
117
|
+
fb_box = fb["b"]
|
|
118
|
+
cands = {frame_engine: fb["t"]}
|
|
119
|
+
x0, y0, x1, y1 = fb_box
|
|
120
|
+
for n in sorted(ocr):
|
|
121
|
+
if n == frame_engine:
|
|
122
|
+
continue
|
|
123
|
+
boxes = ocr[n].get(str(pi), {}).get("boxes", [])
|
|
124
|
+
if not boxes:
|
|
125
|
+
continue
|
|
126
|
+
if granularity.get(n) == "word":
|
|
127
|
+
inside = []
|
|
128
|
+
for wb in boxes:
|
|
129
|
+
wb_box = wb["b"]
|
|
130
|
+
cx, cy = (wb_box[0] + wb_box[2]) / 2, (wb_box[1] + wb_box[3]) / 2
|
|
131
|
+
if x0 <= cx <= x1 and y0 <= cy <= y1:
|
|
132
|
+
inside.append((wb_box[0], wb["t"]))
|
|
133
|
+
if inside:
|
|
134
|
+
cands[n] = " ".join(t for _, t in sorted(inside))
|
|
135
|
+
else:
|
|
136
|
+
best_iou, best_t = 0.0, None
|
|
137
|
+
for ob in boxes:
|
|
138
|
+
v = layout.iou(fb_box, ob["b"])
|
|
139
|
+
if v > best_iou:
|
|
140
|
+
best_iou, best_t = v, ob["t"]
|
|
141
|
+
if best_iou >= PURE_SCAN_IOU_THR and best_t:
|
|
142
|
+
cands[n] = best_t
|
|
143
|
+
chosen, rule, who = vote.decide(cands, lex)
|
|
144
|
+
if chosen is None:
|
|
145
|
+
# DISPUTED at line level. Emit the frame engine's version so the .md
|
|
146
|
+
# is not lossy, and let the unconfirmed index flag it. This matches
|
|
147
|
+
# the word-path convention where `vote.collapse` is applied.
|
|
148
|
+
chosen = vote.collapse(fb["t"])
|
|
149
|
+
rule = "DISPUTED"
|
|
150
|
+
who = frame_engine
|
|
151
|
+
# Suffix every rule with |NO_LAYER so a reviewer knows the row came from
|
|
152
|
+
# OCR only. `classify()` splits on "|" and reads the base, so bucket
|
|
153
|
+
# accounting is unaffected.
|
|
154
|
+
rule = rule + "|NO_LAYER"
|
|
155
|
+
rec = {"page": pi, "bbox": [round(x, 1) for x in fb_box], "col": 0,
|
|
156
|
+
"y": fb_box[1], "x": fb_box[0], "chosen": chosen,
|
|
157
|
+
"rule": rule, "who": who}
|
|
158
|
+
rec.update(cands)
|
|
159
|
+
rows.append(rec)
|
|
160
|
+
stats[rule] += 1
|
|
161
|
+
return rows, stats
|
|
162
|
+
|
|
163
|
+
|
|
72
164
|
def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
|
|
73
165
|
dpi=300, out_dir=None, lexicon=None, heartbeat=900):
|
|
74
166
|
import pymupdf
|
|
@@ -146,6 +238,12 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
|
|
|
146
238
|
ev, unconf, stats = [], [], collections.Counter()
|
|
147
239
|
frames_used = {}
|
|
148
240
|
pages_md = []
|
|
241
|
+
# 🔴 Number of pages that fell into the pure-scan emission path (see the
|
|
242
|
+
# comment at PURE_SCAN_IOU_THR near the top). Reported in the header so a
|
|
243
|
+
# downstream reader can tell WHY the .md's line granularity is coarser than
|
|
244
|
+
# the word-anchored path would have produced. On the corpus this bug was
|
|
245
|
+
# found on, this number equals doc.page_count for every failing document.
|
|
246
|
+
pure_scan_pages = 0
|
|
149
247
|
|
|
150
248
|
for pi in range(doc.page_count):
|
|
151
249
|
pg = doc[pi]
|
|
@@ -181,6 +279,26 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
|
|
|
181
279
|
progress(pi + 1, doc.page_count, "voting")
|
|
182
280
|
continue
|
|
183
281
|
|
|
282
|
+
# 🔴 PURE-SCAN PATH. Before v0.2.2 the loop below dropped straight into
|
|
283
|
+
# `layout.assign(frame, words)`, which with `words == []` returns an
|
|
284
|
+
# empty owner mapping; every subsequent `for bi in order` iteration
|
|
285
|
+
# then read `owner.get(bi, []) == []` and emitted nothing. On a real
|
|
286
|
+
# scanned page (no text layer at all) this meant the OCR engines ran to
|
|
287
|
+
# completion and their output was thrown away. See the comment at the
|
|
288
|
+
# top of this file for the corpus this was found on.
|
|
289
|
+
if not words:
|
|
290
|
+
pure_scan_pages += 1
|
|
291
|
+
page_rows, page_stats = _emit_pure_scan_page(
|
|
292
|
+
pi, frame, frame_engine, ocr, granularity, lex)
|
|
293
|
+
for rec in page_rows:
|
|
294
|
+
if rec["rule"].startswith(("DISPUTED", "ONLY_ONE")) or rec["rule"].startswith("MEDOID_FLAG"):
|
|
295
|
+
unconf.append(rec)
|
|
296
|
+
ev.extend(page_rows)
|
|
297
|
+
stats.update(page_stats)
|
|
298
|
+
pages_md.append((pi, "\n".join(r["chosen"] for r in page_rows if r["chosen"])))
|
|
299
|
+
progress(pi + 1, doc.page_count, "voting")
|
|
300
|
+
continue
|
|
301
|
+
|
|
184
302
|
cut = layout.gutter([b["b"] for b in frame], pg.rect.width)
|
|
185
303
|
colf = (lambda bb: 0) if cut is None else (lambda bb: 0 if (bb[0] + bb[2]) / 2 < cut else 1)
|
|
186
304
|
owner = layout.assign(frame, words)
|
|
@@ -360,6 +478,13 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
|
|
|
360
478
|
"frame_engine": (max(sorted(frames_used.items()), key=lambda t: t[1])[0]
|
|
361
479
|
if frames_used else None),
|
|
362
480
|
"frame_engine_pages": frames_used,
|
|
481
|
+
# New in v0.2.2. Non-zero means at least one page had no existing text
|
|
482
|
+
# layer at all, so on those pages voting was line-to-line rather than
|
|
483
|
+
# word-to-word. The count is reported here rather than merely tagged
|
|
484
|
+
# inside the rules because a reader who trusts the header should not
|
|
485
|
+
# have to grep evidence.json to find out how many pages fell into the
|
|
486
|
+
# coarser path -- the field naming that count is the honest place.
|
|
487
|
+
"pure_scan_pages": pure_scan_pages,
|
|
363
488
|
"words": len(ev),
|
|
364
489
|
# These four sum to `words`. The assert above enforces it, and they are
|
|
365
490
|
# reported separately because they are NOT the same strength of evidence.
|
|
@@ -388,6 +513,13 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
|
|
|
388
513
|
if len(used) < 3:
|
|
389
514
|
warn = ("THIS RUN HAD ONLY %d ENGINES. Nothing here is confirmed by a quorum. "
|
|
390
515
|
"Treat the whole file as unverified. " % len(used)) + warn
|
|
516
|
+
if pure_scan_pages:
|
|
517
|
+
warn = ("NOTE: %d of %d pages had NO existing text layer. On those pages the "
|
|
518
|
+
"pipeline emitted LINE-level records from OCR only, without the PDF's "
|
|
519
|
+
"own words as anchors, so a rule such as SEP or NUM that separates "
|
|
520
|
+
"digits from punctuation is coarser than on a page with a text layer. "
|
|
521
|
+
"The tag `|NO_LAYER` on every affected row's rule flags this. "
|
|
522
|
+
% (pure_scan_pages, doc.page_count)) + warn
|
|
391
523
|
|
|
392
524
|
md = ["---"]
|
|
393
525
|
for k, v in hdr.items():
|
|
@@ -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
|
|
20
|
-
# the measured run
|
|
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.
|
|
3
|
+
Version: 0.2.2
|
|
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**.
|
|
366
|
-
|
|
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
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# tests/test_purescan.py v1.0
|
|
2
|
+
#
|
|
3
|
+
# THE FAILURE THIS FILE EXISTS TO PREVENT. On a PDF with NO existing text
|
|
4
|
+
# layer, the pipeline in build.py used to iterate the voting loop over
|
|
5
|
+
# `pg.get_text("words") == []` and emit an .md with a valid YAML header and an
|
|
6
|
+
# empty body. Every OCR engine had already produced boxes for the page; nothing
|
|
7
|
+
# in the header said the emission was empty. Found on Igor's I-485 exhibit
|
|
8
|
+
# corpus on 2026-08-17: five of five SCAN documents in the pilot were affected,
|
|
9
|
+
# three of them still emitted 10-19 rows -- but only because a stamp had been
|
|
10
|
+
# added to the PDF layer by the packaging tool, so the "OCR output" was the
|
|
11
|
+
# stamp read three times, not the document read once.
|
|
12
|
+
#
|
|
13
|
+
# The fix is a separate emission path in build.py (`_emit_pure_scan_page`) that
|
|
14
|
+
# runs when `words == []` AND at least one engine produced boxes. This test
|
|
15
|
+
# builds a minimal pure-scan PDF from a PIL image (guaranteed no text layer),
|
|
16
|
+
# runs build(), and asserts:
|
|
17
|
+
#
|
|
18
|
+
# 1. the pipeline exits without raising
|
|
19
|
+
# 2. the .md exists and its BODY (past the YAML header) is non-empty
|
|
20
|
+
# 3. the header field `pure_scan_pages` is >= 1
|
|
21
|
+
# 4. at least two of the tokens rendered into the image appear in the body
|
|
22
|
+
#
|
|
23
|
+
# The last assertion is deliberately weak. It is not a scoring test: OCR
|
|
24
|
+
# accuracy is measured against goldset.json, and both RapidOCR configurations
|
|
25
|
+
# happily read a PIL-rendered TrueType page at the DPI used here. The point is
|
|
26
|
+
# to catch a REGRESSION where the .md returns to being empty on a pure scan,
|
|
27
|
+
# not to demand every glyph.
|
|
28
|
+
#
|
|
29
|
+
# Skips if pillow / rapidocr / onnxruntime are not installed. That is
|
|
30
|
+
# deliberate too: the CI 'replay' matrix does not install OCR engines (its
|
|
31
|
+
# whole design is that replay tests must run without them), so this test is a
|
|
32
|
+
# no-op in the parity suites and a real run only when the doctor's engine
|
|
33
|
+
# dependencies are present.
|
|
34
|
+
import io
|
|
35
|
+
import sys
|
|
36
|
+
import tempfile
|
|
37
|
+
import unittest
|
|
38
|
+
import pathlib
|
|
39
|
+
|
|
40
|
+
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
41
|
+
sys.path.insert(0, str(ROOT))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _make_pure_scan_pdf(text, out_path):
|
|
45
|
+
"""Build a one-page PDF whose only content is a rasterised image.
|
|
46
|
+
|
|
47
|
+
Uses PIL to render `text` onto a white canvas, embeds the raster into a
|
|
48
|
+
fresh PyMuPDF document, and saves. The saved file has NO text layer, i.e.
|
|
49
|
+
`pg.get_text("words")` returns `[]` and `pg.get_text()` returns the empty
|
|
50
|
+
string. That is what a scanner produces from paper, and it is what defeats
|
|
51
|
+
a pipeline anchored to the PDF layer."""
|
|
52
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
53
|
+
import pymupdf
|
|
54
|
+
W, H = 1400, 900
|
|
55
|
+
img = Image.new("RGB", (W, H), "white")
|
|
56
|
+
d = ImageDraw.Draw(img)
|
|
57
|
+
font = None
|
|
58
|
+
for candidate in ("arial.ttf", "DejaVuSans.ttf", "LiberationSans-Regular.ttf"):
|
|
59
|
+
try:
|
|
60
|
+
font = ImageFont.truetype(candidate, 60)
|
|
61
|
+
break
|
|
62
|
+
except Exception:
|
|
63
|
+
continue
|
|
64
|
+
if font is None:
|
|
65
|
+
font = ImageFont.load_default()
|
|
66
|
+
y = 150
|
|
67
|
+
for line in text.splitlines():
|
|
68
|
+
d.text((100, y), line, fill="black", font=font)
|
|
69
|
+
y += 110
|
|
70
|
+
buf = io.BytesIO()
|
|
71
|
+
img.save(buf, format="PNG")
|
|
72
|
+
doc = pymupdf.open()
|
|
73
|
+
page = doc.new_page(width=W * 72 / 150, height=H * 72 / 150)
|
|
74
|
+
page.insert_image(page.rect, stream=buf.getvalue())
|
|
75
|
+
doc.save(str(out_path))
|
|
76
|
+
doc.close()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class PureScan(unittest.TestCase):
|
|
80
|
+
def _require(self, *modules):
|
|
81
|
+
for m in modules:
|
|
82
|
+
try:
|
|
83
|
+
__import__(m)
|
|
84
|
+
except ImportError:
|
|
85
|
+
self.skipTest("%s not installed" % m)
|
|
86
|
+
|
|
87
|
+
def test_build_emits_non_empty_md_and_reports_pure_scan(self):
|
|
88
|
+
self._require("PIL", "pymupdf", "rapidocr", "onnxruntime")
|
|
89
|
+
|
|
90
|
+
with tempfile.TemporaryDirectory() as td:
|
|
91
|
+
td = pathlib.Path(td)
|
|
92
|
+
pdf_path = td / "purescan_fixture.pdf"
|
|
93
|
+
_make_pure_scan_pdf("SCANQUORUM 12-855\nHELLO WORLD 42\nSAMPLE LINE\n", pdf_path)
|
|
94
|
+
|
|
95
|
+
import pymupdf
|
|
96
|
+
doc = pymupdf.open(str(pdf_path))
|
|
97
|
+
self.assertEqual(doc[0].get_text("words"), [],
|
|
98
|
+
"fixture is not a pure scan: get_text('words') is non-empty")
|
|
99
|
+
doc.close()
|
|
100
|
+
|
|
101
|
+
# RapidOCR is enough on its own for a regression test; not
|
|
102
|
+
# requiring Tesseract keeps this test runnable on more machines,
|
|
103
|
+
# and doctor already exercises the missing-engine path.
|
|
104
|
+
from scanquorum.build import build
|
|
105
|
+
hdr = build(str(pdf_path),
|
|
106
|
+
engines=("rapidocr_multi", "rapidocr_en"),
|
|
107
|
+
dpi=200, out_dir=str(td))
|
|
108
|
+
|
|
109
|
+
md_path = td / "purescan_fixture.md"
|
|
110
|
+
self.assertTrue(md_path.exists(), ".md was not written")
|
|
111
|
+
md_text = md_path.read_text(encoding="utf-8")
|
|
112
|
+
|
|
113
|
+
# There are TWO "---" lines in the file: the YAML header opens with
|
|
114
|
+
# one at line 0 and closes with another before the body. Split
|
|
115
|
+
# gives us [head_meta, warning_block, body].
|
|
116
|
+
parts = md_text.split("\n---\n")
|
|
117
|
+
self.assertGreaterEqual(len(parts), 2, "no YAML header separator found")
|
|
118
|
+
body = parts[-1].strip()
|
|
119
|
+
self.assertNotEqual(body, "",
|
|
120
|
+
"body is empty -- the pure-scan bug regressed. "
|
|
121
|
+
"Header was: %r" % md_text[:400])
|
|
122
|
+
|
|
123
|
+
self.assertGreaterEqual(hdr.get("pure_scan_pages", 0), 1,
|
|
124
|
+
"hdr['pure_scan_pages'] did not increment; "
|
|
125
|
+
"either the pure-scan path did not fire, or "
|
|
126
|
+
"the counter was not wired into the header")
|
|
127
|
+
|
|
128
|
+
expect = ["SCANQUORUM", "12-855", "HELLO", "WORLD", "SAMPLE"]
|
|
129
|
+
found = [t for t in expect if t in body]
|
|
130
|
+
self.assertGreaterEqual(len(found), 2,
|
|
131
|
+
"expected >=2 of %r in body, got %r. "
|
|
132
|
+
"OCR may have failed at the fixture DPI or "
|
|
133
|
+
"PIL font choice; check the render before "
|
|
134
|
+
"declaring a regression." % (expect, found))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
if __name__ == "__main__":
|
|
138
|
+
unittest.main(verbosity=2)
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|