scanquorum 0.2.0__py3-none-any.whl

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/doctor.py ADDED
@@ -0,0 +1,285 @@
1
+ # scanquorum/doctor.py v1.0
2
+ #
3
+ # WHAT IS INSTALLED, WHAT IS MISSING, AND EXACTLY HOW TO FIX IT.
4
+ #
5
+ # This exists because of a measured failure, not as a courtesy. Running the
6
+ # pipeline on this machine with Tesseract present but not on PATH produced a
7
+ # complete, confident, well-formed result -- built from three engines instead of
8
+ # four, of which only ONE was an independent OCR opinion, because the two RapidOCR
9
+ # voters share a text detector. The output looked exactly like a good run. Nothing
10
+ # in the file said "the fourth voice was missing"; the numbers simply came out
11
+ # weaker and no one had a baseline to compare them against.
12
+ #
13
+ # A tool whose entire premise is "do not trust an unverified claim" cannot ship a
14
+ # setup step whose failure mode is silence. So:
15
+ #
16
+ # - every dependency is probed by IMPORTING it and reading its version,
17
+ # - every engine is probed by actually RUNNING it on a generated image,
18
+ # - the exit code is nonzero when the quorum would be degraded,
19
+ # - and every failure prints the exact command that fixes it, per platform.
20
+ #
21
+ # Run: python -m scanquorum doctor
22
+ # python -m scanquorum doctor --json (for an agent to parse)
23
+ #
24
+ # Exit codes: 0 = full quorum available
25
+ # 1 = runs, but with fewer independent opinions than intended
26
+ # 2 = cannot run at all
27
+
28
+ import os
29
+ import sys
30
+ import json
31
+ import shutil
32
+ import platform
33
+ import subprocess
34
+
35
+ VERSION = "1.0"
36
+
37
+ MIN_PYTHON = (3, 9)
38
+
39
+ # name -> (import name, pip name, why it is needed, is it required)
40
+ PY_DEPS = [
41
+ ("pymupdf", "pymupdf", "pymupdf", "reads the PDF, its text layer and page images", True),
42
+ # 🔴 The import name is `rapidocr`, NOT `rapidocr_onnxruntime`. The first version
43
+ # of this file guessed the latter, reported the package missing on a machine
44
+ # where it was installed and working, and printed a pip command that would have
45
+ # installed a different, older package. A doctor that misdiagnoses is worse than
46
+ # no doctor, so every name here was checked against the adapter that imports it.
47
+ ("rapidocr", "rapidocr", "rapidocr onnxruntime",
48
+ "two of the four voters; without it only the PDF layer and Tesseract vote", True),
49
+ ("onnxruntime", "onnxruntime", "onnxruntime", "runs the RapidOCR models", True),
50
+ ("numpy", "numpy", "numpy", "box arithmetic and the image buffer handed to RapidOCR", True),
51
+ ]
52
+
53
+ TESSERACT_URLS = {
54
+ "Windows": "https://github.com/UB-Mannheim/tesseract/wiki (installer, or a portable zip)",
55
+ "Darwin": "brew install tesseract",
56
+ "Linux": "sudo apt install tesseract-ocr (Debian/Ubuntu) | sudo dnf install tesseract",
57
+ }
58
+
59
+
60
+ def _v(mod):
61
+ for attr in ("__version__", "VERSION", "version"):
62
+ got = getattr(mod, attr, None)
63
+ if isinstance(got, str):
64
+ return got
65
+ return "unknown"
66
+
67
+
68
+ def check_python(rep):
69
+ ok = sys.version_info[:2] >= MIN_PYTHON
70
+ rep.append({
71
+ "check": "python", "ok": ok, "found": platform.python_version(),
72
+ "want": ">= %d.%d" % MIN_PYTHON,
73
+ "fix": "" if ok else "Install Python %d.%d or newer and re-create the environment." % MIN_PYTHON,
74
+ })
75
+ return ok
76
+
77
+
78
+ def check_deps(rep):
79
+ all_ok = True
80
+ for name, imp, pipname, why, required in PY_DEPS:
81
+ try:
82
+ mod = __import__(imp)
83
+ rep.append({"check": "python package: " + name, "ok": True,
84
+ "found": _v(mod), "want": "any", "note": why, "fix": ""})
85
+ except Exception as exc:
86
+ if required:
87
+ all_ok = False
88
+ rep.append({"check": "python package: " + name, "ok": not required,
89
+ "found": "NOT INSTALLED (%s)" % type(exc).__name__,
90
+ "want": "any", "note": why,
91
+ "fix": "%s -m pip install %s" % (sys.executable, pipname)})
92
+ return all_ok
93
+
94
+
95
+ def check_tesseract(rep):
96
+ """Tesseract is the ONLY voter that draws its own word boxes, so its absence
97
+ does not merely remove a vote -- it removes the independence of the vote that
98
+ remains. That is why this check reports a degraded quorum rather than a
99
+ missing optional extra."""
100
+ exe = os.environ.get("TESSERACT_EXE") or shutil.which("tesseract")
101
+ if not exe or not os.path.exists(exe):
102
+ rep.append({
103
+ "check": "tesseract binary", "ok": False, "found": "NOT FOUND",
104
+ "want": "tesseract 4 or 5 on PATH, or TESSERACT_EXE set",
105
+ "note": "the only voter with its own layout analysis",
106
+ "fix": ("Install it: %s\nThen either add it to PATH, or set the variable:\n"
107
+ " Windows PowerShell: $env:TESSERACT_EXE = 'C:\\path\\to\\tesseract.exe'\n"
108
+ " bash: export TESSERACT_EXE=/usr/bin/tesseract"
109
+ % TESSERACT_URLS.get(platform.system(), TESSERACT_URLS["Linux"])),
110
+ })
111
+ return False
112
+ try:
113
+ out = subprocess.run([exe, "--version"], capture_output=True, text=True, timeout=30)
114
+ ver = (out.stdout or out.stderr).splitlines()[0].strip()
115
+ except Exception as exc:
116
+ rep.append({"check": "tesseract binary", "ok": False, "found": "found but would not run: %r" % exc,
117
+ "want": "runnable", "fix": "Check the file is not blocked by antivirus or quarantine."})
118
+ return False
119
+ # `--list-langs` prints a header line ("List of available languages in ...")
120
+ # and then one language per line. Splitting the whole blob on whitespace and
121
+ # dropping the first token, as this did at first, yields the header's own words
122
+ # as language names.
123
+ langs = []
124
+ try:
125
+ lo = subprocess.run([exe, "--list-langs"], capture_output=True, text=True, timeout=30)
126
+ lines = [l.strip() for l in ((lo.stdout or "") + (lo.stderr or "")).splitlines()]
127
+ langs = [l for l in lines if l and " " not in l and not l.endswith(":")]
128
+ except Exception:
129
+ pass
130
+ has_eng = "eng" in langs
131
+ rep.append({"check": "tesseract binary", "ok": True, "found": "%s [%s]" % (ver, exe),
132
+ "want": "4 or 5", "note": "languages: " + (" ".join(langs) or "could not list"),
133
+ "fix": ""})
134
+ if not has_eng:
135
+ rep.append({"check": "tesseract language data: eng", "ok": False,
136
+ "found": "MISSING", "want": "eng.traineddata",
137
+ "fix": "Install the English language pack (apt: tesseract-ocr-eng). "
138
+ "The binary alone reads nothing."})
139
+ return False
140
+ return True
141
+
142
+
143
+ SMOKE_TEXT = "Interim Decision 2282"
144
+
145
+
146
+ def _smoke_pdf(path):
147
+ """A one-page PDF whose text we know, because the adapters take a PDF PATH and
148
+ not an image. The first version of this function handed them PNG bytes; every
149
+ engine raised, and the doctor reported three broken engines on a machine where
150
+ all three worked. It also printed the whole 6 KB PNG into the error line. Both
151
+ are fixed below, and both are the reason this file gets exercised by
152
+ tests/test_doctor.py rather than trusted."""
153
+ import pymupdf
154
+ doc = pymupdf.open()
155
+ page = doc.new_page(width=430, height=110)
156
+ page.insert_text((22, 62), SMOKE_TEXT, fontsize=20)
157
+ doc.save(path)
158
+ doc.close()
159
+
160
+
161
+ def _short(exc, n=180):
162
+ """Never let a payload into an error line. The binary dump that appeared here
163
+ once made the real message unreadable."""
164
+ s = "%s: %s" % (type(exc).__name__, exc)
165
+ s = " ".join(s.split())
166
+ return s if len(s) <= n else s[:n] + " ...[truncated]"
167
+
168
+
169
+ def check_engines(rep):
170
+ """Import each adapter and RUN it on a generated PDF. Importing proves the
171
+ module loads; only running proves the model weights are present and the binary
172
+ answers. RapidOCR downloads its weights on first use, so a machine with no
173
+ network can import the package and still fail on the first real page.
174
+
175
+ The check is not "did it return something" but "did it return the RIGHT thing":
176
+ an engine that reads a blank page returns a clean empty result, which is
177
+ indistinguishable from success unless you know what the page said."""
178
+ import tempfile
179
+ tmp = os.path.join(tempfile.mkdtemp(prefix="scanquorum-doctor-"), "smoke.pdf")
180
+ try:
181
+ _smoke_pdf(tmp)
182
+ except Exception as exc:
183
+ rep.append({"check": "engine smoke test", "ok": False,
184
+ "found": "could not build the test PDF: " + _short(exc),
185
+ "want": "pymupdf works", "fix": "fix the pymupdf row above first"})
186
+ return 0, []
187
+
188
+ live = []
189
+ for name in ("rapidocr_multi", "rapidocr_en", "tesseract"):
190
+ try:
191
+ mod = __import__("scanquorum.engines." + name, fromlist=["run", "GRANULARITY"])
192
+ except Exception as exc:
193
+ rep.append({"check": "engine: " + name, "ok": False,
194
+ "found": "adapter did not load: " + _short(exc),
195
+ "want": "loads and runs", "fix": "see the rows above"})
196
+ continue
197
+ try:
198
+ out = mod.run(tmp)
199
+ boxes = (out or {}).get("0", {}).get("boxes", [])
200
+ text = " ".join(b.get("t", "") for b in boxes)
201
+ # "2282" is the part that matters: a digit sequence is what this whole
202
+ # project is about getting right, and it is what a half-loaded model
203
+ # gets wrong first.
204
+ read_it = "2282" in text.replace(" ", "")
205
+ rep.append({
206
+ "check": "engine: " + name, "ok": read_it,
207
+ "found": ("read %r" % text[:60]) if boxes else "ran but read NOTHING",
208
+ "want": "text containing 2282",
209
+ "note": "granularity: %s" % getattr(mod, "GRANULARITY", "?"),
210
+ "fix": "" if read_it else
211
+ ("The engine ran but did not read the test page correctly. For RapidOCR "
212
+ "this usually means the model weights are missing or only partly "
213
+ "downloaded: delete the model cache and let it fetch again with a "
214
+ "network connection."),
215
+ })
216
+ if read_it:
217
+ live.append(name)
218
+ except Exception as exc:
219
+ rep.append({"check": "engine: " + name, "ok": False,
220
+ "found": "raised " + _short(exc),
221
+ "want": "runs", "fix": "see the rows above"})
222
+ return len(live), live
223
+
224
+
225
+ def independence(live):
226
+ """How many genuinely independent OCR opinions the live engines represent.
227
+ This is the number that decides whether a vote means anything, and it is NOT
228
+ the engine count: rapidocr_multi and rapidocr_en share a PP-OCRv6 detector."""
229
+ correlated = [{"rapidocr_multi", "rapidocr_en"}]
230
+ n = len(live)
231
+ for group in correlated:
232
+ overlap = group & set(live)
233
+ if len(overlap) > 1:
234
+ n -= len(overlap) - 1
235
+ return n
236
+
237
+
238
+ def main(argv=None):
239
+ as_json = "--json" in (argv or sys.argv[1:])
240
+ rep = []
241
+ hard_ok = check_python(rep)
242
+ hard_ok = check_deps(rep) and hard_ok
243
+ check_tesseract(rep)
244
+ n_live, live = check_engines(rep)
245
+ indep = independence(live)
246
+
247
+ verdict_code = 0
248
+ if not hard_ok or n_live == 0:
249
+ verdict_code = 2
250
+ verdict = ("CANNOT RUN. Fix the rows marked FAIL above, in order; each one prints "
251
+ "the exact command.")
252
+ elif indep < 2:
253
+ verdict_code = 1
254
+ verdict = ("RUNS, BUT THE QUORUM IS DEGRADED. %d engine(s) live, but only %d "
255
+ "INDEPENDENT OCR opinion(s). Two engines that share a text detector are "
256
+ "nearer one voter than two, so agreement between them is weaker evidence "
257
+ "than the count suggests. Install Tesseract for a voter that draws its own "
258
+ "boxes." % (n_live, indep))
259
+ else:
260
+ verdict = ("READY. %d OCR engine(s) live, %d independent opinion(s), plus the PDF's "
261
+ "own text layer as a further voter." % (n_live, indep))
262
+
263
+ if as_json:
264
+ print(json.dumps({"version": VERSION, "checks": rep, "engines_live": live,
265
+ "independent_opinions": indep, "exit_code": verdict_code,
266
+ "verdict": verdict}, ensure_ascii=False, indent=1))
267
+ return verdict_code
268
+
269
+ print("scanquorum doctor v%s python %s on %s\n"
270
+ % (VERSION, platform.python_version(), platform.platform()))
271
+ for r in rep:
272
+ print(" [%s] %-32s %s" % ("PASS" if r["ok"] else "FAIL", r["check"], r["found"]))
273
+ if r.get("note"):
274
+ print(" %s" % r["note"])
275
+ if not r["ok"] and r.get("fix"):
276
+ for line in r["fix"].splitlines():
277
+ print(" -> %s" % line)
278
+ print("\n" + "=" * 74)
279
+ print(verdict)
280
+ print("=" * 74)
281
+ return verdict_code
282
+
283
+
284
+ if __name__ == "__main__":
285
+ sys.exit(main())
@@ -0,0 +1,8 @@
1
+ """Engine adapters. Each exposes run(pdf, dpi, progress) -> {page_str: {"boxes": [...]}}
2
+ where a box is {"t": text, "b": (x0,y0,x1,y1) in PDF points, "s": confidence or None}.
3
+
4
+ An adapter for an engine that is not installed must raise ImportError at import
5
+ time. It must never return empty results that look like a successful run -- a
6
+ silently absent voter turns a four-engine quorum into a three-engine one without
7
+ saying so, and the output would claim a confidence it does not have.
8
+ """
@@ -0,0 +1,64 @@
1
+ # scanquorum/engines/rapidocr_en.py
2
+ """RapidOCR (PP-OCR family) -- English-specialised v5 mobile recogniser. Faster, and wrong in different places, which is what a second voter is for.
3
+
4
+ pip install rapidocr onnxruntime
5
+
6
+ CONFIGURATION IS NOT GUESSED. These parameter names and enum values are the ones
7
+ that actually ran in the measurement behind README.md. An earlier version of this
8
+ adapter invented plausible keys ("Global.lang_det") and every page failed with
9
+ `ValueError: ... is not a valid key` -- which the pipeline correctly reported as
10
+ an ABSENT ENGINE rather than as empty results, so the run degraded to one voter
11
+ and said so instead of quietly claiming a quorum.
12
+
13
+ Measured note kept from that work: PP-OCRv6 in this build has NO mobile tier at
14
+ all -- neither detector nor recogniser. Asking for one raises. When one branch of
15
+ a config turns out not to exist, check every branch of that family, not just the
16
+ one that broke.
17
+ """
18
+ import numpy as np
19
+ import pymupdf
20
+ from rapidocr import RapidOCR, ModelType, OCRVersion, LangRec # noqa: F401
21
+
22
+ _DET = {"Det.ocr_version": OCRVersion.PPOCRV6, "Det.model_type": ModelType.MEDIUM}
23
+ PARAMS = dict(_DET, **{"Rec.ocr_version": OCRVersion.PPOCRV5, "Rec.model_type": ModelType.MOBILE, "Rec.lang_type": LangRec.EN})
24
+
25
+ _ENGINE = None
26
+
27
+
28
+ def _engine():
29
+ global _ENGINE
30
+ if _ENGINE is None:
31
+ _ENGINE = RapidOCR(params=dict(PARAMS))
32
+ return _ENGINE
33
+
34
+
35
+ # This engine returns line-level boxes. See build.py for why it matters.
36
+ GRANULARITY = "line"
37
+
38
+
39
+ def run(pdf, dpi=300, progress=None):
40
+ doc = pymupdf.open(pdf)
41
+ eng = _engine()
42
+ k = 72.0 / dpi
43
+ out = {}
44
+ for pi in range(doc.page_count):
45
+ pm = doc[pi].get_pixmap(dpi=dpi)
46
+ arr = np.frombuffer(pm.samples, dtype=np.uint8).reshape(pm.height, pm.width, pm.n)
47
+ if pm.n >= 3:
48
+ # RGB(A) -> BGR, to match what cv2 hands the model. Getting this
49
+ # backwards does not crash; it quietly costs accuracy.
50
+ arr = np.ascontiguousarray(arr[:, :, 2::-1])
51
+ boxes = []
52
+ res = eng(arr)
53
+ if getattr(res, "txts", None):
54
+ for box, txt, sc in zip(res.boxes, res.txts, res.scores):
55
+ xs = [float(p[0]) for p in box]
56
+ ys = [float(p[1]) for p in box]
57
+ boxes.append({"t": str(txt), "s": round(float(sc), 4),
58
+ "b": [round(min(xs) * k, 2), round(min(ys) * k, 2),
59
+ round(max(xs) * k, 2), round(max(ys) * k, 2)]})
60
+ out[str(pi)] = {"boxes": boxes}
61
+ if progress:
62
+ progress(pi + 1, doc.page_count, "rapidocr_en")
63
+ doc.close()
64
+ return out
@@ -0,0 +1,64 @@
1
+ # scanquorum/engines/rapidocr_multi.py
2
+ """RapidOCR (PP-OCR family) -- multilingual v6 medium recogniser. Best SINGLE layer measured: 95.9 % against 91.5 % for the existing text layer.
3
+
4
+ pip install rapidocr onnxruntime
5
+
6
+ CONFIGURATION IS NOT GUESSED. These parameter names and enum values are the ones
7
+ that actually ran in the measurement behind README.md. An earlier version of this
8
+ adapter invented plausible keys ("Global.lang_det") and every page failed with
9
+ `ValueError: ... is not a valid key` -- which the pipeline correctly reported as
10
+ an ABSENT ENGINE rather than as empty results, so the run degraded to one voter
11
+ and said so instead of quietly claiming a quorum.
12
+
13
+ Measured note kept from that work: PP-OCRv6 in this build has NO mobile tier at
14
+ all -- neither detector nor recogniser. Asking for one raises. When one branch of
15
+ a config turns out not to exist, check every branch of that family, not just the
16
+ one that broke.
17
+ """
18
+ import numpy as np
19
+ import pymupdf
20
+ from rapidocr import RapidOCR, ModelType, OCRVersion, LangRec # noqa: F401
21
+
22
+ _DET = {"Det.ocr_version": OCRVersion.PPOCRV6, "Det.model_type": ModelType.MEDIUM}
23
+ PARAMS = dict(_DET, **{"Rec.ocr_version": OCRVersion.PPOCRV6, "Rec.model_type": ModelType.MEDIUM})
24
+
25
+ _ENGINE = None
26
+
27
+
28
+ def _engine():
29
+ global _ENGINE
30
+ if _ENGINE is None:
31
+ _ENGINE = RapidOCR(params=dict(PARAMS))
32
+ return _ENGINE
33
+
34
+
35
+ # This engine returns line-level boxes. See build.py for why it matters.
36
+ GRANULARITY = "line"
37
+
38
+
39
+ def run(pdf, dpi=300, progress=None):
40
+ doc = pymupdf.open(pdf)
41
+ eng = _engine()
42
+ k = 72.0 / dpi
43
+ out = {}
44
+ for pi in range(doc.page_count):
45
+ pm = doc[pi].get_pixmap(dpi=dpi)
46
+ arr = np.frombuffer(pm.samples, dtype=np.uint8).reshape(pm.height, pm.width, pm.n)
47
+ if pm.n >= 3:
48
+ # RGB(A) -> BGR, to match what cv2 hands the model. Getting this
49
+ # backwards does not crash; it quietly costs accuracy.
50
+ arr = np.ascontiguousarray(arr[:, :, 2::-1])
51
+ boxes = []
52
+ res = eng(arr)
53
+ if getattr(res, "txts", None):
54
+ for box, txt, sc in zip(res.boxes, res.txts, res.scores):
55
+ xs = [float(p[0]) for p in box]
56
+ ys = [float(p[1]) for p in box]
57
+ boxes.append({"t": str(txt), "s": round(float(sc), 4),
58
+ "b": [round(min(xs) * k, 2), round(min(ys) * k, 2),
59
+ round(max(xs) * k, 2), round(max(ys) * k, 2)]})
60
+ out[str(pi)] = {"boxes": boxes}
61
+ if progress:
62
+ progress(pi + 1, doc.page_count, "rapidocr_multi")
63
+ doc.close()
64
+ return out
@@ -0,0 +1,70 @@
1
+ # scanquorum/engines/tesseract.py
2
+ """Tesseract 5 through its own binary, in hOCR mode.
3
+
4
+ THE WEAKEST OF THE FOUR ENGINES AND THE MOST VALUABLE ADDITION -- because it is
5
+ the only one that draws its own text boxes. The two RapidOCR voters share a
6
+ detector (2,921 of 3,006 boxes byte-identical), so they are nearer one voice than
7
+ two. Independence beats accuracy in an ensemble: adding this engine moved the gold
8
+ set from 49/56 to 53/56, helping 4 times and hurting 0, and in one of those the
9
+ correct reading had been proposed by no other engine at all.
10
+
11
+ Needs the `tesseract` binary. Set TESSERACT_EXE, or have it on PATH. A portable
12
+ unpacked copy is fine -- nothing needs to be installed system-wide or touch the
13
+ registry. Language data is a separate download (`eng.traineddata`); if
14
+ TESSDATA_PREFIX is not set, the directory next to the binary is tried.
15
+
16
+ The page goes in on stdin and hOCR comes back on stdout: no temporary files, so
17
+ two runs in parallel cannot collide over the same scratch path.
18
+ """
19
+ import os
20
+ import re
21
+ import html
22
+ import shutil
23
+ import subprocess
24
+ import pymupdf
25
+
26
+ EXE = os.environ.get("TESSERACT_EXE") or shutil.which("tesseract")
27
+ if not EXE or not os.path.exists(EXE):
28
+ raise ImportError("tesseract binary not found; set TESSERACT_EXE or put it on PATH")
29
+
30
+ # Taken from real hOCR output, not from documentation. Note `x_wconf` for the word
31
+ # confidence -- an adapter written from memory used `x_conf` and matched nothing,
32
+ # while looking exactly like a parser that worked.
33
+ RE_WORD = re.compile(
34
+ r"<span class='ocrx_word'[^>]*title='bbox (\d+) (\d+) (\d+) (\d+); x_wconf (\d+)'[^>]*>(.*?)</span>",
35
+ re.S)
36
+ RE_TAG = re.compile(r"<[^>]+>")
37
+
38
+
39
+ # This engine returns word-level boxes. See build.py for why it matters.
40
+ GRANULARITY = "word"
41
+
42
+
43
+ def run(pdf, dpi=300, progress=None):
44
+ env = dict(os.environ)
45
+ env.setdefault("TESSDATA_PREFIX", os.path.join(os.path.dirname(EXE), "tessdata"))
46
+ doc = pymupdf.open(pdf)
47
+ k = 72.0 / dpi
48
+ out = {}
49
+ for pi in range(doc.page_count):
50
+ png = doc[pi].get_pixmap(dpi=dpi).tobytes("png")
51
+ p = subprocess.run([EXE, "stdin", "stdout", "--dpi", str(dpi), "-l", "eng",
52
+ "--psm", "3", "hocr"],
53
+ input=png, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
54
+ if p.returncode != 0:
55
+ raise RuntimeError("tesseract failed on page %d: %s"
56
+ % (pi, p.stderr.decode("utf-8", "replace")[-300:]))
57
+ doc_h = p.stdout.decode("utf-8", "replace")
58
+ boxes = []
59
+ for m in RE_WORD.finditer(doc_h):
60
+ x0, y0, x1, y1, conf = (int(g) for g in m.groups()[:5])
61
+ t = html.unescape(RE_TAG.sub("", m.group(6))).strip()
62
+ if t:
63
+ boxes.append({"t": t, "s": conf / 100.0,
64
+ "b": [round(x0 * k, 2), round(y0 * k, 2),
65
+ round(x1 * k, 2), round(y1 * k, 2)]})
66
+ out[str(pi)] = {"boxes": boxes}
67
+ if progress:
68
+ progress(pi + 1, doc.page_count, "tesseract")
69
+ doc.close()
70
+ return out
scanquorum/layout.py ADDED
@@ -0,0 +1,106 @@
1
+ # scanquorum/layout.py v1.0
2
+ #
3
+ # Where things are on the page. Three jobs, all geometric, none of them about
4
+ # characters: find the column gutter, decide which OCR line owns each word, and
5
+ # look a word up by its box quickly.
6
+ import collections
7
+
8
+
9
+ def iou(a, b):
10
+ x0, y0 = max(a[0], b[0]), max(a[1], b[1])
11
+ x1, y1 = min(a[2], b[2]), min(a[3], b[3])
12
+ if x1 <= x0 or y1 <= y0:
13
+ return 0.0
14
+ i = (x1 - x0) * (y1 - y0)
15
+ ua = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i
16
+ return i / ua if ua > 0 else 0.0
17
+
18
+
19
+ def gutter(boxes, page_w):
20
+ """Find the vertical whitespace channel of a two-column page, or None.
21
+
22
+ 🔴 HEURISTIC, and the tool's weakest part. It looks for a band between 30 %
23
+ and 70 % of the width that almost no box crosses. It is right on the corpus
24
+ this was measured on and is guaranteed nowhere else. Reading order is not
25
+ otherwise checked, so a wrong answer here produces text that is perfectly
26
+ recognised and in the wrong order -- a quotation that is verbatim and
27
+ meaningless. See testing/TO-TEST.md#g6."""
28
+ if len(boxes) < 10:
29
+ return None
30
+ occ = [0] * 100
31
+ for b in boxes:
32
+ for i in range(max(0, int(b[0] / page_w * 100)), min(99, int(b[2] / page_w * 100)) + 1):
33
+ occ[i] += 1
34
+ thr = max(1, int(0.02 * len(boxes)))
35
+ best, i = None, 30
36
+ while i <= 70:
37
+ if occ[i] <= thr:
38
+ j = i
39
+ while j <= 70 and occ[j] <= thr:
40
+ j += 1
41
+ if best is None or (j - i) > (best[1] - best[0]):
42
+ best = (i, j)
43
+ i = j
44
+ else:
45
+ i += 1
46
+ return (best[0] + best[1]) / 2 / 100 * page_w if best and (best[1] - best[0]) >= 3 else None
47
+
48
+
49
+ def assign(ocr_lines, words):
50
+ """Map each word of the existing text layer to EXACTLY ONE OCR line.
51
+
52
+ 🔴 THE DEFECT THIS FUNCTION EXISTS TO CLOSE. The obvious loop -- for each OCR
53
+ line, take every word whose centre falls inside it -- emits a word once per
54
+ line that covers it. OCR line boxes overlap constantly on full-width pages, so
55
+ the assembled text came out as 'On On On November November November', inflating
56
+ one document by 1.29x and 4,801 surplus tokens.
57
+
58
+ It was nearly invisible on narrow-column pages (7 cases in 29,858), which is
59
+ why it survived two rounds of code review and died the first time anyone used
60
+ the output to pull a real quotation.
61
+
62
+ Resolution: the word belongs to the line whose vertical centre is nearest; ties
63
+ go to the tighter box. Stable under nested and slightly shifted detections."""
64
+ owner = collections.defaultdict(list)
65
+ for wi, w in enumerate(words):
66
+ cx, cy = (w[0] + w[2]) / 2, (w[1] + w[3]) / 2
67
+ best, bi = None, -1
68
+ for i, eb in enumerate(ocr_lines):
69
+ r = eb["b"]
70
+ if not (r[0] - 2 <= cx <= r[2] + 2 and r[1] - 2 <= cy <= r[3] + 2):
71
+ continue
72
+ sc = (abs(cy - (r[1] + r[3]) / 2), (r[2] - r[0]) * (r[3] - r[1]))
73
+ if best is None or sc < best:
74
+ best, bi = sc, i
75
+ if bi >= 0:
76
+ owner[bi].append(wi)
77
+ return owner
78
+
79
+
80
+ class BoxIndex:
81
+ """Look up an engine's reading by box. Bucketed vertically because the naive
82
+ scan is ~730 words x ~750 boxes x 200 pages = 100 million overlap tests."""
83
+
84
+ def __init__(self, boxes, bucket=6.0):
85
+ self.bucket = bucket
86
+ self.idx = collections.defaultdict(list)
87
+ for bx in boxes or ():
88
+ for k in range(int(bx["b"][1] // bucket), int(bx["b"][3] // bucket) + 1):
89
+ self.idx[k].append(bx)
90
+
91
+ def at(self, bbox, thr=0.25):
92
+ seen, best, bt = set(), 0.0, None
93
+ for k in range(int(bbox[1] // self.bucket), int(bbox[3] // self.bucket) + 1):
94
+ for bx in self.idx.get(k, ()):
95
+ if id(bx) in seen:
96
+ continue
97
+ seen.add(id(bx))
98
+ v = iou(bbox, bx["b"])
99
+ if v > best:
100
+ best, bt = v, bx
101
+ if bt is None or best <= thr:
102
+ return None, None
103
+ t = bt.get("t")
104
+ # A line box holds several words; a single-word query wants the word, and
105
+ # returning the whole line would manufacture disagreement at every token.
106
+ return (t.split()[0] if t and len(t.split()) == 1 else t), bt.get("s")