scanquorum 0.2.2__tar.gz → 0.3.0__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 (29) hide show
  1. {scanquorum-0.2.2/scanquorum.egg-info → scanquorum-0.3.0}/PKG-INFO +16 -4
  2. {scanquorum-0.2.2 → scanquorum-0.3.0}/README.md +14 -2
  3. {scanquorum-0.2.2 → scanquorum-0.3.0}/pyproject.toml +1 -1
  4. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/__init__.py +1 -1
  5. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/build.py +422 -43
  6. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/verify_ai.py +11 -2
  7. {scanquorum-0.2.2 → scanquorum-0.3.0/scanquorum.egg-info}/PKG-INFO +16 -4
  8. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum.egg-info/SOURCES.txt +1 -0
  9. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum.egg-info/requires.txt +1 -1
  10. {scanquorum-0.2.2 → scanquorum-0.3.0}/tests/test_purescan.py +2 -2
  11. scanquorum-0.3.0/tests/test_strict_and_mixed.py +317 -0
  12. {scanquorum-0.2.2 → scanquorum-0.3.0}/LICENSE +0 -0
  13. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/__main__.py +0 -0
  14. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/doctor.py +0 -0
  15. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/engines/__init__.py +0 -0
  16. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/engines/rapidocr_en.py +0 -0
  17. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/engines/rapidocr_multi.py +0 -0
  18. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/engines/tesseract.py +0 -0
  19. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/layout.py +0 -0
  20. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum/vote.py +0 -0
  21. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum.egg-info/dependency_links.txt +0 -0
  22. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum.egg-info/entry_points.txt +0 -0
  23. {scanquorum-0.2.2 → scanquorum-0.3.0}/scanquorum.egg-info/top_level.txt +0 -0
  24. {scanquorum-0.2.2 → scanquorum-0.3.0}/setup.cfg +0 -0
  25. {scanquorum-0.2.2 → scanquorum-0.3.0}/tests/test_doctor.py +0 -0
  26. {scanquorum-0.2.2 → scanquorum-0.3.0}/tests/test_goldset.py +0 -0
  27. {scanquorum-0.2.2 → scanquorum-0.3.0}/tests/test_riskcov.py +0 -0
  28. {scanquorum-0.2.2 → scanquorum-0.3.0}/tests/test_safety.py +0 -0
  29. {scanquorum-0.2.2 → scanquorum-0.3.0}/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.2
3
+ Version: 0.3.0
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
@@ -29,7 +29,7 @@ Requires-Dist: onnxruntime<2,>=1.17
29
29
  Requires-Dist: numpy<3,>=1.24
30
30
  Requires-Dist: pillow<13,>=10
31
31
  Provides-Extra: measured
32
- Requires-Dist: pymupdf==1.28.0; extra == "measured"
32
+ Requires-Dist: pymupdf==1.28.2; extra == "measured"
33
33
  Requires-Dist: rapidocr==3.9.2; extra == "measured"
34
34
  Requires-Dist: onnxruntime==1.28.0; extra == "measured"
35
35
  Requires-Dist: numpy==2.4.6; extra == "measured"
@@ -254,7 +254,10 @@ one opinion agreeing with itself, and the header says so instead of counting it
254
254
 
255
255
  `engines_unavailable` is empty here. If an engine had failed to load, the run would still have
256
256
  produced this file, complete and confident, with fewer voters. That field and the console
257
- warning are the only places it would show.
257
+ warning are the only places it would show. Since 0.3.0 there is one floor under that: if fewer
258
+ than two OCR engines load, `build` refuses with exit 2 and writes nothing, and with `--no-strict`
259
+ it writes the file and exits 1 - a run with no second engine is the PDF's own text layer wearing this
260
+ tool's header.
258
261
 
259
262
  The four count fields **sum to `words`**, and the code asserts it. `unconfirmed` is also
260
263
  asserted to equal the number of entries in the file it names, so the sentence "listed in X" is
@@ -274,11 +277,20 @@ a page.
274
277
 
275
278
  ## Install
276
279
 
280
+ ```bash
281
+ pip install scanquorum # working tool
282
+ pip install scanquorum[measured] # exact pins used for every published number
283
+ scanquorum doctor # <- run this before anything else
284
+ scanquorum build samples/02-matter-of-gaglioti-14-IN-Dec-677.pdf
285
+ ```
286
+
287
+ From a checkout instead, if you want to hack on it:
288
+
277
289
  ```bash
278
290
  git clone https://github.com/igorsaevets/scanquorum
279
291
  cd scanquorum
280
292
  python -m pip install -r requirements.txt
281
- python -m scanquorum doctor # <- run this before anything else
293
+ python -m scanquorum doctor
282
294
  python -m scanquorum build samples/02-matter-of-gaglioti-14-IN-Dec-677.pdf
283
295
  ```
284
296
 
@@ -216,7 +216,10 @@ one opinion agreeing with itself, and the header says so instead of counting it
216
216
 
217
217
  `engines_unavailable` is empty here. If an engine had failed to load, the run would still have
218
218
  produced this file, complete and confident, with fewer voters. That field and the console
219
- warning are the only places it would show.
219
+ warning are the only places it would show. Since 0.3.0 there is one floor under that: if fewer
220
+ than two OCR engines load, `build` refuses with exit 2 and writes nothing, and with `--no-strict`
221
+ it writes the file and exits 1 - a run with no second engine is the PDF's own text layer wearing this
222
+ tool's header.
220
223
 
221
224
  The four count fields **sum to `words`**, and the code asserts it. `unconfirmed` is also
222
225
  asserted to equal the number of entries in the file it names, so the sentence "listed in X" is
@@ -236,11 +239,20 @@ a page.
236
239
 
237
240
  ## Install
238
241
 
242
+ ```bash
243
+ pip install scanquorum # working tool
244
+ pip install scanquorum[measured] # exact pins used for every published number
245
+ scanquorum doctor # <- run this before anything else
246
+ scanquorum build samples/02-matter-of-gaglioti-14-IN-Dec-677.pdf
247
+ ```
248
+
249
+ From a checkout instead, if you want to hack on it:
250
+
239
251
  ```bash
240
252
  git clone https://github.com/igorsaevets/scanquorum
241
253
  cd scanquorum
242
254
  python -m pip install -r requirements.txt
243
- python -m scanquorum doctor # <- run this before anything else
255
+ python -m scanquorum doctor
244
256
  python -m scanquorum build samples/02-matter-of-gaglioti-14-IN-Dec-677.pdf
245
257
  ```
246
258
 
@@ -64,7 +64,7 @@ dependencies = [
64
64
  # The exact set the README's numbers were measured with on 2026-08-06, Python 3.14.6, Windows 11.
65
65
  # Quote a figure from the README only from an environment installed this way.
66
66
  measured = [
67
- "pymupdf==1.28.0",
67
+ "pymupdf==1.28.2",
68
68
  "rapidocr==3.9.2",
69
69
  "onnxruntime==1.28.0",
70
70
  "numpy==2.4.6",
@@ -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.2"
6
+ __version__ = "0.3.0"
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,14 +33,14 @@ 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.2"
36
+ VERSION = "1.3"
37
37
 
38
38
  # When the PDF has no text layer at all (`pg.get_text("words") == []`), the
39
39
  # word-anchored voting path below has nothing to iterate: `owner` is empty,
40
40
  # every `for bi in order` loop does zero work, and the .md file comes back
41
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,
42
+ # a full page of boxes it has already read. Found on a private corpus of
43
+ # scanned exhibits on 2026-08-17: 5 of 5 pilot pure-scan documents emitted 0 rows,
44
44
  # and 3 of them still emitted 10-19 rows -- but only because a stamp had been
45
45
  # ADDED to the PDF layer by the packaging tool, so the "OCR output" was the
46
46
  # stamp read three times, not the document read once. See CHANGELOG.md 0.2.2.
@@ -61,6 +61,105 @@ PURE_SCAN_IOU_THR = 0.30
61
61
  # which one it was is written into the sidecar header.
62
62
  FRAME_PREFERENCE = ("rapidocr_en", "rapidocr_multi", "tesseract")
63
63
 
64
+ # 🔴 v0.3.0. THE PURE-SCAN FIX OF v0.2.2 WAS TESTED ON THE WRONG SHAPE OF PAGE.
65
+ # It fires only when `pg.get_text("words") == []`, i.e. when the page has NO text
66
+ # at all. The commonest scanned exhibit is not that page. It is a page with a
67
+ # stamp, an exhibit label or a Bates number in the PDF layer -- 5 to 20 words --
68
+ # and the entire body of the document as one image underneath.
69
+ #
70
+ # On such a page `words != []`, so the pure-scan path never runs; the word path
71
+ # runs instead and emits ONLY the label, because the label is the only thing it
72
+ # has anchors for. Every OCR engine has read the letter underneath and its boxes
73
+ # are discarded exactly as they were before v0.2.2. The bug survived its own fix.
74
+ #
75
+ # MEASURED on a private three-page scanned letter, 2026-08-17: pages 1-2 carry
76
+ # a 152-character exhibit header and
77
+ # a ~200 KB image of the letter. ScanQuorum v0.2.2 emitted 235 words, all of them
78
+ # the header repeated; `pure_scan_pages` was 0. Adobe Acrobat's OCR extracted
79
+ # 1830 + 2640 characters from the same two pages.
80
+ #
81
+ # The repair does not add a threshold, because a threshold would have to guess
82
+ # what "too few words" means. It uses the structure that is already computed:
83
+ # `layout.assign()` maps each PDF word to exactly one OCR line box, so a frame
84
+ # box that ends up owning NO word is, by construction, a line the OCR engines
85
+ # read and the PDF layer does not have. Those boxes -- and only those -- are put
86
+ # through the same line-level vote the pure-scan path uses.
87
+ #
88
+ # The one hazard is double emission: `assign()` gives a word to the nearest line
89
+ # box only, so where two OCR detections overlap, the loser owns nothing and would
90
+ # be emitted a second time as an "orphan". A box is therefore skipped when this
91
+ # much of its area is already covered by boxes that did own words.
92
+ ORPHAN_MIN_COVER = 0.50
93
+
94
+
95
+ class ScanQuorumInsufficientEngines(RuntimeError):
96
+ """Not enough independent OCR engines loaded to form a quorum.
97
+
98
+ 🔴 v0.3.0. This used to be a printed warning and nothing else: `build()`
99
+ carried on with whatever loaded, returned exit status 0 and a normal result
100
+ dict, and the caller had no programmatic way to tell an ensemble result from
101
+ a bare copy of the PDF's own text layer.
102
+
103
+ MEASURED, 2026-08-17: a caller passed a PATH where `engines=` was expected.
104
+ A string is iterable, so every character of the path was tried
105
+ as an engine name, each one failed to import, all failures were swallowed, and
106
+ the run completed with `pdf_layer` as the only voter -- 235 words, 0 agreed,
107
+ 235 unconfirmed, exit 0. The output was `page.get_text()` wearing a quorum
108
+ tool's header.
109
+
110
+ A tool whose entire claim is "it reports what it could not do" must not
111
+ degrade quietly to the thing it exists to replace. Pass `strict=False` to opt
112
+ back into the old behaviour deliberately.
113
+ """
114
+
115
+
116
+ class ScanQuorumUnknownEngine(ValueError):
117
+ """An engine NAME that has no adapter -- a typo, not a missing dependency.
118
+
119
+ A ValueError subclass so that callers catching ValueError keep working; its
120
+ own class so that `main()` can refuse it with exit 2 without also swallowing
121
+ every unrelated ValueError raised deep inside an OCR run.
122
+ """
123
+
124
+
125
+ # The four buckets every decided word falls into. Module level rather than local
126
+ # to `build()` because the emission loops must test membership with the SAME
127
+ # function that later counts them -- see `classify` below.
128
+ EXACT, SUBSTANCE, RULED, UNCONFIRMED = "exact", "substance", "ruled", "unconfirmed"
129
+
130
+
131
+ def classify(rule):
132
+ """Total by construction. An unrecognised rule raises rather than landing
133
+ in a bucket -- the previous version's failure was a rule quietly falling on
134
+ the flattering side of the line, so silence is the thing to forbid.
135
+
136
+ 🔴 v0.3.0 MOVED THIS OUT OF `build()`. It used to be a closure defined AFTER
137
+ the page loop, while the loop decided what to put in the unconfirmed index
138
+ with a hand-written copy of the same rule list. The two lists disagreed: this
139
+ function sends `EMPTY` and `VOTE1/n` to UNCONFIRMED, the loop's copy did not
140
+ append either of them. Any document that produced one would have run every
141
+ engine to completion and then died on the closing
142
+ `assert unconf_n == len(unconf)` -- after the expensive part, with a message
143
+ about an index rather than about the rule. One definition, used by both.
144
+ """
145
+ base = rule.split("|")[0]
146
+ if base.startswith("VOTE"):
147
+ try:
148
+ k = int(base[4:].split("/")[0]) # "VOTE3/4" -> 3
149
+ except ValueError:
150
+ raise SystemExit("unparseable VOTE rule %r -- refusing to count it" % rule)
151
+ return EXACT if k >= 2 else UNCONFIRMED # k == 1 is not a quorum
152
+ if base in ("SEP", "SEP=", "NUM"):
153
+ return SUBSTANCE
154
+ if base in ("LEX", "PATTERN"):
155
+ return RULED
156
+ if base in ("DISPUTED", "MEDOID_FLAG", "ONLY_ONE", "EMPTY"):
157
+ return UNCONFIRMED
158
+ raise SystemExit(
159
+ "UNKNOWN RULE %r in the evidence. Add it to classify() in build.py and decide "
160
+ "deliberately which bucket it belongs to. Refusing to guess -- guessing here is "
161
+ "how the header came to overstate by eleven points." % rule)
162
+
64
163
 
65
164
  def _sha256(p):
66
165
  h = hashlib.sha256()
@@ -70,26 +169,143 @@ def _sha256(p):
70
169
  return h.hexdigest()
71
170
 
72
171
 
172
+ def _available_engines():
173
+ """Adapter names that exist in this installation, for the error message.
174
+
175
+ A refusal that does not say what the legal values were is a refusal the
176
+ caller has to go read the source to act on."""
177
+ d = pathlib.Path(__file__).parent / "engines"
178
+ return sorted(p.stem for p in d.glob("*.py") if not p.stem.startswith("_"))
179
+
180
+
73
181
  def load_engines(names, pdf, dpi, progress):
74
- """Return {engine_name: {page: {"boxes": [{"t":text,"b":bbox,"s":conf}]}}}.
182
+ """Return (loaded, missing, unknown).
75
183
 
184
+ `loaded` maps engine_name -> {page: {"boxes": [{"t":text,"b":bbox,"s":conf}]}}.
76
185
  An engine that is not installed is reported and omitted. It is never faked and
77
- never silently replaced by another engine's output."""
78
- out, missing = {}, []
186
+ never silently replaced by another engine's output.
187
+
188
+ 🔴 v0.3.0. TWO FAILURES USED TO LOOK IDENTICAL HERE and both landed in
189
+ `missing`, where the caller could only print them:
190
+
191
+ * `tesseract` -- the adapter exists, the binary is not installed. That is a
192
+ MACHINE fact. Carrying on with the remaining voters is correct.
193
+ * `tesserct` -- there is no such adapter. That is a CALLER fact: a typo, or
194
+ a value of the wrong type. Carrying on is never correct, because the
195
+ caller believes it asked for an engine that is now silently absent.
196
+
197
+ They are separated so `build()` can refuse the second while tolerating the
198
+ first. `unknown` holds only the second kind.
199
+
200
+ The `isinstance` guard is the same defect one level up. `engines="tesseract"`
201
+ -- or, as actually measured, `engines=` receiving a filesystem path -- is a
202
+ perfectly good iterable of single characters, and every character became an
203
+ "engine that is not installed". Nine words of type check for a run that
204
+ otherwise completes, reports success, and means nothing.
205
+ """
206
+ if isinstance(names, (str, bytes)):
207
+ raise TypeError(
208
+ "engines= must be a sequence of engine NAMES, not a string. Got %r. "
209
+ "A string is iterable, so this would have been read one character at a "
210
+ "time and every character reported as a missing engine, leaving the run "
211
+ "with no OCR voter at all. Pass a tuple: engines=(%r,)"
212
+ % (names, names if isinstance(names, str) else names.decode("ascii", "replace")))
213
+ out, missing, unknown = {}, [], []
79
214
  for n in names:
80
215
  try:
81
216
  mod = __import__("scanquorum.engines." + n, fromlist=["run"])
82
217
  except ImportError as e:
83
- missing.append((n, "no adapter: %r" % e))
218
+ # Distinguish "no such adapter module" (caller's typo) from "the
219
+ # adapter is there but its own dependency is not" (machine fact).
220
+ # The adapter modules import rapidocr / PIL at module scope, so an
221
+ # ImportError naming something OTHER than the adapter itself is the
222
+ # second kind.
223
+ adapter = "scanquorum.engines." + n
224
+ if getattr(e, "name", None) in (adapter, n):
225
+ unknown.append((n, "no such engine adapter: %r" % e))
226
+ else:
227
+ missing.append((n, "adapter present, dependency missing: %r" % e))
84
228
  continue
85
229
  try:
86
230
  out[n] = mod.run(pdf, dpi=dpi, progress=progress)
87
231
  except Exception as e:
88
232
  missing.append((n, repr(e)[:120]))
89
- return out, missing
233
+ return out, missing, unknown
234
+
235
+
236
+ def _orphan_boxes(frame, owner):
237
+ """Frame boxes that own no PDF word and are not already covered by one that does.
90
238
 
239
+ 🔴 v0.3.0, and the whole of the MIXED-page repair. See the note at
240
+ ORPHAN_MIN_COVER. `layout.assign()` hands each word to the single nearest line
241
+ box, so "owns nothing" has two very different causes and only one of them is
242
+ interesting:
91
243
 
92
- def _emit_pure_scan_page(pi, frame, frame_engine, ocr, granularity, lex):
244
+ * the box sits over an IMAGE -- the PDF layer has no words there because the
245
+ text is pixels. This is the case worth emitting, and it is the one the
246
+ v0.2.2 fix missed on every page that also had a stamp or a header.
247
+ * the box OVERLAPS a box that won the words. `layout.assign` was written
248
+ precisely because overlapping detections used to emit the same word once
249
+ per covering line ('On On On November November November', one document
250
+ inflated 1.29x). Emitting the loser as an orphan would reintroduce that
251
+ bug through the back door, so it is filtered here by area coverage.
252
+
253
+ Returns the indices into `frame`, in the original order.
254
+ """
255
+ owned = [frame[i]["b"] for i in owner if owner.get(i)]
256
+ out = []
257
+ for bi, fb in enumerate(frame):
258
+ if owner.get(bi):
259
+ continue
260
+ if _union_cover(fb["b"], owned) < ORPHAN_MIN_COVER:
261
+ out.append(bi)
262
+ return out
263
+
264
+
265
+ def _union_cover(box, others):
266
+ """Fraction of `box` covered by the UNION of `others`.
267
+
268
+ 🔴 THE FIRST VERSION OF THIS TOOK THE MAXIMUM OVER ONE BOX AT A TIME, and an
269
+ outside reviewer refuted it on the same day it was written. Two owned boxes
270
+ covering 30 % and 40 % of DIFFERENT parts of an orphan leave 70 % of it
271
+ accounted for, while `max` sees 0.40, reads that as "mostly uncovered" and
272
+ emits the orphan anyway -- reintroducing the exact double-emission this
273
+ filter exists to prevent. A weaker check in the place whose whole job is to
274
+ be the check.
275
+
276
+ Exact, not approximate, by coordinate compression: the union's area is the
277
+ sum of the elementary cells of the grid formed by every rectangle edge, kept
278
+ when the cell falls inside at least one rectangle. Line boxes on a page
279
+ number in the hundreds and the clipped list here is normally two or three,
280
+ so the O(n^3) worst case never arrives; and an exact answer removes a
281
+ tuning parameter rather than adding one.
282
+ """
283
+ x0, y0, x1, y1 = box
284
+ area = (x1 - x0) * (y1 - y0)
285
+ if area <= 0:
286
+ return 1.0 # a degenerate box is never worth emitting
287
+ clipped = []
288
+ for ob in others:
289
+ cx0, cy0 = max(x0, ob[0]), max(y0, ob[1])
290
+ cx1, cy1 = min(x1, ob[2]), min(y1, ob[3])
291
+ if cx1 > cx0 and cy1 > cy0:
292
+ clipped.append((cx0, cy0, cx1, cy1))
293
+ if not clipped:
294
+ return 0.0
295
+ xs = sorted({c for r in clipped for c in (r[0], r[2])})
296
+ ys = sorted({c for r in clipped for c in (r[1], r[3])})
297
+ covered = 0.0
298
+ for i in range(len(xs) - 1):
299
+ for j in range(len(ys) - 1):
300
+ cx, cy = (xs[i] + xs[i + 1]) / 2.0, (ys[j] + ys[j + 1]) / 2.0
301
+ for r in clipped:
302
+ if r[0] <= cx <= r[2] and r[1] <= cy <= r[3]:
303
+ covered += (xs[i + 1] - xs[i]) * (ys[j + 1] - ys[j])
304
+ break
305
+ return covered / area
306
+
307
+
308
+ def _emit_pure_scan_page(pi, frame, frame_engine, ocr, granularity, lex, colf=None):
93
309
  """Line-level records for a page whose PDF has no text layer.
94
310
 
95
311
  The word-anchored path in `build()` iterates over `pg.get_text("words")`. On a
@@ -152,7 +368,8 @@ def _emit_pure_scan_page(pi, frame, frame_engine, ocr, granularity, lex):
152
368
  # OCR only. `classify()` splits on "|" and reads the base, so bucket
153
369
  # accounting is unaffected.
154
370
  rule = rule + "|NO_LAYER"
155
- rec = {"page": pi, "bbox": [round(x, 1) for x in fb_box], "col": 0,
371
+ rec = {"page": pi, "bbox": [round(x, 1) for x in fb_box],
372
+ "col": 0 if colf is None else colf(fb_box),
156
373
  "y": fb_box[1], "x": fb_box[0], "chosen": chosen,
157
374
  "rule": rule, "who": who}
158
375
  rec.update(cands)
@@ -162,7 +379,20 @@ def _emit_pure_scan_page(pi, frame, frame_engine, ocr, granularity, lex):
162
379
 
163
380
 
164
381
  def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
165
- dpi=300, out_dir=None, lexicon=None, heartbeat=900):
382
+ dpi=300, out_dir=None, lexicon=None, heartbeat=900,
383
+ strict=True, orphan_lines=True):
384
+ """Run the pipeline over one PDF.
385
+
386
+ strict -- refuse to produce output that cannot be called a quorum:
387
+ an unknown engine name, or fewer than two OCR engines
388
+ loaded, raises instead of printing a warning. See
389
+ `ScanQuorumInsufficientEngines`. Pass False to opt back
390
+ into the pre-0.3.0 behaviour deliberately.
391
+ orphan_lines -- emit OCR lines that the PDF's own text layer does not
392
+ cover (a stamped scan: header in the layer, letter in an
393
+ image). See `_orphan_boxes`. Pass False for the exact
394
+ v0.2.2 emission.
395
+ """
166
396
  import pymupdf
167
397
  pdf = pathlib.Path(pdf)
168
398
  out_dir = pathlib.Path(out_dir or pdf.parent)
@@ -195,7 +425,18 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
195
425
  print(" existing text layer produced by: %s / %s"
196
426
  % (meta.get("producer") or "-", meta.get("creator") or "-"))
197
427
 
198
- ocr, missing = load_engines(engines, pdf, dpi, progress)
428
+ ocr, missing, unknown = load_engines(engines, pdf, dpi, progress)
429
+ # 🔴 v0.3.0. An engine name that does not exist is the caller's error, and it
430
+ # is fatal in strict mode even if other engines loaded: the caller asked for
431
+ # a specific set of voters and is about to be handed a different one without
432
+ # being told in any way a program can read.
433
+ for n, why in unknown:
434
+ print(" 🔴 NO SUCH ENGINE: %-16s %s" % (n, why))
435
+ if unknown and strict:
436
+ raise ScanQuorumUnknownEngine(
437
+ "unknown engine name(s): %s. Available adapters: %s. "
438
+ "Nothing was written. Pass strict=False to run with the rest anyway."
439
+ % (", ".join(n for n, _ in unknown), ", ".join(_available_engines())))
199
440
  # Each adapter declares whether it returns line boxes or word boxes.
200
441
  # Defaulting to "line" is the safe side: a word engine mistaken for a line
201
442
  # engine still aligns correctly, the reverse silently mutes the voter.
@@ -225,6 +466,19 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
225
466
  if len(ocr) < 2:
226
467
  print(" ⚠ fewer than two OCR engines besides the PDF's own text layer.")
227
468
  print(" There is no quorum here at all -- treat every word as unconfirmed.")
469
+ # 🔴 v0.3.0. Until now this printed and carried on. See the docstring of
470
+ # ScanQuorumInsufficientEngines for the run that made it a defect rather
471
+ # than a nicety: exit 0, a normal result dict, and `page.get_text()`
472
+ # dressed as an ensemble result. A warning nobody is reading is not a
473
+ # report, and this tool's whole claim is that it reports.
474
+ if strict:
475
+ raise ScanQuorumInsufficientEngines(
476
+ "%d OCR engine(s) loaded (%s); at least 2 are needed for any quorum. "
477
+ "Requested: %s. Unavailable: %s. Nothing was written -- a run with no "
478
+ "quorum would be the PDF's own text layer wearing this tool's header. "
479
+ "Pass strict=False if you deliberately want that."
480
+ % (len(ocr), ", ".join(sorted(ocr)) or "none",
481
+ ", ".join(engines), "; ".join("%s (%s)" % (n, w) for n, w in missing) or "none"))
228
482
  elif independent < 3:
229
483
  print(" ⚠ only %d INDEPENDENT OCR opinions." % independent)
230
484
  for group in CORRELATED:
@@ -244,6 +498,18 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
244
498
  # the word-anchored path would have produced. On the corpus this bug was
245
499
  # found on, this number equals doc.page_count for every failing document.
246
500
  pure_scan_pages = 0
501
+ # 🔴 v0.3.0. Pages no engine saw at all used to be counted into
502
+ # `frames_used` under the key None -- see the guard at the frame selection
503
+ # below. Counted separately, where it is a fact about the document rather
504
+ # than a corrupt entry in a metadata dict.
505
+ pages_without_ocr = 0
506
+ # v0.3.0. Lines emitted by the MIXED-page repair (see ORPHAN_MIN_COVER), and
507
+ # how many pages produced any. Both go in the header: on a page with a stamp
508
+ # over a scanned letter these are the body of the document, and a reader who
509
+ # sees `orphan_lines: 0` on a document they know is scanned has learnt that
510
+ # the repair did not fire and the .md is the stamp only.
511
+ orphan_line_rows = 0
512
+ orphan_line_pages = 0
247
513
 
248
514
  for pi in range(doc.page_count):
249
515
  pg = doc[pi]
@@ -265,7 +531,21 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
265
531
  if b:
266
532
  frame, frame_engine = b, n
267
533
  break
268
- frames_used[frame_engine] = frames_used.get(frame_engine, 0) + 1
534
+ # 🔴 v0.3.0 CRASH, FOUND BY READING RATHER THAN BY A FAILING RUN, and it
535
+ # only fires on documents with a blank page. `frame_engine` is None when
536
+ # no engine produced a box for this page -- a blank verso, a full-page
537
+ # photograph, a separator sheet. The old line counted that None as a
538
+ # frame engine, so `frames_used` grew a None key; then, at the end of the
539
+ # run, the header does
540
+ # max(sorted(frames_used.items()), key=...)
541
+ # and `sorted` compares None with 'rapidocr_en' -> TypeError. The run dies
542
+ # AFTER every engine has finished, in the metadata, over a field that
543
+ # merely records what happened. Blank pages are ordinary in scanned
544
+ # exhibits, which is exactly the corpus 0.2.2 was written for.
545
+ if frame is None:
546
+ pages_without_ocr += 1
547
+ else:
548
+ frames_used[frame_engine] = frames_used.get(frame_engine, 0) + 1
269
549
  if frame is None:
270
550
  # No OCR saw this page. Keep the existing layer, mark it unconfirmed.
271
551
  for w in words:
@@ -290,8 +570,12 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
290
570
  pure_scan_pages += 1
291
571
  page_rows, page_stats = _emit_pure_scan_page(
292
572
  pi, frame, frame_engine, ocr, granularity, lex)
573
+ # v0.3.0: `classify` decides, not a second hand-written copy of its
574
+ # rule list. See the note on `classify` -- the two copies disagreed
575
+ # about EMPTY and about VOTE1/n, and the disagreement surfaced as a
576
+ # failed assert at the end of the run rather than here.
293
577
  for rec in page_rows:
294
- if rec["rule"].startswith(("DISPUTED", "ONLY_ONE")) or rec["rule"].startswith("MEDOID_FLAG"):
578
+ if classify(rec["rule"]) == UNCONFIRMED:
295
579
  unconf.append(rec)
296
580
  ev.extend(page_rows)
297
581
  stats.update(page_stats)
@@ -360,13 +644,35 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
360
644
  # ONLY_ONE word (~340 per document: running heads, margins, gutters
361
645
  # that layout analysis discards). A machine-readable warning that is
362
646
  # false is worse than no warning, because it is believed.
363
- if rule in ("DISPUTED", "MEDOID_FLAG") or rule.startswith("ONLY_ONE"):
647
+ if classify(rule) == UNCONFIRMED:
364
648
  if chosen is None:
365
649
  rec["chosen"] = vote.collapse(w[4])
366
650
  unconf.append(rec)
367
651
  rows.append(rec)
368
652
  stats[rule] += 1
369
653
 
654
+ # 🔴 v0.3.0. THE MIXED PAGE -- see the long note at ORPHAN_MIN_COVER.
655
+ # Everything above this point can only emit text the PDF layer already
656
+ # had, because every emission is anchored to a word in `words`. On a
657
+ # stamped scan that is the stamp and nothing else, while `frame` holds
658
+ # the OCR's reading of the whole letter. Those frame boxes that own no
659
+ # word are that letter. They are voted line-to-line by the same cascade
660
+ # the pure-scan path uses, and tagged |NO_LAYER for the same reason.
661
+ if orphan_lines:
662
+ orphans = _orphan_boxes(frame, owner)
663
+ if orphans:
664
+ orphan_rows, orphan_stats = _emit_pure_scan_page(
665
+ pi, [frame[bi] for bi in orphans], frame_engine, ocr,
666
+ granularity, lex, colf=colf)
667
+ for rec in orphan_rows:
668
+ if classify(rec["rule"]) == UNCONFIRMED:
669
+ unconf.append(rec)
670
+ rows.extend(orphan_rows)
671
+ stats.update(orphan_stats)
672
+ if orphan_rows:
673
+ orphan_line_rows += len(orphan_rows)
674
+ orphan_line_pages += 1
675
+
370
676
  for wi, w in enumerate(words):
371
677
  if wi in used_w:
372
678
  continue
@@ -415,30 +721,9 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
415
721
  # means the engines agreed on the digits and disagreed on the punctuation, and
416
722
  # a punctuation disagreement in a case citation is `12-869` against `12369`.
417
723
  # Folding that into "read identically" is precisely the claim we cannot make.
418
- EXACT, SUBSTANCE, RULED, UNCONFIRMED = "exact", "substance", "ruled", "unconfirmed"
419
-
420
- def classify(rule):
421
- """Total by construction. An unrecognised rule raises rather than landing
422
- in a bucket -- the previous version's failure was a rule quietly falling on
423
- the flattering side of the line, so silence is the thing to forbid."""
424
- base = rule.split("|")[0]
425
- if base.startswith("VOTE"):
426
- try:
427
- k = int(base[4:].split("/")[0]) # "VOTE3/4" -> 3
428
- except ValueError:
429
- raise SystemExit("unparseable VOTE rule %r -- refusing to count it" % rule)
430
- return EXACT if k >= 2 else UNCONFIRMED # k == 1 is not a quorum
431
- if base in ("SEP", "SEP=", "NUM"):
432
- return SUBSTANCE
433
- if base in ("LEX", "PATTERN"):
434
- return RULED
435
- if base in ("DISPUTED", "MEDOID_FLAG", "ONLY_ONE", "EMPTY"):
436
- return UNCONFIRMED
437
- raise SystemExit(
438
- "UNKNOWN RULE %r in the evidence. Add it to classify() in build.py and decide "
439
- "deliberately which bucket it belongs to. Refusing to guess -- guessing here is "
440
- "how the header came to overstate by eleven points." % rule)
441
-
724
+ # `classify` and the four bucket names now live at module level -- see the
725
+ # note on that function. They were defined HERE, after the loop that had to
726
+ # agree with them, and the two definitions of "unconfirmed" drifted apart.
442
727
  counts = {EXACT: 0, SUBSTANCE: 0, RULED: 0, UNCONFIRMED: 0}
443
728
  weak = 0
444
729
  for r in ev:
@@ -470,6 +755,13 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
470
755
  "pages": doc.page_count,
471
756
  "engines": used,
472
757
  "engines_unavailable": [n for n, _ in missing],
758
+ # 🔴 v0.3.0, from the round-43 review. Under `strict=False` an unknown
759
+ # engine NAME was printed and then dropped: it appeared in no header
760
+ # field, so a machine reading the sidecar could not see that the caller
761
+ # asked for a voter that never existed. A typo is exactly the thing a
762
+ # downstream reader needs to know about, and the terminal is not where
763
+ # it will look.
764
+ "engines_unknown_name": [n for n, _ in unknown],
473
765
  # 🔴 THE SAME BUG CLASS, INSIDE THE FIX FOR THE SAME BUG CLASS, ONE COMMIT
474
766
  # LATER. `max(frames_used, key=frames_used.get)` returns whichever key the
475
767
  # dict yielded first when two engines framed an equal number of pages.
@@ -485,6 +777,17 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
485
777
  # have to grep evidence.json to find out how many pages fell into the
486
778
  # coarser path -- the field naming that count is the honest place.
487
779
  "pure_scan_pages": pure_scan_pages,
780
+ # New in v0.3.0. Pages on which the PDF's own text layer covered only
781
+ # part of what the engines read -- a stamp or an exhibit header over a
782
+ # scanned body -- and the rows recovered from the uncovered part. Zero
783
+ # on a document you know is scanned means the repair did not fire and
784
+ # what follows is the stamp, not the letter.
785
+ "mixed_pages_with_recovered_lines": orphan_line_pages,
786
+ "recovered_lines_not_in_pdf_layer": orphan_line_rows,
787
+ # Pages no engine produced a single box for. Blank versos and separator
788
+ # sheets are ordinary; a high count on a document that is not mostly
789
+ # blank means the engines failed, not that the paper was empty.
790
+ "pages_without_ocr": pages_without_ocr,
488
791
  "words": len(ev),
489
792
  # These four sum to `words`. The assert above enforces it, and they are
490
793
  # reported separately because they are NOT the same strength of evidence.
@@ -497,9 +800,39 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
497
800
  "existing_layer_producer": meta.get("producer") or "",
498
801
  "generated_by": "scanquorum %s (build.py v%s)" % (__version__, VERSION),
499
802
  }
803
+ # 🔴🔴 v0.3.0. THIS SENTENCE SAID "INDEPENDENT" AND THE NUMBER IN FRONT OF IT
804
+ # DID NOT MEAN THAT. Found by an outside reviewer, and it is the sharpest
805
+ # finding of the round because it is this project's own signature defect --
806
+ # a claim that is greener than the evidence, in the machine-readable header,
807
+ # in the field a downstream model trusts most.
808
+ #
809
+ # `exact` counts every row two OCR engines agreed on. On the commonest
810
+ # install -- no Tesseract, the two RapidOCR configurations present -- those
811
+ # two SHARE A TEXT DETECTOR, so a large part of `exact` is one opinion
812
+ # agreeing with itself. The number was already computed, as
813
+ # `agreed_exactly_from_correlated_voters_only`, and sat in a header field
814
+ # while the prose two lines below made the stronger claim.
815
+ #
816
+ # MEASURED on the private letter of the MIXED-page note at the top of this
817
+ # file, across the v0.3.0 change: that field went 4 -> 31 while
818
+ # `agreed_exactly` went 188 -> 245. So 27 of the 57 newly "confirmed" rows,
819
+ # very nearly half, are the correlated pair confirming itself.
820
+ #
821
+ # The sentence now carries the qualification inline. A caveat in a separate
822
+ # field is a caveat nobody reads.
823
+ weak_clause = ""
824
+ if weak:
825
+ weak_clause = (
826
+ " OF THOSE %d, HOWEVER, %d WERE CARRIED ONLY BY ENGINES THAT SHARE A TEXT "
827
+ "DETECTOR (%s) -- for those rows the two readings are closer to one opinion "
828
+ "agreeing with itself than to two, and the word 'independent' above does not "
829
+ "apply to them. Install a voter that draws its own boxes (Tesseract) to make "
830
+ "this number meaningful."
831
+ % (exact, weak, " and ".join(sorted(
832
+ set().union(*[g & set(ocr) for g in CORRELATED]) or {"-"}))))
500
833
  warn = (
501
834
  "Of the %d words in this file, %d were read IDENTICALLY by at least two independent "
502
- "OCR engines. A further %d were read with the same digits but different punctuation "
835
+ "OCR engines.%s A further %d were read with the same digits but different punctuation "
503
836
  "(the engines saw the same number and disagreed about a hyphen or a space); for a "
504
837
  "case or docket citation that difference can be the difference between two documents. "
505
838
  "Another %d were chosen by dictionary or by pattern with NO second engine agreeing. "
@@ -508,11 +841,31 @@ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
508
841
  "passage, check it against that index; if a word from it appears in what you are "
509
842
  "about to quote, say that the word is unverified rather than presenting it as the "
510
843
  "text of the document. No language model wrote or corrected any character in this file."
511
- % (len(ev), exact, substance, ruled, unconf_n, stem + ".unconfirmed.json")
844
+ # weak_clause is a %s ARGUMENT, not a concatenation: it is already
845
+ # formatted, and splicing it into the format string would make any '%'
846
+ # inside it a format spec on the next line someone edits.
847
+ % (len(ev), exact, weak_clause, substance, ruled, unconf_n,
848
+ stem + ".unconfirmed.json")
512
849
  )
513
850
  if len(used) < 3:
514
851
  warn = ("THIS RUN HAD ONLY %d ENGINES. Nothing here is confirmed by a quorum. "
515
852
  "Treat the whole file as unverified. " % len(used)) + warn
853
+ if orphan_line_pages:
854
+ # 🔴 The second half of this sentence exists because an outside reviewer
855
+ # pointed out that the recovered rows are LINES and they are counted in
856
+ # a field called `words`. Every ratio a reader computes from this header
857
+ # is therefore a mixture of word-level and line-level records, and no
858
+ # field name says so. Saying it here is cheaper than renaming a field
859
+ # that downstream code already reads.
860
+ warn = ("NOTE: on %d page(s) the PDF's own text layer covered only part of what "
861
+ "the OCR engines read -- typically a stamp or an exhibit header sitting "
862
+ "over a scanned body. %d line(s) of the uncovered part were recovered and "
863
+ "are tagged `|NO_LAYER`; before v0.3.0 they were discarded and the body "
864
+ "text of such a page did not appear here at all. THOSE %d RECORDS ARE "
865
+ "WHOLE LINES, NOT WORDS, and they are counted in `words` and in "
866
+ "`agreed_exactly` alongside word-level records -- so any rate you compute "
867
+ "from this header mixes the two. "
868
+ % (orphan_line_pages, orphan_line_rows, orphan_line_rows)) + warn
516
869
  if pure_scan_pages:
517
870
  warn = ("NOTE: %d of %d pages had NO existing text layer. On those pages the "
518
871
  "pipeline emitted LINE-level records from OCR only, without the PDF's "
@@ -584,10 +937,36 @@ def main(argv=None):
584
937
  ap.add_argument("--lexicon", help="JSON word->count, built from the document's own text")
585
938
  ap.add_argument("--heartbeat", type=int, default=900,
586
939
  help="seconds between progress files (default 900 = 15 min)")
940
+ ap.add_argument("--no-strict", dest="strict", action="store_false",
941
+ help="produce output even when fewer than two OCR engines loaded "
942
+ "or an engine name is unknown. The result is then NOT a quorum "
943
+ "and the header says so; off by default since v0.3.0.")
944
+ ap.add_argument("--no-orphan-lines", dest="orphan_lines", action="store_false",
945
+ help="do not recover OCR lines the PDF's text layer does not cover "
946
+ "(exact v0.2.2 emission). See ORPHAN_MIN_COVER in build.py.")
587
947
  a = ap.parse_args(argv)
588
948
  lex = json.loads(pathlib.Path(a.lexicon).read_text(encoding="utf-8")) if a.lexicon else {}
589
- build(a.pdf, engines=tuple(x for x in a.engines.split(",") if x), dpi=a.dpi,
590
- out_dir=a.out_dir, lexicon=lex, heartbeat=a.heartbeat)
949
+ # A refusal is "cannot run": exit 2, the code `doctor` uses for that state,
950
+ # and a message instead of a traceback. Left uncaught it exited 1 -- the code
951
+ # for "the file was written but the quorum is degraded" -- so a pipeline
952
+ # reading the exit code would go looking for an output that was never made.
953
+ try:
954
+ hdr = build(a.pdf, engines=tuple(x for x in a.engines.split(",") if x), dpi=a.dpi,
955
+ out_dir=a.out_dir, lexicon=lex, heartbeat=a.heartbeat,
956
+ strict=a.strict, orphan_lines=a.orphan_lines)
957
+ except (ScanQuorumInsufficientEngines, ScanQuorumUnknownEngine) as e:
958
+ print("\n exit 2: refused, nothing was written.\n %s" % e, file=sys.stderr)
959
+ return 2
960
+ # 🔴 v0.3.0, from the same review that refuted the coverage metric. With
961
+ # `--no-strict` the run completes, and until now it also exited 0 -- so a
962
+ # pipeline that checks only the exit code could not tell a full quorum from
963
+ # a single voter, which is the one distinction this tool exists to make.
964
+ # `doctor` already uses exactly this convention: 0 = full quorum, 1 = runs
965
+ # but degraded. `build` now matches it instead of inventing a second one.
966
+ if len(hdr["engines"]) < 3: # engines[] includes "pdf_layer"
967
+ print("\n exit 1: fewer than two OCR engines voted. The file was written and "
968
+ "its header says so, but nothing in it is confirmed by a quorum.")
969
+ return 1
591
970
  return 0
592
971
 
593
972
 
@@ -79,12 +79,21 @@ def _parse_choice(text, n_candidates):
79
79
  because the model does not get a vote on whether it obeys."""
80
80
  if not text or not text.strip():
81
81
  return None # a blank reply used to crash this
82
- head = text.strip().splitlines()[0][:80]
82
+ # 🔴 v0.3.0. THE 80-CHARACTER TRUNCATION WAS INSIDE THE SAFETY CHECK.
83
+ # `head` used to be `...splitlines()[0][:80]` and the regex below is anchored
84
+ # to the END of it, so the cut could MANUFACTURE a match that the real reply
85
+ # does not have: a reply of 'CHOICE: 12' followed by 70 characters of
86
+ # anything truncates to 'CHOICE: 12' + padding and, if that padding is
87
+ # whitespace, satisfies `\s*$`. Truncating input before an end-anchored
88
+ # pattern can only ever turn a non-match into a match, which is the wrong
89
+ # direction for the one function in this file whose job is to refuse.
90
+ # The whole line is matched now; the truncation survives only for logging.
91
+ line = text.strip().splitlines()[0]
83
92
  # The number must be the WHOLE value, not the start of one. Without the
84
93
  # trailing guard, 'CHOICE: 12-855' -- a model putting the TEXT where the
85
94
  # index goes -- parses as index 12, and with twelve or more candidates that
86
95
  # silently selects one. The range check hid this while the lists were short.
87
- m = re.match(r"\s*CHOICE\s*:?\s*(\d{1,3})\s*[.)]?\s*$", head, re.I)
96
+ m = re.fullmatch(r"\s*CHOICE\s*:?\s*(\d{1,3})\s*[.)]?\s*", line, re.I)
88
97
  if m:
89
98
  i = int(m.group(1))
90
99
  return i if 1 <= i <= n_candidates else None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scanquorum
3
- Version: 0.2.2
3
+ Version: 0.3.0
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
@@ -29,7 +29,7 @@ Requires-Dist: onnxruntime<2,>=1.17
29
29
  Requires-Dist: numpy<3,>=1.24
30
30
  Requires-Dist: pillow<13,>=10
31
31
  Provides-Extra: measured
32
- Requires-Dist: pymupdf==1.28.0; extra == "measured"
32
+ Requires-Dist: pymupdf==1.28.2; extra == "measured"
33
33
  Requires-Dist: rapidocr==3.9.2; extra == "measured"
34
34
  Requires-Dist: onnxruntime==1.28.0; extra == "measured"
35
35
  Requires-Dist: numpy==2.4.6; extra == "measured"
@@ -254,7 +254,10 @@ one opinion agreeing with itself, and the header says so instead of counting it
254
254
 
255
255
  `engines_unavailable` is empty here. If an engine had failed to load, the run would still have
256
256
  produced this file, complete and confident, with fewer voters. That field and the console
257
- warning are the only places it would show.
257
+ warning are the only places it would show. Since 0.3.0 there is one floor under that: if fewer
258
+ than two OCR engines load, `build` refuses with exit 2 and writes nothing, and with `--no-strict`
259
+ it writes the file and exits 1 - a run with no second engine is the PDF's own text layer wearing this
260
+ tool's header.
258
261
 
259
262
  The four count fields **sum to `words`**, and the code asserts it. `unconfirmed` is also
260
263
  asserted to equal the number of entries in the file it names, so the sentence "listed in X" is
@@ -274,11 +277,20 @@ a page.
274
277
 
275
278
  ## Install
276
279
 
280
+ ```bash
281
+ pip install scanquorum # working tool
282
+ pip install scanquorum[measured] # exact pins used for every published number
283
+ scanquorum doctor # <- run this before anything else
284
+ scanquorum build samples/02-matter-of-gaglioti-14-IN-Dec-677.pdf
285
+ ```
286
+
287
+ From a checkout instead, if you want to hack on it:
288
+
277
289
  ```bash
278
290
  git clone https://github.com/igorsaevets/scanquorum
279
291
  cd scanquorum
280
292
  python -m pip install -r requirements.txt
281
- python -m scanquorum doctor # <- run this before anything else
293
+ python -m scanquorum doctor
282
294
  python -m scanquorum build samples/02-matter-of-gaglioti-14-IN-Dec-677.pdf
283
295
  ```
284
296
 
@@ -23,4 +23,5 @@ tests/test_goldset.py
23
23
  tests/test_purescan.py
24
24
  tests/test_riskcov.py
25
25
  tests/test_safety.py
26
+ tests/test_strict_and_mixed.py
26
27
  tests/test_vote_parity.py
@@ -5,7 +5,7 @@ numpy<3,>=1.24
5
5
  pillow<13,>=10
6
6
 
7
7
  [measured]
8
- pymupdf==1.28.0
8
+ pymupdf==1.28.2
9
9
  rapidocr==3.9.2
10
10
  onnxruntime==1.28.0
11
11
  numpy==2.4.6
@@ -4,8 +4,8 @@
4
4
  # layer, the pipeline in build.py used to iterate the voting loop over
5
5
  # `pg.get_text("words") == []` and emit an .md with a valid YAML header and an
6
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,
7
+ # in the header said the emission was empty. Found on a private corpus of
8
+ # scanned exhibits on 2026-08-17: five of five SCAN documents in the pilot were affected,
9
9
  # three of them still emitted 10-19 rows -- but only because a stamp had been
10
10
  # added to the PDF layer by the packaging tool, so the "OCR output" was the
11
11
  # stamp read three times, not the document read once.
@@ -0,0 +1,317 @@
1
+ # tests/test_strict_and_mixed.py v1.0
2
+ #
3
+ # THE THREE FAILURES THIS FILE EXISTS TO PREVENT. All three were found on
4
+ # 2026-08-18, on a private corpus of scanned exhibits and by reading the code that
5
+ # had just been written for the previous one.
6
+ #
7
+ # 1. SILENT FALLBACK. `build(pdf, "some/path")` -- a caller passing a path where
8
+ # `engines=` was expected -- ran to completion, exit 0, and returned a normal
9
+ # result dict. A string is iterable, so every CHARACTER of the path was tried
10
+ # as an engine name, every import failed, every failure was swallowed, and the
11
+ # run finished with `pdf_layer` as its only voter: 235 words, 0 agreed, 235
12
+ # unconfirmed. The output was `page.get_text()` wearing a quorum tool's header.
13
+ # A warning was printed. Nothing else marked it.
14
+ #
15
+ # 2. THE MIXED PAGE -- the pure-scan fix of 0.2.2 missing the commonest shape of
16
+ # scanned exhibit. That fix fires only when the page has NO text at all. A
17
+ # scanned letter with an exhibit stamp has 5-20 words in the PDF layer and the
18
+ # whole letter as an image, so `words != []`, the fix never runs, and the .md
19
+ # contains the stamp and nothing else. MEASURED on a private three-page
20
+ # scanned letter: 235 words emitted, all of them the header repeated,
21
+ # `pure_scan_pages: 0`, while Adobe Acrobat read 4470 characters of letter off
22
+ # the same two pages.
23
+ #
24
+ # 3. THE BLANK-PAGE CRASH. `frames_used[None] += 1` on a page no engine saw,
25
+ # then `max(sorted(frames_used.items()), ...)` in the header ->
26
+ # `TypeError: '<' not supported between 'NoneType' and 'str'`. It fires only
27
+ # when a document has BOTH a blank page and a non-blank one, which is every
28
+ # scanned exhibit with a blank verso, and it fires AFTER all the OCR has been
29
+ # paid for, in a metadata field.
30
+ #
31
+ # The first two tests below need no OCR engine and no network: they assert that
32
+ # `build()` REFUSES, and the refusal happens before any engine runs. They belong
33
+ # in every CI job. The rest skip without rapidocr.
34
+ import io
35
+ import sys
36
+ import unittest
37
+ import pathlib
38
+ import tempfile
39
+
40
+ ROOT = pathlib.Path(__file__).resolve().parent.parent
41
+ sys.path.insert(0, str(ROOT))
42
+
43
+
44
+ def _font(size):
45
+ from PIL import ImageFont
46
+ for candidate in ("arial.ttf", "DejaVuSans.ttf", "LiberationSans-Regular.ttf"):
47
+ try:
48
+ return ImageFont.truetype(candidate, size)
49
+ except Exception:
50
+ continue
51
+ return ImageFont.load_default()
52
+
53
+
54
+ def _make_stamped_scan_pdf(header, body_lines, out_path):
55
+ """A page shaped like a real scanned exhibit.
56
+
57
+ The header is REAL TEXT in the PDF layer -- an exhibit stamp added by a
58
+ packaging tool. The body is an IMAGE of a letter, with no text layer at all.
59
+ So `pg.get_text("words")` returns the handful of stamp words and nothing
60
+ else, which is precisely the shape that defeats the `words == []` test.
61
+ """
62
+ from PIL import Image, ImageDraw
63
+ import pymupdf
64
+ W, H = 1400, 1000
65
+ img = Image.new("RGB", (W, H), "white")
66
+ d = ImageDraw.Draw(img)
67
+ f = _font(56)
68
+ y = 120
69
+ for line in body_lines:
70
+ d.text((90, y), line, fill="black", font=f)
71
+ y += 110
72
+ buf = io.BytesIO()
73
+ img.save(buf, format="PNG")
74
+
75
+ doc = pymupdf.open()
76
+ page = doc.new_page(width=W * 72 / 150, height=H * 72 / 150)
77
+ # image occupies everything below the stamp line
78
+ rect = pymupdf.Rect(0, 40, page.rect.width, page.rect.height)
79
+ page.insert_image(rect, stream=buf.getvalue())
80
+ # the stamp goes in as genuine text, on top
81
+ page.insert_text((20, 24), header, fontsize=9, fontname="helv")
82
+ doc.save(str(out_path))
83
+ doc.close()
84
+
85
+
86
+ def _make_blank_plus_text_pdf(out_path):
87
+ """Two pages: one genuinely blank, one with a rasterised line.
88
+
89
+ A blank verso is ordinary in scanned exhibits and it is what makes the
90
+ frame-engine metadata crash reachable."""
91
+ from PIL import Image, ImageDraw
92
+ import pymupdf
93
+ doc = pymupdf.open()
94
+ doc.new_page(width=612, height=792) # page 1: entirely blank
95
+ W, H = 1200, 400
96
+ img = Image.new("RGB", (W, H), "white")
97
+ ImageDraw.Draw(img).text((80, 140), "SECOND PAGE HAS WORDS", fill="black", font=_font(58))
98
+ buf = io.BytesIO()
99
+ img.save(buf, format="PNG")
100
+ p2 = doc.new_page(width=W * 72 / 150, height=H * 72 / 150)
101
+ p2.insert_image(p2.rect, stream=buf.getvalue())
102
+ doc.save(str(out_path))
103
+ doc.close()
104
+
105
+
106
+ class RefusesWithoutQuorum(unittest.TestCase):
107
+ """No OCR engine needed: every assertion here is that build() stops early."""
108
+
109
+ def _tiny_pdf(self, td):
110
+ import pymupdf
111
+ p = pathlib.Path(td) / "tiny.pdf"
112
+ doc = pymupdf.open()
113
+ page = doc.new_page()
114
+ page.insert_text((72, 72), "hello", fontsize=12, fontname="helv")
115
+ doc.save(str(p))
116
+ doc.close()
117
+ return p
118
+
119
+ def test_a_string_where_engines_belong_is_a_TypeError(self):
120
+ try:
121
+ import pymupdf # noqa: F401
122
+ except ImportError:
123
+ self.skipTest("pymupdf not installed")
124
+ from scanquorum.build import build
125
+ with tempfile.TemporaryDirectory() as td:
126
+ p = self._tiny_pdf(td)
127
+ with self.assertRaises(TypeError) as cm:
128
+ build(str(p), engines="rapidocr_multi", out_dir=td)
129
+ msg = str(cm.exception)
130
+ self.assertIn("engines=", msg)
131
+ # The message must show what to write instead. A refusal that does
132
+ # not is a refusal the caller has to guess their way out of.
133
+ self.assertIn("tuple", msg.lower())
134
+
135
+ def test_a_path_where_engines_belong_is_a_TypeError(self):
136
+ """The exact call that was measured. It used to return a result dict."""
137
+ try:
138
+ import pymupdf # noqa: F401
139
+ except ImportError:
140
+ self.skipTest("pymupdf not installed")
141
+ from scanquorum.build import build
142
+ with tempfile.TemporaryDirectory() as td:
143
+ p = self._tiny_pdf(td)
144
+ with self.assertRaises(TypeError):
145
+ build(str(p), r"D:\some\output\directory", out_dir=td)
146
+
147
+ def test_unknown_engine_name_is_refused_in_strict_mode(self):
148
+ try:
149
+ import pymupdf # noqa: F401
150
+ except ImportError:
151
+ self.skipTest("pymupdf not installed")
152
+ from scanquorum.build import build
153
+ with tempfile.TemporaryDirectory() as td:
154
+ p = self._tiny_pdf(td)
155
+ with self.assertRaises(ValueError) as cm:
156
+ build(str(p), engines=("tesserct",), out_dir=td)
157
+ # and it must list what WAS available, or the typo is unfixable
158
+ self.assertIn("tesseract", str(cm.exception))
159
+
160
+ def test_a_cli_refusal_exits_2_and_writes_nothing(self):
161
+ """Refused is 'cannot run' (2), never 'ran but degraded' (1).
162
+
163
+ Found while preparing the 0.3.0 release: uncaught, a refusal was a
164
+ traceback and exit 1 -- the code that promises a written, degraded file --
165
+ so a pipeline reading exit codes would look for an output never made.
166
+ Both refusals are checked: a typo in an engine name, and an engine list
167
+ with no OCR engine in it at all.
168
+ """
169
+ try:
170
+ import pymupdf # noqa: F401
171
+ except ImportError:
172
+ self.skipTest("pymupdf not installed")
173
+ from scanquorum import build as B
174
+ with tempfile.TemporaryDirectory() as td:
175
+ p = self._tiny_pdf(td)
176
+ for engines in ("tesserct", ","):
177
+ rc = B.main([str(p), "--engines", engines, "--out-dir", td])
178
+ self.assertEqual(rc, 2, "engines=%r" % engines)
179
+ self.assertFalse((pathlib.Path(td) / "tiny.md").exists(),
180
+ "a refusal wrote an output file (engines=%r)" % engines)
181
+
182
+ def test_classify_is_total_and_sends_EMPTY_and_VOTE1_to_unconfirmed(self):
183
+ """The two rules the old hand-written copy of this list did not append.
184
+
185
+ They are why the duplicate existed at all: `classify` counted them as
186
+ unconfirmed, the emission loop did not add them to the index, and the
187
+ closing `assert unconf_n == len(unconf)` would have fired at the end of
188
+ a long run with a message about an index rather than about a rule."""
189
+ from scanquorum.build import classify, UNCONFIRMED, EXACT, SUBSTANCE, RULED
190
+ self.assertEqual(classify("EMPTY"), UNCONFIRMED)
191
+ self.assertEqual(classify("VOTE1/3"), UNCONFIRMED)
192
+ self.assertEqual(classify("VOTE1/3|NO_LAYER"), UNCONFIRMED)
193
+ self.assertEqual(classify("VOTE2/3"), EXACT)
194
+ self.assertEqual(classify("VOTE2/3|NO_LAYER"), EXACT)
195
+ self.assertEqual(classify("SEP="), SUBSTANCE)
196
+ self.assertEqual(classify("PATTERN|NO_LAYER"), RULED)
197
+ with self.assertRaises(SystemExit):
198
+ classify("SOMETHING_NOBODY_DECIDED_ABOUT")
199
+
200
+ def test_orphan_boxes_does_not_re_emit_a_box_that_lost_its_words(self):
201
+ """The double-emission hazard, in isolation.
202
+
203
+ `layout.assign` gives each word to ONE line box. Where two detections
204
+ overlap, the loser owns nothing -- and emitting it as an 'orphan' would
205
+ bring back the bug assign() was written to kill ('On On On November
206
+ November November', one document inflated 1.29x)."""
207
+ from scanquorum.build import _orphan_boxes
208
+ frame = [
209
+ {"b": (0, 0, 100, 20), "t": "winner"}, # owns words
210
+ {"b": (2, 1, 98, 19), "t": "loser"}, # overlapping, owns none
211
+ {"b": (0, 200, 100, 220), "t": "image"}, # far away, owns none
212
+ ]
213
+ owner = {0: [0, 1, 2]}
214
+ self.assertEqual(_orphan_boxes(frame, owner), [2])
215
+
216
+ def test_coverage_is_the_union_not_the_largest_single_overlap(self):
217
+ """Refuted by an outside reviewer on the day the filter was written.
218
+
219
+ Two owned boxes covering 30 % and 40 % of DIFFERENT halves of an orphan
220
+ account for 70 % of it. Taking the maximum over one box at a time sees
221
+ 0.40, calls that "mostly uncovered", and emits the orphan -- which is
222
+ precisely the double emission the filter exists to prevent."""
223
+ from scanquorum.build import _union_cover, _orphan_boxes
224
+ orphan = (0.0, 0.0, 100.0, 10.0) # area 1000
225
+ left = (0.0, 0.0, 30.0, 10.0) # 30 %
226
+ right = (60.0, 0.0, 100.0, 10.0) # 40 %, disjoint from `left`
227
+ self.assertAlmostEqual(_union_cover(orphan, [left]), 0.30, places=6)
228
+ self.assertAlmostEqual(_union_cover(orphan, [right]), 0.40, places=6)
229
+ self.assertAlmostEqual(_union_cover(orphan, [left, right]), 0.70, places=6)
230
+ # overlapping rectangles must not be counted twice
231
+ self.assertAlmostEqual(_union_cover(orphan, [left, (20.0, 0.0, 50.0, 10.0)]),
232
+ 0.50, places=6)
233
+ self.assertAlmostEqual(_union_cover(orphan, []), 0.0, places=6)
234
+
235
+ # and end to end: the 30 %+40 % orphan is now suppressed, as it must be
236
+ frame = [{"b": left, "t": "a"}, {"b": right, "t": "b"}, {"b": orphan, "t": "c"}]
237
+ self.assertEqual(_orphan_boxes(frame, {0: [0], 1: [1]}), [])
238
+
239
+
240
+ class MixedAndBlankPages(unittest.TestCase):
241
+ def _require(self, *modules):
242
+ for m in modules:
243
+ try:
244
+ __import__(m)
245
+ except ImportError:
246
+ self.skipTest("%s not installed" % m)
247
+
248
+ def test_a_stamped_scan_emits_the_letter_not_only_the_stamp(self):
249
+ self._require("PIL", "pymupdf", "rapidocr", "onnxruntime")
250
+ from scanquorum.build import build
251
+ import pymupdf
252
+ with tempfile.TemporaryDirectory() as td:
253
+ td = pathlib.Path(td)
254
+ pdf = td / "stamped.pdf"
255
+ body = ["QUORUM LETTER 12-855", "SECOND BODY LINE", "THIRD BODY LINE"]
256
+ _make_stamped_scan_pdf("Exhibit A-1 - Sample Document", body, pdf)
257
+
258
+ # The fixture must have the shape the bug needs, or the test is
259
+ # asserting nothing. Both halves are checked.
260
+ d = pymupdf.open(str(pdf))
261
+ words = d[0].get_text("words")
262
+ d.close()
263
+ self.assertNotEqual(words, [], "fixture has no text layer -- that is "
264
+ "the pure-scan case, already covered")
265
+ self.assertLess(len(words), 30, "fixture stamp is too big to model a stamp")
266
+
267
+ hdr = build(str(pdf), engines=("rapidocr_multi", "rapidocr_en"),
268
+ dpi=200, out_dir=str(td))
269
+
270
+ body_md = (td / "stamped.md").read_text(encoding="utf-8").split("\n---\n")[-1]
271
+ self.assertGreaterEqual(
272
+ hdr.get("mixed_pages_with_recovered_lines", 0), 1,
273
+ "the MIXED repair did not fire; the .md is the stamp only. "
274
+ "Header was: %r" % {k: hdr[k] for k in list(hdr)[:12]})
275
+ self.assertEqual(hdr.get("pure_scan_pages", -1), 0,
276
+ "this page HAS a text layer; pure_scan_pages must stay 0, "
277
+ "or the two paths have been confused")
278
+ found = [t for t in ("QUORUM", "LETTER", "SECOND", "THIRD", "BODY") if t in body_md]
279
+ self.assertGreaterEqual(
280
+ len(found), 2,
281
+ "expected >=2 body tokens in the .md, got %r. The stamp alone is "
282
+ "the failure this test exists to catch." % found)
283
+
284
+ def test_a_blank_page_does_not_crash_the_header(self):
285
+ self._require("PIL", "pymupdf", "rapidocr", "onnxruntime")
286
+ from scanquorum.build import build
287
+ with tempfile.TemporaryDirectory() as td:
288
+ td = pathlib.Path(td)
289
+ pdf = td / "blank_plus.pdf"
290
+ _make_blank_plus_text_pdf(pdf)
291
+ # Before the fix this raised TypeError comparing None with a str,
292
+ # AFTER every engine had finished, while building metadata.
293
+ hdr = build(str(pdf), engines=("rapidocr_multi", "rapidocr_en"),
294
+ dpi=200, out_dir=str(td))
295
+ self.assertIsNotNone(hdr["frame_engine"])
296
+ self.assertNotIn(None, hdr["frame_engine_pages"])
297
+ self.assertGreaterEqual(hdr["pages_without_ocr"], 1,
298
+ "the blank page was not counted; either the "
299
+ "fixture is not blank or the counter is not wired")
300
+
301
+ def test_two_engines_is_a_quorum_and_one_is_not(self):
302
+ self._require("PIL", "pymupdf", "rapidocr", "onnxruntime")
303
+ from scanquorum.build import build, ScanQuorumInsufficientEngines
304
+ with tempfile.TemporaryDirectory() as td:
305
+ td = pathlib.Path(td)
306
+ pdf = td / "one_engine.pdf"
307
+ _make_blank_plus_text_pdf(pdf)
308
+ with self.assertRaises(ScanQuorumInsufficientEngines):
309
+ build(str(pdf), engines=("rapidocr_multi",), dpi=150, out_dir=str(td))
310
+ # and the escape hatch still works, deliberately
311
+ hdr = build(str(pdf), engines=("rapidocr_multi",), dpi=150,
312
+ out_dir=str(td), strict=False)
313
+ self.assertEqual(hdr["engines"], ["pdf_layer", "rapidocr_multi"])
314
+
315
+
316
+ if __name__ == "__main__":
317
+ unittest.main(verbosity=2)
File without changes
File without changes