scanquorum 0.2.1__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.
Files changed (28) hide show
  1. {scanquorum-0.2.1/scanquorum.egg-info → scanquorum-0.2.2}/PKG-INFO +1 -1
  2. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/__init__.py +1 -1
  3. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/build.py +133 -1
  4. {scanquorum-0.2.1 → scanquorum-0.2.2/scanquorum.egg-info}/PKG-INFO +1 -1
  5. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum.egg-info/SOURCES.txt +1 -0
  6. scanquorum-0.2.2/tests/test_purescan.py +138 -0
  7. {scanquorum-0.2.1 → scanquorum-0.2.2}/LICENSE +0 -0
  8. {scanquorum-0.2.1 → scanquorum-0.2.2}/README.md +0 -0
  9. {scanquorum-0.2.1 → scanquorum-0.2.2}/pyproject.toml +0 -0
  10. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/__main__.py +0 -0
  11. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/doctor.py +0 -0
  12. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/engines/__init__.py +0 -0
  13. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/engines/rapidocr_en.py +0 -0
  14. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/engines/rapidocr_multi.py +0 -0
  15. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/engines/tesseract.py +0 -0
  16. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/layout.py +0 -0
  17. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/verify_ai.py +0 -0
  18. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum/vote.py +0 -0
  19. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum.egg-info/dependency_links.txt +0 -0
  20. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum.egg-info/entry_points.txt +0 -0
  21. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum.egg-info/requires.txt +0 -0
  22. {scanquorum-0.2.1 → scanquorum-0.2.2}/scanquorum.egg-info/top_level.txt +0 -0
  23. {scanquorum-0.2.1 → scanquorum-0.2.2}/setup.cfg +0 -0
  24. {scanquorum-0.2.1 → scanquorum-0.2.2}/tests/test_doctor.py +0 -0
  25. {scanquorum-0.2.1 → scanquorum-0.2.2}/tests/test_goldset.py +0 -0
  26. {scanquorum-0.2.1 → scanquorum-0.2.2}/tests/test_riskcov.py +0 -0
  27. {scanquorum-0.2.1 → scanquorum-0.2.2}/tests/test_safety.py +0 -0
  28. {scanquorum-0.2.1 → 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.1
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
@@ -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.1"
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.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():
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scanquorum
3
- Version: 0.2.1
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
@@ -20,6 +20,7 @@ scanquorum/engines/rapidocr_multi.py
20
20
  scanquorum/engines/tesseract.py
21
21
  tests/test_doctor.py
22
22
  tests/test_goldset.py
23
+ tests/test_purescan.py
23
24
  tests/test_riskcov.py
24
25
  tests/test_safety.py
25
26
  tests/test_vote_parity.py
@@ -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)
File without changes
File without changes
File without changes
File without changes