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/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """ScanQuorum -- accept a word from a scanned page only when independent OCR
2
+ engines agree, and show you the ones they do not.
3
+
4
+ No language model is involved in transcription. See README.md.
5
+ """
6
+ __version__ = "0.2.0"
7
+
8
+ # A Windows console defaults to a legacy code page (cp1251, cp866, cp1252...) and
9
+ # raises UnicodeEncodeError the first time anything prints a character outside it.
10
+ # Measured on the first end-to-end run: this tool died on its own "engine not
11
+ # available" warning, because that line carries a red-circle emoji -- so the crash
12
+ # destroyed the diagnostic it was trying to deliver, and the traceback pointed at
13
+ # the print rather than at the real problem. Reconfiguring here, once, covers every
14
+ # entry point.
15
+ #
16
+ # errors="replace" rather than "strict": a report that prints "?" is still a
17
+ # report; a report that raises is not. No glyph here is worth losing a run over.
18
+ import sys as _sys
19
+
20
+ for _s in (_sys.stdout, _sys.stderr):
21
+ try:
22
+ _s.reconfigure(encoding="utf-8", errors="replace")
23
+ except Exception:
24
+ pass
scanquorum/__main__.py ADDED
@@ -0,0 +1,38 @@
1
+ import sys
2
+
3
+ USAGE = """scanquorum <command> [options]
4
+
5
+ doctor check the install and say exactly what is missing. RUN THIS FIRST.
6
+ build <pdf> read a PDF with every installed engine, write .md + unconfirmed index
7
+ verify-ai ask a vision model about the unconfirmed places (it may only CHOOSE)
8
+ version
9
+
10
+ Docs: README.md What it cannot do: artifacts/ARTIFACTS.md
11
+ """
12
+
13
+
14
+ def main():
15
+ if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help", "help"):
16
+ print(USAGE)
17
+ return 0
18
+ cmd, rest = sys.argv[1], sys.argv[2:]
19
+ if cmd == "doctor":
20
+ from .doctor import main as m
21
+ return m(rest)
22
+ if cmd == "build":
23
+ from .build import main as m
24
+ return m(rest)
25
+ if cmd in ("verify-ai", "verify_ai"):
26
+ from .verify_ai import main as m
27
+ return m(rest)
28
+ if cmd == "version":
29
+ from . import __version__
30
+ print("scanquorum " + __version__)
31
+ return 0
32
+ print("unknown command %r\n" % cmd)
33
+ print(USAGE)
34
+ return 2
35
+
36
+
37
+ if __name__ == "__main__":
38
+ sys.exit(main())
scanquorum/build.py ADDED
@@ -0,0 +1,463 @@
1
+ # scanquorum/build.py v1.0
2
+ #
3
+ # THE PIPELINE. One PDF in; a quorum-checked text layer, a Markdown sidecar and an
4
+ # index of everything that could not be confirmed, out.
5
+ #
6
+ # python -m scanquorum build document.pdf
7
+ #
8
+ # What happens, in order:
9
+ # 1. read the text layer already in the PDF, with each word's box
10
+ # 2. run the OCR engines that are installed on this machine
11
+ # 3. for every word, ask vote.decide() what the engines collectively read
12
+ # 4. write: <name>.md clean text, provenance header, page markers
13
+ # <name>.unconfirmed.json every place a person should look at
14
+ # <name>.evidence.json every candidate from every engine
15
+ #
16
+ # DESIGN RULE THROUGHOUT: the tool reports what it could not do. A missing engine is
17
+ # printed, counted, and recorded in the sidecar header -- never silently skipped. A
18
+ # three-engine run and a four-engine run produce different confidence and the output
19
+ # has to say which one it was.
20
+ import os
21
+ import sys
22
+ import json
23
+ import time
24
+ import hashlib
25
+ import pathlib
26
+ import argparse
27
+ import collections
28
+
29
+ from . import vote
30
+ from . import layout
31
+ from . import __version__
32
+
33
+ # Module version, bumped when this file's behaviour changes. Distinct from the
34
+ # package version above on purpose: the sidecar header records both, so a reader
35
+ # who finds an odd number can tell whether the pipeline or the packaging moved.
36
+ VERSION = "1.1"
37
+
38
+ # Which engine's line boxes define the page's layout, in order of preference.
39
+ # STATED, not alphabetical -- see the note at the frame selection below. The
40
+ # first name in this list that produced boxes on a page frames that page, and
41
+ # which one it was is written into the sidecar header.
42
+ FRAME_PREFERENCE = ("rapidocr_en", "rapidocr_multi", "tesseract")
43
+
44
+
45
+ def _sha256(p):
46
+ h = hashlib.sha256()
47
+ with open(p, "rb") as f:
48
+ for chunk in iter(lambda: f.read(1 << 20), b""):
49
+ h.update(chunk)
50
+ return h.hexdigest()
51
+
52
+
53
+ def load_engines(names, pdf, dpi, progress):
54
+ """Return {engine_name: {page: {"boxes": [{"t":text,"b":bbox,"s":conf}]}}}.
55
+
56
+ An engine that is not installed is reported and omitted. It is never faked and
57
+ never silently replaced by another engine's output."""
58
+ out, missing = {}, []
59
+ for n in names:
60
+ try:
61
+ mod = __import__("scanquorum.engines." + n, fromlist=["run"])
62
+ except ImportError as e:
63
+ missing.append((n, "no adapter: %r" % e))
64
+ continue
65
+ try:
66
+ out[n] = mod.run(pdf, dpi=dpi, progress=progress)
67
+ except Exception as e:
68
+ missing.append((n, repr(e)[:120]))
69
+ return out, missing
70
+
71
+
72
+ def build(pdf, engines=("rapidocr_multi", "rapidocr_en", "tesseract"),
73
+ dpi=300, out_dir=None, lexicon=None, heartbeat=900):
74
+ import pymupdf
75
+ pdf = pathlib.Path(pdf)
76
+ out_dir = pathlib.Path(out_dir or pdf.parent)
77
+ out_dir.mkdir(parents=True, exist_ok=True)
78
+ stem = pdf.stem
79
+ t0 = time.time()
80
+ last_beat = [t0]
81
+
82
+ def progress(done, total, what=""):
83
+ """Long runs must leave a trace on disk, not only on a terminal nobody is
84
+ watching. Without this, a stalled run and a slow run look identical."""
85
+ now = time.time()
86
+ if now - last_beat[0] < heartbeat and done < total:
87
+ return
88
+ last_beat[0] = now
89
+ pct = 100.0 * done / max(total, 1)
90
+ eta = (now - t0) / max(done, 1) * (total - done) / 60.0
91
+ rec = {"stage": what, "done": done, "total": total, "percent": round(pct, 1),
92
+ "minutes_left": round(eta, 1), "finished": done >= total,
93
+ "stale_if_older_than_seconds": heartbeat * 2,
94
+ "updated": time.strftime("%Y-%m-%dT%H:%M:%S")}
95
+ (out_dir / (stem + ".progress.json")).write_text(
96
+ json.dumps(rec, indent=1), encoding="utf-8", newline="\n")
97
+ print(" [%5.1f%%] %s %d/%d ~%.0f min left" % (pct, what, done, total, eta))
98
+
99
+ doc = pymupdf.open(pdf)
100
+ meta = doc.metadata or {}
101
+ print("scanquorum build v%s" % VERSION)
102
+ print(" document : %s (%d pages)" % (pdf.name, doc.page_count))
103
+ print(" existing text layer produced by: %s / %s"
104
+ % (meta.get("producer") or "-", meta.get("creator") or "-"))
105
+
106
+ ocr, missing = load_engines(engines, pdf, dpi, progress)
107
+ # Each adapter declares whether it returns line boxes or word boxes.
108
+ # Defaulting to "line" is the safe side: a word engine mistaken for a line
109
+ # engine still aligns correctly, the reverse silently mutes the voter.
110
+ granularity = {}
111
+ for n in ocr:
112
+ mod = __import__("scanquorum.engines." + n, fromlist=["GRANULARITY"])
113
+ granularity[n] = getattr(mod, "GRANULARITY", "line")
114
+
115
+ for n, why in missing:
116
+ print(" 🔴 engine NOT available: %-16s %s" % (n, why))
117
+ used = ["pdf_layer"] + sorted(ocr)
118
+ print(" engines voting: %d (%s)" % (len(used), ", ".join(used)))
119
+ # 🔴 THIS WARNING WAS OFF BY ONE, AND AN OUTSIDE REVIEWER FOUND IT.
120
+ # `used` includes "pdf_layer", so on the commonest configuration -- Tesseract
121
+ # not installed, two RapidOCR voters present -- len(used) is exactly 3 and the
122
+ # warning never fired. That is the install most people will have, and it is
123
+ # precisely the one that needed warning: the two RapidOCR voters SHARE A
124
+ # DETECTOR, so "three engines" there is the PDF layer plus roughly one and a
125
+ # bit opinions. Counting voters is not the same as counting independence.
126
+ CORRELATED = [{"rapidocr_multi", "rapidocr_en"}]
127
+ independent = len(ocr)
128
+ for group in CORRELATED:
129
+ overlap = group & set(ocr)
130
+ if len(overlap) > 1:
131
+ independent -= len(overlap) - 1
132
+ print(" independent OCR opinions: %d (voters that do not share a detector)" % independent)
133
+ if len(ocr) < 2:
134
+ print(" âš  fewer than two OCR engines besides the PDF's own text layer.")
135
+ print(" There is no quorum here at all -- treat every word as unconfirmed.")
136
+ elif independent < 3:
137
+ print(" âš  only %d INDEPENDENT OCR opinions." % independent)
138
+ for group in CORRELATED:
139
+ if len(group & set(ocr)) > 1:
140
+ print(" %s share a text detector, so they are nearer one voter than two;"
141
+ % " and ".join(sorted(group & set(ocr))))
142
+ print(" their agreement is weaker evidence than the count suggests.")
143
+ print(" Install Tesseract for a voter that draws its own boxes.")
144
+
145
+ lex = lexicon if lexicon is not None else {}
146
+ ev, unconf, stats = [], [], collections.Counter()
147
+ frames_used = {}
148
+ pages_md = []
149
+
150
+ for pi in range(doc.page_count):
151
+ pg = doc[pi]
152
+ words = pg.get_text("words")
153
+ # 🔴 A FIFTH ORDERING DEPENDENCE, found by a third outside reviewer -- and
154
+ # this one lives OUTSIDE the voter, where the parity test cannot see it.
155
+ # This used to be `for n in sorted(ocr)`, i.e. the frame was whichever
156
+ # engine sorted first ALPHABETICALLY. The frame decides the line boxes, and
157
+ # the line boxes decide which words are compared with which, before
158
+ # decide() is ever called. So installing or removing an engine could change
159
+ # the answer for reasons that have nothing to do with what it read.
160
+ #
161
+ # Now the preference is stated, in this constant, and the engine that was
162
+ # actually used is recorded in the sidecar header -- so two runs that
163
+ # disagree can be told apart without rerunning them.
164
+ frame, frame_engine = None, None
165
+ for n in list(FRAME_PREFERENCE) + sorted(ocr):
166
+ b = ocr.get(n, {}).get(str(pi), {}).get("boxes")
167
+ if b:
168
+ frame, frame_engine = b, n
169
+ break
170
+ frames_used[frame_engine] = frames_used.get(frame_engine, 0) + 1
171
+ if frame is None:
172
+ # No OCR saw this page. Keep the existing layer, mark it unconfirmed.
173
+ for w in words:
174
+ rec = {"page": pi, "bbox": [round(x, 1) for x in w[:4]],
175
+ "pdf_layer": w[4], "chosen": vote.collapse(w[4]),
176
+ "rule": "ONLY_ONE|NO_OCR", "who": "pdf_layer"}
177
+ ev.append(rec)
178
+ unconf.append(rec)
179
+ stats["ONLY_ONE|NO_OCR"] += 1
180
+ pages_md.append((pi, " ".join(w[4] for w in words)))
181
+ progress(pi + 1, doc.page_count, "voting")
182
+ continue
183
+
184
+ cut = layout.gutter([b["b"] for b in frame], pg.rect.width)
185
+ colf = (lambda bb: 0) if cut is None else (lambda bb: 0 if (bb[0] + bb[2]) / 2 < cut else 1)
186
+ owner = layout.assign(frame, words)
187
+ idx = {n: layout.BoxIndex(ocr[n].get(str(pi), {}).get("boxes", [])) for n in ocr}
188
+ order = sorted(range(len(frame)),
189
+ key=lambda i: (colf(frame[i]["b"]), round(frame[i]["b"][1], 1), frame[i]["b"][0]))
190
+ rows, used_w = [], set()
191
+
192
+ for bi in order:
193
+ wis = sorted(owner.get(bi, []))
194
+ used_w.update(wis)
195
+ a_tok = [words[wi][4] for wi in wis]
196
+
197
+ # 🔴 GRANULARITY. Neural OCR returns LINE boxes; Tesseract returns WORD
198
+ # boxes. Looking a single word's box up in a line index gives an IoU of
199
+ # roughly word-area over line-area -- almost always under threshold --
200
+ # so the engine returns None for nearly every word and silently stops
201
+ # voting. Measured when this was wrong: VOTE4/4 collapsed from 77 % to
202
+ # 0.3 %, and VOTE2/2 rose to 76 %, i.e. two of four voters had quietly
203
+ # left the room while the output still looked healthy.
204
+ #
205
+ # So line engines are matched line-to-line and their token SEQUENCE is
206
+ # aligned against the word sequence; word engines are looked up
207
+ # directly by box.
208
+ seqs = {}
209
+ for n in sorted(ocr):
210
+ if granularity.get(n) == "word":
211
+ continue
212
+ best, bt = 0.0, None
213
+ for ob in ocr[n].get(str(pi), {}).get("boxes", []):
214
+ v = layout.iou(frame[bi]["b"], ob["b"])
215
+ if v > best:
216
+ best, bt = v, ob
217
+ toks = bt["t"].split() if (bt and best > 0.3) else []
218
+ seqs[n] = vote.align(a_tok, toks) if toks else {}
219
+
220
+ for i, wi in enumerate(wis):
221
+ w = words[wi]
222
+ box = (w[0], w[1], w[2], w[3])
223
+ cands = {"pdf_layer": w[4]}
224
+ for n in sorted(ocr):
225
+ if granularity.get(n) == "word":
226
+ cands[n] = idx[n].at(box)[0]
227
+ else:
228
+ m = seqs.get(n, {}).get(i, [])
229
+ # Exactly one aligned token, or nothing. An ambiguous
230
+ # alignment is dropped rather than guessed: comparing a
231
+ # word against its neighbour manufactures disagreement,
232
+ # and disagreement costs a person's time.
233
+ cands[n] = m[0] if len(m) == 1 else None
234
+ chosen, rule, who = vote.decide(cands, lex)
235
+ rec = {"page": pi, "bbox": [round(x, 1) for x in box], "col": colf(box),
236
+ "y": box[1], "x": box[0], "chosen": chosen, "rule": rule, "who": who}
237
+ rec.update(cands)
238
+ # 🔴 EVERY word not carried by a quorum belongs in the unconfirmed
239
+ # index -- not only the contested ones. An outside reviewer caught
240
+ # the header claiming that anything absent from this index had been
241
+ # read identically by two engines, which was false for every
242
+ # ONLY_ONE word (~340 per document: running heads, margins, gutters
243
+ # that layout analysis discards). A machine-readable warning that is
244
+ # false is worse than no warning, because it is believed.
245
+ if rule in ("DISPUTED", "MEDOID_FLAG") or rule.startswith("ONLY_ONE"):
246
+ if chosen is None:
247
+ rec["chosen"] = vote.collapse(w[4])
248
+ unconf.append(rec)
249
+ rows.append(rec)
250
+ stats[rule] += 1
251
+
252
+ for wi, w in enumerate(words):
253
+ if wi in used_w:
254
+ continue
255
+ box = (w[0], w[1], w[2], w[3])
256
+ rec = {"page": pi, "bbox": [round(x, 1) for x in box], "col": colf(box),
257
+ "y": box[1], "x": box[0], "pdf_layer": w[4],
258
+ "chosen": vote.collapse(w[4]), "rule": "ONLY_ONE|OCR_BLIND",
259
+ "who": "pdf_layer"}
260
+ rows.append(rec)
261
+ unconf.append(rec)
262
+ stats["ONLY_ONE|OCR_BLIND"] += 1
263
+
264
+ rows.sort(key=lambda r: (r["col"], round(r["y"], 1), r["x"]))
265
+ ev.extend(rows)
266
+ pages_md.append((pi, " ".join(r["chosen"] for r in rows if r["chosen"])))
267
+ progress(pi + 1, doc.page_count, "voting")
268
+
269
+ # ---------------- outputs ------------------------------------------------
270
+ # 🔴 A QUORUM OF CORRELATED VOTERS IS NOT A QUORUM. Found by a fourth outside
271
+ # reviewer, and it is sharper than the console warning fixed earlier: that one
272
+ # was about what the run PRINTS, this one is about the NUMBER itself. A 2-of-3
273
+ # majority carried by rapidocr_multi + rapidocr_en is one shared text detector
274
+ # agreeing with itself, and counting it as two independent confirmations is the
275
+ # same overstatement the tool exists to catch elsewhere.
276
+ # 🔴 A DETERMINISTIC REPAIR IS NOT A VOTE, AND THIS FIELD CALLED IT ONE.
277
+ #
278
+ # Until v1.1 `accepted_by_quorum` counted VOTE* together with SEP/NUM/LEX/
279
+ # PATTERN. Measured on the 41-page EOIR index, that is 29,160 of 29,853 words
280
+ # (97.68 %) reported as "read identically by at least two independent OCR
281
+ # engines" -- while the number of words that actually won a vote is 25,838
282
+ # (86.55 %). An eleven-point overstatement, in the machine-readable header, in
283
+ # the one field a downstream model is most likely to trust, in a tool whose
284
+ # entire pitch is that it does not overstate.
285
+ #
286
+ # LEX is the clearest case: it picks the candidate that appears in a lexicon.
287
+ # That is a dictionary breaking a tie, not a second engine agreeing. PATTERN
288
+ # is a regex doing the same. Both are defensible ways to choose; neither is
289
+ # corroboration, and the difference is the whole product.
290
+ #
291
+ # So the three buckets below PARTITION the corpus and the assert proves it.
292
+ # `classify` is deliberately total: an unrecognised rule raises instead of
293
+ # falling into a bucket, because the previous version's failure mode was
294
+ # exactly a rule quietly landing on the flattering side of the line.
295
+ # The buckets are ordered from strongest evidence to none, and the DIFFERENCE
296
+ # between the first two is the one that matters most in this corpus: `SEP`
297
+ # means the engines agreed on the digits and disagreed on the punctuation, and
298
+ # a punctuation disagreement in a case citation is `12-869` against `12369`.
299
+ # Folding that into "read identically" is precisely the claim we cannot make.
300
+ EXACT, SUBSTANCE, RULED, UNCONFIRMED = "exact", "substance", "ruled", "unconfirmed"
301
+
302
+ def classify(rule):
303
+ """Total by construction. An unrecognised rule raises rather than landing
304
+ in a bucket -- the previous version's failure was a rule quietly falling on
305
+ the flattering side of the line, so silence is the thing to forbid."""
306
+ base = rule.split("|")[0]
307
+ if base.startswith("VOTE"):
308
+ try:
309
+ k = int(base[4:].split("/")[0]) # "VOTE3/4" -> 3
310
+ except ValueError:
311
+ raise SystemExit("unparseable VOTE rule %r -- refusing to count it" % rule)
312
+ return EXACT if k >= 2 else UNCONFIRMED # k == 1 is not a quorum
313
+ if base in ("SEP", "SEP=", "NUM"):
314
+ return SUBSTANCE
315
+ if base in ("LEX", "PATTERN"):
316
+ return RULED
317
+ if base in ("DISPUTED", "MEDOID_FLAG", "ONLY_ONE", "EMPTY"):
318
+ return UNCONFIRMED
319
+ raise SystemExit(
320
+ "UNKNOWN RULE %r in the evidence. Add it to classify() in build.py and decide "
321
+ "deliberately which bucket it belongs to. Refusing to guess -- guessing here is "
322
+ "how the header came to overstate by eleven points." % rule)
323
+
324
+ counts = {EXACT: 0, SUBSTANCE: 0, RULED: 0, UNCONFIRMED: 0}
325
+ weak = 0
326
+ for r in ev:
327
+ bucket = classify(r.get("rule", ""))
328
+ counts[bucket] += 1
329
+ if bucket == EXACT:
330
+ # Weak when every engine that backed it comes from one correlated group
331
+ # and nothing outside that group agreed.
332
+ backers = set((r.get("who") or "").split(","))
333
+ for group in CORRELATED:
334
+ if backers and backers <= group:
335
+ weak += 1
336
+ break
337
+ assert sum(counts.values()) == len(ev), (
338
+ "the buckets must account for every word: %r != %d" % (counts, len(ev)))
339
+ exact, substance, ruled = counts[EXACT], counts[SUBSTANCE], counts[RULED]
340
+ unconf_n = counts[UNCONFIRMED]
341
+ # The header says "N unconfirmed, listed in <file>". That sentence is only true
342
+ # if N is the length of that file. Tying the two together in an assert is what
343
+ # makes it a fact rather than a caption -- the earlier version of this header
344
+ # named a count and a file that did not match, and nothing noticed.
345
+ assert unconf_n == len(unconf), (
346
+ "the unconfirmed index would be incomplete: %d words are unconfirmed but the index "
347
+ "holds %d. Every unconfirmed word must be listed, or the header lies about where "
348
+ "to find them." % (unconf_n, len(unconf)))
349
+ hdr = {
350
+ "source_pdf": pdf.name,
351
+ "source_sha256": _sha256(pdf),
352
+ "pages": doc.page_count,
353
+ "engines": used,
354
+ "engines_unavailable": [n for n, _ in missing],
355
+ # 🔴 THE SAME BUG CLASS, INSIDE THE FIX FOR THE SAME BUG CLASS, ONE COMMIT
356
+ # LATER. `max(frames_used, key=frames_used.get)` returns whichever key the
357
+ # dict yielded first when two engines framed an equal number of pages.
358
+ # Caught by a fifth reviewer. It is only metadata, which is exactly why it
359
+ # survived: nobody audits the field that merely records what happened.
360
+ "frame_engine": (max(sorted(frames_used.items()), key=lambda t: t[1])[0]
361
+ if frames_used else None),
362
+ "frame_engine_pages": frames_used,
363
+ "words": len(ev),
364
+ # These four sum to `words`. The assert above enforces it, and they are
365
+ # reported separately because they are NOT the same strength of evidence.
366
+ "agreed_exactly": exact,
367
+ "agreed_on_digits_not_punctuation": substance,
368
+ "chosen_by_rule_no_second_engine": ruled,
369
+ "unconfirmed": unconf_n,
370
+ "agreed_exactly_from_correlated_voters_only": weak,
371
+ "unconfirmed_index": stem + ".unconfirmed.json",
372
+ "existing_layer_producer": meta.get("producer") or "",
373
+ "generated_by": "scanquorum %s (build.py v%s)" % (__version__, VERSION),
374
+ }
375
+ warn = (
376
+ "Of the %d words in this file, %d were read IDENTICALLY by at least two independent "
377
+ "OCR engines. A further %d were read with the same digits but different punctuation "
378
+ "(the engines saw the same number and disagreed about a hyphen or a space); for a "
379
+ "case or docket citation that difference can be the difference between two documents. "
380
+ "Another %d were chosen by dictionary or by pattern with NO second engine agreeing. "
381
+ "The remaining %d are not confirmed at all and are listed in %s with page and "
382
+ "coordinates. THE BODY TEXT BELOW MARKS NONE OF THESE INLINE, so before quoting any "
383
+ "passage, check it against that index; if a word from it appears in what you are "
384
+ "about to quote, say that the word is unverified rather than presenting it as the "
385
+ "text of the document. No language model wrote or corrected any character in this file."
386
+ % (len(ev), exact, substance, ruled, unconf_n, stem + ".unconfirmed.json")
387
+ )
388
+ if len(used) < 3:
389
+ warn = ("THIS RUN HAD ONLY %d ENGINES. Nothing here is confirmed by a quorum. "
390
+ "Treat the whole file as unverified. " % len(used)) + warn
391
+
392
+ md = ["---"]
393
+ for k, v in hdr.items():
394
+ md.append("%s: %s" % (k, json.dumps(v, ensure_ascii=False) if isinstance(v, (list, dict)) else v))
395
+ md.append("warning: >")
396
+ md.append(" " + warn)
397
+ md.append("---")
398
+ md.append("")
399
+ # A human-readable line in the BODY, not only in the YAML header. A reviewer
400
+ # pointed out that the header's warning is addressed to an AI reader, and a
401
+ # person who scrolls past the front matter -- or a RAG chunker that drops it --
402
+ # sees nothing at all. One line costs nothing and closes that gap.
403
+ md.append("> **%d of the %d words below (%.2f %%) were NOT read identically by two "
404
+ "independent OCR engines.** Of those, %d are listed by page and coordinates in "
405
+ "`%s`; the rest were settled by a punctuation rule, a dictionary or a pattern."
406
+ % (len(ev) - exact, len(ev), 100.0 * (len(ev) - exact) / max(len(ev), 1),
407
+ unconf_n, stem + ".unconfirmed.json"))
408
+ md.append("> None of them is marked inline, so check that index before quoting any passage.")
409
+ md.append("")
410
+ for pi, text in pages_md:
411
+ md.append("<!-- page %d -->" % (pi + 1))
412
+ md.append(text)
413
+ md.append("")
414
+
415
+ (out_dir / (stem + ".md")).write_text("\n".join(md), encoding="utf-8", newline="\n")
416
+ (out_dir / (stem + ".unconfirmed.json")).write_text(
417
+ json.dumps(unconf, ensure_ascii=False, indent=1), encoding="utf-8", newline="\n")
418
+ (out_dir / (stem + ".evidence.json")).write_text(
419
+ json.dumps(ev, ensure_ascii=False), encoding="utf-8", newline="\n")
420
+
421
+ print("\n=== HOW EACH WORD WAS DECIDED ===")
422
+ for r, n in sorted(stats.items(), key=lambda t: -t[1]):
423
+ print(" %-22s %7d (%.2f%%)" % (r, n, 100.0 * n / max(len(ev), 1)))
424
+ tot = max(len(ev), 1)
425
+ print("\n words : %d" % len(ev))
426
+ print(" read IDENTICALLY by >=2 engines : %6d (%.2f%%) <- the only strong claim"
427
+ % (exact, 100.0 * exact / tot))
428
+ if weak:
429
+ print(" of which carried ONLY by voters that share a detector: %d (%.2f%%)"
430
+ % (weak, 100.0 * weak / max(exact, 1)))
431
+ print(" those are one opinion agreeing with itself -- weaker than the count.")
432
+ print(" same digits, different punctuation: %6d (%.2f%%)" % (substance, 100.0 * substance / tot))
433
+ print(" chosen by dictionary or pattern : %6d (%.2f%%) no second engine agreed"
434
+ % (ruled, 100.0 * ruled / tot))
435
+ print(" not confirmed, shown to you : %6d (%.2f%%)" % (unconf_n, 100.0 * unconf_n / tot))
436
+ print(" " + "-" * 62)
437
+ print(" %d + %d + %d + %d = %d" % (exact, substance, ruled, unconf_n,
438
+ exact + substance + ruled + unconf_n))
439
+ print("\n -> %s.md" % stem)
440
+ print(" -> %s.unconfirmed.json" % stem)
441
+ print(" -> %s.evidence.json" % stem)
442
+ doc.close()
443
+ return hdr
444
+
445
+
446
+ def main(argv=None):
447
+ ap = argparse.ArgumentParser(prog="scanquorum build")
448
+ ap.add_argument("pdf")
449
+ ap.add_argument("--engines", default="rapidocr_multi,rapidocr_en,tesseract")
450
+ ap.add_argument("--dpi", type=int, default=300)
451
+ ap.add_argument("--out-dir")
452
+ ap.add_argument("--lexicon", help="JSON word->count, built from the document's own text")
453
+ ap.add_argument("--heartbeat", type=int, default=900,
454
+ help="seconds between progress files (default 900 = 15 min)")
455
+ a = ap.parse_args(argv)
456
+ lex = json.loads(pathlib.Path(a.lexicon).read_text(encoding="utf-8")) if a.lexicon else {}
457
+ build(a.pdf, engines=tuple(x for x in a.engines.split(",") if x), dpi=a.dpi,
458
+ out_dir=a.out_dir, lexicon=lex, heartbeat=a.heartbeat)
459
+ return 0
460
+
461
+
462
+ if __name__ == "__main__":
463
+ sys.exit(main())