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.
@@ -0,0 +1,265 @@
1
+ # scanquorum/verify_ai.py v1.0
2
+ #
3
+ # THE AI STANDING IN FOR THE HUMAN AT THE ONE STEP THAT NEEDS EYES.
4
+ #
5
+ # When the engines cannot agree, someone has to look at the pixels. `verify_ui.py`
6
+ # opens a window and asks a person. This module asks a vision model instead, and
7
+ # it is deliberately built so that the model CANNOT do the thing that would ruin
8
+ # the document.
9
+ #
10
+ # ================= THE ONE RULE THIS FILE EXISTS TO ENFORCE ==================
11
+ #
12
+ # THE MODEL NEVER TRANSCRIBES. IT ONLY CHOOSES, OR ABSTAINS.
13
+ #
14
+ # It is shown the crop and the candidate readings the OCR engines produced, and
15
+ # it must answer with an INDEX into that list, or with "none of these". Free text
16
+ # coming back from the model is discarded, not parsed. This is enforced in code
17
+ # (`_parse_choice`), not requested in a prompt -- a prompt is a wish, and the
18
+ # whole point of this project is that a language model asked to read a scan will
19
+ # produce fluent, confident, wrong text and no downstream check will notice.
20
+ #
21
+ # So the worst case here is that the model picks the wrong engine's reading --
22
+ # a visible error of the same kind a tired person makes. It cannot invent a
23
+ # citation that no engine ever saw, because there is no code path for that.
24
+ #
25
+ # ============================ AND IT IS AUDITED =============================
26
+ #
27
+ # A model that says "yes, looks right" to everything is worse than no model, and
28
+ # it is indistinguishable from a good one unless you test for it. So every run
29
+ # includes NEGATIVE CONTROLS: a fraction of the questions are asked with the
30
+ # correct candidate REMOVED from the list. The only defensible answer is "none of
31
+ # these". The abstention rate on those controls is printed and stored.
32
+ #
33
+ # This is not hypothetical. Measured on this project's own queue, on the same
34
+ # task, with the same prompt: one model abstained on 95 % of negative controls,
35
+ # another on 46 %. The second model was confidently choosing a wrong reading half
36
+ # the time it was given no right answer. Same task, same prompt -- so the safety
37
+ # property belongs to the MODEL, not to the harness, and it has to be re-measured
38
+ # for every model you point this at. `--control-rate 0` disables it, and the run
39
+ # then reports its own verdicts as unaudited.
40
+ #
41
+ # Usage:
42
+ # python -m scanquorum.verify_ai --pending pending.json --model <id> --pages 2
43
+ #
44
+ # Secrets: the API key is read from the environment and is never printed, logged
45
+ # or written to any output file. Only its presence and length are ever reported.
46
+ import os
47
+ import re
48
+ import io
49
+ import sys
50
+ import json
51
+ import base64
52
+ import random
53
+ import pathlib
54
+ import argparse
55
+ import datetime
56
+ import urllib.request
57
+
58
+ VERSION = "1.0"
59
+ ENDPOINT = "https://openrouter.ai/api/v1/chat/completions"
60
+
61
+ SYSTEM = (
62
+ "You compare printed text on a scanned page against a short list of readings "
63
+ "produced by OCR engines. You are NOT transcribing and you must never write out "
64
+ "text of your own.\n\n"
65
+ "Answer with a single line, exactly one of:\n"
66
+ " CHOICE: <n> where <n> is the number of the reading that matches the paper\n"
67
+ " NONE if none of the listed readings matches what is printed\n\n"
68
+ "A wrong choice is worse than NONE. If the crop is unclear, if the region is cut "
69
+ "off, or if the correct reading is simply not in the list, answer NONE. You will "
70
+ "sometimes be given a list from which the correct reading has been deliberately "
71
+ "removed; NONE is the only correct answer in that case."
72
+ )
73
+
74
+
75
+ def _parse_choice(text, n_candidates):
76
+ """Accept ONLY an index or an abstention. Everything else is an abstention.
77
+
78
+ This is the safety boundary. It is a function, not a prompt instruction,
79
+ because the model does not get a vote on whether it obeys."""
80
+ if not text or not text.strip():
81
+ return None # a blank reply used to crash this
82
+ head = text.strip().splitlines()[0][:80]
83
+ # The number must be the WHOLE value, not the start of one. Without the
84
+ # trailing guard, 'CHOICE: 12-855' -- a model putting the TEXT where the
85
+ # index goes -- parses as index 12, and with twelve or more candidates that
86
+ # 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)
88
+ if m:
89
+ i = int(m.group(1))
90
+ return i if 1 <= i <= n_candidates else None
91
+ return None
92
+
93
+
94
+ def _png(pdf_path, page, bbox, dpi, pad):
95
+ import pymupdf
96
+ doc = pymupdf.open(pdf_path)
97
+ pg = doc[page]
98
+ x0, y0, x1, y1 = bbox
99
+ clip = pymupdf.Rect(max(0, x0 - pad), max(0, y0 - pad * 0.4),
100
+ min(pg.rect.width, x1 + pad), min(pg.rect.height, y1 + pad * 0.4))
101
+ pix = pg.get_pixmap(dpi=dpi, clip=clip)
102
+ out = pix.tobytes("png")
103
+ doc.close()
104
+ return out
105
+
106
+
107
+ def _page_text(pdf_path, page, radius):
108
+ """Context the model is allowed to see: the plain text of this page and up to
109
+ `radius` pages either side. It is context for judging plausibility, never a
110
+ source to copy from -- the answer format makes copying impossible."""
111
+ import pymupdf
112
+ doc = pymupdf.open(pdf_path)
113
+ lo, hi = max(0, page - radius), min(doc.page_count - 1, page + radius)
114
+ parts = []
115
+ for p in range(lo, hi + 1):
116
+ parts.append("--- page %d ---\n%s" % (p + 1, doc[p].get_text()[:6000]))
117
+ doc.close()
118
+ return "\n".join(parts)
119
+
120
+
121
+ def ask(model, key, img_png, prompt, timeout=120):
122
+ body = {
123
+ "model": model,
124
+ "messages": [
125
+ {"role": "system", "content": SYSTEM},
126
+ {"role": "user", "content": [
127
+ {"type": "text", "text": prompt},
128
+ {"type": "image_url", "image_url": {
129
+ "url": "data:image/png;base64," + base64.b64encode(img_png).decode()}},
130
+ ]},
131
+ ],
132
+ "max_tokens": 24, # an index and nothing else needs no more room
133
+ "temperature": 0,
134
+ }
135
+ req = urllib.request.Request(
136
+ ENDPOINT, data=json.dumps(body).encode(),
137
+ headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
138
+ with urllib.request.urlopen(req, timeout=timeout) as r:
139
+ j = json.loads(r.read().decode())
140
+ return j["choices"][0]["message"]["content"]
141
+
142
+
143
+ def main(argv=None):
144
+ ap = argparse.ArgumentParser(prog="scanquorum verify-ai")
145
+ ap.add_argument("--pending", required=True, help="questions written by `scanquorum check --ui`")
146
+ ap.add_argument("--pdf", help="override the source PDF path")
147
+ ap.add_argument("--model", default="qwen/qwen3.8-vl-max")
148
+ ap.add_argument("--out", default="ai_verdicts.json")
149
+ ap.add_argument("--pages", type=int, default=1,
150
+ help="pages of surrounding text to show as context (0-2)")
151
+ ap.add_argument("--dpi", type=int, default=700)
152
+ ap.add_argument("--control-rate", type=float, default=0.2,
153
+ help="fraction of questions asked with the right answer removed")
154
+ ap.add_argument("--limit", type=int, default=0)
155
+ ap.add_argument("--seed", type=int, default=17)
156
+ a = ap.parse_args(argv)
157
+
158
+ key = os.environ.get("OPENROUTER_API_KEY") or ""
159
+ if not key:
160
+ raise SystemExit("OPENROUTER_API_KEY is not set. Nothing was sent.")
161
+ print("scanquorum verify_ai v%s | model %s | key present (%d chars, never printed)"
162
+ % (VERSION, a.model, len(key)))
163
+
164
+ items = json.loads(pathlib.Path(a.pending).read_text(encoding="utf-8"))
165
+ if a.limit:
166
+ items = items[:a.limit]
167
+ rng = random.Random(a.seed)
168
+ out, ctrl_total, ctrl_abstain, decided, abstained = {}, 0, 0, 0, 0
169
+
170
+ for n, it in enumerate(items, 1):
171
+ pdf = a.pdf or it.get("pdf")
172
+ cands = list(it["candidates"])
173
+ truth = it.get("current")
174
+ is_ctrl = (rng.random() < a.control_rate and truth in cands and len(cands) > 1)
175
+ if is_ctrl:
176
+ cands = [c for c in cands if c != truth]
177
+ ctrl_total += 1
178
+
179
+ img = _png(pdf, it["page"], it["bbox"], a.dpi, 150)
180
+ ctx = _page_text(pdf, it["page"], a.pages) if a.pages else ""
181
+ lines = "\n".join(" %d. %s" % (i, c) for i, c in enumerate(cands, 1))
182
+ prompt = (
183
+ "Document: %s\nPage: %d\n\n"
184
+ "The region inside the red box on the image is a single token.\n"
185
+ "Readings proposed by the OCR engines:\n%s\n\n"
186
+ "%sWhich numbered reading matches what is printed? Answer CHOICE: <n> or NONE."
187
+ % (it.get("doc", "?"), it["page"] + 1, lines,
188
+ ("Surrounding text for context only -- do not copy from it:\n%s\n\n" % ctx[:9000]) if ctx else "")
189
+ )
190
+ try:
191
+ raw = ask(a.model, key, img, prompt)
192
+ except Exception as e:
193
+ print(" #%-4d request failed: %r" % (n, e))
194
+ continue
195
+ pick = _parse_choice(raw, len(cands))
196
+
197
+ if is_ctrl:
198
+ if pick is None:
199
+ ctrl_abstain += 1
200
+ print(" #%-4d [CONTROL] %s" % (n, "abstained (correct)" if pick is None
201
+ else "CHOSE %r WITH NO RIGHT ANSWER PRESENT" % cands[pick - 1]))
202
+ continue
203
+
204
+ if pick is None:
205
+ abstained += 1
206
+ print(" #%-4d abstained -> stays for a human" % n)
207
+ continue
208
+ decided += 1
209
+ out[it["key"]] = {
210
+ "answer": cands[pick - 1],
211
+ "when": datetime.datetime.now().isoformat(timespec="seconds"),
212
+ "source": "vision model %s, chose among engine readings" % a.model,
213
+ "doc": it.get("doc"), "page": it["page"], "bbox": it["bbox"],
214
+ "candidates": cands,
215
+ }
216
+ print(" #%-4d -> %r" % (n, cands[pick - 1]))
217
+
218
+ # 🔴 THE FILE MUST CARRY ITS OWN AUDIT RESULT. Found by an outside reviewer:
219
+ # this file used to have an identical shape whether the negative controls ran or
220
+ # not, so an operator who passed --control-rate 0 "to save tokens" produced
221
+ # something downstream code would treat exactly like an audited result. The audit
222
+ # belongs INSIDE the artefact, not only in terminal scrollback nobody keeps.
223
+ rate = (100.0 * ctrl_abstain / ctrl_total) if ctrl_total else None
224
+ audited = bool(ctrl_total) and rate >= 90
225
+ doc = {
226
+ "_audit": {
227
+ "model": a.model,
228
+ "controls_run": ctrl_total,
229
+ "controls_abstained": ctrl_abstain,
230
+ "abstention_rate_percent": None if rate is None else round(rate, 1),
231
+ "audited": audited,
232
+ "verdict": ("controls passed -- the model abstained when given no right answer"
233
+ if audited else
234
+ "NOT AUDITED -- no negative controls were run in this run"
235
+ if not ctrl_total else
236
+ "FAILED THE CONTROLS -- this model chose a reading when none was "
237
+ "correct; treat every verdict below as a suggestion for a human, "
238
+ "not as an answer"),
239
+ },
240
+ "verdicts": out,
241
+ }
242
+ pathlib.Path(a.out).write_text(json.dumps(doc, ensure_ascii=False, indent=1),
243
+ encoding="utf-8", newline="\n")
244
+
245
+ print("\n=== RESULT ===")
246
+ print(" decided by the model : %d" % decided)
247
+ print(" abstained : %d (these still need a human)" % abstained)
248
+ if ctrl_total:
249
+ rate = 100.0 * ctrl_abstain / ctrl_total
250
+ print(" negative controls : %d asked, %d abstained (%.0f %%)" % (ctrl_total, ctrl_abstain, rate))
251
+ print(" ^ this is the number that decides whether to trust the run above.")
252
+ if rate < 90:
253
+ print(" 🔴 THIS MODEL FAILS THE CONTROL. It picked a reading when none was correct")
254
+ print(" in %.0f %% of controls. Its verdicts above are not safe to accept" % (100 - rate))
255
+ print(" unattended -- treat them as suggestions for a human, not as answers.")
256
+ else:
257
+ print(" negative controls : NONE RUN -- these verdicts are unaudited.")
258
+ print("\n written to %s" % a.out)
259
+ print(" NOTE: this file is deliberately NOT the human verdict file. A person's")
260
+ print(" answer outranks a model's, and the two must never be merged silently.")
261
+ return 0
262
+
263
+
264
+ if __name__ == "__main__":
265
+ sys.exit(main())
scanquorum/vote.py ADDED
@@ -0,0 +1,295 @@
1
+ # scanquorum/vote.py v1.0
2
+ #
3
+ # THE DECISION ENGINE. Given what several independent OCR engines read at the same
4
+ # place on the page, decide what to accept -- or refuse to decide and say so.
5
+ #
6
+ # ONE INVARIANT GOVERNS EVERY RULE BELOW:
7
+ #
8
+ # No rule may return a string that no engine proposed.
9
+ #
10
+ # Every branch returns either a candidate verbatim, or a normalised form of a
11
+ # candidate, or None. Nothing here composes characters, "corrects spelling",
12
+ # or asks a language model. That is the entire reason this file can be trusted
13
+ # with a legal quotation: the worst it can do is pick the wrong engine's answer,
14
+ # which is a visible error, not an invented one.
15
+ #
16
+ # The cascade is ordered by how much evidence each rule requires, most first.
17
+ # A rule only runs when every rule above it has declined.
18
+ #
19
+ # PARITY: tests/test_vote_parity.py replays 29,853 real decisions recorded from
20
+ # the measured run and asserts this file reproduces every one of them. If you
21
+ # change anything here and that test still passes, you changed nothing that
22
+ # matters; if it fails, you changed the measured behaviour and the numbers in
23
+ # README.md no longer describe this code.
24
+ import re
25
+ import difflib
26
+ import unicodedata
27
+ import collections
28
+
29
+ VERSION = "1.0"
30
+
31
+ # Characters that different engines emit for "a dash". A citation printed as
32
+ # 12-855 comes back as 12‑855, 12–855 or 12—855 depending on the engine, and
33
+ # three spellings of the same dash look like three disagreeing engines.
34
+ DASHES = "‐‑‒–—―−­⁃·•‧・-"
35
+ TBL = {ord(c): "-" for c in DASHES}
36
+ STRIP = ".,;:()[]{}'\"`«»"
37
+
38
+ # Letter/digit confusions that every OCR engine makes, because the glyphs are
39
+ # genuinely ambiguous at 300 dpi in a 1970s typewriter face.
40
+ CONF = {"l": "1", "I": "1", "|": "1", "i": "1", "O": "0", "o": "0", "D": "0",
41
+ "S": "5", "s": "5", "B": "8", "Z": "2", "z": "2", "G": "6", "T": "7",
42
+ "q": "9", "g": "9", "A": "4", "J": "1", "b": "6"}
43
+
44
+ CIT = re.compile(r"^\d{1,2}-\d{2,4}$") # 12-855 volume-page citation
45
+ STAT = re.compile(r"^\d{2,3}(\([a-zA-Z0-9]{1,3}\))+$") # 245(a)(1) statute subsection
46
+
47
+
48
+ def norm(t):
49
+ return unicodedata.normalize("NFKC", str(t)).translate(TBL)
50
+
51
+
52
+ def collapse(t):
53
+ """Squeeze runs of the same non-alphanumeric: '3--172' and '3—172' are one token."""
54
+ return re.sub(r"([^A-Za-z0-9])\1+", r"\1", norm(t))
55
+
56
+
57
+ def key(tok):
58
+ return collapse(tok).strip(STRIP).lower()
59
+
60
+
61
+ def skel(tok):
62
+ """Only the letters and digits -- '11-911' and '11911' share a skeleton."""
63
+ return re.sub(r"[^A-Za-z0-9]", "", norm(tok)).lower()
64
+
65
+
66
+ def digitish(t):
67
+ return "".join(CONF.get(c, c) for c in collapse(t))
68
+
69
+
70
+ def ndig(t):
71
+ return sum(c.isdigit() for c in str(t))
72
+
73
+
74
+ def noise(tok):
75
+ return len(re.findall(r"[^A-Za-z0-9]", norm(tok)))
76
+
77
+
78
+ def has_sep(tok):
79
+ return bool(re.search(r"[A-Za-z0-9][^A-Za-z0-9]+[A-Za-z0-9]", norm(tok)))
80
+
81
+
82
+ def lev(a, b):
83
+ """Levenshtein distance. Used only to pick the most central candidate."""
84
+ if a == b:
85
+ return 0
86
+ prev = list(range(len(b) + 1))
87
+ for i, ca in enumerate(a, 1):
88
+ cur = [i]
89
+ for j, cb in enumerate(b, 1):
90
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
91
+ prev = cur
92
+ return prev[-1]
93
+
94
+
95
+ def pick_form(forms):
96
+ """Choose among surface forms that are ALREADY KNOWN to be the same word.
97
+
98
+ 🔴 TIE-BREAK, SITE 1 of 3. This replaces `Counter(forms).most_common(1)`,
99
+ which breaks a tie by INSERTION ORDER -- that is, by the order the engines
100
+ happen to sit in a Python dict. Measured on 11,780 real candidate sets:
101
+ 165 of them (1.40 %) changed their answer when the engines were reordered,
102
+ and 29 of those changed a DIGIT -- '12-869' against '12369', '1910' against
103
+ '1940'. In a citation index that is a different citation.
104
+
105
+ The same defect had already been found and fixed one branch below, for the
106
+ 2:2 vote split, with the note that insertion order decides "silently, and by
107
+ an accident of dict ordering". It was fixed in one place out of four.
108
+
109
+ Here the tie is NOT substantive: every form has the same `key()`, so they
110
+ differ only in punctuation that `key()` strips. Flagging 'sec' against
111
+ 'sec.' would bury the reader in noise. So this one is settled by a stated,
112
+ deterministic rule instead of by luck: fewest stray marks, then shortest,
113
+ then lexicographic. The other two sites hold genuinely different digits and
114
+ are sent to the reader instead.
115
+
116
+ 🔴 THE FIRST VERSION OF THIS FUNCTION WAS WRONG, and the parity test caught
117
+ it on its first run. It applied the tie-break to ALL the forms and ignored
118
+ how many engines backed each one -- so with 'children;' from three engines
119
+ and 'children:' from one it returned the SINGLE engine's reading, because
120
+ ':' sorts before ';'. Three engines agreeing is not a tie. Count first;
121
+ break only the tie that is actually there.
122
+ """
123
+ c = collections.Counter(forms)
124
+ best = max(c.values())
125
+ tied = [f for f in c if c[f] == best]
126
+ return min(tied, key=lambda f: (noise(f), len(f), f))
127
+
128
+
129
+ def align(pivot, other):
130
+ """Line up one engine's tokens against another's, so the same word on the page
131
+ is compared with the same word, not with its neighbour. Where the alignment is
132
+ ambiguous the candidate is dropped rather than guessed -- a mis-aligned
133
+ comparison manufactures disagreement, and disagreement costs a human's time."""
134
+ kp, ko = [key(t) for t in pivot], [key(t) for t in other]
135
+ sm = difflib.SequenceMatcher(None, kp, ko, autojunk=False)
136
+ m = {}
137
+ for op, i1, i2, j1, j2 in sm.get_opcodes():
138
+ if op == "equal" or (op == "replace" and (i2 - i1) == (j2 - j1)):
139
+ for d in range(i2 - i1):
140
+ m[i1 + d] = [other[j1 + d]]
141
+ elif op == "replace":
142
+ for d in range(i1, i2):
143
+ m[d] = other[j1:j2]
144
+ elif op == "delete":
145
+ for d in range(i1, i2):
146
+ m.setdefault(d, [])
147
+ return m
148
+
149
+
150
+ def decide(cands, lexicon):
151
+ """Return (chosen, rule, who).
152
+
153
+ `cands` maps engine name -> what that engine read here, or None if it read
154
+ nothing. `chosen` is None only when the engines cannot be reconciled, and
155
+ that is a result, not a failure: it is the tool telling you which words a
156
+ person still has to look at.
157
+ """
158
+ have = [(s, v) for s, v in cands.items() if v is not None and str(v).strip()]
159
+ if not have:
160
+ return None, "EMPTY", ""
161
+ if len(have) == 1:
162
+ return norm(have[0][1]), "ONLY_ONE", have[0][0]
163
+
164
+ # ---- 2. SEP: same digits, disagreement is only about the separator --------
165
+ # '11-911' vs '11911' vs '11-9\l'. Decided on the majority SKELETON, not on
166
+ # full equality: requiring full equality meant one damaged candidate stopped
167
+ # the rule firing even though the other two agreed.
168
+ #
169
+ # TIE-BREAK, SITE 2 of 3 -- see the note above `pick_form` below. If two
170
+ # skeleton groups are the same size, `max()` returns whichever the dict
171
+ # happened to yield first. Those groups hold DIFFERENT DIGITS, so that is a
172
+ # substantive disagreement decided by nothing. It falls through instead.
173
+ by_sk = collections.defaultdict(list)
174
+ for s, v in have:
175
+ by_sk[skel(v)].append((s, v))
176
+ sizes = sorted((len(g) for g in by_sk.values()), reverse=True)
177
+ sep_tied = len(sizes) > 1 and sizes[0] == sizes[1]
178
+ grp = max(by_sk.values(), key=len)
179
+ sk0 = skel(grp[0][1])
180
+ if not sep_tied and (len(grp) >= 2 or len(by_sk) == 1):
181
+ if sk0 and sk0.isdigit():
182
+ withs = [(s, v) for s, v in grp if has_sep(v)]
183
+ if withs:
184
+ # TIE-BREAK, SITE 4 of 4 -- found by the parity test only AFTER
185
+ # the first three were fixed, which is the argument for having
186
+ # the test at all. '9-50,' and '9.50,' both collapse to two
187
+ # stray marks and five characters, so `min` returned whichever
188
+ # the dict yielded first. The primary key stays exactly as
189
+ # measured; what follows it is how many engines wrote that form,
190
+ # then the form itself, so the result cannot depend on ordering.
191
+ cnt = collections.Counter(collapse(v) for _, v in withs)
192
+ s, v = min(withs, key=lambda t: (noise(collapse(t[1])), len(collapse(t[1])),
193
+ -cnt[collapse(t[1])], collapse(t[1])))
194
+ tag = "SEP" if len(withs) < len(grp) else "SEP="
195
+ return collapse(v), tag, ",".join(sorted(x for x, _ in withs))
196
+
197
+ # ---- 3. VOTE: a plain majority of engines read the same thing ------------
198
+ # A 2:2 split is NOT a majority. Counter.most_common would break that tie by
199
+ # insertion order -- silently, and by an accident of dict ordering. A split
200
+ # down the middle is a dispute and must fall through to the rules below.
201
+ #
202
+ # It also matters on the merits: two of the four engines share a text
203
+ # detector, so "2 against 2" is often one correlated voice against two
204
+ # independent ones rather than an even contest.
205
+ votes = collections.Counter(key(v) for _, v in have)
206
+ ranked = votes.most_common()
207
+ top, n = ranked[0]
208
+ if len(ranked) > 1 and ranked[1][1] == n:
209
+ n = 0
210
+ if n >= 2:
211
+ who = sorted(s for s, v in have if key(v) == top)
212
+ forms = [collapse(v) for s, v in have if key(v) == top]
213
+ return pick_form(forms), "VOTE%d/%d" % (n, len(have)), ",".join(who)
214
+
215
+ # ---- 4. NUM: agreement appears once l/1, O/0, S/5, B/8 are folded --------
216
+ # Among the candidates that agree after folding, keep the one that needed the
217
+ # fewest substitutions -- i.e. the engine that already read digits as digits.
218
+ #
219
+ # TIE-BREAK, SITE 3 of 3. Two digit-forms backed by the same number of
220
+ # engines is '351,' against '851,' -- a real disagreement about a real
221
+ # number. `most_common(1)` would have picked one by dict order. It falls
222
+ # through to the reader instead.
223
+ if sum(ndig(v) for _, v in have) >= 2:
224
+ dv = collections.Counter(digitish(v).strip(STRIP).lower() for _, v in have)
225
+ dranked = dv.most_common()
226
+ dtop, dn = dranked[0]
227
+ if len(dranked) > 1 and dranked[1][1] == dn:
228
+ dn = 0
229
+ if dn >= 2:
230
+ grp2 = [(s, v) for s, v in have if digitish(v).strip(STRIP).lower() == dtop]
231
+ # Same two primary keys as measured -- most digits, then fewest stray
232
+ # marks -- expressed as a `min` so that deterministic tie-breakers can
233
+ # follow them. '212(a)(28)(I)(ii);' and '212(a)(28)(I)(il);' match on
234
+ # both primary keys, and `max` was returning whichever came first.
235
+ c2 = collections.Counter(collapse(v) for _, v in grp2)
236
+ s, v = min(grp2, key=lambda t: (-ndig(t[1]), noise(t[1]),
237
+ -c2[collapse(t[1])], collapse(t[1])))
238
+ return collapse(v), "NUM", ",".join(sorted(x for x, _ in grp2))
239
+
240
+ # ---- 5. LEX: one candidate is a word this document actually uses ---------
241
+ # The lexicon is built from the document's own confident text, not from a
242
+ # dictionary, so it carries the case names and terms of art this document
243
+ # uses and nothing else.
244
+ #
245
+ # A FABRICATION PATH CLOSED HERE, named by an outside reviewer: a real
246
+ # surname absent from the lexicon ('Smythe') could be replaced by a frequent
247
+ # lexicon word ('Smith'). So LEX never touches a capitalised token -- which
248
+ # is exactly where surnames and case names live. Measured cost of the
249
+ # restriction: zero. Every LEX firing in the gold set was lower-case.
250
+ #
251
+ # Weighted by frequency, because the lexicon contains hyphenation debris
252
+ # ('los' from 'loss'), and an unweighted rule preferred the debris.
253
+ if not any(str(v)[:1].isupper() for _, v in have):
254
+ hits = sorted(((lexicon.get(key(v), 0), s, v) for s, v in have if key(v) in lexicon),
255
+ reverse=True)
256
+ if hits:
257
+ w1 = hits[0][0]
258
+ w2 = hits[1][0] if len(hits) > 1 else 0
259
+ if w1 >= 5 and w1 >= 2 * max(w2, 1) or (len(hits) == 1 and w1 >= 2):
260
+ return collapse(hits[0][2]), "LEX", hits[0][1]
261
+
262
+ # ---- 6. PATTERN: exactly one candidate has the shape of a citation ------
263
+ # A SECOND FABRICATION PATH CLOSED HERE: the SHAPE of a citation is not the
264
+ # TRUTH of a citation. '12-856' matches the pattern exactly as well as
265
+ # '12-855' does, and picking on shape alone would mint a citation to a
266
+ # decision that may not exist. So the DIGITS must additionally match at least
267
+ # one other engine: shape from one, digits from two.
268
+ pat = []
269
+ for s, v in have:
270
+ if not ((CIT.match(key(v)) or STAT.match(key(v))) and noise(norm(v)) <= 1):
271
+ continue
272
+ dv = re.sub(r"\D", "", norm(v))
273
+ if any(re.sub(r"\D", "", norm(v2)) == dv for s2, v2 in have if s2 != s):
274
+ pat.append((s, v))
275
+ if len(pat) == 1:
276
+ return collapse(pat[0][1]), "PATTERN", pat[0][0]
277
+
278
+ # ---- 7. MEDOID: propose the most central candidate, do NOT accept it -----
279
+ # A THIRD FABRICATION PATH CLOSED HERE. This rule used to decide. An outside
280
+ # reviewer pointed out that it was accepting tokens no two engines had ever
281
+ # agreed on -- unverified text entering a quotation through the back door.
282
+ # It now FLAGS instead: the token is shown to the reader, marked unconfirmed.
283
+ # The cost is a slightly longer review queue. That is the right trade for a
284
+ # quotation of law: places to look at are cheap, a wrong citation is not.
285
+ if len(have) >= 3:
286
+ vals = [collapse(v) for _, v in have]
287
+ tot = [sum(lev(vals[i], vals[j]) for j in range(len(vals)) if j != i)
288
+ for i in range(len(vals))]
289
+ mn = min(tot)
290
+ if tot.count(mn) == 1:
291
+ i = tot.index(mn)
292
+ return vals[i], "MEDOID_FLAG", have[i][0]
293
+
294
+ # ---- Nothing reconciled them. Say so. -----------------------------------
295
+ return None, "DISPUTED", ""