diff --git a/pipeline/book2corpus/__init__.py b/pipeline/book2corpus/__init__.py new file mode 100644 index 00000000..fd1ae9be --- /dev/null +++ b/pipeline/book2corpus/__init__.py @@ -0,0 +1,3 @@ +"""book2corpus: turn a textbook into a corpus an AI agent can work from.""" + +__version__ = "0.1.0" diff --git a/pipeline/book2corpus/admission.py b/pipeline/book2corpus/admission.py new file mode 100644 index 00000000..86611f8f --- /dev/null +++ b/pipeline/book2corpus/admission.py @@ -0,0 +1,631 @@ +"""Admission: the rules that decide whether a name belongs in the index. + +The model proposes names; this decides. Three things make the decision +trustworthy. Every decision carries the id of the rule that made it, so +the corpus can say how many names each rule turned away and a person can +look at the ones a rule turned away in a hurry. A rule that fails a gold +term fails loudly: the gold set is the books' own words, so the check is +in the tests and in the replay, not in someone's memory. And a name the +rules are unsure about is not dropped but held in a tier of its own, +counted apart, with a way out. + +The rules changed twice, for reasons worth keeping. The first version +banned any token shorter than three characters, and it treated a long +list of adjectives as if they were function words. It killed 9,800 of +82,922 names - among them "C fibers", "CT", "short-term memory" and +"Wernicke's area". The second version was measured against the gold +set, the books' own indexes, and the gold set found four more faults in +it: a corporate suffix read as a publisher when it was the book's own +abbreviation ("long-term depression (LTD)"), a university read as a +publisher in the middle of a real term ("Yale Attitude Change +Programme"), a modal read as a function word when it was a noun ("free +will"), and a name's own parenthetical read as part of the name. + +The tiers, per the ruling of Claude Fable 5.2 (27 Nov 2026): + admit the name is a term + quarantine the name may be a term; it is held, counted, and reviewed + reject the name is not a term + +Rules version 5. It is part of every key the stages compute. +""" +import re +import unicodedata + +RULES_VERSION = 5 + +# --- the verdicts --------------------------------------------------------- +ADMIT = "admit" +QUARANTINE = "quarantine" +REJECT = "reject" + +# --- the rule ids --------------------------------------------------------- +EMPTY = "R01_empty" +NO_TOKENS = "R02_no_tokens" +TOO_MANY_WORDS = "R03_too_many_words" +ALL_STOPWORDS = "R04_all_stopwords" +STOPWORD_OPEN = "R05_stopword_open" +STOPWORD_CLOSE = "R06_stopword_close" +HEAD_CLOSE = "R07_head_close" +SHORT_TOKEN = "R08_short_token" +PUBLISHER = "R09_publisher" +FURNITURE = "R10_furniture" +NOT_VERBATIM = "R11_not_verbatim" +LONG_NO_SHAPE = "R12a_long_without_shape" +INDEX_ONLY = "R12b_index_only" +CAPTION_ONLY = "R12c_caption_only" + +ALL_RULES = (EMPTY, NO_TOKENS, TOO_MANY_WORDS, ALL_STOPWORDS, STOPWORD_OPEN, + STOPWORD_CLOSE, HEAD_CLOSE, SHORT_TOKEN, PUBLISHER, FURNITURE, + NOT_VERBATIM, LONG_NO_SHAPE, INDEX_ONLY, CAPTION_ONLY) + +# --- the closed-class core ------------------------------------------------ +# Function words only. The first version also held "long", "short", +# "large", "small", "good", "first" and the numerals; those are content +# words, and "short-term memory" is a term. +STOPWORDS = frozenset(""" +the a an and or but of in on at to for with without from by as +is are was were be been being am +it its this that these those there here +his her their our your my me him them us they he she we you i +not no nor so if then than because while when where which who whom whose what how why +all any both each few more most other some only own same too very +can could may might must shall should will would do does did done have has had having +about per +versus vs eg ie etc +see also +""".split()) + +# The function words that may not OPEN a term. A closed list, not the +# whole core: "Me Too" and "I Am Dolphin" are titles, and the gold set +# found them. +OPEN_STOP = frozenset(""" +the a an of and or but nor if because while when where which who whom +whose what how why although though unless until since as by for from in +into on onto to with without within about above across after against along +among around at before behind below beneath beside between beyond during +except inside near off outside over past per regarding through throughout +toward towards under underneath up upon via versus vs eg ie etc than +""".split()) + +# The function words that may not END a term. Closed as well, and it is +# a shorter list than the core: "free will", "psychological well being" +# and "Generation Me" are terms, and the modal and the participle are +# nouns there. +CLOSE_STOP = frozenset(""" +the a an of and or but nor if because while when where which who whom +whose although though unless until since than that these this those there +here his her their our your my me him them us they he she we you i +is are was were be been has have had do does did done with without within +about above across after against along among around at before behind below +beneath beside between beyond during except inside near off outside over +past per regarding through throughout toward towards under underneath upon +via versus vs eg ie etc +""".split()) + +# The words that may not end a term: a term is "duty of care", not "care +# of". Only positional words belong here. "area", "point", "name" and +# "form" are real endings - "fusiform face area" is a term - and banning +# them cost 710 names. +HEAD_BLOCK = frozenset(""" +right left top bottom centre center middle front back side end edge +""".split()) + +# The words that are the furniture of a book and never a term on their +# own. They are not banned as words: "table", "figure" and "index" sit +# inside real terms ("the corruption perceptions index"). What is debris +# is a furniture word with a number after it: "Figure 3", "Table 2.1". +FURNITURE_WORDS = frozenset(""" +figure fig figs table tab page pages chapter chap appendix appendices +plate plates panel +""".split()) + +FURNITURE_LAST = frozenset(""" +contents caption glossary bibliography references preface foreword +""".split()) + +# A publisher, a place, or a phrase from the front of the book. Matched on +# WHOLE TOKENS, so "Press" is caught and "pressing" is not. The +# corporate suffixes must be written as a company writes them: the +# gold set found "long-term depression (LTD)" refused because "ltd" was +# read as a company. +PUBLISHER_PHRASES = ( + ("university", "press"), + ("publishing",), + ("publisher",), + ("routledge",), + ("palgrave",), + ("macmillan",), + ("springer",), + ("wiley",), + ("et", "al"), +) + +# These are the company forms: a company writes "Ltd", not "ltd". +PUBLISHER_EXACT = ("Ltd", "Inc", "Press", "LLP", "PLC", "Co") + +# These are places and schools. On their own they are a publisher or a +# place; inside a name they are not: "Yale Attitude Change Programme" is +# a term, and the gold set said so. +STANDALONE_PLACES = ("oxford", "harvard", "yale", "princeton", "cambridge") + +MAX_TERM_WORDS = 6 + +GREEK = set("αβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ") + +# The shapes a long name may have. A statute, a case, or a title with a +# lower-case "of" or "and" in it. +STATUTE_RE = re.compile( + r"\b(?:Act|Order|Regulations|Code|Rules|Statute)\b", re.I) +CASE_RE = re.compile(r"\bv\.?\s|\bversus\b", re.I) +TITLE_MINOR = frozenset(""" +of and the for in on to de van von der la le du dos das +""".split()) + +# The Latin words that open a real term in a law corpus. +LATIN_OPEN = frozenset(""" +in re ex vis inter intra de del della dei versus et +""".split()) + +_PUNCT = ".,;:!?()[]{}\"'*" +_LINE_BREAK_HYPHEN = re.compile(r"-[ \t]*\n[ \t]*") +_DASH = re.compile(r"[\u2010\u2011\u2012\u2013\u2014\u2212]") + + +def head_of(text): + """The name without its parenthetical. + + A name may carry an alias in brackets: "functional near-infrared + spectroscopy (fNIRS)", "unconditioned stimulus (US)", "d-prime + (d')". The alias is not part of the name, so the rules judge the + head and leave the alias alone. The gold set found the rules + refusing "MAOA (monoamine oxidase A)" because the alias ended with + a word the rules do not allow a name to end with. + """ + text = (text or "").strip() + cut = text.find("(") + if cut <= 0: + return text, "" + return text[:cut].strip(), text[cut:].strip() + + +def tokens(text): + """The tokens of a name, for the rules. + + A hyphenated compound is one token and an apostrophised word is one + token, so "omega-3 fatty acids" is three tokens and not five, and + "Wernicke's" does not leave a stranded "s". + """ + out = [] + for raw in (text or "").split(): + raw = raw.strip().strip(_PUNCT).strip("-") + if not raw: + continue + if not any(ch.isalnum() for ch in raw): + continue + out.append(raw) + return out + + +def fold(text): + """The form a name is compared by. + + NFKC, then the ligatures and the dashes a PDF or a scan makes, then + the diacritics off, then case folded. A dash becomes a space, the + way the corpus has always compared phrases, so "occipito-temporal" + and "occipitotemporal" are the same two words. + """ + if not text: + return "" + text = unicodedata.normalize("NFKC", text) + text = (text.replace("\ufb00", "ff").replace("\ufb01", "fi") + .replace("\ufb02", "fl").replace("\ufb03", "ffi") + .replace("\ufb04", "ffl")) + text = _LINE_BREAK_HYPHEN.sub("", text) + text = _DASH.sub(" ", text) + text = "".join(c for c in unicodedata.normalize("NFD", text) + if unicodedata.category(c) != "Mn") + return re.sub(r"\s+", " ", text).strip().casefold() + + +def fold_tokens(text): + """The folded words of a text: the runs of letters and digits.""" + return re.findall(r"[a-z0-9]+", fold(text)) + + +# --- the citation tier ----------------------------------------------------- +# A law book's index carries the cases it talks about and the judges who +# decided them; a psychology book carries the authors it cites. Those are +# names, not senses that two books can share: a person named in six books +# is a person, not a concept. They stay in the book's own index and are +# held back from the link stage. +# +# The rules are deliberately narrow. A shape alone is not enough: +# "vitamin A" and "Abbott J" have the same shape and different natures, +# and only the book the entry came from tells them apart. The law +# corpora corroborate a name, the books' own name indexes corroborate a +# name, and nothing else does. +# +# Every shared form the tier could touch is labelled by hand in +# tests/fixtures/citation_tier_labels.json - a person, a case, a term or +# junk - and the rules have to reproduce those labels. +CITATION_RULES_VERSION = 2 + +# a case name: a party, a standalone v, a party +CASE_SHAPE = re.compile(r"(^|\s)v\.?(\s|$)", re.I) +# the titles a judge's name carries in a law book's index +JUDGE_ABBR = frozenset(["cj", "jj", "lj", "kb", "hl", "cb", "lc", + "mr", "mrs", "dr", "sc", "pc", "ja", "pj"]) +# an initial: one letter, with the periods a name index prints +INITIAL = re.compile(r"^[A-Za-z]\.?$") +# a row of initials written without a space: "R.P.", "M.E.P." +INITIAL_ROW = re.compile(r"^([A-Za-z]\.)+[A-Za-z]?$") +# the suffixes a company carries, which are not a given name +COMPANY_SUFFIX = frozenset(["ltd", "inc", "plc", "llc", "co", + "corp", "gmbh"]) + +HELD_NONE = (False, "") +HELD_CASE = (True, "C01_case_shape") +HELD_SURNAME = (True, "C02_surname_given") +HELD_ABBR = (True, "C03_judge_abbrev") +HELD_INITIAL = (True, "C04_judge_initial") + +# a scope is a name index when this much of it is names +PEOPLE_FRACTION = 0.5 +PEOPLE_MINIMUM = 5 + + +def personal_tail(label): + """The name after a comma, when it reads as a person's name. + + "Freud, S.", "Allport, Gordon W." and "Rousseau, Jean-Jacques" + are people; "Constitution of Ireland, 1937", "Copyright, Designs + and Patents Act 1988" and "memory, working" are not. A name is a + row of words that all begin with a capital, and not a year and not + a company suffix. + """ + text = (label or "").strip() + if "," not in text: + return False + tail = text.rsplit(",", 1)[1].strip() + if not tail: + return False + words = tail.split() + if not words: + return False + if "".join(words).replace(".", "").isdigit(): + return False + for word in words: + letters = [ch for ch in word if ch.isalpha()] + if not letters or not letters[0].isupper(): + return False + if len(words) == 1: + if INITIAL_ROW.match(words[0]): + return True + if words[0].lower() in COMPANY_SUFFIX: + return False + if words[0].isupper() and len(words[0]) > 2: + return False + return True + + +def people_shaped(label): + """True when the label reads as a name, the way the books file them. + + The test is a surname with a name, or a judge's title. It does not + use the single-letter shape, so the scope census below cannot + confirm itself. + """ + text = (label or "").strip() + words = text.split() + if len(words) < 2: + return False + if personal_tail(text): + return True + return words[-1].strip(",.").lower() in JUDGE_ABBR + + +def is_people_scope(labels): + """True when a scope is the book's own name index.""" + items = list(labels) + if len(items) < PEOPLE_MINIMUM: + return False + names = sum(1 for label in items if people_shaped(label)) + return names >= PEOPLE_FRACTION * len(items) + + +def citation_tier(label, books=(), law_books=frozenset(), + people_scope=False): + """Is this entry a name rather than a sense? The answer and the rule. + + The rule id is part of the answer, so the corpus can say how many + entries each rule held back, and a person can look at them. + """ + text = (label or "").strip() + words = text.split() + if len(words) < 2: + return HELD_NONE + in_law = any(book in law_books for book in books) + if CASE_SHAPE.search(text) and not personal_tail(text): + return HELD_CASE + if personal_tail(text) and (people_scope or in_law): + return HELD_SURNAME + last = words[-1].strip(",.").lower() + if last in JUDGE_ABBR and in_law: + return HELD_ABBR + if INITIAL.match(words[-1].strip(",")) and in_law: + return HELD_INITIAL + return HELD_NONE + + +def licensed(token, attested=frozenset()): + """The licence a short token needs. + + A token shorter than three characters is debris when it is ordinary + prose - "al", "ir" - and is a term when it carries its own mark: an + acronym ("CT", "ACh"), a digit ("fNIRS", "A1"), a Greek letter, a + hyphenated compound ("co-contraction"), or a word the book itself + uses. + """ + if not token: + return False + if any(ch.isdigit() for ch in token): + return True + if any(ch in GREEK for ch in token): + return True + if any(ch.isupper() for ch in token): + return True + if "-" in token: + return True + if token.casefold() in attested: + return True + return False + + +def _is_publisher(toks, lowered): + for phrase in PUBLISHER_PHRASES: + n = len(phrase) + for i in range(len(toks) - n + 1): + if tuple(lowered[i:i + n]) == phrase: + return True + for tok in toks: + if tok in PUBLISHER_EXACT: + return True + # a place on its own is a place + if len(toks) == 1 and lowered[0] in STANDALONE_PLACES: + return True + return False + + +def _is_furniture(toks, lowered): + """The furniture of a book: a word of the apparatus and a number. + + "Figure 3" and "Table 2.1" are debris. "table" and "figure" alone + are not: "the corruption perceptions index" and "Impossible figures" + are terms. + """ + for i, tok in enumerate(lowered): + if tok in FURNITURE_WORDS: + if i + 1 < len(toks) and re.match(r"^\d", toks[i + 1]): + return True + if tok in ("appendix", "appendices") and i + 1 < len(toks) \ + and re.match(r"^[a-z]$", lowered[i + 1]): + return True + return False + + +def _has_title_shape(toks): + """A title with a lower-case "of" or "and" in it: a manual, an act.""" + minor = 0 + for tok in toks: + if tok in TITLE_MINOR: + minor += 1 + elif tok[:1].islower(): + return False + return minor > 0 and len(toks) >= 3 + + +class Profile: + """What a corpus is, and what its rules are. + + One engine, two profiles. The prose profile is English psychology + textbooks; the law profile lets a Latin word open a term ("In re"), + admits a statute or a case by its shape, and counts its own + positions. + """ + + def __init__(self, kind="prose", max_words=MAX_TERM_WORDS, + latin_open=False, structural=False, short_words=frozenset()): + self.kind = kind + self.max_words = max_words + self.latin_open = latin_open + self.structural = structural + self.short_words = short_words + + def as_dict(self): + return {"kind": self.kind, "max_words": self.max_words, + "latin_open": self.latin_open, "structural": self.structural, + "short_words": sorted(self.short_words), + "rules_version": RULES_VERSION} + + +PROSE = Profile() +LAW = Profile(kind="law", max_words=MAX_TERM_WORDS, latin_open=True, + structural=True, + short_words=frozenset(["v", "i", "ii", "iii", "iv", + "in", "re", "ex", "de", "et"])) + + +def profile_for(book, kind=None): + """The profile of a book: prose unless the caller says law.""" + return LAW if kind == "law" else PROSE + + +def admit(name, profile=PROSE, attested=frozenset(), book_text=None, + caption_text=None, index_terms=frozenset()): + """The decision on one name. + + Returns a dict with "verdict" (admit, quarantine or reject), "rule" + (the id of the rule that decided it) and "reason" (a sentence for a + person). + """ + original = (name or "").strip() + if not original: + return {"verdict": REJECT, "rule": EMPTY, + "reason": "the name is empty"} + + head, alias = head_of(original) + judged = head if head else original + toks = tokens(judged) + if not toks: + return {"verdict": REJECT, "rule": NO_TOKENS, + "reason": "the name has no tokens"} + + lowered = [t.casefold() for t in toks] + folded = fold(original) + + # the length rule. A long name needs a shape; a name the book + # indexes but the body does not carry is held for a person. + if len(toks) > profile.max_words: + if profile.structural and (STATUTE_RE.search(original) + or CASE_RE.search(original)): + pass + elif _has_title_shape(toks): + pass + elif folded in index_terms: + return {"verdict": QUARANTINE, "rule": INDEX_ONLY, + "reason": "the book indexes this name but the body " + "does not carry it"} + else: + return {"verdict": REJECT, "rule": TOO_MANY_WORDS, + "reason": "the name has %d words and no shape" + % len(toks)} + + # the stopwords are matched on the word as it stands: a capitalised + # "A" is not the article, and "The Big Bang" keeps its "The". + if all(t in STOPWORDS for t in toks): + return {"verdict": REJECT, "rule": ALL_STOPWORDS, + "reason": "every word is a function word"} + + if toks[0] in OPEN_STOP and not (profile.latin_open + and lowered[0] in LATIN_OPEN): + return {"verdict": REJECT, "rule": STOPWORD_OPEN, + "reason": "the name opens with the function word %r" % toks[0]} + + if toks[-1] in CLOSE_STOP: + return {"verdict": REJECT, "rule": STOPWORD_CLOSE, + "reason": "the name ends with the function word %r" % toks[-1]} + if lowered[-1] in HEAD_BLOCK: + return {"verdict": REJECT, "rule": HEAD_CLOSE, + "reason": "the name ends with the position word %r" % toks[-1]} + if lowered[-1] in FURNITURE_LAST: + return {"verdict": REJECT, "rule": FURNITURE, + "reason": "the name ends with the furniture word %r" % toks[-1]} + + for tok, low in zip(toks, lowered): + if tok in STOPWORDS: + continue + if len(tok) < 3 and not licensed(tok, attested) \ + and low not in profile.short_words: + return {"verdict": REJECT, "rule": SHORT_TOKEN, + "reason": "the token %r has no licence" % tok} + + if _is_publisher(toks, lowered): + return {"verdict": REJECT, "rule": PUBLISHER, + "reason": "the name is a publisher or a place"} + + if _is_furniture(toks, lowered): + return {"verdict": REJECT, "rule": FURNITURE, + "reason": "the name is the furniture of a book"} + + if book_text is not None and not book_text.contains(original): + if caption_text is not None and caption_text.contains(original): + return {"verdict": QUARANTINE, "rule": CAPTION_ONLY, + "reason": "the name occurs only in a figure caption"} + return {"verdict": REJECT, "rule": NOT_VERBATIM, + "reason": "the name does not occur in the book"} + + return {"verdict": ADMIT, "rule": "", "reason": ""} + + +def edit_distance_at_most(a, b, limit): + """True when a and b are within limit edits of each other.""" + if abs(len(a) - len(b)) > limit: + return False + previous = list(range(len(b) + 1)) + for i, ca in enumerate(a, 1): + current = [i] + best = i + for j, cb in enumerate(b, 1): + value = min(previous[j] + 1, current[j - 1] + 1, + previous[j - 1] + (ca != cb)) + current.append(value) + if value < best: + best = value + if best > limit: + return False + previous = current + return previous[-1] <= limit + + +class BookText: + """The text of a book, folded once, so every name is cheap to check. + + The lookup is exact first: the name's words must stand together, in + their own order, in the book's words. Only if that fails is the + fuzzy path used, and it allows one word of the name to be off by up + to two characters, which is what a scan does to a word. + """ + + def __init__(self, text, tolerance=2): + self.tokens = fold_tokens(text) + self.positions = {} + for i, tok in enumerate(self.tokens): + self.positions.setdefault(tok, []).append(i) + self.tolerance = tolerance + self.set = set(self.tokens) + + def _near(self, a, b): + if a == b: + return True + if len(a) < 8 or len(b) < 8: + return False + if abs(len(a) - len(b)) > self.tolerance: + return False + if a[0] != b[0] and a[-1] != b[-1]: + return False + return edit_distance_at_most(a, b, self.tolerance) + + def _exact_at(self, start, needle): + window = self.tokens[start:start + len(needle)] + return len(window) == len(needle) and window == needle + + def contains(self, name): + """Does the name occur in the book?""" + needle = fold_tokens(name) + if not needle: + return False + n = len(needle) + for i, tok in enumerate(needle): + if tok in self.positions: + for pos in self.positions[tok]: + start = pos - i + if start >= 0 and self._exact_at(start, needle): + return True + if self.tolerance <= 0: + return False + # the fuzzy path: one word may be off by a character or two + for i, tok in enumerate(needle): + if tok in self.positions: + for pos in self.positions[tok]: + for shift in (i, -i): + start = pos + shift + if start < 0: + continue + window = self.tokens[start:start + n] + if len(window) < n: + continue + bad = [k for k in range(n) if window[k] != needle[k]] + if len(bad) == 1 and self._near(needle[bad[0]], + window[bad[0]]): + return True + return False diff --git a/pipeline/book2corpus/assignment.py b/pipeline/book2corpus/assignment.py new file mode 100644 index 00000000..17be7a38 --- /dev/null +++ b/pipeline/book2corpus/assignment.py @@ -0,0 +1,170 @@ +"""Which picture is whose: an assignment, not a run of passes. + +A page holds a few figures and a few pictures, and the right answer is not +one figure at a time. Two figures can want the same picture, and a pass +that gives the picture to whichever figure it meets first is not a rule, +it is a race - and the order of the figures is the order of the notes, not +the order of the evidence. + +So the claims are written into a matrix, one row per figure and one column +per picture on that page, each claim worth its tier and its score, and the +best whole assignment of the matrix is taken. + +Then every match is asked the harder question: what was it worth against +the best alternative? Forbidding the match and settling the page again +says what the page would look like without it. A match whose alternative +is nearly as good is not a match, it is a coin toss, and a coin toss is +left unclaimed - the reader is told a picture is there and not told which. +Exact ties are left unclaimed too. + +The solver is the Hungarian algorithm for the assignment problem, written +out here so that the build needs nothing but the standard library. A page +is small, a book is very many pages, and the whole thing costs nothing. +""" + +INFINITY = float("inf") +# a weight this low is a weight that is never wanted +FORBID = 1e9 + + +def hungarian(cost): + """The cheapest assignment of rows to columns; rows <= columns. + + Returns the column index of every row, in row order. The algorithm is + the usual one: a potential for every row and every column, and the + shortest augmenting path for each row in turn. Ties go to the lowest + column index, so the answer does not depend on anything but the + matrix. + """ + rows = len(cost) + if not rows: + return [] + columns = len(cost[0]) + u = [0.0] * (rows + 1) + v = [0.0] * (columns + 1) + p = [0] * (columns + 1) # the row in each column + way = [0] * (columns + 1) # how the column was reached + for i in range(1, rows + 1): + p[0] = i + j0 = 0 + minv = [INFINITY] * (columns + 1) + used = [False] * (columns + 1) + while True: + used[j0] = True + i0 = p[j0] + delta = INFINITY + j1 = 0 + for j in range(1, columns + 1): + if used[j]: + continue + cur = cost[i0 - 1][j - 1] - u[i0] - v[j] + if cur < minv[j]: + minv[j] = cur + way[j] = j0 + if minv[j] < delta: + delta = minv[j] + j1 = j + for j in range(columns + 1): + if used[j]: + u[p[j]] += delta + v[j] -= delta + else: + minv[j] -= delta + j0 = j1 + if p[j0] == 0: + break + while True: + j1 = way[j0] + p[j0] = p[j1] + j0 = j1 + if j0 == 0: + break + out = [-1] * rows + for j in range(1, columns + 1): + if p[j]: + out[p[j] - 1] = j - 1 + return out + + +def solve(weights): + """The best assignment of a weight matrix; the column of every row.""" + cost = [[-w for w in row] for row in weights] + return hungarian(cost) + + +def _total(weights, chosen): + total = 0.0 + for row, column in enumerate(chosen): + if column >= 0: + total += weights[row][column] + return total + + +def match_page(rows, columns, edge, tier_rank, tier_step, margin): + """The claims of a page, settled. + + rows and columns are the figures and the pictures of one page, in a + canonical order. edge(row, column) returns (tier, score) when the row + claims that column, and None when it does not. + + The tiers are ordered by strength of evidence, not by how often they + happen to be right: a tier is worth tier_step, and the score inside + it is worth one, so a tier always beats a better score in a weaker + tier. Every row also gets a column of its own, worth nothing, which + is how a figure ends up with no picture at all. + + Returns a dict: row index -> what was found for that row, whether the + claim was accepted or refused. + """ + count = len(rows) + width = len(columns) + if not count or not width: + return {} + weights = [] + claims = {} + for i, row in enumerate(rows): + line = [] + for j, column in enumerate(columns): + found = edge(row, column) + if found is None: + line.append(-FORBID) + else: + tier, score = found + line.append(tier_rank.get(tier, 0) * tier_step + score) + claims[(i, j)] = found + # the column of its own: the figure is left without a picture + line.extend([0.0 if k == i else -FORBID for k in range(count)]) + weights.append(line) + + chosen = solve(weights) + best = _total(weights, chosen) + + # a row with one claim, on a column no other row claims, loses nothing + # but the claim itself: the margin is known without settling the page + # again, and the page is not settled again for nothing + claimants = {} + rows_claiming = {} + for (i, j) in claims: + claimants.setdefault(j, []).append(i) + rows_claiming[i] = rows_claiming.get(i, 0) + 1 + + out = {} + for i, j in enumerate(chosen): + if j < 0 or j >= width or (i, j) not in claims: + continue + weight = weights[i][j] + rival = None + if len(claimants.get(j, [])) == 1 and rows_claiming.get(i, 0) == 1: + loss = weight + else: + saved = weights[i][j] + weights[i][j] = -FORBID + other = solve(weights) + weights[i][j] = saved + loss = best - _total(weights, other) + if 0 <= other[i] < width and (i, other[i]) in claims: + rival = other[i] + tier, score = claims[(i, j)] + out[i] = {"column": j, "tier": tier, "score": score, + "margin": loss, "accepted": loss >= margin, "rival": rival} + return out \ No newline at end of file diff --git a/pipeline/book2corpus/batch.py b/pipeline/book2corpus/batch.py new file mode 100644 index 00000000..cb920474 --- /dev/null +++ b/pipeline/book2corpus/batch.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""book2corpus/batch.py - the bulk route: one job, many questions. + +Written 27 Nov 2026 by MCode, after the Message Batches API of Anthropic. + +A corpus of forty books has thousands of independent questions to ask: +every chapter, every term, every pair of books that shares a term. Asking +them one at a time means holding a thread pool, waiting out rate limits, +and watching a cap. The Batches API takes the whole job at once: the +requests are submitted together, they are worked through asynchronously, +and the answers come back when they are all there. + +Two things are true of it and both are worth knowing. A batched request +costs half what the same request costs on its own. And a batch lives for +a day: if it has not finished by then it is gone, so the work it carries +must be worth doing again. + +The ledger does not care how the answer arrived. The key of a judgment is +the hash of the question and the model, so an answer from a batch and an +answer asked on its own are the same answer as far as the corpus is +concerned, and a rerun that has the key does not ask again. +""" +import json +import os +import time +import urllib.error +import urllib.request + +ANTHROPIC_API = "https://api.anthropic.com/v1/messages" +BATCHES_API = "https://api.anthropic.com/v1/messages/batches" +ANTHROPIC_VERSION = "2023-06-01" + +# how long to wait between the polls, and how long to wait at all +POLL_SECONDS = 20 +POLL_LIMIT = 6 * 60 * 60 + + +def _key(path): + """The key of a service, read from the store and never printed.""" + with open(os.path.expanduser(path), encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + if ":" in line: + return line.split(":", 1)[1].strip() + return line + raise RuntimeError("no key in %s" % path) + + +def _headers(): + return {"x-api-key": _key("~/claude-keys/anthropic.header"), + "anthropic-version": ANTHROPIC_VERSION, + "content-type": "application/json"} + + +def submit(requests, model="claude-sonnet-5-5", max_tokens=1500): + """Submit the requests as one batch and return its id. + + A request is {"key": ..., "prompt": ...}: the key is the hash of the + question and the model, and it is how the answer is filed. + """ + body = {"requests": []} + for item in requests: + body["requests"].append({ + "custom_id": item["key"], + "params": { + "model": model, + "max_tokens": max_tokens, + "system": item.get("system") or "", + "messages": [{"role": "user", + "content": [{"type": "text", + "text": item["prompt"]}]}], + }, + }) + request = urllib.request.Request(BATCHES_API, + data=json.dumps(body).encode("utf-8"), + headers=_headers()) + with urllib.request.urlopen(request, timeout=120) as response: + answer = json.load(response) + return answer.get("id") + + +def status(batch_id): + """Where the batch has got to.""" + request = urllib.request.Request("%s/%s" % (BATCHES_API, batch_id), + headers=_headers()) + with urllib.request.urlopen(request, timeout=60) as response: + return json.load(response) + + +def wait(batch_id, poll=POLL_SECONDS, limit=POLL_LIMIT): + """Wait for the batch, and say how long it took.""" + started = time.time() + while time.time() - started < limit: + answer = status(batch_id) + state = answer.get("processing_status") + if state == "ended": + return answer, time.time() - started + time.sleep(poll) + raise RuntimeError("the batch did not end in time: %s" % batch_id) + + +def collect(batch_id, poll=POLL_SECONDS, limit=POLL_LIMIT): + """The answers of a finished batch, keyed by the key of the question. + + A request that failed is not an answer: it comes back as missing, and + the ledger decides what to do with missing. + """ + answer, seconds = wait(batch_id, poll, limit) + if answer.get("processing_status") != "ended": + raise RuntimeError("the batch is not finished: %s" % batch_id) + url = answer.get("results_url") + if not url: + raise RuntimeError("the batch has no results: %s" % batch_id) + request = urllib.request.Request(url, headers=_headers()) + with urllib.request.urlopen(request, timeout=300) as response: + raw = response.read().decode("utf-8") + # the results come back one object a line + results = [] + for line in raw.splitlines(): + line = line.strip() + if not line: + continue + try: + results.append(json.loads(line)) + except ValueError: + continue + out = {} + for row in results: + key = row.get("custom_id") + if not key: + continue + result = row.get("result") or {} + if result.get("type") != "succeeded": + out[key] = {"key": key, "verdict": "error", "ok": False, + "answer": None, "raw": None, + "reason": str(result.get("error") or + "the batch did not answer")[:200], + "tokens_in": 0, "tokens_out": 0} + continue + message = result.get("message") or {} + content = message.get("content") or [] + text = "".join(block.get("text", "") for block in content + if block.get("type") == "text") + usage = message.get("usage") or {} + out[key] = {"key": key, "verdict": None, "ok": True, + "answer": None, "raw": text[:1200], + "reason": "", "tokens_in": usage.get("input_tokens", 0), + "tokens_out": usage.get("output_tokens", 0)} + return out, seconds diff --git a/pipeline/book2corpus/book.py b/pipeline/book2corpus/book.py new file mode 100644 index 00000000..1a9c7843 --- /dev/null +++ b/pipeline/book2corpus/book.py @@ -0,0 +1,353 @@ +"""The pipeline: pages in, paragraphs out. + +Order matters. Chapters are found from the page bodies, because the running +head is furniture. Footnotes are split per page with the chapter's own +footnote number sequence as the constraint, because the OCR interleaves them +with the body text. Paragraphs are assembled from the marker spine, and the +mini-table-of-contents that opens each chapter is dropped and kept only as a +noisy list of headings to check the detected ones against. + +Every input line is counted, so the conservation gate can prove that no text +was lost on the way through. +""" +from collections import Counter + +from . import layout, scrub, structure +from .ir import Paragraph + + +class Book: + def __init__(self, pages, meta=None): + self.pages = pages + self.meta = meta or {} + self.chapters = [] + self.paragraphs = [] + self.footnotes = [] + # this book prints its notes at the foot of the page + self.note_layout = "foot_of_page" + # and it numbers its paragraphs: those numbers are its citation + # scheme, the way its own index and its tables of cases cite them + self.paragraph_numbering = "numbered" + self.note_anchors = [] # (note, paragraph) settled once ids exist + self.front_pages = [] + self.back_pages = [] + self.input_lines = sum(len(p.lines) for p in pages) + self.line_buckets = Counter() + self.anomalies = [] + self.spine = {"found": 0, "gaps": [], "expected_by_chapter": {}} + self._vocab = None + + # -- stages ------------------------------------------------------------ + def run(self): + for page in self.pages: + layout.split_furniture(page) + self.line_buckets["furniture"] += len(page.header_lines) + len(page.furniture) + self.chapters = structure.detect_chapters(self.pages) + titles = self._chapter_titles_from_contents() + for ch in self.chapters: + if ch.number in titles: + ch.title = titles[ch.number] + self._mark_minitoc() + self._split_footnotes() + self.hyphenated, self.joined = structure.build_vocabulary(self.pages) + for ch in self.chapters: + self._assemble(ch) + self._front_and_back() + return self + + def _chapter_titles_from_contents(self): + """The book's own contents pages list the chapters and their titles. + + They are clean where the running heads are not, so they win. + """ + import re as _re + found = {} + for page in self.pages[:60]: + for ln in page.lines: + m = _re.match(r"^Chapter\s+(\d{1,2})\s+(.{3,90})$", ln.text.strip()) + if m: + title = m.group(2).strip().rstrip(".,") + title = _re.sub(r"^[(\s]+", "", title) + if title and int(m.group(1)) not in found: + found[int(m.group(1))] = title + return found + + def _mark_minitoc(self): + """The mini-table-of-contents that opens a chapter. + + Its numbers are page references, not footnote numbers, and they poison + the footnote sequence, so they are marked and kept out of the split. + """ + self.minitoc_ids = set() + for ch in self.chapters: + page = self.pages[ch.start_leaf] + for ln in page.lines: + if structure.marker_of(ln): + break + # the chapter's first division heading sits before the first + # paragraph too, and it is real: keep it + m = structure.ROMAN_HEAD_RE.match(ln.text.strip()) + if m: + letters = [c for c in m.group(2) if c.isalpha()] + if letters and sum(1 for c in letters if c.isupper()) / len(letters) > 0.8: + ch.expected_headings.append(ln.text) + continue + self.minitoc_ids.add(id(ln)) + ch.expected_headings.append(ln.text) + ch.minitoc_dropped = len([ln for ln in page.lines if id(ln) in self.minitoc_ids]) + + def _split_footnotes(self): + """Per page, with the chapter's footnote sequence as the constraint. + + Every page is split, front and back matter included, so that no line + is left behind outside the chapter bodies. + """ + chapter_of = {} + for ch in self.chapters: + for leaf in range(ch.start_leaf, ch.end_leaf + 1): + chapter_of[leaf] = ch.number + expected_by_chapter = {} + for page in self.pages: + number = chapter_of.get(page.leaf) + if number is None: + # front and back matter: no footnote sequence to continue + layout.split_footnotes(page, expected_next=None, + exclude=self.minitoc_ids) + self.line_buckets["footnote"] += len(page.footnotes) + continue + expected = expected_by_chapter.get(number, 1) + layout.split_footnotes(page, expected_next=expected, + exclude=self.minitoc_ids) + self.line_buckets["footnote"] += len(page.footnotes) + nums = [layout.footnote_number(ln) for ln in page.footnotes] + nums = [n for n in nums if n is not None] + if nums: + expected_by_chapter[number] = max(nums) + 1 + for ln in page.footnotes: + if layout.PARAGRAPH_MARKER_RE.match(ln.text): + # a numbered paragraph inside the notes: the boundary of + # this page is wrong, and the paragraphs it swallowed are + # missing from the corpus + self.anomalies.append({"kind": "paragraph_in_notes", + "chapter": number, "leaf": page.leaf, + "marker": ln.text.strip()[:12]}) + break + + def _chapter_pages(self, ch): + return [p for p in self.pages if ch.start_leaf <= p.leaf <= ch.end_leaf] + + def _assemble(self, ch): + ch.pages = self._chapter_pages(ch) + ch.title = structure.majority_title(ch.pages, ch.title) + items = [] + for page in ch.pages: + for ln in page.body: + items.append((ln, page)) + if not items: + return + + # the mini-table-of-contents that opens the chapter is always dropped, + # whether or not a paragraph marker follows it + kept = [] + for ln, page in items: + if id(ln) in self.minitoc_ids: + self.line_buckets["dropped_minitoc"] += 1 + continue + kept.append((ln, page)) + items = kept + ch.expected_headings = [t for t in ch.expected_headings if 2 < len(t) < 120] + + section_path = [] + next_roman = 1 + current = None + + def close_current(): + nonlocal current + current = None + + for idx, (ln, page) in enumerate(items): + cand = structure.marker_candidate(ln.text) + # a marker whose chapter digit is not this chapter's is a + # cross-reference in the back matter, not the start of a + # paragraph, and must not become one + marker = structure.marker_of(ln) if (cand and cand["chapter"] == ch.number) else None + if marker: + close_current() + current = Paragraph(kind="body", chapter=ch.number, + native_marker=marker, section_path=list(section_path)) + current.leaf_start = page.leaf + current.page_start = page.printed_page + current.text = structure.strip_marker(ln.text) + current.path = list(section_path) + current.bboxes.append({"leaf": page.leaf, "x0": ln.x0, "y0": ln.y0, + "x1": ln.x1, "y1": ln.y1}) + self.paragraphs.append(current) + ch.paragraphs.append(current) + self.line_buckets["body"] += 1 + self._spine_check(ch, marker) + continue + + nxt = items[idx + 1][0] if idx + 1 < len(items) else None + nxt_is_marker = nxt is not None and structure.marker_of(nxt) is not None + pitch, right = layout.page_metrics(page)[1], max((x.x1 for x in page.lines), default=page.width) + nxt_is_heading = False + if nxt is not None and not nxt_is_marker: + # the line after the next one may be a paragraph marker, and + # that is what makes the next line a heading: a heading is + # often followed by a sub-heading, and the sub-heading by + # the paragraph it introduces + nxt2 = items[idx + 2][0] if idx + 2 < len(items) else None + nxt2_is_marker = (nxt2 is not None + and structure.marker_of(nxt2) is not None) + nxt_is_heading = bool(nxt2_is_marker and structure.is_heading_slot( + nxt, page, pitch, right, True, next_roman, False)) + heading = None + candidate = structure.division_candidate(ln.text.strip()) + if candidate: + value, raw, rest = candidate + # the chapter's own sequence decides: a division may not skip + # back, and the OCR's own variants are repaired by the sequence + if value == next_roman or (value == next_roman - 1 and "U" in raw): + title = rest if (len(rest) >= 3 and rest[:1].isupper()) else "[title not legible in the scan]" + if "\u2019" not in title and "\u2018" not in title: + title = title.rstrip("'\u201d\u2019!.").strip() + heading = ("h2", "%s. %s" % (structure.canonical_roman(next_roman), title), next_roman) + if heading is None: + heading = structure.is_heading_slot(ln, page, pitch, right, nxt_is_marker, + next_roman, nxt_is_heading) + if heading: + kind, text, value = heading + close_current() + para = Paragraph(kind="heading", text=text, chapter=ch.number, + section_path=list(section_path)) + para.level = kind + para.leaf_start = page.leaf + para.leaf_end = page.leaf + para.page_start = page.printed_page + para.page_end = page.printed_page + para.bboxes.append({"leaf": page.leaf, "x0": ln.x0, "y0": ln.y0, + "x1": ln.x1, "y1": ln.y1}) + self.paragraphs.append(para) + ch.paragraphs.append(para) + self.line_buckets["heading"] += 1 + if kind == "h2": + section_path = [text] + para.path = list(section_path) + next_roman = (value or next_roman) + 1 + else: + section_path = section_path[:1] + [text] + para.path = list(section_path) + continue + + if current is None: + # text with no paragraph marker in front of it: keep it as body + current = Paragraph(kind="body", chapter=ch.number, section_path=list(section_path)) + current.leaf_start = page.leaf + current.page_start = page.printed_page + current.text = ln.text + current.path = list(section_path) + self.paragraphs.append(current) + ch.paragraphs.append(current) + self.line_buckets["body"] += 1 + continue + current.text = structure.join_lines([current.text, ln.text], self.hyphenated, self.joined) + self.line_buckets["body"] += 1 + current.leaf_end = page.leaf + current.page_end = page.printed_page + current.bboxes.append({"leaf": page.leaf, "x0": ln.x0, "y0": ln.y0, + "x1": ln.x1, "y1": ln.y1}) + + self._footnotes_for(ch) + + def _spine_check(self, ch, marker): + parts = marker.split(".") + if int(parts[0]) != ch.number: + self.anomalies.append({"kind": "marker_chapter_mismatch", "chapter": ch.number, + "marker": marker}) + return + self.spine["found"] += 1 + tail = [int(p) for p in parts[1:]] + key = "ch%d" % ch.number + expected = self.spine["expected_by_chapter"].get(key, 0) + 1 + if tail and tail[-1] >= expected: + self.spine["expected_by_chapter"][key] = tail[-1] + else: + self.spine["gaps"].append({"chapter": ch.number, "marker": marker, "expected": expected}) + + def _footnotes_for(self, ch): + """Assign numbers and anchor the notes to paragraphs on their page.""" + page_paras = {} + for para in ch.paragraphs: + if para.kind != "body": + continue + page_paras.setdefault(para.leaf_start, []).append(para) + expected = 1 + for page in ch.pages: + if not page.footnotes: + continue + notes = [] + for ln in page.footnotes: + num = layout.footnote_number(ln) + if num is None: + if notes: + notes[-1]["text"] = structure.join_lines([notes[-1]["text"], ln.text]) + continue + use = num if abs(num - expected) <= 3 else expected + notes.append({"n": use, "text": ln.text, "anchor": "exact", + "leaf": page.leaf, "printed": page.printed_page, + "chapter": ch.number, "chapter_key": str(ch.number)}) + expected = use + 1 + clusters = len(structure.SUPERSCRIPT_RE.findall(" ".join(x.text for x in page.body))) + paras = page_paras.get(page.leaf, []) + if clusters and clusters == len(notes) and len(paras) == len(notes): + for para, note in zip(paras, notes): + note["anchor"] = "exact" + note["anchor_id"] = None + para.footnote_ids.append(note) + self.note_anchors.append((note, para)) + else: + for note in notes: + note["anchor"] = "approximate" + if paras: + paras[-1].footnote_ids.append(note) + note["anchor_id"] = None + self.note_anchors.append((note, paras[-1])) + else: + note["anchor_id"] = None + self.anomalies.append({"kind": "note_without_paragraph", + "chapter": ch.number, "leaf": page.leaf, + "number": note["n"]}) + self.footnotes.extend(notes) + + def link_footnotes(self): + """Point every note at the paragraph it belongs to. + + The paragraphs carry no ids until they are numbered, so the anchor + is settled after the numbering: until then the note knows the + paragraph but not what the paragraph is called. + """ + for note, para in self.note_anchors: + note["anchor_id"] = para.id or None + + def _front_and_back(self): + """Everything before the first chapter and after the last one.""" + if not self.chapters: + return + first = self.chapters[0].start_leaf + last = self.chapters[-1].end_leaf + self.front_pages = [p for p in self.pages if p.leaf < first] + self.back_pages = [p for p in self.pages if p.leaf > last] + for page in self.front_pages + self.back_pages: + stamped = set(id(ln) for ln in scrub.stamp_lines(page.body)) + for ln in page.body: + if id(ln) in stamped: + # the stamp of the digitisation, not the book: it goes + # in a bucket of its own, so that no line of the source + # vanishes and the conservation gate still holds + self.line_buckets["digitisation"] += 1 + continue + para = Paragraph(kind="body", text=ln.text, + leaf_start=page.leaf, leaf_end=page.leaf, + page_start=page.printed_page, page_end=page.printed_page) + self.paragraphs.append(para) + self.line_buckets["body"] += 1 diff --git a/pipeline/book2corpus/cli.py b/pipeline/book2corpus/cli.py new file mode 100644 index 00000000..8fed0a66 --- /dev/null +++ b/pipeline/book2corpus/cli.py @@ -0,0 +1,372 @@ +"""book2corpus: turn a textbook into a corpus an AI agent can work from. + + python3 -m book2corpus.cli --pages pages.jsonl --leaf-map leaf_page_map.json \ + --out --title "The title" --author "The author" --year 2001 + +The build has one rule: files are only ever outputs. Everything a stage +needs is passed to it, so no stage can read back a file an earlier build +left behind and show the wrong title, the wrong counts or an empty +contents list. The corpus is built in a temporary directory and swapped +into place at the end, so a build that fails leaves the last good corpus +alone. +""" +import argparse +import json +import os +import shutil +import sys + +from . import emit, ids, ingest, profile as profile_mod, provenance, qa, verify +from .book import Book + +EXIT_GATE = 1 +EXIT_TOOL = 2 +EXIT_EXPECTATIONS = 3 +EXIT_PROFILE = 4 + +# the files a corpus carries that the build does not produce: the committed +# expectations the build is checked against, and the hand-written citations +CARRIED = ("expectations.json", "probes.json") + + +def _expectations_summary(gates, counts, profile_summary): + """What the corpus looks like today: the numbers a change should show.""" + return { + "counts": counts, + "profile": profile_summary, + "gates": {g.name: {"status": g.status, "checked": g.checked, + "suspect_count": g.suspect_count} + for g in gates}, + "suspects": {row["gate"]: row["count"] for row in verify.collect_suspects(gates)}, + } + + +def _compare_expectations(path, summary): + """The committed expectations, and what changed against them. + + A number that moves is either a regression or an improvement, and only + a person can tell which, so the build proposes and stops. + """ + if not path or not os.path.exists(path): + return [] + with open(path, encoding="utf-8") as fh: + expected = json.load(fh) + diff = [] + for section in ("counts", "profile"): + for key, value in (expected.get(section) or {}).items(): + got = (summary.get(section) or {}).get(key) + if got != value: + diff.append("%s.%s: expected %s, got %s" % (section, key, value, got)) + for name, wanted in (expected.get("gates") or {}).items(): + got = (summary.get("gates") or {}).get(name) + if got is None: + diff.append("gates.%s: not measured any more" % name) + continue + for key, value in wanted.items(): + if got.get(key) != value: + diff.append("gates.%s.%s: expected %s, got %s" + % (name, key, value, got.get(key))) + for name, value in (expected.get("suspects") or {}).items(): + got = (summary.get("suspects") or {}).get(name) + if got != value: + diff.append("suspects.%s: expected %s, got %s" % (name, value, got)) + return diff + + +def main(argv=None): + # the rules are checked before any work: a rule that quietly stops + # matching leaves the corpus without its citation scheme, and the + # conservation gate would still pass + from . import structure + structure.self_test() + from . import selfcheck + failures = selfcheck.run() + if failures: + print("the tool's own checks failed, so no corpus was built:") + for failure in failures: + print(" - %s" % failure) + return EXIT_TOOL + + ap = argparse.ArgumentParser(prog="book2corpus") + ap.add_argument("--pages", help="pages.jsonl from the scan adapter") + ap.add_argument("--pdf", help="a born-digital PDF") + ap.add_argument("--source", choices=["scan", "digital"], default="scan") + ap.add_argument("--leaf-map", default=None, help="leaf -> printed page map") + ap.add_argument("--source-pdf", default=None, + help="the PDF a scan was made from, hashed into the manifest") + ap.add_argument("--out", required=True) + ap.add_argument("--title", default="") + ap.add_argument("--author", default="") + ap.add_argument("--year", default="") + ap.add_argument("--edition", default="") + ap.add_argument("--isbn", default="") + ap.add_argument("--source-uri", default="") + ap.add_argument("--header-band", type=float, default=None, + help="the band at the top of the page that holds the running head") + ap.add_argument("--folio-band", type=float, default=None, + help="the band at the foot of the page that holds the folio") + ap.add_argument("--front-pages", type=int, default=0, + help="the leaves of the book that are front matter") + ap.add_argument("--note-layout", default="end_of_chapter", + choices=("end_of_chapter", "foot_of_page"), + help="where the book puts its notes") + ap.add_argument("--paragraph-numbers", default=None, + help="the pattern that marks the start of the book's own numbered paragraph") + ap.add_argument("--extracts-inline", action="store_true", + help="the book sets its extracts inside the paragraph they belong to") + ap.add_argument("--skip-html", action="store_true") + ap.add_argument("--expect-update", action="store_true", + help="write the new expectations as a proposal and stop") + ap.add_argument("--expect", default=None, + help="the committed expectations to check against " + "(default: expectations.json in the output directory)") + args = ap.parse_args(argv) + + if args.source == "digital": + if not args.pdf: + ap.error("--source digital needs --pdf") + bands = {} + if args.header_band is not None: + bands["header_band"] = args.header_band + if args.folio_band is not None: + bands["folio_band"] = args.folio_band + pages = ingest.load_digital_pdf(args.pdf, **bands) + from .digital import DigitalBook + book = DigitalBook(pages, meta={"title": args.title}, + extracts_inline=args.extracts_inline, + paragraph_numbers=args.paragraph_numbers, + note_layout=args.note_layout, + front_pages=args.front_pages).run() + # a book that numbers its own paragraphs has ids of its own; + # one that does not gets ids anchored to the text + synthetic = getattr(book, "paragraph_numbering", "unnumbered") != "numbered" + else: + if not args.pages: + ap.error("--source scan needs --pages") + pages = ingest.load_scan_jsonl(args.pages) + if args.leaf_map: + ingest.apply_leaf_page_map(pages, ingest.load_leaf_page_map(args.leaf_map)) + book = Book(pages, meta={"title": args.title}) + book.run() + synthetic = False + + front_leaf = book.chapters[0].start_leaf if book.chapters else 0 + assigner = ids.IdAssigner(native=not synthetic, front_leaf=front_leaf, synthetic=synthetic) + assigner.assign(book.paragraphs, book.footnotes) + if hasattr(book, "link_footnotes"): + book.link_footnotes() + + # what kind of book this is: what the source declares, and what the book + # itself says. The two have to agree, or one of them is wrong. + declared = {"note_layout": getattr(book, "note_layout", None), + "paragraph_numbering": getattr(book, "paragraph_numbering", None)} + book_profile = profile_mod.infer_all(book, declared) + profile_summary = {key: value["value"] for key, value in book_profile.items()} + broken = [key for key, value in book_profile.items() + if key in ("note_layout", "paragraph_numbering") + and value.get("status") in ("conflict", "unknown")] + if broken: + print("the book and its source disagree about %s:" % ", ".join(broken)) + for key in broken: + print(" %s: %s" % (key, book_profile[key].get("detail", ""))) + return EXIT_PROFILE + + book_meta = {"title": args.title, "authors": [args.author] if args.author else [], + "year": args.year, "edition": args.edition, "isbn": args.isbn, + "source_uri": args.source_uri} + counts = {"paragraphs": sum(1 for p in book.paragraphs if p.kind == "body"), + "headings": sum(1 for p in book.paragraphs if p.kind == "heading"), + "footnotes": len(book.footnotes), "leaves": len(book.pages), + "chapters": len(book.chapters)} + + # the gates that need nothing written yet + gates, failed = qa.run_all(book) + + # everything is built in a temporary directory and swapped into place at + # the end, so a build that fails leaves the last good corpus alone + out = args.out.rstrip("/") + tmp = out + ".tmp" + if os.path.isdir(tmp): + shutil.rmtree(tmp) + os.makedirs(tmp) + + files = [] + p, n = emit.emit_paragraphs(book, tmp) + files.append({"name": os.path.basename(p), "records": n}) + p, n = emit.emit_footnotes(book, tmp) + files.append({"name": os.path.basename(p), "records": n}) + cdir, written = emit.emit_chapters(book, tmp) + for name, count in written: + files.append({"name": "chapters/" + name, "records": count}) + table_leaves = set() + for page in book.front_pages: + if "Table" in (page.header or ""): + table_leaves.add(page.leaf) + if table_leaves: + p, n = emit.emit_tables(book, tmp, table_leaves) + files.append({"name": os.path.basename(p), "records": n}) + outline = {"chapters": emit.build_outline(book)} + emit.emit_outline(book, tmp) + files.append({"name": "outline.json", "records": len(book.chapters)}) + + records = emit.paragraph_records(book) + notes = emit.footnote_map(book) + if not args.skip_html: + from . import html as html_mod + html_text = html_mod.build_html(records, notes, outline, book_meta, counts, + "digital" if synthetic else "scan") + with open(os.path.join(tmp, "index.html"), "w", encoding="utf-8") as fh: + fh.write(html_text) + files.append({"name": "index.html", "records": len(records)}) + + # the reader and the chapter files are checked against the corpus they + # were made from: the reader is read back from the disk, the corpus is + # the one in memory + gates, failed = qa.run_all(book, render={ + "html_text": html_text if not args.skip_html else "", + "records": records, "book_meta": book_meta, "counts": counts, + "outline": outline, "corpus_dir": tmp}) + suspects = verify.collect_suspects(gates) + + if synthetic: + known_issues = [ + "The text is the PDF's own text layer, read as the publisher set it: " + "there is no OCR noise in it, and no reading of the page image was " + "needed.", + "This book does not number its paragraphs, so the paragraph ids are " + "anchored to the text: the unit, the opening words of the paragraph " + "and a collision counter. They survive a re-split, and the ordinal " + "id each one replaced is kept as an alias.", + "A paragraph is found by its indent, so a paragraph the printer set " + "flush, or one that opens with a quotation mark, may run into the " + "paragraph before it.", + "The notes stand at the end of their chapter and are numbered again " + "in every chapter, so a note is cited by its chapter and its number.", + "The reference marks in the prose are the PDF's own superscripts, so " + "every note is tied to the paragraph that cites it.", + "Tables and figure captions are kept as their own blocks: they are " + "not prose, and the paragraph gates do not judge them.", + "A table is read as its lines, not as its columns: the text layer " + "gives the row, and where the columns fell is not known. The reader " + "shows the rows as they were extracted and says so.", + ] + id_scheme = { + "type": "anchored", + "pattern": "^c\\d{2}-[a-z0-9-]+-\\d+$|^h-\\d{2}-\\d{3}$|^fn-\\d{4}$", + "native": False, + "human_citable": True, + "citation_template": "{authors_short}, {title} ({year}), unit {unit}, para {id}, p {page_start}", + } + page_scheme = {"printed_labels": True, "coverage": 1.0, + "source": "the book's own printed labels, read from the PDF text layer"} + else: + known_issues = [ + "The text comes from a page scan, re-read line by line with Tesseract " + "at 360 dpi and merged with the PDF's own text layer, so " + "that no printed line is merged with another and no line is lost.", + "Words are missing and some are garbled: a few paragraphs end " + "mid-sentence, and the page images are in the PDF if a better reading " + "is wanted. Grade C paragraphs are the worst; check the page image " + "before quoting any of them.", + "The reference marks inside the prose are OCR garbage - they read as " + "'*®' or '***' - so a note cannot be tied to the paragraph that " + "cites it. Every note is placed on the page of its paragraph; the QA " + "report says how many are exact.", + "The notes are numbered again in every chapter, and the OCR mangles " + "some of those numbers, so a note is cited by its chapter and its " + "number rather than by one sequence for the book.", + "A few paragraph numbers are missing or used twice, because the OCR " + "read the same number in two places. The ids stay unique; the book's " + "own number may not be.", + "The tables of cases and statutes are the worst-scanned part of the " + "book: the dot leaders came through as junk and entries run together. " + "Use the page image for an exact citation.", + "The mini-table-of-contents that opens each chapter is unreadable in " + "the OCR and is dropped; the chapter headings are taken from the body " + "instead.", + ] + id_scheme = None + page_scheme = None + + if synthetic: + source_meta = {"type": "digital", "format": "pdf", + "pages": len(book.pages), + "text_origin": "the PDF's own text layer; no OCR was run", + "text_layer_sha256": emit.sha256_of_text_layer(book.pages)} + else: + source_meta = {"type": "scan", "format": "pdf", + "pages_layer_sha256": emit.sha256_of(args.pages) if args.pages else None, + "ocr_engine": "tesseract", + "ocr_origin": "page images re-read line by line, merged " + "with the PDF's own text layer"} + source_meta["isbn_check"] = provenance.check_isbn(book.pages, args.isbn) + + summary = _expectations_summary(gates, counts, profile_summary) + expect_path = args.expect or os.path.join(out, "expectations.json") + diff = _compare_expectations(expect_path, summary) + if diff and not args.expect_update: + proposed = os.path.join(out, "expectations.proposed.json") + with open(proposed, "w", encoding="utf-8") as fh: + json.dump(summary, fh, indent=2, ensure_ascii=False) + print("the corpus no longer matches its committed expectations:") + for line in diff: + print(" %s" % line) + print("proposal written to %s" % proposed) + shutil.rmtree(tmp, ignore_errors=True) + return EXIT_EXPECTATIONS + + qp = os.path.join(tmp, "qa_report.json") + with open(qp, "w", encoding="utf-8") as fh: + json.dump({"gates": [g.as_dict() for g in gates], "failed": failed, + "suspects": suspects, + "anomalies": book.anomalies[:200], + "spine_gaps": book.spine["gaps"][:200]}, fh, indent=2, ensure_ascii=False) + files.append({"name": "qa_report.json", "records": len(gates)}) + + mp, manifest = emit.build_manifest(book, tmp, gates, files, book_meta, source_meta, + known_issues=known_issues, id_scheme=id_scheme, + page_scheme=page_scheme, profile=book_profile, + environment={"dictionary": qa.dictionary_fingerprint()}) + ip, _n = emit.emit_index_md(book, tmp, gates, manifest, files) + files.append({"name": "index.md", "records": _n}) + manifest["files"] = emit.with_hashes(tmp, files) + manifest["expectations"] = summary + + # the corpus carries the files the build does not produce: the committed + # expectations and the hand-written citations + for name in CARRIED: + source = os.path.join(out, name) + if os.path.exists(source): + shutil.copy2(source, os.path.join(tmp, name)) + + emit.write_manifest(mp, manifest) + + # swap it into place + old = out + ".old" + if os.path.isdir(old): + shutil.rmtree(old) + if os.path.isdir(out): + os.rename(out, old) + os.rename(tmp, out) + if os.path.isdir(old): + shutil.rmtree(old) + + print("paragraphs: %d | headings: %d | footnotes: %d" + % (counts["paragraphs"], counts["headings"], counts["footnotes"])) + print("profile:", profile_summary) + print("buckets:", dict(book.line_buckets)) + for g in gates: + print(" %-26s %-5s %s" % (g.name, g.status, g.value)) + if suspects: + print("suspects, worst first:") + for row in suspects: + print(" %-26s %-5s %d" % (row["gate"], row["status"], row["count"])) + if failed: + print("FAILED GATES:", failed) + return EXIT_GATE + print("out:", out) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/book2corpus/counts_line.py b/pipeline/book2corpus/counts_line.py new file mode 100644 index 00000000..f8164f05 --- /dev/null +++ b/pipeline/book2corpus/counts_line.py @@ -0,0 +1,48 @@ +"""The counts line: what the reader says about the book it carries. + +One function for each kind of reader, and the renderer and the gate both +call them. The gate's independence does not come from a second +implementation of the wording - that would drift - it comes from +recomputing the numbers from the corpus and asking this module to write +them out. + +The counts are bound to the reader by an explicit attribute, +data-gate="counts", not by a class name: a class name is presentation and +presentation changes, while the gate has to keep meaning. +""" + +SEP = "\u00b7" + + +def law(counts): + """The counts of a machine corpus: its chapters, its paragraphs, its notes.""" + counts = counts or {} + return "%d chapters %s %d paragraphs %s %d footnotes" % ( + counts.get("chapters", 0), SEP, + counts.get("paragraphs", 0), SEP, + counts.get("footnotes", 0)) + + +def notes(chapters, paragraphs, figures, pictures): + """The counts of a study-notes book: what it holds and what it shows.""" + return "%d chapters %s %d paragraphs %s %d figures %s %d with pictures" % ( + chapters, SEP, paragraphs, SEP, figures, SEP, pictures) + + +def to_html(text): + """The counts as they go into the reader: the dot as an entity.""" + return (text or "").replace(SEP, "·") + + +def numbers(text): + """The numbers in a counts line, in order.""" + out, number = [], "" + for character in text or "": + if character.isdigit(): + number += character + elif number: + out.append(int(number)) + number = "" + if number: + out.append(int(number)) + return out \ No newline at end of file diff --git a/pipeline/book2corpus/debris.py b/pipeline/book2corpus/debris.py new file mode 100644 index 00000000..de8ad307 --- /dev/null +++ b/pipeline/book2corpus/debris.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""book2corpus/debris.py - the debris of a book, and the one way of asking +whether a phrase is in a text. + +Written 26 Nov 2026 by MCode, following the term index of the corpus: the +rule-based extraction was offering the corpus its own furniture as +concepts - "bottom right", "arrow pointing", "(London: Routledge, 1998)" - +so the furniture is taken out first, and the terms are taken out of what +is left. + +The principle under all of it: THE MODEL PROPOSES, CODE PROVES. A model +may say that a phrase is a term; every occurrence of it in the index is +found here, in the actual text, by code. This module holds the one rule +the whole system uses to ask whether a phrase is in a text, so the term +index, the judge and the reader cannot disagree about what "occurs" means. + +Four things are kept apart on purpose: + + the boilerplate the phrases a figure is laid out in, never concepts + the clean text the text without the furniture, with the headings and + the order of the paragraphs left standing + the sentences the text as a reader would say it, and the topic of + each of its paragraphs + the occurrence the question "is this phrase in this text", asked one + way, for the whole corpus + +Every function here is pure: the same text gives the same answer on every +run, and nothing is written, printed or asked of the network. +""" +from __future__ import annotations + +import re +import unicodedata + +# the phrases a figure is laid out in: the words of the page around the +# picture, and never the concepts of the book +FIGURE_BOILERPLATE: frozenset[str] = frozenset(( + "above", + "adapted from", + "arrow point", + "arrow pointing", + "arrow points", + "arrows", + "audio narration", + "below", + "bottom left", + "bottom right", + "caption", + "center", + "centre", + "continued", + "courtesy of", + "diagram", + "figure", + "graph", + "illustration", + "image", + "left", + "overleaf", + "page", + "photo", + "photograph", + "plate", + "right", + "see also", + "source", + "table", + "top left", + "top right", +)) + +# the dashes a printer or a PDF writer leaves inside a compound; they are +# spaces for the comparison, so "Duty-of-Care" is the phrase "duty of care" +DASH_RE = re.compile("[\u002d\u2010\u2011\u2012\u2013\u2014\u2015\u2212]") + +# the headings that open the apparatus at the end of a book +REFERENCE_HEADINGS = frozenset(( + "references", + "bibliography", + "works cited", + "further reading", + "notes", +)) + +# a citation in brackets, and a year with the letter that may follow it +CITATION_PAREN = re.compile(r"\(([^()]*)\)") +YEAR_RE = re.compile(r"(?:1[5-9]\d\d|20\d\d)[a-z]?") +BARE_YEAR_RE = re.compile(r"^\s*(?:1[5-9]\d\d|20\d\d)[a-z]?\s*$") + +# "et al." with the comma that may follow it +ET_AL_RE = re.compile(r"\bet\s+al\.[,\s]*", re.IGNORECASE) + +# the marks that end a sentence +TERMINATOR_RE = re.compile(r"[.!?]") + +# a markdown heading: the hashes, a space, and the rest of the line +HEADING_RE = re.compile(r"^(#+)[ \t]+(.*)$") + + +def _boilerplate_pattern(): + """The one pattern that finds the boilerplate, the longest phrase first.""" + parts = [] + for phrase in sorted(FIGURE_BOILERPLATE, key=lambda item: (-len(item), item)): + words = [re.escape(word) for word in phrase.split()] + parts.append(r"(? str: + """The form a phrase is compared by: folded, one space between words. + + NFKC first, so the odd letters a PDF leaves behind become the letters + they mean; then casefold, so the comparison does not care about the + case; then every dash becomes a space, so "Duty-of-Care" is the phrase + "duty of care". Nothing at all is the empty string. + """ + text = unicodedata.normalize("NFKC", text or "") + text = text.casefold() + # a word broken across two lines is one word: "work-\ning" is "working" + text = LINE_BREAK_HYPHEN.sub("", text) + text = DASH_RE.sub(" ", text) + return re.sub(r"\s+", " ", text).strip() + + +# a word: letters and digits, the marks that hang off them, and the +# possessive that follows +WORD = re.compile(r"(?:[^\W_]|[\u0300-\u036f])+(?:['\u2019][sS])?") +POSSESSIVE = re.compile(r"['\u2019][sS]$") + + +def tokenise_spans(text): + """The words of a text, with the possessives folded into their words. + + A word is the word the text means: "Alzheimer's" is "alzheimer", + and the span covers the possessive, so the gap between two words of a + term never holds one. The words are normalised, so a letter the + book writes with a combining mark is the letter the canonical has. + """ + out = [] + for match in WORD.finditer(text or ""): + word = unicodedata.normalize("NFKC", + POSSESSIVE.sub("", match.group(0))) + out.append((word.casefold(), match.start(), match.end())) + return out + + +def words_of(text): + """The words of a phrase, the way the scan reads them.""" + return [word for word, _start, _end in tokenise_spans(text)] + + +def tokenise(text: str | None) -> list[str]: + """The words of a phrase: the runs of letters and digits in it.""" + return re.findall(r"[a-z0-9]+", normalise(text)) + + +def occurs(haystack: str | None, phrase: str | None) -> bool: + """Is this phrase in this text? The one answer the whole system uses. + + The tokens of the phrase must stand together, in their own order, + inside the tokens of the text. An empty phrase is in no text at all. + """ + want = tokenise(phrase) + if not want: + return False + got = tokenise(haystack) + length = len(want) + if length > len(got): + return False + first = want[0] + for start in range(len(got)): + if got[start] == first and got[start:start + length] == want: + return True + return False + + +def clean(text: str | None) -> str: + """The text without the furniture, the citations and the apparatus. + + The case and the line structure are kept: the headings stay headings + and the paragraphs stay in their order, because a model reads this + text and has to find the places the code found. + + Three things are taken out: + + the apparatus a trailing references section, and all that follows it + the citations "et al.", "(London: Routledge, 1998)", "(2019)" + the boilerplate the phrases of FIGURE_BOILERPLATE, wherever they stand + + The assumption: the last line that is exactly one of the reference + headings opens the apparatus, so everything from that line to the end + of the text goes with it. A "Notes" line in the middle of a book + therefore takes the rest of the book with it. + """ + text = text or "" + text = _drop_references(text) + text = _drop_citations(text) + text = _drop_boilerplate(text) + return _tidy(text) + + +def sentences(text: str | None) -> list[str]: + """The sentences of a text, in order. + + A sentence ends at a full stop, a question mark or an exclamation mark + that is followed by white space or by the end of the text. A piece of + text with no terminator at all is one sentence, because a fragment is + still a sentence to a reader. + """ + parts = re.split(r"(?<=[.!?])\s+", text or "") + return [part.strip() for part in parts if part.strip()] + + +def topic_sentences(text: str | None) -> list[str]: + """The first sentence of every paragraph, in order. + + A paragraph is a run of lines with a blank line between it and the + next. Its first sentence is its topic; when the paragraph has no + terminator at all, its first line stands in for it, cut at 300 + characters. + """ + out = [] + for block in re.split(r"\n[ \t\r]*\n", text or ""): + block = block.strip() + if not block: + continue + if TERMINATOR_RE.search(block): + first = sentences(block)[0] + else: + first = block.split("\n")[0].strip()[:300] + if first: + out.append(first) + return out + + +def headings(text: str | None) -> list[dict]: + """The markdown headings of a text, in order. + + The level is the number of the hashes; the text is the rest of the + line, without the hashes and without its trailing spaces. + """ + out = [] + for line in (text or "").split("\n"): + match = HEADING_RE.match(line) + if match: + out.append({"level": len(match.group(1)), "text": match.group(2).strip()}) + return out + + +def _drop_references(text): + """The text without the trailing references section.""" + lines = text.split("\n") + cut = None + for index, line in enumerate(lines): + label = line.strip().lstrip("#").strip() + if label.rstrip(":").strip().lower() in REFERENCE_HEADINGS: + cut = index + if cut is None: + return text + return "\n".join(lines[:cut]) + + +def _drop_citations(text): + """The text without the citations in brackets and without "et al.".""" + text = CITATION_PAREN.sub(_citation_removed, text) + return ET_AL_RE.sub(" ", text) + + +def _citation_removed(match): + """One bracket of text: gone when it holds a citation, kept when not.""" + inner = match.group(1) + if BARE_YEAR_RE.match(inner): + return " " + if YEAR_RE.search(inner) and ("," in inner or ":" in inner): + return " " + return match.group(0) + + +def _drop_boilerplate(text): + """The text without the phrases a figure is laid out in.""" + return BOILERPLATE_RE.sub(" ", text) + + +def _tidy(text): + """The white space that is left behind, tidied; the lines kept.""" + lines = [] + for line in text.split("\n"): + line = re.sub(r"[ \t]+", " ", line) + line = re.sub(r"^([ \t]*)([:;,])[ \t]+", r"\1", line) + line = re.sub(r"^([ \t]*)([:;,])[ \t]*$", r"\1", line) + line = re.sub(r"[ \t]+([,.;:!?)\]])", r"\1", line) + line = re.sub(r"([(\[])[ \t]+", r"\1", line) + lines.append(line.strip()) + return "\n".join(lines) diff --git a/pipeline/book2corpus/digital.py b/pipeline/book2corpus/digital.py new file mode 100644 index 00000000..290290d0 --- /dev/null +++ b/pipeline/book2corpus/digital.py @@ -0,0 +1,546 @@ +"""Structure for a born-digital book. + +A digital book gives more than a scan does: real fonts, real indents and a +clean text layer, so the rules are sharper. The contents page is clean too, +so it supplies the units of the book, their titles and where each begins. +Section headings are the bold display face. A paragraph is a run of lines +that share an indent, and which indent means "a new paragraph" depends on +whether the unit is prose or a list. The notes are numbered at the end of +each chapter, and the reference mark in the prose names the note it belongs +to. +""" +import re +from collections import Counter + +from . import scrub, structure +from .ir import Chapter, Line, Paragraph + +ENDNOTE_RE = re.compile(r"^([0-9]{1,4})\.\s*\t?\s*(.*)$", re.S) +CHAPTER_NO_RE = re.compile(r"^Chapter\s+([0-9]{1,2})$") +HEAD_FONTS = ("Palatino-Bold", "Palatino-BoldItalic", + "TimesNewRomanPS-Bold", "TimesNewRomanPS-BoldItalic", + "Times-Bold", "Times-BoldItalic") +# the fonts a display line can be set in: the psychology books are set in +# Palatino, the law books in Times +DISPLAY_FONTS = ("Palatino", "TimesNewRomanPS", "Times") +# how much bigger than the body a display line is. A book whose body is +# set in a face we do not know gets its threshold from its own body. +DISPLAY_FACTOR = 1.4 +# a line of dot leaders is an entry in a list of contents +CONTENTS_RE = re.compile(r"\.{3,}") +TABLE_FONTS = ("Optima", "Optima-Bold", "Optima-Oblique") +DISPLAY_SIZE = 12.0 +INDENT_SLACK = 3.0 + +# what a unit is in the book +PROSE = "prose" # running prose: the chapters and the preface +FRONT = "front" # the lists that come before the book +BACK = "back" # the lists that come after it +APPENDIX = "appendix" # the appendices + +# a unit whose title says it is a list of things rather than prose +LIST_TITLE_RE = re.compile(r"^(list of|index\b|references\b|about the|supplemental)", re.I) +# front matter that is still prose +PROSE_TITLE_RE = re.compile(r"^(preface|foreword|introduction|acknowledg)", re.I) +# a line that is nothing but a list of page numbers +PAGE_LIST_RE = re.compile(r"^[0-9,\u2013\u2014\s]+$") + + +def _lines_by_leaf(items): + """The lines of a chapter, gathered by the page they are on.""" + out = {} + for line, page, margin in items: + out.setdefault(page.leaf, []).append(line) + return out + + +def _display_size(body_size, body_font): + """The size at which a line is display rather than text. + + The books we know are set in Palatino, and their display type starts + at twelve points. A book set in another face gets the threshold from + its own body, so that its headings are read as headings. + """ + if body_font and body_font.startswith("Palatino"): + return DISPLAY_SIZE + return max(DISPLAY_SIZE, (body_size or 0) * DISPLAY_FACTOR) + + +def _is_heading(line, display_size=None): + if not line.font.startswith(HEAD_FONTS): + return False + if line.size >= (display_size or DISPLAY_SIZE): + return False + return True + + +def _merge_headings(items): + """A heading that wraps over two lines is one heading.""" + out = [] + for item in items: + line, page, margin = item + if (out and _is_heading(line) and _is_heading(out[-1][0]) + and out[-1][1] is page and abs(out[-1][0].y1 - line.y0) < 40): + prev = out[-1][0] + merged = Line(text=prev.text.rstrip() + " " + line.text.strip(), + x0=prev.x0, x1=line.x1, + y0=prev.y0, y1=line.y1, size=max(prev.size, line.size), + font=prev.font, lead=prev.lead or line.lead, + sources=prev.sources + line.sources, + marks=list(prev.marks) + list(line.marks)) + out[-1] = (merged, page, margin) + continue + out.append(item) + return out + + +def _mostly_upper(text): + """Level one headings are set in capitals; level two in ordinary case.""" + letters = [c for c in text if c.isalpha()] + if not letters: + return False + return sum(1 for c in letters if c.isupper()) / len(letters) > 0.8 + + +def _is_display(line, display_size=None): + if not line.font.startswith(DISPLAY_FONTS): + return False + return line.size >= (display_size or DISPLAY_SIZE) + + +def _left_margin(lines): + """The text block's left edge. + + The leftmost of the two commonest line starts: a paragraph's first line + and its continuation lines sit at two different indents, and the block's + edge is the left of the two. The minimum over all the lines would be + wrong, because a centred heading sits further left than the text. + """ + xs = Counter(round(ln.x0, 1) for ln in lines if ln.x0 > 40) + if not xs: + return 0.0 + top = [x for x, _ in xs.most_common(2)] + return min(top) + + +def _role_of(label, title, before_first, after_last): + """What kind of unit this is: prose, a list, or an appendix.""" + if label.startswith("Appendix"): + return APPENDIX + if PROSE_TITLE_RE.match(title): + return PROSE + if LIST_TITLE_RE.match(title): + return BACK if not before_first else FRONT + if before_first: + return FRONT + if after_last: + return BACK + return PROSE + + +class DigitalBook: + """The same surface as Book, built from a born-digital text layer.""" + + def __init__(self, pages, meta=None, extracts_inline=False, + front_pages=0, + note_layout="end_of_chapter", + paragraph_numbers=None): + self.pages = pages + # a book may set its extracts inside the paragraph they belong to + self.extracts_inline = extracts_inline + # a book may print its contents and its tables before the text + self.front_leaf_count = front_pages + # a book that numbers its own paragraphs says where they begin + self.paragraph_numbers = (re.compile(paragraph_numbers) + if paragraph_numbers else None) + self.meta = meta or {} + self.chapters = [] + self.paragraphs = [] + self.footnotes = [] + # this book prints its notes at the end of the chapter + self.note_layout = note_layout + # and it does not number its paragraphs: it has no citation scheme + # of its own, so the ids are synthetic + self.paragraph_numbering = ("numbered" if paragraph_numbers else "unnumbered") + self.front_pages = [] + self.back_pages = [] + self.input_lines = sum(len(p.lines) for p in pages) + self.line_buckets = Counter() + self.anomalies = [] + self.pending_marks = [] # (paragraph, number) resolved once ids exist + self.spine = {"found": 0, "gaps": [], "expected_by_chapter": {}} + + def run(self): + self._find_chapters() + self._assemble() + self._front_and_back() + return self + + # -- chapters ---------------------------------------------------------- + def _contents_entries(self): + """(label, title, page) for every unit the contents page lists. + + A title that wraps over several lines is still one entry: the lines + are gathered until the line that gives the page number. + """ + items = [] + pending = [] + for page in self._contents_pages(): + for line in page.lines: + text = line.text.rstrip("\n").replace("\ufeff", "").strip() + if not text: + continue + if _is_display(line): + continue # the title of the contents page itself + page_label = (re.fullmatch(r"[0-9]{1,4}", text) + or re.fullmatch(r"[ivxlcdm]{1,7}", text, re.I)) + if page_label and pending: + items.append((pending, text)) + pending = [] + continue + if page_label: + continue # the folio of the contents page + # the number of a chapter entry is set in bold and its title + # in roman, so the leading face is what says "chapter" + pending.append((text, line.lead or line.font)) + out = [] + for lines, page in items: + joined = " ".join(t.replace("\t", " ") for t, _ in lines).strip() + bold = "Bold" in lines[0][1] + label, title = "", joined + m = re.match(r"^([0-9]{1,2})\s+(.*)$", joined) + if bold and m: + label, title = "Chapter %s" % m.group(1), m.group(2).strip() + else: + m = re.match(r"^(Appendix [A-Z])\s*:?\s*(.*)$", joined) + if m: + label, title = m.group(1), m.group(2).strip() + out.append((label, title, page)) + return out + + def _contents_pages(self): + """The pages the contents run over, found from the 'Contents' title. + + The run ends at the next page with a title of its own: the list of + figures and the list of tables are separate lists, not part of the + contents. + """ + index = None + for i, page in enumerate(self.pages[:40]): + if page.header.replace("\ufeff", "").strip().lower() == "contents": + index = i + break + if index is None: + for i, page in enumerate(self.pages[:40]): + if _display_title(page).lower() == "contents": + index = i + break + if index is None: + return [] + + def tabs(page): + return sum(1 for ln in page.lines if "\t" in ln.text) + + start = index + while start - 1 >= 0 and tabs(self.pages[start - 1]): + start -= 1 + end = index + while end + 1 < len(self.pages): + nxt = self.pages[end + 1] + title = _display_title(nxt) + if title and title.lower() != "contents": + break # the list of figures or the list of tables + head = nxt.header.replace("\ufeff", "").strip().lower() + if head and head != "contents": + break + if tabs(nxt) or not nxt.lines: + end += 1 + continue + break + return self.pages[start:end + 1] + + def _find_chapters(self): + """The units of the book, taken from the contents page.""" + folio = {} + for page in self.pages: + if page.printed_page: + folio.setdefault(str(page.printed_page).strip().lower(), page.leaf) + entries = self._contents_entries() + if not entries: + return self._chapters_from_display() + + first = last = None + for i, (label, title, page) in enumerate(entries): + if label.startswith("Chapter"): + if first is None: + first = i + last = i + if first is None: + first = last = 0 + + units = [] + for i, (label, title, page) in enumerate(entries): + leaf = folio.get(str(page).strip().lower()) + if leaf is None: + self.anomalies.append({"kind": "contents_page_not_found", + "title": title, "page": page}) + continue + role = _role_of(label, title, i < first, i > last) + units.append((leaf, label, title, role)) + units.sort(key=lambda u: u[0]) + + for index, (leaf, label, title, role) in enumerate(units): + end = (units[index + 1][0] - 1 if index + 1 < len(units) + else len(self.pages) - 1) + ch = Chapter(number=index + 1, title=title, + start_leaf=leaf, end_leaf=end) + ch.label = label + ch.expected_headings = [] if role == PROSE else [role] + self.chapters.append(ch) + + def _chapters_from_display(self): + """Fallback: find 'Chapter N' on the page and read the title beside it.""" + starts = [] + for page in self.pages: + number = None + title = "" + for line in page.lines: + text = line.text.strip().lstrip("\ufeff") + if number is None and CHAPTER_NO_RE.match(text) and _is_display(line): + number = int(CHAPTER_NO_RE.match(text).group(1)) + continue + if number is not None and _is_display(line) and not title: + title = text + break + if number is not None: + starts.append((number, title, page.leaf)) + for index, (number, title, leaf) in enumerate(starts): + end = starts[index + 1][2] - 1 if index + 1 < len(starts) else len(self.pages) - 1 + self.chapters.append(Chapter(number=number, title=title, start_leaf=leaf, end_leaf=end)) + + def _chapter_pages(self, ch): + return [p for p in self.pages if ch.start_leaf <= p.leaf <= ch.end_leaf] + + # -- paragraphs -------------------------------------------------------- + def _assemble(self): + for ch in self.chapters: + ch.pages = self._chapter_pages(ch) + items = [] + for page in ch.pages: + margin = _left_margin(page.lines) + for line in page.lines: + items.append((line, page, margin)) + self._chapter_text(ch, _merge_headings(items)) + + def _chapter_text(self, ch, items): + roles = set(ch.expected_headings) + flags = [r for r in ("appendix", "front", "back") if r in roles] + # a list hangs its entries: the entry itself is flush and its + # continuation lines are indented. Prose does the opposite. + hanging = bool(roles & {"front", "back"}) + # the body's own type size: a block quotation is set smaller + sizes = Counter(round(l.size, 1) for l, p, m in items + if not _is_display(l) and not l.font.startswith(TABLE_FONTS)) + body_size = sizes.most_common(1)[0][0] if sizes else 0 + body_fonts = Counter(l.font for l, p, m in items + if not _is_display(l) + and not l.font.startswith(TABLE_FONTS)) + body_font = body_fonts.most_common(1)[0][0] if body_fonts else "" + display_size = _display_size(body_size, body_font) + + # a page may be set in a smaller body than the rest of the + # chapter - a page of nothing but citations - so the size that + # tells a quotation from the text is the page's own + page_sizes = {} + for leaf, leaf_lines in _lines_by_leaf(items).items(): + counter = Counter(round(l.size, 1) for l in leaf_lines + if not _is_display(l) + and not l.font.startswith(TABLE_FONTS)) + if counter: + page_sizes[leaf] = counter.most_common(1)[0][0] + section = [] + current = None + prev_indented = None + in_notes = False + note = None + expected = 1 + + for line, page, margin in items: + text = line.text.strip().lstrip("\ufeff") + marker = None + if not text: + continue + if _is_display(line, display_size): + self.line_buckets["furniture"] += 1 + continue + if line.font.startswith(TABLE_FONTS): + # a table or a figure caption: kept, but not prose. It does + # not end the paragraph it stands beside: a figure at the top + # of a page carries on the paragraph from the page before. + para = Paragraph(kind="table", text=text, chapter=ch.number) + para.leaf_start = page.leaf + para.leaf_end = page.leaf + para.page_start = page.printed_page + para.page_end = page.printed_page + para.flags = list(flags) + self.paragraphs.append(para) + ch.paragraphs.append(para) + self.line_buckets["table"] += 1 + continue + + if in_notes: + m = ENDNOTE_RE.match(text) + if m and int(m.group(1)) == expected: + note = {"n": int(m.group(1)), "text": m.group(2).strip(), + "anchor": "exact", "leaf": page.leaf, + "printed": page.printed_page, "chapter": ch.number, + "chapter_key": str(ch.number)} + self.footnotes.append(note) + expected += 1 + self.line_buckets["footnote"] += 1 + elif note is not None: + note["text"] = structure.join_lines([note["text"], text], strict=True) + self.line_buckets["footnote"] += 1 + else: + self.line_buckets["furniture"] += 1 + continue + + if _is_heading(line, display_size): + current = None + if text.strip().upper() == "NOTES" and not (roles & {"front", "back"}): + # the notes of this chapter start here + in_notes = True + expected = 1 + note = None + level = "h2" if _mostly_upper(text) else "h3" + para = Paragraph(kind="heading", text=text, chapter=ch.number, + section_path=list(section)) + para.level = level + para.path = [text] + para.leaf_start = page.leaf + para.leaf_end = page.leaf + para.page_start = page.printed_page + para.page_end = page.printed_page + para.flags = list(flags) + self.paragraphs.append(para) + ch.paragraphs.append(para) + self.line_buckets["heading"] += line.sources + section = [text] + continue + + indented = line.x0 > margin + INDENT_SLACK + page_list = bool(PAGE_LIST_RE.match(text)) + if current is None: + start = True + elif hanging: + # a list: the entry is flush, its continuation lines hang + start = (not indented) and not page_list + else: + # prose: the paragraph's first line is indented, and the + # lines of a block quotation all are, so a new paragraph + # also needs the line before it to have been flush + # a book that sets its extracts inside the paragraph they + # belong to keeps the paragraph whole: the extract + # continues it instead of starting a new one + start = indented and not prev_indented + marker = None + if self.paragraph_numbers is not None: + found = self.paragraph_numbers.match(text) + if found: + start = True + marker = found.group(1) + if self.extracts_inline and abs(line.size - page_sizes.get(page.leaf, body_size)) > 0.25: + start = False + + if start: + current = Paragraph(kind="body", chapter=ch.number, + section_path=list(section)) + current.path = list(section) + current.leaf_start = page.leaf + current.page_start = page.printed_page + current.text = text + current.flags = list(flags) + if CONTENTS_RE.search(current.text or ""): + # a line of dot leaders is an entry in a list of + # contents, not prose + current.flags = list(flags) + ["contents"] + if marker: + current.native_marker = marker + page_body = page_sizes.get(page.leaf, body_size) + if abs(line.size - page_body) > 0.25: + current.flags = list(flags) + ["quotation"] + current.bboxes.append({"leaf": page.leaf, "x0": line.x0, "y0": line.y0, + "x1": line.x1, "y1": line.y1}) + self.paragraphs.append(current) + ch.paragraphs.append(current) + self.line_buckets["body"] += 1 + else: + current.text = structure.join_lines([current.text, text], strict=True) + current.leaf_end = page.leaf + current.page_end = page.printed_page + current.bboxes.append({"leaf": page.leaf, "x0": line.x0, "y0": line.y0, + "x1": line.x1, "y1": line.y1}) + self.line_buckets["body"] += 1 + prev_indented = indented + for mark in line.marks: + self.pending_marks.append((current, int(mark))) + + def link_footnotes(self): + """Tie each reference mark in the prose to the note it numbers. + + The notes come at the end of their chapter, so the marks are still + waiting when the prose is read, and the paragraphs have no ids until + they are numbered. Both are settled here, after the numbering. + """ + taken = set() + for para, number in self.pending_marks: + found = None + for note in self.footnotes: + if (note["n"] == number and note["chapter"] == para.chapter + and id(note) not in taken): + found = note + break + if found is None: + # the note this mark names is already anchored to another + # paragraph: the mark points at a note that is not there + self.anomalies.append({"kind": "mark_without_note", + "number": number, "chapter": para.chapter}) + continue + found["anchor_id"] = para.id or None + para.footnote_ids.append(found) + taken.add(id(found)) + + # -- front and back ---------------------------------------------------- + def _front_and_back(self): + if not self.chapters: + self.front_pages = list(self.pages) + return + first = self.chapters[0].start_leaf + last = self.chapters[-1].end_leaf + self.front_pages = [p for p in self.pages if p.leaf < first] + if self.front_leaf_count: + self.front_pages = [p for p in self.pages + if p.leaf < self.front_leaf_count] + self.back_pages = [p for p in self.pages if p.leaf > last] + for page in self.front_pages + self.back_pages: + stamped = set(id(ln) for ln in scrub.stamp_lines(page.lines)) + for line in page.lines: + if id(line) in stamped: + self.line_buckets["digitisation"] += 1 + continue + text = line.text.replace("\ufeff", "").strip() + if not text: + continue + para = Paragraph(kind="body", text=text, chapter=0, + leaf_start=page.leaf, leaf_end=page.leaf, + page_start=page.printed_page, page_end=page.printed_page) + self.paragraphs.append(para) + self.line_buckets["body"] += 1 + + +def _display_title(page): + """The title a page carries at the top: the display face, set large.""" + for line in page.lines: + if line.font.startswith("Palatino") and line.size >= 16.0: + return line.text.strip() + return "" diff --git a/pipeline/book2corpus/emit.py b/pipeline/book2corpus/emit.py new file mode 100644 index 00000000..c8f33b40 --- /dev/null +++ b/pipeline/book2corpus/emit.py @@ -0,0 +1,429 @@ +"""Artefacts. + +The agent contract is paragraphs.jsonl plus manifest.json. Everything else - +the chapter Markdown, the HTML reader - is derived from it, so the files a +person reads and the files a machine reads cannot drift apart. +""" +import hashlib +import json +import os +import re + +SCHEMA_VERSION = "1.0.0" + +REFS_RE = re.compile(r"((?:\d{1,2}\.\d{1,3})(?:\s*[-–]\s*\d{1,2}\.\d{1,3})?(?:,\s*\d{1,2}\.\d{1,3})*)\s*$") +JUNK_RUN_RE = re.compile(r"[A-Za-z.,'’*|]{10,}") + + +def sha256_of(path): + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def sha256_of_text_layer(pages): + """A hash of the reading itself: the lines, with their places on the page. + + This pins the text the corpus was built from, so a rebuild can be + checked against it, without saying anything about the file the reading + came out of. + """ + h = hashlib.sha256() + for page in pages: + h.update(("%d\t%s\n" % (page.leaf, page.printed_page)).encode("utf-8")) + for line in page.lines: + h.update(("%s\t%s\t%s\t%s\t%s\n" % (line.text, line.x0, line.y0, + line.x1, line.y1)).encode("utf-8")) + return h.hexdigest() + + +def _clean_entry(text): + """Drop the OCR of the dot leaders, which is low-entropy junk.""" + def repl(m): + run = m.group(0) + letters = [c for c in run.lower() if c.isalpha()] + if len(run) >= 10 and len(set(letters)) <= 3: + return " | " + return run + out = JUNK_RUN_RE.sub(repl, text) + out = re.sub(r"\s*\|\s*", " | ", out) + return re.sub(r"\s+", " ", out).strip(" |") + + +def parse_table_line(line): + """A flattened table line: name and citation, then the paragraph refs.""" + m = REFS_RE.search(line) + if not m: + return None + refs_raw = m.group(1) + head = line[:m.start()] + if not head.strip(): + return None + parts = [p.strip() for p in head.split("|") if p.strip()] + refs = [] + for r in re.findall(r"\d{1,2}\.\d{1,3}", refs_raw): + refs.append(r) + entries = [] + for part in parts: + part = _clean_entry(part) + if part: + entries.append(part) + if not entries: + return None + return entries, refs + + +def block_kind(para): + """What kind of thing this record is: prose, a quotation, a table, a heading. + + An agent that reads the corpus needs to know that a block quotation is + someone else's words and that a table is not a sentence. + """ + if para.kind == "heading": + return "heading" + if para.kind == "table": + return "table" + if "quotation" in (para.flags or []): + return "quotation" + return "paragraph" + + +def paragraph_records(book): + """The corpus itself: one record per paragraph, as a list. + + The reader and the gates are made from this list, so what they show and + what they check are the same records that are written out. + """ + records = [] + for i, para in enumerate(book.paragraphs): + para.seq = i + rec = { + "id": para.id, + "seq": para.seq, + "kind": para.kind, + "block_kind": block_kind(para), + "text": para.text, + "section_path": para.section_path, + "native_marker": para.native_marker, + "chapter": para.chapter, + "leaf_start": para.leaf_start, + "leaf_end": para.leaf_end, + "page_start": para.page_start, + "page_end": para.page_end, + "quality": para.quality or {"grade": "B", "flags": []}, + "flags": list(para.flags or []), + "footnote_ids": [f.get("id") for f in para.footnote_ids if f.get("id")], + } + if para.bboxes: + rec["bboxes"] = para.bboxes[:4] + if getattr(para, "aliases", None): + # the id this paragraph had before: a citation made against + # it still resolves + rec["aliases"] = list(para.aliases) + records.append(rec) + return records + + +def emit_paragraphs(book, outdir): + path = os.path.join(outdir, "paragraphs.jsonl") + records = paragraph_records(book) + with open(path, "w", encoding="utf-8") as fh: + for rec in records: + fh.write(json.dumps(rec, ensure_ascii=False) + "\n") + return path, len(records) + + +def footnote_map(book): + """The notes by their id, the way the reader wants them.""" + return {note["id"]: note for note in book.footnotes if note.get("id")} + + +def emit_footnotes(book, outdir): + path = os.path.join(outdir, "footnotes.jsonl") + with open(path, "w", encoding="utf-8") as fh: + for note in book.footnotes: + rec = dict(note) + rec.pop("chapter_key", None) + fh.write(json.dumps(rec, ensure_ascii=False) + "\n") + return path, len(book.footnotes) + + +def emit_chapters(book, outdir): + """One Markdown file per chapter, one paragraph per line, each with its id.""" + cdir = os.path.join(outdir, "chapters") + os.makedirs(cdir, exist_ok=True) + written = [] + for ch in book.chapters: + stem = ("%s - %s" % (ch.label, ch.title)) if ch.label else ch.title + stem = re.sub(r"[^A-Za-z0-9 ]", " ", stem) + stem = re.sub(r"\s+", " ", stem).strip() or "Untitled" + name = "%02d %s.md" % (ch.number, stem) + path = os.path.join(cdir, name) + heading = ("%s: %s" % (ch.label, ch.title)) if ch.label else ch.title + lines = ["# %s" % heading, ""] + pages = [p for p in ch.pages] + if pages: + lines.append("Pages %s-%s of the printed book." % ( + pages[0].printed_page or "?", pages[-1].printed_page or "?")) + lines.append("") + for para in ch.paragraphs: + if para.kind == "heading": + level = "##" if (para.section_path and para.section_path[0] == para.text) else "###" + lines.append("%s %s" % (level, para.text)) + lines.append("") + continue + lines.append("[%s] %s" % (para.id, para.text)) + for note in para.footnote_ids: + lines.append("[%s] %s" % (note.get("id"), note.get("text", ""))) + lines.append("") + with open(path, "w", encoding="utf-8") as fh: + fh.write("\n".join(lines).rstrip() + "\n") + written.append((name, len(ch.paragraphs))) + + # the front and back matter belong to the book too: they are in the + # corpus, so they are in the chapter files as well + loose = [p for p in book.paragraphs if p.kind == "body" and not (p.chapter or 0)] + if loose: + name = "00 Front and back matter.md" + path = os.path.join(cdir, name) + lines = ["# Front and back matter", ""] + for para in loose: + lines.append("[%s] %s" % (para.id, para.text)) + lines.append("") + with open(path, "w", encoding="utf-8") as fh: + fh.write("\n".join(lines).rstrip() + "\n") + written.append((name, len(loose))) + return cdir, written + + +def emit_tables(book, outdir, table_leaves): + """The tables of cases and statutes, parsed to entry/citation/refs.""" + path = os.path.join(outdir, "tables.jsonl") + rows = [] + for page in book.pages: + if page.leaf not in table_leaves: + continue + for ln in page.body: + parsed = parse_table_line(ln.text) + if not parsed: + continue + entries, refs = parsed + for entry in entries: + rows.append({"source": page.header or "Table", + "entry": entry, + "page": page.printed_page, + "leaf": page.leaf, + "refs": refs}) + with open(path, "w", encoding="utf-8") as fh: + for row in rows: + fh.write(json.dumps(row, ensure_ascii=False) + "\n") + return path, len(rows) + + +def _snippet(text, limit=120): + text = " ".join((text or "").split()) + return text if len(text) <= limit else text[:limit - 1].rstrip() + "…" + + +def _first_page(book, start_leaf, end_leaf): + for leaf in range(start_leaf, end_leaf + 1): + if book.pages[leaf].printed_page: + return book.pages[leaf].printed_page + return None + + +def _last_page(book, start_leaf, end_leaf): + for leaf in range(end_leaf, start_leaf - 1, -1): + if book.pages[leaf].printed_page: + return book.pages[leaf].printed_page + return None + + +def build_outline(book): + """The book's shape: chapters, divisions, sub-divisions, paragraphs. + + This is the index an agent reads to find a passage and the sidebar is + built from, so the two cannot disagree. + """ + chapters = [] + for ch in book.chapters: + entry = {"number": ch.number, "label": ch.label, "title": ch.title, + "page_start": _first_page(book, ch.start_leaf, ch.end_leaf), + "page_end": _last_page(book, ch.start_leaf, ch.end_leaf), + "divisions": [], "paragraphs": []} + division = None + subsection = None + for para in ch.paragraphs: + if para.kind == "heading": + if getattr(para, "level", "h3") == "h2": + division = {"title": para.text, "page": para.page_start, + "subsections": [], "paragraphs": []} + entry["divisions"].append(division) + subsection = None + else: + subsection = {"title": para.text, "page": para.page_start, + "paragraphs": []} + if division is None: + division = {"title": None, "page": para.page_start, + "subsections": [], "paragraphs": []} + entry["divisions"].append(division) + division["subsections"].append(subsection) + continue + item = {"id": para.id, "page": para.page_start, + "grade": (para.quality or {}).get("grade"), + "text": (para.text or "")[:160]} + if subsection is not None: + subsection["paragraphs"].append(item) + elif division is not None: + division["paragraphs"].append(item) + else: + entry["paragraphs"].append(item) + chapters.append(entry) + return chapters + + +def emit_outline(book, outdir): + path = os.path.join(outdir, "outline.json") + with open(path, "w", encoding="utf-8") as fh: + json.dump({"schema_version": SCHEMA_VERSION, "chapters": build_outline(book)}, + fh, indent=1, ensure_ascii=False) + return path + + +def emit_index_md(book, outdir, gates, manifest, files): + """The human-readable companion to manifest.json.""" + path = os.path.join(outdir, "index.md") + meta_book = manifest["book"] + lines = [] + lines.append("# %s - %s (%s)" % (meta_book.get("title", ""), ", ".join(meta_book.get("authors", [])), meta_book.get("year", ""))) + lines.append("") + lines.append("A chaptered corpus of the book, built for an AI agent to work from: the commentary as numbered paragraphs, the tables of cases and statutes parsed, and a self-contained HTML reader.") + lines.append("") + lines.append("## What is here") + lines.append("") + lines.append("| File | What it is |") + lines.append("| --- | --- |") + lines.append("| paragraphs.jsonl | The agent contract: one JSON object per paragraph, with its id, section path, pages and text. Start here. |") + lines.append("| footnotes.jsonl | The notes at the foot of each page, with the paragraph they are anchored to. |") + lines.append("| tables.jsonl | The table of cases and the table of statutes, parsed into entry, citation and paragraph references. |") + lines.append("| chapters/ | One Markdown file per chapter, one paragraph per line, each line prefixed with its paragraph number. |") + lines.append("| index.html | A self-contained reader: contents, search, paragraph jump, light and dark, print styles. |") + lines.append("| manifest.json | The machine-readable manifest: schema version, id scheme, counts, the QA results and the file list. |") + lines.append("| qa_report.json | Every QA gate, its value, its threshold and its status. |") + lines.append("") + lines.append("## The book") + lines.append("") + lines.append("- %d chapters, %d numbered paragraphs, %d headings, %d footnotes." % (manifest["counts"]["chapters"], manifest["counts"]["paragraphs"], manifest["counts"]["headings"], manifest["counts"]["footnotes"])) + source = (manifest.get("source") or {}).get("type", "scan") + if source == "digital": + lines.append("- Source: %d pages of the book's own PDF text layer; no OCR was run." % manifest["counts"]["leaves"]) + lines.append("- Printed page numbers are the book's own folios, read from the PDF text layer.") + lines.append("- Paragraph ids are anchored to the text: the unit, the paragraph's opening words and a collision counter. They survive a re-split, and the ordinal id each one replaced is kept as an alias.") + else: + lines.append("- Source: %d pages of scan, re-read line by line and merged with the PDF's own text layer." % manifest["counts"]["leaves"]) + lines.append("- Printed page numbers come from the scan's own page map, not from the OCR.") + lines.append("- Paragraph ids are the book's own paragraph numbers, so a passage can be cited the way the book cites it.") + lines.append("") + lines.append("## Chapters") + lines.append("") + for ch in build_outline(book): + lines.append("### %d. %s" % (ch["number"], + ("%s: %s" % (ch["label"], ch["title"])) + if ch.get("label") else ch["title"])) + lines.append("") + lines.append("Pages %s-%s." % (ch["page_start"] or "?", ch["page_end"] or "?")) + lines.append("") + for para in ch["paragraphs"]: + lines.append("- %s %s" % (para["id"], _snippet(para["text"]))) + for div in ch["divisions"]: + if div["title"]: + lines.append("") + lines.append("**%s** (p %s)" % (div["title"], div["page"] or "?")) + for para in div["paragraphs"]: + lines.append("- %s %s" % (para["id"], _snippet(para["text"]))) + for sub in div["subsections"]: + lines.append("") + lines.append(" *%s* (p %s)" % (sub["title"], sub["page"] or "?")) + for para in sub["paragraphs"]: + lines.append(" - %s %s" % (para["id"], _snippet(para["text"]))) + lines.append("") + lines.append("") + lines.append("## Quality gates") + lines.append("") + lines.append("| Gate | Status | Detail |") + lines.append("| --- | --- | --- |") + for g in gates: + lines.append("| %s | %s | %s |" % (g.name, g.status, g.detail or str(g.value)[:120])) + lines.append("") + lines.append("## Known issues") + lines.append("") + for issue in manifest.get("known_issues", []): + lines.append("- %s" % issue) + lines.append("") + with open(path, "w", encoding="utf-8") as fh: + fh.write(chr(10).join(lines)) + return path, len(lines) + + +def build_manifest(book, outdir, gates, files, book_meta, source_meta, known_issues=None, + id_scheme=None, page_scheme=None, profile=None, environment=None): + path = os.path.join(outdir, "manifest.json") + counts = { + "paragraphs": sum(1 for p in book.paragraphs if p.kind == "body"), + "headings": sum(1 for p in book.paragraphs if p.kind == "heading"), + "footnotes": len(book.footnotes), + "leaves": len(book.pages), + "chapters": len(book.chapters), + } + manifest = { + "schema_version": SCHEMA_VERSION, + "book": book_meta, + "source": source_meta, + "id_scheme": id_scheme or { + "type": "native", + "pattern": "^(fm|bm)-p\\d{4}$|^\\d{1,2}\\.\\d{1,3}(\\.\\d{1,3})?$", + "native": True, + "human_citable": True, + "citation_template": "{authors_short}, {title} ({year}), para {native_marker}, p {page_start}", + }, + "page_scheme": page_scheme or {"printed_labels": True, "coverage": 1.0, + "source": "the scan page map (machine inferred)"}, + "counts": counts, + "profile": profile or {}, + # the word list the grades were measured against, so that a gate + # result can be read again and not taken on trust + "environment": environment or {}, + "chapters": [{"number": c.number, "label": c.label, "title": c.title, + "leaf_start": c.start_leaf, "leaf_end": c.end_leaf, + "page_start": _first_page(book, c.start_leaf, c.end_leaf), + "page_end": _last_page(book, c.start_leaf, c.end_leaf), + "paragraphs": len([p for p in c.paragraphs if p.kind == "body"]), + "headings": len([p for p in c.paragraphs if p.kind == "heading"])} + for c in book.chapters], + "qa": [g.as_dict() for g in gates], + "files": files, + "build": {"tool_version": "0.1.0", "config_sha256": None}, + "known_issues": list(known_issues or []), + } + return path, manifest + + +def with_hashes(outdir, files): + """The file list with the hash of each file, so a stale manifest beside + a new corpus is detectable and not merely wrong.""" + out = [] + for entry in files: + path = os.path.join(outdir, entry["name"]) + row = dict(entry) + if os.path.exists(path): + row["bytes"] = os.path.getsize(path) + row["sha256"] = sha256_of(path) + out.append(row) + return out + + +def write_manifest(path, manifest): + with open(path, "w", encoding="utf-8") as fh: + json.dump(manifest, fh, indent=2, ensure_ascii=False) diff --git a/pipeline/book2corpus/figures.py b/pipeline/book2corpus/figures.py new file mode 100644 index 00000000..a597f93b --- /dev/null +++ b/pipeline/book2corpus/figures.py @@ -0,0 +1,802 @@ +"""Matching the notes' figure blocks to the library's images. + +Every figure block in the notes asks for one image: the picture the book +printed. The library holds the pictures, one record per image, carrying +the page it was taken from, the chapter, the caption the book printed and +a written description of what the image shows. + +The rules here are evidence rules. A block gets an image only when the +data says which image it is, and the tier says on what: + + numbered the figure's own number agrees with the catalogue's + verified the printed caption agrees + description-match the two written descriptions agree closely + probable the captions share enough words + inferred one picture left on the page, one block still unmatched + ordinal the order of the pictures on the page says which is which + candidate several pictures could be; none of them is claimed + none no picture for that page + +How the claims are settled: + + The page is settled as a whole. The claims are written into a matrix, + one row per figure and one column per picture on that page, each claim + worth its tier and its score, and the best assignment of the matrix is + taken - see assignment.py. A greedy pass over the tiers would give a + contested picture to whichever figure it met first, and the order of + the figures is the order of the notes, not the order of the evidence. + + Every match is then asked what it was worth against its best + alternative: forbidding the match and settling the page again says what + the page would look like without it. A match whose alternative is + nearly as good is not a match. Exact ties are left unclaimed. + + A rival also has to be far away before a description can speak at all. + On a page, with a handful of pictures, a rival has to be a quarter of + the winner and three fifths of it below; in a chapter, with many + pictures, a rival has to be an eighth and three quarters below. Both + descriptions have to carry enough words to be compared at all: two + words match by luck, five words match by meaning. + + One picture may serve two figures in one case only: the panels of one + figure, which the notes write as 3.2a and 3.2b and the catalogue holds + once as 3.2. That sharing is declared, and the gate checks the + declaration. + + One printed figure may be held twice: once cut out of the page, once + rendered from the book's own vector art. That is one picture, not two, + and the second copy is never a rival for the first. +""" + +import hashlib +import os +import re + +from . import assignment + +# Bumped by hand when the meaning of a match changes: a new threshold, a +# new tier order, a new tie rule. The build key carries it, so a reader +# built by an older rule is never mistaken for one built by this rule. +ALGORITHM_VERSION = 1 + +STOPWORDS = frozenset(""" +a an the of and in on at to for with is are was were be been being it its +this that these those as by from not no or but if then than so such can +may might must will would shall should do does did done have has had +having we you they he she i their his her our your my me him them us +there here what which who whom whose when where why how all any both +each few more most other some only own same too very s t +""".split()) + +FIGURE_NUMBER_RE = re.compile(r"^(?:fig(?:ure)?\.?\s*)?(\d+(?:\.\d+)*)([a-z]?)$") + +# Thresholds. These are not guesses: they were measured against the +# blocks that a page key or a printed caption already resolves, where the +# answer is known, and the number at which the answer stops agreeing is +# where the threshold sits. See scripts/calibrate_figures.py. +DESCRIPTION_HI = 0.85 +# Two words match by luck. Five words match by meaning: below that a +# description cannot speak, however high the similarity. +MIN_DESC_WORDS = 5 +# A page pool holds a handful of pictures and one of them is right, so a +# rival has to be far away before it stops the rule. A chapter pool +# holds many, and the rival has to be further away still. The rival has +# to satisfy both: a ratio, which rules when the scores are low, and a +# gap, which rules when they are high. +RIVAL_RATIO_PAGE = 4.0 +RIVAL_GAP_PAGE = 0.60 +RIVAL_RATIO_CHAPTER = 8.0 +RIVAL_GAP_CHAPTER = 0.75 +VETO_LO = 0.30 +CAPTION_MIN = 0.50 +ORDINAL_MIN = 0.90 + +# The tiers, in the order of the strength of the evidence they assert: +# the book's own number, then the book's own caption, then text +# similarity. Measured precision does not separate the top four tiers +# within their confidence intervals; it decides what is shown, not which +# claim wins a contested picture. +TIER_RANK = {"numbered": 5, "verified": 4, "description-match": 3, + "probable": 2, "inferred": 1} +# A tier is worth this much and a score inside it is worth one, so a +# stronger tier always beats a better score in a weaker tier. +TIER_STEP = 10.0 +# How much a match has to be worth against its best alternative, in +# score. A match whose rival is nearly as good is a coin toss. +MARGIN = 0.15 + +GENERIC_PAGE = frozenset(("unnumbered", "none", "")) + +TIERS = ("numbered", "verified", "description-match", "probable", + "inferred", "ordinal", "candidate", "none") + +BADGE = { + "numbered": "matched by the figure's own number", + "verified": "matched by the printed caption", + "description-match": "descriptions agree (text similarity)", + "probable": "matched by a similar caption", + "inferred": "matched by position on the page", + "ordinal": "assumed by order (not certain)", + "candidate": "no picture confirmed; candidates named below", + "none": "no picture found for this figure", +} + +KEY_NAME = {"pdf-page": "the PDF page", "printed-page": "the printed page", + "chapter": "the chapter", "book": "the book"} + + +def norm(text): + return re.sub(r"[^a-z0-9]+", " ", (text or "").lower()).strip() + + +def tokens(text): + """The words that carry meaning in a description or a caption.""" + return set(word for word in re.findall(r"[a-z0-9]+", (text or "").lower()) + if word not in STOPWORDS and len(word) > 2) + + +def jaccard(left, right): + if not left or not right: + return 0.0 + union = len(left | right) + return len(left & right) / union if union else 0.0 + + +def figure_number(text): + """'Fig. 3.2' -> ('3.2', ''); '3.2a' -> ('3.2', 'a'); 'unnumbered' -> None.""" + if not text: + return None + raw = str(text).strip().lower() + if raw in ("none", "unnumbered", "un-numbered", "un numbered", ""): + return None + found = FIGURE_NUMBER_RE.match(raw) + if not found: + return None + return (found.group(1), found.group(2)) + + +def base_number(label): + """'3.2a' -> '3.2'; 'Figure 3.2' -> '3.2'; 'unnumbered' -> ''.""" + found = re.match(r"^(?:fig(?:ure)?\.?\s*)?(\d+(?:\.\d+)*)", + (label or "").strip().lower()) + return found.group(1) if found else "" + + +def picture_key(record): + """The printed picture a record holds. + +The library holds one printed figure twice: once cut out of the page +(fig_p0022_0.jpeg) and once rendered from the book's own vector art +(vec_p0022_0.png). The two are one picture. The name carries the page +and the place on the page, so the two copies are recognised by it and +not by their captions, which do not always agree. + """ + name = os.path.basename(record.get("file") or "") + stem = name.rsplit(".", 1)[0] + for prefix in ("fig_", "vec_"): + if stem.startswith(prefix): + stem = stem[len(prefix):] + break + return stem or str(record.get("id") or "") + + +def page_key(record): + """The order the pictures of a page are in, whatever order they arrive in. + +The catalogue's file name carries the place of the picture on its page +(fig_p0001_0, fig_p0001_1), so the order of a page is recovered from the +data and not from the order the records happen to come in. Everything +that depends on order depends on this. + """ + return (norm(record.get("page") or ""), + norm(record.get("printed_page") or ""), + picture_key(record), + str(record.get("id") or "")) + + +def build_pools(records): + by_pdf, by_printed, by_chapter = {}, {}, {} + for record in records: + by_pdf.setdefault(norm(record.get("page") or ""), []).append(record) + by_printed.setdefault(norm(record.get("printed_page") or ""), []).append(record) + by_chapter.setdefault(norm(record.get("chapter") or ""), []).append(record) + return by_pdf, by_printed, by_chapter + + +def pool_for(block, by_pdf, by_printed, by_chapter, records): + """The pictures a block could be, and the key that found them. + + The PDF page is the sharpest key and the printed page comes next; a + chapter is what is left for notes that carry no page at all. When + both page keys point somewhere, the one whose pictures carry the page + label the notes give wins, because the page label is the book's own. + """ + pdf = norm(block.get("pdf_page") or "") + printed = norm(block.get("page") or "") + if printed in GENERIC_PAGE: + printed = "" + pdf_pool = (by_pdf.get(pdf) or []) if pdf else [] + printed_pool = (by_printed.get(printed) or []) if printed else [] + if pdf_pool and printed_pool: + if any(norm(r.get("printed_page") or "") == printed for r in pdf_pool): + return pdf_pool, "pdf-page" + return printed_pool, "printed-page" + if pdf_pool: + return pdf_pool, "pdf-page" + if printed_pool: + return printed_pool, "printed-page" + chapter_pool = by_chapter.get(norm(block.get("stem") or "")) or [] + if chapter_pool: + return chapter_pool, "chapter" + return records, "book" + + +class Matcher(object): + """The claims of one book, settled page by page.""" + + def __init__(self, blocks, records, library=None): + self.records = records + self.library = library + self.by_pdf, self.by_printed, self.by_chapter = build_pools(records) + self._record_tokens = {} + self._record_captions = {} + self._digests = {} + self.figures = [b for b in blocks if b.get("kind") == "figure"] + self.claims = {} + self.used = set() + self.panel_groups = [] + for index, block in enumerate(self.figures): + for key in ("image", "tier", "candidates", "key", "conflict", "detail", + "released", "demoted", "shared_with", "refusal", "margin"): + block.pop(key, None) + pool, key = pool_for(block, self.by_pdf, self.by_printed, + self.by_chapter, records) + block["_pool"] = pool + block["_key"] = key + block["_index"] = index + block["_label_num"] = figure_number(block.get("label")) + caption = (block.get("fields", {}).get("CAPTION") or "") + block["_caption"] = norm(caption) + block["_caption_tokens"] = tokens(caption) + block["_content_tokens"] = tokens(block.get("fields", {}).get("CONTENT") or "") + block["_ranked"] = self.rank(block) + + # ---- the evidence ------------------------------------------------ + + def record_tokens(self, record): + key = record.get("id") + if key not in self._record_tokens: + self._record_tokens[key] = tokens(record.get("description") or "") + return self._record_tokens[key] + + def record_caption(self, record): + key = record.get("id") + if key not in self._record_captions: + self._record_captions[key] = norm(record.get("caption_clean") + or record.get("caption") or "") + return self._record_captions[key] + + def similarity(self, block, record): + return jaccard(block["_content_tokens"], self.record_tokens(record)) + + def columns_of(self, pictures): + """The printed pictures of a pool: the catalogue holds some twice.""" + columns = [] + index = {} + for record in pictures: + key = picture_key(record) + if key not in index: + index[key] = len(columns) + columns.append([]) + columns[index[key]].append(record) + return columns + + def rank(self, block): + """The pictures of the block's pool, best description first. + + The two copies of one printed figure are ranked as one picture: + the second copy is not a rival for the first. + """ + columns = self.columns_of(sorted(block["_pool"], key=page_key)) + ranked = [] + for records in columns: + best = max(records, key=lambda record: self.similarity(block, record)) + ranked.append((self.similarity(block, best), best, records)) + ranked.sort(key=lambda entry: (-entry[0], picture_key(entry[1]))) + return ranked + + def top_two(self, block, pool): + """The best two pictures for a block by description, and their scores.""" + best_score, best_record = 0.0, None + second_score, second_record = 0.0, None + for record in pool: + score = self.similarity(block, record) + if score > best_score: + second_score, second_record = best_score, best_record + best_score, best_record = score, record + elif score > second_score: + second_score, second_record = score, record + return best_score, best_record, second_score, second_record + + def enough_words(self, block, record): + """Do both descriptions carry enough words to be compared?""" + return (len(block["_content_tokens"]) >= MIN_DESC_WORDS + and len(self.record_tokens(record)) >= MIN_DESC_WORDS) + + def rival_far(self, block, winner, rival, winner_record, rival_record): + """Is the rival far enough away for the winner to stand? + + The rival is the best other picture of the pool. A rival that is + the same picture - the catalogue holds one figure twice on a page, + once as a vector render and once cut from the page - is not a + rival at all. + """ + if (rival_record is not None and winner_record is not None + and self.same_picture(winner_record, rival_record)): + return True + if block["_key"] in ("pdf-page", "printed-page"): + ratio, gap = RIVAL_RATIO_PAGE, RIVAL_GAP_PAGE + else: + ratio, gap = RIVAL_RATIO_CHAPTER, RIVAL_GAP_CHAPTER + return rival <= winner / ratio and rival <= winner - gap + + def same_picture(self, record, other): + """Are these two records the same printed picture?""" + if other is None or record is None: + return False + if record.get("id") == other.get("id"): + return True + if picture_key(record) and picture_key(record) == picture_key(other): + return True + caption = self.record_caption(record) + other_caption = self.record_caption(other) + if caption and caption == other_caption: + description = norm(record.get("description") or "") + other_description = norm(other.get("description") or "") + if description and description == other_description: + return True + return self.same_file(record, other) + + def file_digest(self, path): + if path not in self._digests: + digest = hashlib.sha256() + try: + with open(path, "rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + except OSError: + self._digests[path] = None + else: + self._digests[path] = digest.hexdigest() + return self._digests[path] + + def same_file(self, left, right): + """Are these two records the same picture on disk?""" + if not self.library: + return False + first = left.get("file") + second = right.get("file") + if not first or not second: + return False + if first == second: + return True + path_a = os.path.join(self.library, first) + path_b = os.path.join(self.library, second) + try: + if os.path.getsize(path_a) != os.path.getsize(path_b): + return False + except OSError: + return False + digest_a = self.file_digest(path_a) + digest_b = self.file_digest(path_b) + if digest_a is None or digest_b is None: + return False + return digest_a == digest_b + + # ---- the claims -------------------------------------------------- + + def figure_claims(self, block, pool_size, group_size): + """What this figure can claim on the pictures of its page. + + Every claim says which tier it would be and how well it scores. + The strongest claim for a figure and a picture is the one that is + kept, because a stronger tier always beats a better score in a + weaker tier. + """ + out = [] + number = block["_label_num"] + if number: + for record in block["_pool"]: + found = figure_number(record.get("figure")) + if not found: + continue + if found == number: + out.append((record, "numbered", self.similarity(block, record), + {"number": number[0], "panel": number[1]})) + elif found[1] == "" and found[0] == number[0]: + # the catalogue holds the figure, the notes write one + # of its panels + out.append((record, "numbered", self.similarity(block, record), + {"number": number[0], "panel": number[1], + "panel_tolerant": True})) + caption = block["_caption"] + if caption and caption != "none": + for record in block["_pool"]: + printed = self.record_caption(record) + if printed and printed == caption: + out.append((record, "verified", self.similarity(block, record), + None)) + ranked = block["_ranked"] + if ranked: + score, record = ranked[0][0], ranked[0][1] + rival_score = ranked[1][0] if len(ranked) > 1 else 0.0 + rival_record = ranked[1][1] if len(ranked) > 1 else None + if (score >= DESCRIPTION_HI and self.enough_words(block, record) + and self.rival_far(block, score, rival_score, record, + rival_record)): + out.append((record, "description-match", score, + {"similarity": round(score, 3)})) + if block["_caption_tokens"] and block["_caption"] != "none": + for record in block["_pool"]: + printed = record.get("caption_clean") or record.get("caption") or "" + if not printed or printed == "none": + continue + score = jaccard(block["_caption_tokens"], tokens(printed)) + if score >= CAPTION_MIN: + out.append((record, "probable", score, + {"similarity": round(score, 3)})) + if pool_size == 1 and group_size == 1: + # one picture on the page, one figure that wants it + out.append((block["_pool"][0], "inferred", 0.0, None)) + return out + + def numbered_claim(self, block, record): + """Does the figure claim this picture by its own number?""" + number = block["_label_num"] + if not number: + return None + found = figure_number(record.get("figure")) + if not found: + return None + if found == number: + return {"number": number[0], "panel": number[1]} + if found[1] == "" and found[0] == number[0]: + return {"number": number[0], "panel": number[1], "panel_tolerant": True} + return None + + def assign(self, block, record, tier, key, detail=None, margin=None): + block["image"] = dict(record) + block["tier"] = tier + block["key"] = key + if detail: + block["detail"] = detail + if margin is not None: + block["margin"] = round(margin, 3) + self.claims.setdefault(record.get("id"), block) + self.used.add(record.get("id")) + return True + + def unresolved(self): + return [b for b in self.figures if not b.get("image")] + + def groups(self): + """The figures that draw on the same pool, in the order they appear.""" + groups = {} + for block in self.figures: + groups.setdefault(id(block["_pool"]), []).append(block) + out = [] + for key in sorted(groups, key=lambda k: groups[k][0]["_index"]): + out.append((groups[key][0]["_pool"], groups[key])) + return out + + # ---- settling ----------------------------------------------------- + + def claim_panels(self): + """The panels of one figure, decided before the page is settled. + + The notes write a multi-panel figure as several blocks, 15.3a to + 15.3e, and the catalogue holds the panels once, as 15.3. The + book's own number says so, and nothing else does, so it is settled + first: the picture is theirs, and the rest of the page is settled + without them. Sharing is permitted, not required: if every panel + has a picture of its own, nothing is shared and this rule does + not come into it. + """ + self.panel_groups = [] + for pool, group in self.groups(): + reaching = {} + for block in group: + if self.exact_numbered(block): + continue # the figure has a picture of its own + for record in block["_pool"]: + claim = self.numbered_claim(block, record) + if not claim or not claim.get("panel_tolerant"): + continue + found = figure_number(record.get("figure")) + if not found or found[1]: + continue # the catalogue names the panel itself + reaching.setdefault(record.get("id"), []).append((block, record, claim)) + for record_id, claims in reaching.items(): + if len(claims) < 2: + continue + bases = set(base_number(block.get("label")) + for block, _record, _claim in claims) + if len(bases) != 1: + continue + suffixes = [(figure_number(block.get("label")) or ("", ""))[1] + for block, _record, _claim in claims] + if len(set(suffixes)) != len(suffixes): + continue # the same panel twice: not a panel group + for block, record, claim in claims: + block["_panel_claim"] = (record, claim) + block["shared_with"] = [other for other, _r, _c in claims + if other is not block] + self.panel_groups.append(([block for block, _r, _c in claims], + claims[0][1])) + + def exact_numbered(self, block): + """The picture this figure names exactly, if it names one.""" + for record in block["_pool"]: + claim = self.numbered_claim(block, record) + if claim and not claim.get("panel_tolerant"): + return record + return None + + def settle(self): + """Every page, settled as a whole.""" + self.claim_panels() + for pool, group in self.groups(): + pictures = sorted(pool, key=page_key) + columns = self.columns_of(pictures) + claims = {} + rows = [] + for block in group: + found = block.get("_panel_claim") + if found: + record, claim = found + self.assign(block, record, "numbered", block["_key"], + dict(claim)) + continue + rows.append(block) + claims[id(block)] = self.claims_of(block, len(pictures), len(group)) + + def edge(block, column, claims=claims): + """The strongest claim this figure has on this picture.""" + best = None + for record in column: + for held, tier, score, _detail in claims[id(block)]: + if held.get("id") != record.get("id"): + continue + rank = (TIER_RANK.get(tier, 0), score) + if best is None or rank > best[0]: + best = (rank, tier, score, held) + break + if best is None: + return None + return (best[1], best[2]) + + settled = assignment.match_page(rows, columns, edge, + TIER_RANK, TIER_STEP, MARGIN) + for index, block in enumerate(rows): + found = settled.get(index) + if not found: + continue + if not found["accepted"]: + # the rival was too close: the picture is not claimed, + # and the refusal says which rival and by how much + block["refusal"] = self.refusal(block, found, claims, columns) + continue + records = columns[found["column"]] + picture = records[0] + detail = None + for held, _tier, _score, note in claims[id(block)]: + if held.get("id") == picture.get("id"): + detail = note + break + self.assign(block, picture, found["tier"], block["_key"], + detail, found["margin"]) + + def resolve_conflicts(self): + """One picture, one figure. + + A page can be found by two keys - the PDF page and the printed page + - and two figures on either side of them draw on pools that + overlap, so the picture is offered to both. Within one pool the + assignment settles it; across pools the stronger evidence wins, + and the figure that loses keeps the picture as a candidate. + """ + owners = {} + for block in self.figures: + image = block.get("image") + if not image: + continue + owners.setdefault(image.get("id"), []).append(block) + for image_id, group in owners.items(): + if len(group) < 2: + continue + shared = set(id(other) for block in group + for other in (block.get("shared_with") or [])) + if len(group) == 2 and shared: + continue # the panels of one figure, declared + group.sort(key=lambda block: (-TIER_RANK.get(block.get("tier"), 0), + -(block.get("margin") or 0), + block.get("_index", 0))) + keeper = group[0] + for block in group[1:]: + record = block.get("image") + block["image"] = None + block["tier"] = "candidate" + block["candidates"] = ([dict(record)] + + [c for c in (block.get("candidates") or []) + if c.get("id") != record.get("id")]) + block["contested"] = keeper.get("_index") + + def claims_of(self, block, pool_size, group_size): + """The claims of one figure, strongest first.""" + found = self.figure_claims(block, pool_size, group_size) + found.sort(key=lambda claim: (-TIER_RANK.get(claim[1], 0), -claim[2])) + return found + + def refusal(self, block, found, claims, columns): + """What stopped the claim, and what the rival was.""" + winner = columns[found["column"]][0] + rival = None + rival_score = None + if found.get("rival") is not None: + for record in columns[found["rival"]]: + for held, _tier, score, _note in claims[id(block)]: + if held.get("id") == record.get("id"): + rival = record + rival_score = score + break + if rival is not None: + break + return {"margin": round(found["margin"], 3), + "tie": found["margin"] <= 0, + "picture": winner.get("id"), + "score": round(found["score"], 3), + "rival": (rival or {}).get("id"), + "rival_number": (rival or {}).get("figure"), + "rival_score": (round(rival_score, 3) + if rival_score is not None else None)} + + def pass_ordinal(self): + """The order of the pictures on the page says which is which. + + Measured against the blocks a key already resolves, the order gets + the picture right 0.856 of the time - under the bar a picture has + to clear. So the order names the pictures and claims none of + them: they are listed, in the order the page holds them, and the + reader is told they are unconfirmed. + """ + for pool, group in self.groups(): + if pool is self.records: + continue + if any(block.get("refusal") for block in group): + # a claim on this page was refused: the order of the page + # no longer says which picture is which + continue + free = [] + seen = set() + for record in sorted(pool, key=page_key): + if record.get("id") in self.used: + continue + key = picture_key(record) + if key in seen: + continue + seen.add(key) + free.append(record) + unresolved = [b for b in group if not b.get("image")] + if len(free) != len(unresolved) or len(free) < 2: + continue + if not self.order_consistent(pool, unresolved, free): + continue + for block, record in zip(unresolved, free): + block["candidates"] = free[:6] + block["tier"] = "ordinal" + block["key"] = block["_key"] + block["detail"] = {"assumed": "order on the page"} + + def order_consistent(self, pool, unresolved, free): + """Would the pairing contradict the matches already made?""" + order = {picture_key(record): index + for index, record in enumerate(sorted(pool, key=page_key))} + chosen = {} + for record_id, block in self.claims.items(): + if block.get("_pool") is pool and block.get("image"): + chosen[block["_index"]] = order.get(picture_key(block["image"]), -1) + pairs = [] + position = 0 + for block in sorted(self.figures, key=lambda b: b["_index"]): + if block.get("_pool") is not pool: + continue + if block in unresolved: + pairs.append((position, + order.get(picture_key(free[unresolved.index(block)]), -1))) + elif block["_index"] in chosen: + pairs.append((position, chosen[block["_index"]])) + position += 1 + for (first_at, first_record), (second_at, second_record) in zip(pairs, pairs[1:]): + if first_at < second_at and first_record >= second_record: + return False + return True + + def pass_veto(self): + """A key match the descriptions contradict: the key stands. + + The key is the evidence the book itself gives - the number it + printed, the caption it printed - and a description that reads + differently is not proof against it. So the block is flagged and + the flag goes to the audit, rather than the picture being taken + away on a weaker kind of evidence. + """ + for block in self.figures: + if block.get("tier") not in ("numbered", "verified"): + continue + if not block["_content_tokens"]: + continue + record = block.get("image") + if not record: + continue + if self.similarity(block, record) >= VETO_LO: + continue + score, other, second, rival = self.top_two(block, block["_pool"]) + if other is None or other.get("id") == record.get("id"): + continue + if score < DESCRIPTION_HI or second > DESCRIPTION_HI / RIVAL_RATIO_PAGE: + continue + if self.same_picture(record, rival): + continue + block["conflict"] = True + block["rival"] = other + detail = dict(block.get("detail") or {}) + detail["rival"] = other.get("id") + block["detail"] = detail + + def finish(self): + """What is left keeps its candidates, named and not shown.""" + for block in self.unresolved(): + if block.get("tier") == "ordinal": + # the pictures are named in order; none of them is claimed + continue + if not block["_pool"]: + block["tier"] = "none" + continue + block["candidates"] = [record for _score, record, _records + in block["_ranked"][:6]] + block["tier"] = "candidate" + for block in self.figures: + for key in ("_pool", "_key", "_index", "_label_num", "_caption", + "_caption_tokens", "_content_tokens", "_ranked", "rival", + "_panel_claim"): + block.pop(key, None) + return self.summary() + + def summary(self): + tiers = {} + keys = {} + for block in self.figures: + tier = block.get("tier") or "none" + tiers[tier] = tiers.get(tier, 0) + 1 + key = block.get("key") or "-" + keys[key] = keys.get(key, 0) + 1 + return {"tiers": tiers, "keys": keys, + "figures": len(self.figures), + "conflicts": sum(1 for b in self.figures if b.get("conflict"))} + + +def match(blocks, records, library=None): + """Give every figure block an image, on evidence, and say how.""" + if os.environ.get("B2C_MATCH", "on").strip().lower() == "off": + # the text only: no picture is looked for, and the reader says so + figures = [b for b in blocks if b.get("kind") == "figure"] + for block in figures: + block["tier"] = "none" + return {"tiers": {"none": len(figures)}, "keys": {}, + "figures": len(figures), "conflicts": 0} + matcher = Matcher(blocks, records, library) + matcher.settle() + matcher.resolve_conflicts() + matcher.pass_ordinal() + matcher.pass_veto() + return matcher.finish() \ No newline at end of file diff --git a/pipeline/book2corpus/html.py b/pipeline/book2corpus/html.py new file mode 100644 index 00000000..6a348772 --- /dev/null +++ b/pipeline/book2corpus/html.py @@ -0,0 +1,371 @@ +"""The HTML reader. + +One self-contained file: no network, no build step, just open it. The reader +is generated from the corpus, so it cannot drift from paragraphs.jsonl. + +The reader reads nothing. Everything it shows is passed in - the records, +the notes, the outline, the book's own metadata and the counts - and it +returns a string. A stage that read back a file it had not just written +would show the previous build's title and contents, which is exactly the +kind of bug a reader cannot see in itself. + +The book is laid out as the book is: the text is grouped by the printed page +it came from, each page carries the running head and the folio, and the +contents sidebar is the book's own hierarchy - chapter, division, +sub-division, paragraph - with the current division opening as you read. + +Each block is one element of the kind it is: a paragraph is a paragraph, a +quotation is a quotation, and the lines of a table are shown as the lines +they are, because the text layer does not say where the columns were. +""" +import os +import re +from collections import OrderedDict + +from . import index_block + +from . import counts_line + +HERE = os.path.dirname(os.path.abspath(__file__)) +TEMPLATE = (open(os.path.join(HERE, "templates", "reader.head.html"), encoding="utf-8").read() + + open(os.path.join(HERE, "templates", "reader.tail.html"), encoding="utf-8").read()) + +TABLE_NOTE = ("Columns not recovered from the text layer; the rows are shown " + "as they were extracted.") + + +def _esc(text): + text = "" if text is None else str(text) + return text.replace("&", "&").replace("<", "<").replace(">", ">") + + +def _chapter_titles(outline): + """Each unit's own name and its title, by number.""" + return {ch["number"]: (ch.get("label") or "", ch["title"]) + for ch in outline.get("chapters", [])} + + +def _chapter_title(text): + """The chapter's own name, without the digit the running head carries. + + The running head of this book ends with a stray "1" on some chapters + ("Causation1", "Damages1"); it is a mark from the scan, not part of + the name. A digit that stands on its own is left alone. + """ + name = (text or "").strip() + if len(name) > 3 and name[-1] == "1" and name[-2].isalpha(): + name = name[:-1].rstrip() + return name + + +def _links(paragraphs): + out = [] + for para in paragraphs: + grade = (para.get("grade") or "") + # the book's own paragraph number when it has one, its own opening + # words otherwise: a list of internal ids helps nobody + label = (para.get("marker") or "").strip() + if not label: + words = (para.get("text") or "").split() + label = " ".join(words[:9]) + if not label: + label = para["id"] + out.append('%s' + % (" low" if grade == "C" else "", _esc(para["id"]), + _esc(para.get("page") or ""), + _esc((para.get("text") or "")[:160]), _esc(label))) + return chr(10).join(out) + + +def _build_nav(outline): + """The contents: chapter, division, sub-division, paragraphs.""" + out = [] + for ch in outline.get("chapters", []): + pages = "%s–%s" % (ch.get("page_start") or "?", ch.get("page_end") or "?") + out.append('
' + '%s%s' + '%s' + % (_esc(ch.get("label") or ch["number"]), + _esc(_chapter_title(ch.get("title"))), _esc(pages))) + if ch.get("paragraphs"): + out.append('
%s
' % _links(ch["paragraphs"])) + for div in ch.get("divisions", []): + title = div.get("title") or "Introduction" + out.append('
' + '%s%s' + % (_esc(div.get("page") or ""), _esc(title), _esc(div.get("page") or ""))) + if div.get("paragraphs"): + out.append('
%s
' % _links(div["paragraphs"])) + for sub in div.get("subsections", []): + out.append('
' + '%s%s%s
' + % (_esc(sub.get("page") or ""), _esc(sub.get("title") or ""), + _esc(sub.get("page") or ""), + _links(sub.get("paragraphs") or []))) + out.append("
") + out.append("
") + return "\n".join(out) + + +def _marks_in(text, notes, pid): + """The reference marks in the prose, made into links to their notes. + + The characters are not changed: the mark keeps its brackets and is + wrapped in a sup, so the reader and the corpus still hold the same + text, character for character. Returns the marked-up text and the + ids of the marks that were found - a scan whose reference marks are + OCR rubbish has none, and its notes then point back to the paragraph. + """ + marks = {} + for index, (fid, note) in enumerate(notes, 1): + marks[str(note.get("n"))] = ("%s-r%d" % (pid, index), fid) + out = [] + position = 0 + found = [] + for hit in re.finditer(r"\[(\d{1,4})\]", text or ""): + number = hit.group(1) + if number not in marks: + continue + ref_id, fid = marks[number] + out.append(_esc(text[position:hit.start()])) + out.append('[%s]' + % (_esc(ref_id), _esc(fid), _esc(fid), _esc(number))) + position = hit.end() + found.append(ref_id) + out.append(_esc(text[position:])) + return chr(10).join(out), found + + +DOT_RUN_RE = re.compile(r"\.{4,}") + + +def _without_dot_leaders(text): + """The books' own contents lines, without the dot leaders. + + The leaders are the book's own setting, but a screen cannot draw a + leader that ends on the margin, so the run of dots is hidden and the + words around it are left exactly as they are. + """ + return DOT_RUN_RE.sub( + lambda m: '' + m.group(0) + '', text) + + +LAW_TOC_RE = re.compile(r"^(.*?)(\s*\.{4,}\s*)(.*)$") + + +def _law_toc(text, pid=""): + """A line of the book own contents: the title, the leaders, the page. + + The book's own contents are apparatus, not text: they are the only + lines where a run of dots means something. The dots stay in the + document, so the text is still exactly the text, and the line is set + as a column instead of a row of dots. + """ + found = LAW_TOC_RE.match(text or "") + if not found: + return None + title, dots, page = found.group(1).strip(), found.group(2).strip(), found.group(3).strip() + if not title: + return None + # the book's own run of dots stays in the text: the reader hides it, + # the words are the book's own + return ('

%s' + '' + '%s

' + % (_esc(pid), _esc(title), _esc(dots), _esc(page))) + + +def _unit(rec, footnotes): + """One block: its wrapper, its number, its text, its notes. + + The element that holds the text is chosen by what the block is, so a + quotation reads as a quotation and a table's lines read as a table's + lines. The number stays outside the quotation: it is a locator for + the unit, not part of the quoted words. + """ + pid = rec["id"] + marker = rec.get("native_marker") or pid + grade = (rec.get("quality") or {}).get("grade", "") + cls = "para para-unit" + (" low" if grade == "C" else "") + notes = [] + for fid in rec.get("footnote_ids", []): + note = footnotes.get(fid) + if note: + notes.append((fid, note)) + marked, mark_ids = _marks_in(rec.get("text") or "", notes, pid) + # the books' own contents lines: the words stay, the dot leaders are + # hidden, because a screen cannot draw a leader that ends on the margin + marked = _without_dot_leaders(marked) + kind = rec.get("block_kind") or "paragraph" + if kind == "quotation": + content = '
%s
' % ( + _esc(pid), marked) + elif kind == "table": + content = '

%s

' % (_esc(pid), marked) + else: + toc = _law_toc(rec.get("text") or "", pid) + if toc: + content = toc + else: + content = '

%s

' % (_esc(pid), marked) + out = ['
' + % (cls, _esc(pid), _esc(pid), len(notes), _esc(kind))] + if rec.get("native_marker"): + out.append('%s' + % (_esc(pid), _esc(marker), _esc(marker))) + # the ids this paragraph had before: an old citation still lands + # on the right paragraph + for alias in rec.get("aliases", []) or []: + out.append('' % _esc(alias)) + out.append(content) + if notes: + out.append('
') + for index, (fid, note) in enumerate(notes, 1): + ref_id = "%s-r%d" % (pid, index) + back = ref_id if ref_id in mark_ids else pid + out.append('
' + % (_esc(fid), _esc(pid), _esc(ref_id), + _esc(str(note.get("n", ""))))) + # the number links to the mark in the prose when the + # source has one; a scan whose marks are OCR rubbish + # has none, and the number links to the paragraph + out.append('%s %s' + % (_esc(back), _esc(note.get("n", "")), + _esc(note.get("text", "")))) + out.append('↩ ¶%s' + % (_esc(back), _esc(back), _esc(marker), _esc(marker))) + out.append('
') + out.append('
') + out.append('
') + return chr(10).join(out) + + +def _build_body(records, footnotes, outline): + """The text, grouped into the printed pages it came from.""" + titles = _chapter_titles(outline) + pages = OrderedDict() + for rec in records: + key = rec.get("page_start") or ("leaf-%s" % rec.get("leaf_start")) + pages.setdefault(key, []).append(rec) + + out = [] + for page_key, recs in pages.items(): + folio = "" if page_key.startswith("leaf-") else page_key + # the folio repeats across the front matter, so the leaf is part of + # the anchor: two anchors with one id break every link to them + anchor = "page-%s-%s" % (folio or "leaf", recs[0].get("leaf_start")) + chapter = recs[0].get("chapter") or 0 + label, title = titles.get(chapter, ("", "")) + runhead = ("%s · %s" % (_esc(label), _esc(title))) if label else _esc(title) + out.append('
' % (_esc(anchor), _esc(folio))) + if runhead: + out.append('
%s
' % runhead) + out.append('
') + index = 0 + while index < len(recs): + rec = recs[index] + if rec.get("kind") == "heading": + level = "h2" if rec.get("level") == "h2" else "h3" + out.append('<%s class="sec" id="%s" data-para="%s">%s' + % (level, _esc(rec["id"]), _esc(rec["id"]), + _esc(rec["text"]), level)) + index += 1 + continue + if rec.get("block_kind") == "table": + # a run of table lines is one table: the text layer gives the + # lines, not the columns, so the rows are shown as they were + # extracted and the reader is told that + run = [] + while (index < len(recs) + and recs[index].get("kind") != "heading" + and recs[index].get("block_kind") == "table"): + run.append(recs[index]) + index += 1 + out.append('
') + out.append('

%s

' % _esc(TABLE_NOTE)) + for one in run: + out.append(_unit(one, footnotes)) + out.append('
') + continue + out.append(_unit(rec, footnotes)) + index += 1 + out.append("
") + if folio: + out.append('
%s
' % _esc(folio)) + out.append("
") + return "\n".join(out) + + +def _orphan_notes(records, footnotes): + """The notes that belong to no paragraph in this reading. + + They were read from the book, so they are part of it: the reader shows + them rather than dropping them, and says why they stand on their own. + """ + owned = set() + for rec in records: + for fid in rec.get("footnote_ids", []) or []: + owned.add(fid) + return [note for fid, note in sorted(footnotes.items()) if fid not in owned] + + +def _orphan_section(orphans): + if not orphans: + return "" + out = ['
', + '

Notes that belong to no paragraph in this reading

', + '

These notes were read from the book, but the ' + 'paragraph they belong to was not found. They are kept here rather ' + 'than dropped.

'] + for note in orphans: + out.append('
' + '%s %s
' + % (_esc(note.get("id")), _esc(str(note.get("n", ""))), + _esc(note.get("n", "")), _esc(note.get("text", "")))) + out.append('
') + return chr(10).join(out) + + +def build_html(records, footnotes, outline, book_meta, counts, source_type="scan", + index_payload=None): + """The reader, as a string. + + Nothing is read from disk here: the reader is a function of the corpus + it was handed, so it cannot show a title, a count or a contents list + left behind by an earlier build. + """ + doc = TEMPLATE + doc = doc.replace("{{TITLE}}", _esc((book_meta or {}).get("title", ""))) + doc = doc.replace("{{SUBTITLE}}", _esc("%s %s" % ( + ", ".join((book_meta or {}).get("authors", []) or []), + (book_meta or {}).get("year", "")))) + counts = counts or {} + doc = doc.replace("{{COUNTS}}", counts_line.to_html(counts_line.law(counts))) + doc = doc.replace("{{KIND}}", "law") + doc = doc.replace("{{SEARCH}}", "Search the book (press / )") + doc = doc.replace("{{JUMP}}", "paragraph 1.1") + doc = doc.replace("{{CITATION}}", _esc((book_meta or {}).get("citation") or "")) + if not (book_meta or {}).get("citation"): + doc = doc.replace('

', "") + doc = doc.replace("{{NAV}}", _build_nav(outline or {"chapters": []})) + doc = doc.replace("{{BODY}}", _build_body(records, footnotes, outline or {"chapters": []})) + doc = doc.replace("{{ORPHANS}}", _orphan_section(_orphan_notes(records, footnotes))) + doc = doc.replace("{{INDEX}}", index_block.render(index_payload)) + if source_type == "digital": + note = ("This text is the book's own, read from its born-digital PDF: there is no OCR " + "noise in it.") + note_more = ("Paragraphs marked as quotations are another author's words. The " + "paragraph numbers are the book's own, so a passage can be cited the " + "way the book cites it.") + else: + note = ("Scan with OCR text: the wording may carry OCR errors.") + note_more = ("Grade C paragraphs are marked; check the page image before quoting " + "them. The paragraph numbers are the book's own, so a passage can be " + "cited the way the book cites it.") + doc = doc.replace("{{NOTE}}", note) + doc = doc.replace("{{NOTE_MORE}}", "

%s

" % note_more) + return doc diff --git a/pipeline/book2corpus/ids.py b/pipeline/book2corpus/ids.py new file mode 100644 index 00000000..ff66d99b --- /dev/null +++ b/pipeline/book2corpus/ids.py @@ -0,0 +1,114 @@ +"""Identifiers. + +Two schemes, declared in the manifest so an agent knows how to cite: + + native the book's own paragraph numbers (this book: "7.14"). Human + citable: it is how the book's index and its tables of cases + refer to passages. + + anchored content-anchored ids for a book with no native numbering + ("c05-the-state-of-nature-0"): the chapter, the opening + words of the paragraph, and a collision counter. An id that + survives a re-split, because it is anchored to the text and + not to a position - a paragraph that moves because something + else was re-split keeps its id. + +The ordinal id an anchored id replaces is kept as an alias, so a citation +made before the change still resolves: the alias table is total, and the +old id still finds the paragraph. +""" +import re +import unicodedata + +NATIVE_RE = re.compile(r"^\d{1,2}\.\d{1,3}(?:\.\d{1,3})?$") +SLUG_WORDS = 4 +SLUG_MAX = 24 + + +def slug_of(text, words=SLUG_WORDS, cap=SLUG_MAX): + """A short, readable fingerprint of a paragraph's opening words. + + The opening words are the anchor: a paragraph's end may move, and its + neighbours may be re-split, but where it begins is what identifies it. + """ + norm = unicodedata.normalize("NFKC", text or "").lower() + norm = "".join(ch for ch in norm if not unicodedata.combining(ch)) + tokens = re.findall(r"[a-z0-9]+", norm) + if not tokens: + return "x" + return "-".join(tokens[:words])[:cap].strip("-") or "x" + + +class IdAssigner: + def __init__(self, native, front_leaf=0, synthetic=False): + self.native = native + self.front_leaf = front_leaf + self.synthetic = synthetic + self.counters = {} + self.used = set() + self.aliases = {} + + def _next(self, prefix, key): + k = (prefix, key) + self.counters[k] = self.counters.get(k, 0) + 1 + return self.counters[k] + + def _legacy_id(self, para): + """The ordinal id this paragraph used to have.""" + if para.kind == "body" and para.native_marker is None: + if self.synthetic: + key = "c%02d" % (para.chapter or 0) + return "%s-p%04d" % (key, self._next(key, key)) + scope = "fm" if para.leaf_start < self.front_leaf else "bm" + return "%s-p%04d" % (scope, self._next(scope, scope)) + if para.kind == "heading": + return "h-%d-%03d" % (para.chapter or 0, self._next("h", para.chapter)) + return "x-%04d" % self._next("x", 0) + + def _anchored_ids(self, paragraphs): + """A content-anchored id per paragraph, with a collision counter. + + The counter is per chapter and per slug, assigned in reading + order, so two paragraphs that begin the same way are told apart. + """ + out = {} + counters = {} + for para in paragraphs: + if para.kind != "body" or para.native_marker: + continue + chapter = para.chapter or 0 + slug = slug_of(para.text) + key = (chapter, slug) + k = counters.get(key, 0) + counters[key] = k + 1 + out[id(para)] = "c%02d-%s-%d" % (chapter, slug, k) + return out + + def assign(self, paragraphs, footnotes): + anchored = self._anchored_ids(paragraphs) if self.synthetic else {} + for para in paragraphs: + if para.kind == "body" and self.native and para.native_marker: + para.id = para.native_marker + elif para.kind == "heading": + para.id = "h-%d-%03d" % (para.chapter or 0, + self._next("h", para.chapter)) + elif para.kind == "body" and para.native_marker is None: + legacy = self._legacy_id(para) + para.id = anchored.get(id(para), legacy) + if legacy != para.id: + para.aliases = [legacy] + self.aliases[legacy] = para.id + else: + para.id = "x-%04d" % self._next("x", 0) + while para.id in self.used: + para.id = para.id + "~" + self.used.add(para.id) + for note in footnotes: + if note.get("id"): + self.used.add(note["id"]) + continue + note["id"] = "%s-fn-%03d" % (note["chapter_key"], note["n"]) + while note["id"] in self.used: + note["id"] = note["id"] + "~" + self.used.add(note["id"]) + note["citation"] = "%s fn %s" % (note["chapter_key"], note["n"]) diff --git a/pipeline/book2corpus/index_block.py b/pipeline/book2corpus/index_block.py new file mode 100644 index 00000000..a59966fd --- /dev/null +++ b/pipeline/book2corpus/index_block.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""book2corpus/index_block.py - the little block of cross-references. + +Written 26 Nov 2026 by MCode, after the ruling of Claude Opus 5.5 on the +corpus-wide term index (briefs 12 and 13). + +A reader has to stand on its own: it cannot ask the corpus a question at +read time. So the build answers the question in advance and writes the +answer into the reader, and this module says what that answer looks like. + +The ruling is that the reader shows ONE thing: a back-of-book index of the +book's own terms, and under each term one line saying which other books +use the same term. The counts, the five-places-per-book lists and the +whole slice are build data, not study aids, so they do not go in the page: +they go in .index.json beside it. + +So the block embedded in the HTML is small and holds only what is shown: +the term, the anchors of its first few occurrences in this book, and at +most three other books, each with its title, the chapter where the term +first appears there, and the link to that reader. +""" +import json +from html import escape + +BLOCK_VERSION = 1 + +# the anchors of the occurrences of one term +MAX_ANCHORS = 5 + +# the other books under one term +MAX_ALSO = 3 + + +def build(slice_rows, title_of=None, link_to=None, max_also=MAX_ALSO): + """The block, from the slice of one book. + + title_of(book) gives the title of another book; link_to(book, anchor) + gives the relative link to the place in that book where the term is. + """ + out = [] + for row in slice_rows: + also = [] + for other in row.get("also") or []: + book = other.get("book") + anchor = other.get("anchor") or "" + also.append([other.get("title") or book, + other.get("chapter") or "", + link_to(book, anchor) if link_to else ""]) + if len(also) >= max_also: + break + out.append({ + "l": row.get("label") or "", + "a": list(row.get("anchors") or [])[:MAX_ANCHORS], + "x": also, + }) + out.sort(key=lambda item: item["l"]) + return {"v": BLOCK_VERSION, "terms": out} + + +def render(payload): + """The index section, as the reader shows it. + + The reader shows one thing: the book's own terms, and under each term + the other books that use it in the same sense. The counts and the + whole slice stay in the data file; they are not study aids. + """ + rows = (payload or {}).get("terms") or [] + if not rows: + return "" + out = ['
', + '
Index
', + '
', + '

The terms of this book, and the other books ' + 'in the corpus that use the same term in the same sense. Every term ' + 'here was named by a reader of this book and checked against its ' + 'own text.

', + '
'] + for index, row in enumerate(rows, 1): + anchors = row.get("a") or [] + places = "" + if anchors: + links = [] + for number, anchor in enumerate(anchors, 1): + links.append('%d' + % (escape(anchor), number, number)) + places = ' (%s)' % " ".join(links) + out.append('
%s%s
' + % (index, escape(row.get("l") or ""), places)) + also = row.get("x") or [] + if also: + items = [] + for entry in also: + values = list(entry) + ["", "", ""] + title, chapter, href = values[0], values[1], values[2] + shown = escape(title) + if href: + shown = '%s' % (escape(href), shown) + if chapter: + shown += ' %s' % escape(chapter) + items.append(shown) + out.append('
Also in: %s
' % "; ".join(items)) + out.append('
') + return "\n".join(out) + + +def to_json(payload): + """The block as it is written into the page: one line, no spaces.""" + return json.dumps(payload, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + + +def from_json(text): + """The block, read back.""" + if not text: + return {"v": BLOCK_VERSION, "terms": []} + return json.loads(text) diff --git a/pipeline/book2corpus/ingest.py b/pipeline/book2corpus/ingest.py new file mode 100644 index 00000000..61a3896b --- /dev/null +++ b/pipeline/book2corpus/ingest.py @@ -0,0 +1,140 @@ +"""Adapters: source files in, pages of lines out. + +Only this layer knows what the source is. Everything else works on the IR. +""" +import glob +import json +import os +import re +from collections import Counter + +from .ir import Line, Page + +MARKER_RE = re.compile(r"^\[(\d+\.\d+(?:\.\d+)?)\]") + + +def load_scan_jsonl(path): + """Adapter for a scanned PDF that has been dumped to pages.jsonl.""" + pages = [] + with open(path, encoding="utf-8") as fh: + for line in fh: + rec = json.loads(line) + page = Page(pdf_page=rec["pdf_page"], leaf=rec["pdf_page"] - 1, + printed_page=(str(rec["printed_page"]) if rec["printed_page"] is not None else None), + height=rec.get("page_height", 647.8), + width=rec.get("page_width", 403.6), + header=rec.get("header", ""), + header_marker=rec.get("marker_top")) + for b in rec.get("lines", []): + page.lines.append(Line(text=b["text"], x0=b["x0"], x1=b["x1"], + y0=b["y0"], y1=b["y1"], size=b["size"])) + pages.append(page) + return pages + + +def load_leaf_page_map(path): + """The page map of the scan: leaf index -> printed page label.""" + if not os.path.exists(path): + return {} + with open(path, encoding="utf-8") as fh: + return {int(k): v for k, v in json.load(fh).items()} + + +def apply_leaf_page_map(pages, mapping): + """The scan's own page map wins; the OCR'd folio is only a cross-check.""" + for p in pages: + if p.leaf in mapping: + p.printed_page = mapping[p.leaf] + + +# ---------------------------------------------------------------- digital --- + +HEADER_BAND = 60.0 # y below this is the running head +FOLIO_BAND = 45.0 # y above height-this is the foot of the page +MARK_SIZE = 8.5 # a reference mark is set smaller than the text + + +def _line_text(spans): + """The line's text: the spans are contiguous pieces, so join them.""" + return "".join(s.get("text", "") for s in spans) + + +def load_digital_pdf(path, header_band=HEADER_BAND, folio_band=FOLIO_BAND, + mark_size=MARK_SIZE): + """Adapter for a born-digital PDF: a real text layer with real fonts. + + The running head and the folio are furniture; reference marks (the + superscript numbers a scholarly book uses for its endnotes) are read off + the small type and kept with the line that carries them. + """ + import fitz + + doc = fitz.open(path) + pages = [] + for index in range(doc.page_count): + page = doc[index] + height, width = page.rect.height, page.rect.width + obj = Page(pdf_page=index + 1, leaf=index, printed_page=None, + height=height, width=width) + header, folio = [], None + for block in page.get_text("dict").get("blocks", []): + if block.get("type") != 0: + continue + for line in block.get("lines", []): + # a span that carries only a space is still a space: dropping + # it welds two words together ("ITS" + "CONSEQUENCES") + spans = [s for s in line.get("spans", []) if s.get("text", "")] + if not spans: + continue + size = max(s.get("size", 0) for s in spans) + # the line's face is the one that carries the most characters, + # and a tie is broken by name: a set has no order, so an + # arbitrary choice would change between runs + weight = Counter() + for s in spans: + weight[s.get("font", "")] += len(s.get("text", "")) + main = sorted(weight, key=lambda f: (-weight[f], f))[0] + lead = spans[0].get("font", "") + x0, y0, x1, y1 = line["bbox"] + # a reference mark is set smaller than the text: keep it, but + # mark it so the reader can link it to the note it numbers + parts = [] + marks = [] + for s in spans: + t = s.get("text", "") + if s.get("size", 99) <= mark_size and t.strip().isdigit(): + marks.append(t.strip()) + parts.append("[%s]" % t.strip()) + else: + parts.append(t) + text = "".join(parts) + if y1 < header_band: + header.append((text, main, size)) + continue + if y0 > height - folio_band: + t = text.strip() + if re.fullmatch(r"[0-9ivxlcdm]{1,5}", t, re.I) and size >= 8.5: + folio = t + continue + if not text.strip(): + continue # a line that carries only spaces is not text + obj.lines.append(Line(text=text, x0=round(x0, 1), x1=round(x1, 1), + y0=round(y0, 1), y1=round(y1, 1), + size=round(size, 2), font=main, lead=lead, + marks=marks)) + for text, font, size in header: + if "Italic" in font: + obj.header = text.strip() + elif folio is None and re.fullmatch(r"[0-9ivxlcdm]{1,5}", text.strip(), re.I): + folio = text.strip() + if folio is None: + # on a chapter's opening page the folio is dropped to the foot + for index, line in enumerate(obj.lines): + t = line.text.strip() + if 8.5 <= line.size <= 9.4 and re.fullmatch(r"[0-9ivxlcdm]{1,5}", t, re.I): + folio = t + del obj.lines[index] # the folio is furniture, not text + break + obj.printed_page = folio + pages.append(obj) + return pages diff --git a/pipeline/book2corpus/ir.py b/pipeline/book2corpus/ir.py new file mode 100644 index 00000000..07ec616f --- /dev/null +++ b/pipeline/book2corpus/ir.py @@ -0,0 +1,87 @@ +"""Intermediate representation. + +Every adapter produces pages of lines; every later stage reads only these +objects. Nothing downstream touches the source file, which is what makes the +conservation gate possible: each line must end up in exactly one bucket. +""" +from dataclasses import dataclass, field +from typing import Optional + + +@dataclass +class Line: + text: str + x0: float + x1: float + y0: float + y1: float + size: float + font: str = "" + lead: str = "" # the face of the line's first span + sources: int = 1 # how many source lines this one stands for + marks: list = field(default_factory=list) # reference numbers carried by the line + + @property + def chars(self) -> int: + return max(1, len(self.text)) + + @property + def char_width(self) -> float: + """Rendered width per character: a measured proxy for the font size.""" + return (self.x1 - self.x0) / self.chars + + @property + def height(self) -> float: + return self.y1 - self.y0 + + +@dataclass +class Page: + pdf_page: int + leaf: int + printed_page: Optional[str] + height: float + width: float + lines: list = field(default_factory=list) + header: str = "" + header_marker: Optional[str] = None + header_lines: list = field(default_factory=list) + furniture: list = field(default_factory=list) + body: list = field(default_factory=list) + footnotes: list = field(default_factory=list) + + +@dataclass +class Paragraph: + kind: str = "body" # body | heading | footnote | table + text: str = "" + native_marker: Optional[str] = None + section_path: list = field(default_factory=list) + path: list = field(default_factory=list) + level: str = "" + leaf_start: int = 0 + leaf_end: int = 0 + page_start: Optional[str] = None + page_end: Optional[str] = None + quality: dict = field(default_factory=dict) + footnote_ids: list = field(default_factory=list) + anchor_id: Optional[str] = None + bboxes: list = field(default_factory=list) + id: str = "" + seq: int = 0 + chapter: int = 0 + flags: list = field(default_factory=list) + + +@dataclass +class Chapter: + number: int + title: str + start_leaf: int + label: str = "" # the book's own name for the unit: "Chapter 1" + end_leaf: int = 0 + paragraphs: list = field(default_factory=list) + expected_headings: list = field(default_factory=list) + minitoc_dropped: int = 0 + pages: list = field(default_factory=list) + divisions: list = field(default_factory=list) diff --git a/pipeline/book2corpus/judge.py b/pipeline/book2corpus/judge.py new file mode 100644 index 00000000..1668ca28 --- /dev/null +++ b/pipeline/book2corpus/judge.py @@ -0,0 +1,682 @@ +"""The judge: a model asked whether a picture is the figure the notes mean. + +The judge is the one part of the corpus that talks to a model. Everything +about it is written to be measured: + + * a call that fails is missing data, not a verdict. A rate of missing + calls is reported per tier, and a tier with more than a tenth of its + sample missing stays closed. + * a rate limit is waited out, a server error is tried again a few times, + and a request that is wrong is not tried again at all. + * the number of calls at once grows when the provider is happy and halves + when it is not, and a circuit breaker stops the run when the provider + has said no too often. + * every call is charged to a ledger, and the run stops before it + overshoots the cap. + * the verdict for a pair is cached under the hash of what was asked, so + the same question is never paid for twice and a correction re-audits + only the figures that changed. +""" +import base64 +import hashlib +import json +import os +import random +import re +import subprocess +import threading +import time +import urllib.error +import urllib.request + +from . import batch +from .pipeline import backoff_delay, classify_error + +SYSTEM = ("You check whether a picture from a textbook is the picture a note " + "describes.\nYou are given the picture itself, the caption the book " + "printed under it, and a written description of what the note says " + "the figure shows. Answer whether the picture and the text are about " + "the same figure.\nReply with one JSON object and nothing else:\n" + "{\"verdict\": \"match\" | \"partial\" | \"mismatch\" | " + "\"cannot_tell\", \"reason\": \"one sentence\"}\n" + "\"match\" means the picture shows what the text describes.\n" + "\"partial\" means it is the same figure but the text describes " + "something the picture does not show, or shows something extra.\n" + "\"mismatch\" means they are different figures.\n" + "\"cannot_tell\" means the picture is too small, blank or unclear " + "to judge.") + +# the models that think, and take the effort switch with them +THINKING_MODELS = ("claude-opus-5-5", "claude-sonnet-5-5") + +# the system of a general question: the question carries its own shape +TEXT_SYSTEM = ("You answer a question about documents. Reply with the JSON " + "object the question asks for, and nothing else.") + +QUESTION = ("The caption the book printed: {caption}\n" + "The written description of the figure: {description}\n" + "The kind of figure: {kind}\n" + "Is the picture the same figure as the text describes?") + +GEMINI_API = "https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s" +ANTHROPIC_API = "https://api.anthropic.com/v1/messages" +OPENROUTER_API = "https://openrouter.ai/api/v1/chat/completions" + +# the door the Antigravity suite is opened with +AGY_CLI = os.path.expanduser("~/.local/bin/agy") + +# the doors a judge may be asked through +# +# A route names the models it may carry and the door it carries them +# through. The model is checked against the route before the first call, +# and a model the route does not carry is refused: a stage that asked a +# different model behind the same name would answer a different question, +# and the cache would carry that answer under the old question's key. +# +# The antigravity route is the same model behind another door. The name in +# the settings stays the one the corpus was judged with, so the cache still +# answers, and the model it carries there is written in "on_the_other_side". +# +# The gemini CLI itself is no longer a door: it answers "This client is no +# longer supported for Gemini Code Assist for individuals" and stops. The +# Gemini models come through the antigravity route instead. +ROUTES = { + "anthropic": { + "door": "anthropic", + "models": ("claude-opus-5-5", "claude-sonnet-5-5", + "claude-haiku-4-5-20251001"), + }, + "gemini": { + "door": "gemini", + "models": ("gemini-3.8-flash", "gemini-3.1-flash-lite", + "gemini-3.1-pro-preview"), + }, + "openrouter": { + "door": "openrouter", + "models": ("google/gemini-3.8-flash",), + }, + "antigravity": { + "door": "antigravity", + "models": ("claude-sonnet-5-5", "claude-opus-5-5", + "gemini-4-neon-xhigh", "gemini-4-carbon-high", + "gemini-4-hydrogen-xhigh"), + "on_the_other_side": { + "claude-sonnet-5-5": "claude-sonnet-5-5-high", + "claude-opus-5-5": "claude-opus-5-5-high", + "gemini-4-neon-xhigh": "gemini-4-neon-xhigh", + "gemini-4-carbon-high": "gemini-4-carbon-high", + "gemini-4-hydrogen-xhigh": "gemini-4-hydrogen-xhigh", + }, + }, +} + + +def _key(path): + """The key of a service, read from the store and never printed.""" + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + if ":" in line: + return line.split(":", 1)[1].strip() + return line + raise RuntimeError("no key in %s" % path) + + +def media_type(path): + lower = path.lower() + if lower.endswith(".png"): + return "image/png" + if lower.endswith(".webp"): + return "image/webp" + if lower.endswith(".gif"): + return "image/gif" + return "image/jpeg" + + +class ParseFailure(Exception): + """The model answered, but not in the shape that was asked for. + + This is worth trying again: the same question, asked again, is often + answered properly. It is not a dead end, and it is never a verdict. + """ + + retryable = True + + +class Judge(object): + """One model asked one question, carefully.""" + + def __init__(self, settings, ledger, breaker, cache_path=None): + self.settings = settings + self.ledger = ledger + self.breaker = breaker + self.lock = threading.Lock() + self.workers = settings.get("workers", 4) + self.max_workers = settings.get("max_workers", 16) + self.attempts = settings.get("attempts", 5) + self.base = settings.get("backoff_base", 2.0) + self.cap = settings.get("backoff_cap", 60.0) + self.model = settings.get("model", "gemini-3.8-flash") + # the door this judge is asked through, and the models that door + # may carry. An empty route means the model name decides, which + # is how the corpus has always been judged. + self.route = (settings.get("route") or "").strip() + if self.route and self.route not in ROUTES: + raise ValueError("the judge has no route called %r" % self.route) + self.timeout = int(settings.get("timeout", 240)) + # what an answer may cost: a thinking model spends this before it + # says anything, and a prompt that needs thought can spend it all + self.max_output = int(settings.get("max_output_tokens", 900)) + self.fallback = settings.get("fallback_model", "claude-sonnet-5-5") + self.cache = {} + self.cache_path = cache_path + if cache_path and os.path.exists(cache_path): + with open(cache_path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except ValueError: + continue + self.cache[row.get("key")] = row + + # ---- the cache ---------------------------------------------------- + + @staticmethod + def pair_key(picture_path, caption, description, kind, model, prompt_hash): + """What makes a question the same question.""" + with open(picture_path, "rb") as fh: + picture = hashlib.sha256(fh.read()).hexdigest() + material = json.dumps({"picture": picture, "caption": caption or "", + "description": description or "", "kind": kind or "", + "model": model, "prompt": prompt_hash}, + sort_keys=True, ensure_ascii=False) + return hashlib.sha256(material.encode("utf-8")).hexdigest() + + def cached(self, key): + with self.lock: + return self.cache.get(key) + + def remember(self, key, row): + with self.lock: + self.cache[key] = row + if self.cache_path: + os.makedirs(os.path.dirname(self.cache_path), exist_ok=True) + with open(self.cache_path, "a", encoding="utf-8") as fh: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + + # ---- the call ----------------------------------------------------- + + def _gemini(self, path, kind, caption, description): + with open(path, "rb") as fh: + data = base64.b64encode(fh.read()).decode("ascii") + body = {"contents": [{"parts": [ + {"inline_data": {"mime_type": media_type(path), "data": data}}, + {"text": SYSTEM + "\n\n" + QUESTION.format( + caption=caption or "none", description=description or "none", + kind=kind or "unknown")}]}], + "generationConfig": {"maxOutputTokens": 900, "temperature": 0, + "thinkingConfig": {"thinkingBudget": 0}}} + key = _key(os.path.expanduser("~/claude-keys/gemini.header")) + url = GEMINI_API % (self.model, key) + request = urllib.request.Request( + url, data=json.dumps(body).encode("utf-8"), + headers={"content-type": "application/json"}) + with urllib.request.urlopen(request, timeout=180) as response: + answer = json.load(response) + text = "".join(part.get("text", "") + for part in answer["candidates"][0]["content"]["parts"]) + usage = answer.get("usageMetadata") or {} + return text, usage.get("promptTokenCount", 0), usage.get("candidatesTokenCount", 0) + + def _anthropic(self, path, kind, caption, description): + with open(path, "rb") as fh: + data = base64.b64encode(fh.read()).decode("ascii") + body = {"model": self.fallback, "max_tokens": 1500, + "thinking": {"type": "adaptive"}, + "output_config": {"effort": "low"}, + "system": SYSTEM, + "messages": [{"role": "user", "content": [ + {"type": "image", "source": {"type": "base64", + "media_type": media_type(path), + "data": data}}, + {"type": "text", "text": QUESTION.format( + caption=caption or "none", + description=description or "none", + kind=kind or "unknown")}]}]} + key = _key(os.path.expanduser("~/claude-keys/anthropic.header")) + request = urllib.request.Request( + ANTHROPIC_API, data=json.dumps(body).encode("utf-8"), + headers={"x-api-key": key, "content-type": "application/json", + "anthropic-version": "2023-06-01"}) + with urllib.request.urlopen(request, timeout=180) as response: + answer = json.load(response) + text = "".join(block.get("text", "") for block in answer.get("content", []) + if block.get("type") == "text") + usage = answer.get("usage") or {} + return text, usage.get("input_tokens", 0), usage.get("output_tokens", 0) + + def _gemini_text(self, prompt, model, config): + """One answer from a Gemini model. + + A model that only works in thinking mode refuses a thinking + budget of zero, so the question is asked again without one: the + model then thinks as much as it wants, and the room for the + answer grows to cover the thinking. + """ + key = _key(os.path.expanduser("~/claude-keys/gemini.header")) + url = GEMINI_API % (model, key) + body = {"contents": [{"parts": [{"text": prompt}]}], + "generationConfig": config} + request = urllib.request.Request( + url, data=json.dumps(body).encode("utf-8"), + headers={"content-type": "application/json"}) + try: + with urllib.request.urlopen(request, timeout=180) as response: + answer = json.load(response) + except urllib.error.HTTPError as exc: + detail = exc.read().decode("utf-8", "replace") + if exc.code != 400 or "thinking" not in detail.lower(): + raise + body["generationConfig"] = { + name: value for name, value in config.items() + if name != "thinkingConfig"} + body["generationConfig"]["maxOutputTokens"] = max( + 8192, config.get("maxOutputTokens") or 0) + request = urllib.request.Request( + url, data=json.dumps(body).encode("utf-8"), + headers={"content-type": "application/json"}) + with urllib.request.urlopen(request, timeout=180) as response: + answer = json.load(response) + text = "".join(part.get("text", "") + for part in answer["candidates"][0]["content"]["parts"]) + usage = answer.get("usageMetadata") or {} + return (text, usage.get("promptTokenCount", 0), + usage.get("candidatesTokenCount", 0)) + + @staticmethod + def _bearer(path): + """A key that is already a header value, ready to be sent.""" + value = _key(os.path.expanduser(path)) + if value.lower().startswith("bearer "): + return value + return "Bearer " + value + + def _openrouter(self, prompt, model, max_tokens=1024): + """One answer from a model that another account pays for. + + The same model can be reached through more than one door. When + the door it came from is spent, the same model behind another + door is the same model, and the answer is the same answer. + """ + body = {"model": model, "max_tokens": max_tokens, "temperature": 0, + "messages": [{"role": "user", "content": prompt}]} + request = urllib.request.Request( + OPENROUTER_API, data=json.dumps(body).encode("utf-8"), + headers={"content-type": "application/json", + "Authorization": self._bearer("~/claude-keys/openrouter.header")}) + with urllib.request.urlopen(request, timeout=180) as response: + answer = json.load(response) + text = answer["choices"][0]["message"]["content"] + usage = answer.get("usage") or {} + return text, usage.get("prompt_tokens", 0), usage.get("completion_tokens", 0) + + def _antigravity(self, prompt, model): + """One answer from the Antigravity suite. + + The CLI is the door, and its answer comes in an envelope: the + answer is the response, and an envelope that says the call + failed is a failure, not an answer. The model the door carries + is the one written in the route, so the name the corpus uses + stays the name the corpus uses. + """ + there = ROUTES["antigravity"]["on_the_other_side"].get(model, model) + command = [AGY_CLI, "--print", prompt, + "--model", there, + "--output-format", "json", + "--dangerously-skip-permissions", + "--print-timeout", "%ds" % self.timeout] + try: + completed = subprocess.run(command, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=self.timeout + 60) + except subprocess.TimeoutExpired: + raise RuntimeError("the antigravity route did not answer in time") + raw = completed.stdout.decode("utf-8", "replace") + start = raw.find("{") + end = raw.rfind("}") + if start < 0 or end < start: + raise RuntimeError("the antigravity route answered no envelope") + try: + envelope = json.loads(raw[start:end + 1]) + except ValueError: + raise RuntimeError("the antigravity route answered an envelope " + "that does not parse") + if envelope.get("status") != "SUCCESS": + raise RuntimeError("the antigravity route failed: %s" + % (envelope.get("error") or "no reason given")) + usage = envelope.get("usage") or {} + return (envelope.get("response") or "", + int(usage.get("input_tokens") or 0), + int(usage.get("output_tokens") or 0)) + + @staticmethod + def _verdict(text): + """The answer in the text: the last complete JSON object. + + The model sometimes writes an object, then thinks, then writes the + final object. The greedy span from the first brace to the last takes + all of it, which is two objects and does not parse, so the objects + are taken one at a time and the last one wins. The first and the + last are compared, and a difference is written down, because that is + the case where the model changed its mind. + """ + objects = Judge._objects(text or "") + if not objects: + return None + if len(objects) > 1 and objects[0] != objects[-1]: + print("the model wrote %d JSON objects and the first is not the " + "last; the last one is the answer" % len(objects)) + return objects[-1] + + @staticmethod + def _objects(text): + """Every complete top-level JSON object in the text, in order. + + A brace inside a string is not a brace, so the strings are read + as strings while the object is counted, and the objects inside an + object are not counted again. + """ + found = [] + index = 0 + length = len(text) + while index < length: + start = text.find('{', index) + if start < 0: + break + depth = 0 + in_string = False + escape = False + end = -1 + for position in range(start, length): + ch = text[position] + if in_string: + if escape: + escape = False + elif ch == chr(92): + escape = True + elif ch == chr(34): + in_string = False + continue + if ch == chr(34): + in_string = True + elif ch == '{': + depth += 1 + elif ch == '}': + depth -= 1 + if depth == 0: + end = position + break + if end < 0: + break + try: + found.append(json.loads(text[start:end + 1])) + except ValueError: + pass + index = end + 1 + return found + + def text(self, prompt, key, model=None, expect=None, allowed=None, + parse=None): + """One answer from the model, from the cache when it is there. + + This is the same call as judge() without the picture: it is how + the corpus asks the model a question about two things at once, and + how the cache keeps the answer. + + `expect` names the field the answer has to carry and `allowed` + the values it may carry. An answer without that field, or with a + value outside the set, is not an answer: it is a parse failure and + it is tried again like any other failure. Nothing here invents a + default - a question the model did not answer stays missing. + """ + model = model or self.model + if self.route and model not in ROUTES[self.route]["models"]: + raise RuntimeError( + "the route %s does not carry the model %s, and a judge that" + " asks another model behind the same name answers a" + " different question" % (self.route, model)) + found = self.cached(key) + if found is not None: + found = dict(found) + found["cached"] = True + return found + attempt = 0 + while attempt < self.attempts: + attempt += 1 + try: + if self.route: + text, tokens_in, tokens_out = self._antigravity( + prompt, model) + elif model.startswith("claude-"): + body = {"model": model, "max_tokens": 1500, + "system": TEXT_SYSTEM, + "messages": [{"role": "user", + "content": [{"type": "text", + "text": prompt}]}]} + if model in THINKING_MODELS: + # the 5.x models think, and their thinking is + # billed as output; the older ones do not take the + # switch at all + body["thinking"] = {"type": "adaptive"} + body["output_config"] = {"effort": "low"} + request = urllib.request.Request( + ANTHROPIC_API, data=json.dumps(body).encode("utf-8"), + headers={"x-api-key": _key(os.path.expanduser( + "~/claude-keys/anthropic.header")), + "content-type": "application/json", + "anthropic-version": "2023-06-01"}) + with urllib.request.urlopen(request, timeout=180) as response: + answer = json.load(response) + text = "".join(block.get("text", "") + for block in answer.get("content", []) + if block.get("type") == "text") + usage = answer.get("usage") or {} + tokens_in = usage.get("input_tokens", 0) + tokens_out = usage.get("output_tokens", 0) + elif "/" in model: + text, tokens_in, tokens_out = self._openrouter(prompt, model) + else: + text, tokens_in, tokens_out = self._gemini_text( + prompt, model, + {"maxOutputTokens": self.max_output, + "temperature": 0, + "thinkingConfig": {"thinkingBudget": 0}}) + parsed = (parse or self._verdict)(text) + if parsed is None: + raise ParseFailure("the model wrote no verdict") + if expect is not None and parsed.get(expect) not in allowed: + # the model answered outside the set: this is a parse + # failure, and it is tried again, not accepted with a + # value nobody said + raise ParseFailure("the model answered %r for %r" + % (parsed.get(expect), expect)) + self.ledger.add(model, tokens_in, tokens_out) + self.breaker.record(True) + # the answer is kept whole: a prompt may ask for "verdict" + # (a picture) or for "relation" (two terms), and the shape + # of the question decides the shape of the answer + if isinstance(parsed, dict): + # a prompt may ask for a field this prompt did not + # ask for: a form answer has no "verdict", and saying + # "error" would be a lie + verdict = parsed.get("verdict") + relation = parsed.get("relation") + else: + verdict = None + relation = None + # the answer was an answer: a prompt may ask for a field + # this prompt did not ask for, and "verdict" is not the + # field every answer carries + ok = True + row = {"key": key, "verdict": verdict, + "relation": relation, + "ok": ok, + "answer": parsed, + "raw": text[:1200], + "reason": (parsed.get("reason") or "")[:300] + if isinstance(parsed, dict) else "", + "model": model, "tokens_in": tokens_in, + "tokens_out": tokens_out, "cached": False} + self.remember(key, row) + return row + except Exception as exc: + kind_of = classify_error(exc) + self.ledger.failed += 1 + self.breaker.record(False) + if kind_of == "fatal" or attempt >= self.attempts: + # a call that failed is missing data, not an answer: + # it is not cached, so the next run asks again + row = {"key": key, "verdict": "error", + "relation": None, "ok": False, + "answer": None, "raw": None, + "reason": str(exc)[:200], "model": model, + "tokens_in": 0, "tokens_out": 0, "cached": False} + return row + self.ledger.retried += 1 + wait = getattr(exc, "headers", None) and \ + exc.headers.get("retry-after") + if not wait: + wait = backoff_delay(attempt, self.base, self.cap) + time.sleep(float(wait)) + return {"key": key, "verdict": "error", "relation": None, + "answer": None, "raw": None, + "reason": "the judge gave up", + "model": model, "cached": False} + + def text_batch(self, items, model=None, parse=None): + """Many answers, asked as one job. + + The items are (key, prompt) pairs and the keys are the same keys + the single calls use, so an answer that came from a batch and an + answer that was asked on its own are the same answer as far as the + corpus is concerned. The answer is parsed with the same parser and + a request that failed comes back as missing, never as a verdict. + """ + model = model or self.model + if not items: + return {}, None, 0.0 + if parse is None: + parse = self._verdict + batch_id = batch.submit([{"key": key, "prompt": prompt} + for key, prompt in items], + model=model) + answers, seconds = batch.collect(batch_id) + rows = {} + for key, row in answers.items(): + if row.get("ok"): + try: + row["answer"] = parse(row.get("raw") or "") + except Exception: + row["ok"] = False + row["answer"] = None + row["reason"] = "the answer was not the shape that was asked for" + row["model"] = model + if row.get("ok"): + # the batch is not metered by the ledger until now: its + # answers are charged like any other + self.ledger.add(model, row.get("tokens_in", 0), + row.get("tokens_out", 0)) + rows[key] = row + return rows, batch_id, seconds + + def _picture_prompt(self, path, kind, caption, description): + """The question with the picture named, for a door that reads files.""" + return ("The picture is the file %s. Open it and look at it before you\n" + "answer.\n\n%s\n\n%s" + % (os.path.abspath(path), SYSTEM, + QUESTION.format(caption=caption or "none", + description=description or "none", + kind=kind or "unknown"))) + + def judge(self, path, kind, caption, description, model=None): + """One judgement, with the failures handled and the cost charged.""" + prompt_hash = hashlib.sha256((SYSTEM + QUESTION).encode("utf-8")).hexdigest() + model = model or self.model + if self.route and model not in ROUTES[self.route]["models"]: + raise RuntimeError( + "the route %s does not carry the model %s, and a judge that" + " asks another model behind the same name answers a" + " different question" % (self.route, model)) + key = self.pair_key(path, caption, description, kind, model, prompt_hash) + found = self.cached(key) + if found is not None: + found = dict(found) + found["cached"] = True + return found + attempt = 0 + while attempt < self.attempts: + attempt += 1 + try: + if self.route: + text, tokens_in, tokens_out = self._antigravity( + self._picture_prompt(path, kind, caption, description), + model) + elif model == self.fallback: + text, tokens_in, tokens_out = self._anthropic( + path, kind, caption, description) + else: + text, tokens_in, tokens_out = self._gemini( + path, kind, caption, description) + parsed = self._verdict(text) + if parsed is None: + raise RuntimeError("the model wrote no verdict") + self.ledger.add(model, tokens_in, tokens_out) + self.breaker.record(True) + row = {"key": key, "verdict": parsed.get("verdict") or "error", + "reason": (parsed.get("reason") or "")[:300], + "model": model, "tokens_in": tokens_in, + "tokens_out": tokens_out, "cached": False} + self.remember(key, row) + return row + except Exception as exc: + kind_of = classify_error(exc) + self.ledger.failed += 1 + self.breaker.record(False) + if kind_of == "fatal" or attempt >= self.attempts: + row = {"key": key, "verdict": "error", + "relation": None, "answer": None, "raw": None, + "reason": str(exc)[:200], "model": model, + "tokens_in": 0, "tokens_out": 0, "cached": False} + self.remember(key, row) + return row + self.ledger.retried += 1 + wait = getattr(exc, "headers", None) and \ + exc.headers.get("retry-after") + if not wait: + wait = backoff_delay(attempt, self.base, self.cap) + time.sleep(float(wait)) + return {"key": key, "verdict": "error", "relation": None, + "answer": None, "raw": None, + "reason": "the judge gave up", + "model": model, "cached": False} + + +def plant(pairs, share, seed=20261128): + """Put the held-out pairs into a batch, where the judge cannot see them. + + A planted pair must be indistinguishable from a real one: the same + prompt, the same picture, an opaque name, and a position among the + others. The pairs come from a file that is pinned by its hash, so a + change to it has to be deliberate. + """ + random.seed(seed) + held = list(pairs) + random.shuffle(held) + take = int(round(len(pairs) * share)) + planted = held[:take] + return planted \ No newline at end of file diff --git a/pipeline/book2corpus/layout.py b/pipeline/book2corpus/layout.py new file mode 100644 index 00000000..40f774ce --- /dev/null +++ b/pipeline/book2corpus/layout.py @@ -0,0 +1,189 @@ +"""Geometry: where the furniture is, and where the footnotes start. + +Nothing here reads meaning from words. The footnote split is a small +per-page optimisation over candidate boundaries, scored on three measured +signals: type size (rendered character width), the book's own footnote +number sequence, and the vertical gap. +""" +import re + +FOOTNOTE_NUMBER_RE = re.compile(r"^[^A-Za-z0-9]{0,3}(\d{1,3})[^A-Za-z0-9.]{0,3}(?:\s|$)") +# a numbered paragraph of the book, in the shape the book prints it: "[1.20]" +PARAGRAPH_MARKER_RE = re.compile(r"^\s*\[\s*\d{1,2}\s*\.\s*\d{1,3}(?:\s*\.\s*\d{1,3})?\s*\]") +HEADER_BAND = 42.0 # y below this is the running head +FOOTER_BAND = 48.0 # y above height-this is the foot of the page +MIN_FOOTNOTE_GAP = 13.0 # a visible gap between the body and the notes +# a sentence can end here +TERMINAL = ".!?\"'\u2019\u201d\u2019)\"'" + + +def split_furniture(page): + """Take the running head and the folio off the page. Tag, do not delete.""" + head, foot, rest = [], [], [] + for line in page.lines: + if line.y1 < HEADER_BAND: + head.append(line) + elif line.y0 > page.height - FOOTER_BAND and re.fullmatch(r"[0-9ivxlcdm]{1,5}", line.text.strip(), re.I): + foot.append(line) + else: + rest.append(line) + page.header_lines = head + page.furniture = foot + page.lines = rest + return page + + +def median(values): + values = sorted(values) + if not values: + return 0.0 + mid = len(values) // 2 + if len(values) % 2: + return values[mid] + return (values[mid - 1] + values[mid]) / 2.0 + + +def page_metrics(page): + """Measured proxies: character width, line pitch, right margin.""" + widths = [ln.char_width for ln in page.lines] + cw = median(widths) + y0s = [ln.y0 for ln in page.lines] + pitch = median([b - a for a, b in zip(y0s, y0s[1:])]) or 10.0 + right = max((ln.x1 for ln in page.lines), default=page.width) + return cw, pitch, right + + +def footnote_number(line): + m = FOOTNOTE_NUMBER_RE.match(line.text) + return int(m.group(1)) if m else None + + +def split_footnotes(page, expected_next=None, exclude=None): + """Choose the boundary between the body and the notes at the foot. + + Three signals, in this order of trust: + + * the book's own footnote numbering - the notes at the foot carry the + numbers that continue the chapter's sequence, and that sequence is + intact even where the OCR has mangled the words; + * justification - body lines are justified to the right margin, notes are + ragged, so the notes start after the last justified line; + * type size and the vertical gap. + + Block quotations are set smaller than the body, so size alone cannot + separate them from notes; the number and the margin can. + """ + if not page.lines: + return + cw, pitch, right = page_metrics(page) + lower = page.height * 0.45 + + justified = [i for i, ln in enumerate(page.lines) if right and ln.x1 >= right * 0.93] + + exclude = exclude or set() + candidates = [] + for i, line in enumerate(page.lines): + if line.y0 < lower or id(line) in exclude: + continue + if footnote_number(line) is not None or line.char_width < cw * 0.93: + candidates.append(i) + if not candidates: + page.body = list(page.lines) + page.footnotes = [] + return + + def score(i): + below = page.lines[i:] + if not below: + return -1e9 + small_below = sum(1 for ln in below if ln.char_width < cw * 0.93) / len(below) + s = 2.0 * small_below + nums = [footnote_number(ln) for ln in below] + nums = [x for x in nums if x is not None] + if nums and expected_next is not None: + if nums[0] == expected_next: + s += 6.0 + elif expected_next <= nums[0] <= expected_next + 5: + s += 3.0 + else: + s -= 2.0 + if i > 0: + gap = page.lines[i].y0 - page.lines[i - 1].y1 + s += min(gap / pitch, 3.0) / 3.0 + else: + s -= 1.0 + return s + + # Two independent signals, and the page is split where they agree. + # + # 1. The layout: the notes at the foot are separated from the body by a + # visible gap, bigger than the line pitch. + # 2. The book: the notes carry the numbers that continue the chapter's + # sequence, and that sequence survives even where the OCR has mangled + # the words. + lower = page.height * 0.45 + gap_split = len(page.lines) + best_gap = 0.0 + for i in range(1, len(page.lines)): + if page.lines[i].y0 < lower: + continue + gap = page.lines[i].y0 - page.lines[i - 1].y1 + if gap > best_gap: + best_gap, gap_split = gap, i + + seq_split = None + for i, ln in enumerate(page.lines): + if id(ln) in exclude: + continue + n = footnote_number(ln) + if n is None: + continue + if expected_next is None or (expected_next <= n <= expected_next + 5): + seq_split = i + break + + if seq_split is not None and page.lines[seq_split].y0 > page.height * 0.55: + # the book's own numbering says where the notes start + start = seq_split + elif best_gap >= MIN_FOOTNOTE_GAP: + start = gap_split + else: + page.body = list(page.lines) + page.footnotes = [] + return + + # notes whose number the OCR lost sit above the first readable one + limit = max(0, start - 12) + while start > limit: + ln = page.lines[start - 1] + if id(ln) in exclude: + break + if PARAGRAPH_MARKER_RE.match(ln.text): + # a numbered paragraph of the book is body text, whatever its + # width: the notes cannot start above it, or the paragraphs it + # introduces would be swallowed by the notes + break + ragged = bool(right) and ln.x1 < right * 0.90 + if ragged or ln.char_width < cw * 0.93: + start -= 1 + else: + break + # The boundary is wrong if a numbered paragraph of the book sits in the + # notes, or if the body's last line runs on: in both cases the notes + # start lower, at the first line that carries a note number. This + # happens when the gap between body and notes is not where the layout + # thinks it is, and the note numbers on the page then match nothing. + runs_on = True + if start > 0: + tail = page.lines[start - 1].text.rstrip() + runs_on = bool(tail) and (tail[-1] in TERMINAL or tail.endswith("-")) + swallowed = any(PARAGRAPH_MARKER_RE.match(ln.text) + for ln in page.lines[start:]) + if (not runs_on or swallowed) and start < len(page.lines): + for k in range(start, len(page.lines)): + if footnote_number(page.lines[k]) is not None: + start = k + break + + page.body = page.lines[:start] + page.footnotes = page.lines[start:] diff --git a/pipeline/book2corpus/notes.py b/pipeline/book2corpus/notes.py new file mode 100644 index 00000000..8b958e77 --- /dev/null +++ b/pipeline/book2corpus/notes.py @@ -0,0 +1,1336 @@ +"""The notes corpora: study notes turned into a book reader. + +The notes in these corpora are plain text with two structures in them. A +page marker says which page of the book a stretch of text came from. A +figure block records a visual: its type, the caption the book printed, a +written description of what it shows, the text printed inside it, and +where the description came from. + +The pictures themselves live in a separate library of images taken from the +books' own PDFs. This finds the image for each figure on evidence - the +printed caption, then the page, then the order on the page - and puts it +next to the description, saying how it was matched. A figure whose image +cannot be found on evidence keeps its description and says so. + +Nothing is cleaned up and nothing is summarised: the notes are the corpus, +and the reader shows them as they are. +""" +import base64 +import hashlib +import io +import json +import os +import re +from html.parser import HTMLParser + +from . import counts_line +from . import index_block +from . import figures + +# The marker comes in two shapes: bare, and with a note of how the page +# was read ("; read from the image: OCR mode"). Both are the same +# marker, and a marker that is not recognised loses the page it names. +PAGE_RE = re.compile(r"^=== PAGE (.+?) \(PDF page (\d+)(?:;[^)]*)?\) ===\s*$") +FIGURE_RE = re.compile(r"\[FIGURE ([^\]]*)\]\s*$") +CITATION_RE = re.compile(r"^Source:\s*(.+?)\s*$") +FIELDS = ("TYPE", "CAPTION", "CONTENT", "TEXT IN FIGURE", "SOURCE") +FIGURE_INDEX = "agent-index" +MAX_EDGE = 1200 +WEBP_QUALITY = 76 +EMBED_BUDGET = 14 * 1024 * 1024 +SOFT_BUDGET = 25 * 1024 * 1024 +HARD_BUDGET = 50 * 1024 * 1024 +LEVELS = ((1200, 76), (1000, 70), (900, 66)) +RECORDS = {} +CATALOGUE = {} + + +def _norm(text): + return re.sub(r"[^a-z0-9]+", " ", (text or "").lower()).strip() + + +def _sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def parse_chapter(path): + """One chapter file: its title, its citation and its blocks. + + A paragraph is a run of lines separated by a blank line. A figure + block is a header line - which may carry a prefix such as + "FIGURES ON THIS PAGE:" - followed by its fields and a "--". + """ + with io.open(path, encoding="utf-8") as fh: + lines = fh.read().splitlines() + title = "" + citation = "" + blocks = [] + page = None + pdf_page = None + paragraph = [] + index = 0 + + def flush_paragraph(): + if paragraph: + blocks.append({"kind": "paragraph", "text": chr(10).join(paragraph), + "page": page, "pdf_page": pdf_page}) + del paragraph[:] + + while index < len(lines): + line = lines[index] + stripped = line.strip() + found = PAGE_RE.match(line) + if found: + flush_paragraph() + page = found.group(1) + pdf_page = found.group(2) + blocks.append({"kind": "page", "text": stripped, "page": page, + "pdf_page": pdf_page}) + index += 1 + continue + found = FIGURE_RE.search(line) + if found: + flush_paragraph() + if not _fields_follow(lines, index + 1): + # a marker that says a figure sits here, not a figure's own + # record: the notes write it where the picture is + blocks.append({"kind": "placeholder", "text": found.group(1).strip(), + "page": page, "pdf_page": pdf_page, + "fields": {}, "label": found.group(1).strip()}) + index += 1 + continue + fields = {} + last_field = None + cursor = index + 1 + while cursor < len(lines): + nxt = lines[cursor].strip() + if nxt == "--" or nxt == "": + break + if ":" in nxt: + key, value = nxt.split(":", 1) + name = field_name(key) + if name in FIELDS: + fields.setdefault(name, value.strip()) + last_field = name + cursor += 1 + continue + # a line that fits no field belongs to the field above it: + # the descriptions are written over several lines + if fields and last_field: + fields[last_field] = (fields[last_field] + " " + nxt).strip() + cursor += 1 + blocks.append({"kind": "figure", "text": "", "page": page, + "pdf_page": pdf_page, "fields": fields, + "label": found.group(1).strip()}) + index = cursor + 1 + continue + if stripped.startswith("# ") and not title: + title = stripped[2:].strip() + index += 1 + continue + found = CITATION_RE.match(stripped) + if found and not citation: + citation = found.group(1) + index += 1 + continue + if not stripped: + flush_paragraph() + index += 1 + continue + paragraph.append(stripped) + index += 1 + flush_paragraph() + return {"title": title, "citation": citation, "blocks": blocks} + + +def field_name(key): + """The field a line belongs to: the notes write "CONTENT, by type: ..." + as well as "CONTENT: ...", and the two are the same field.""" + return key.strip().upper().split(",")[0].strip() + + +def _fields_follow(lines, start): + """Do a figure's own fields follow this line?""" + for line in lines[start:start + 4]: + stripped = line.strip() + if not stripped: + continue + if stripped == "--": + return False + if ":" in stripped: + return field_name(stripped.split(":", 1)[0]) in FIELDS + return False + return False + + +def _catalogue(library): + """The whole catalogue, read once, grouped by book. + + The file is 31 MB and there are 38 books in it: reading it once per + book made a build read it 38 times. This reads it once and hands out + the group each book needs. + """ + if library in CATALOGUE: + return CATALOGUE[library] + index = os.path.join(library, FIGURE_INDEX + ".jsonl") + grouped = {} + if os.path.exists(index): + with io.open(index, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + record = json.loads(line) + grouped.setdefault(record.get("book"), []).append(record) + CATALOGUE[library] = grouped + return grouped + + +def _all_records(library, book): + """Every catalogue record for one book.""" + return list(_catalogue(library).get(book, [])) + + +def records_for(library, book): + """The catalogue records for one book. + + The whole book, not one chapter. The page is what finds a picture, + and a chapter's name is only one of the keys: a catalogue that names + some chapters and not others must not cut the pictures away. + """ + key = "book|%s" % book + if key not in RECORDS: + RECORDS[key] = _all_records(library, book) + return RECORDS[key] + + +def match_figures(blocks, records, library=None): + """Give every figure block an image, on evidence, and say how. + + The blocks are the whole book's: the passes run one tier at a time + over all of them, so that "the picture left on the page" means the + same thing wherever it is read. + """ + return figures.match(blocks, records, library) + + +def _manifest_entries(book_dir): + """The manifest of the last build, read once. + + It used to be read once per picture: a book with 385 pictures read + and parsed the whole manifest 385 times, which was most of the build. + """ + manifest_path = os.path.join(book_dir, "figures.json") + if not os.path.exists(manifest_path): + return {} + try: + with open(manifest_path, encoding="utf-8") as fh: + return {e.get("id"): e + for e in (json.load(fh) or {}).get("figures", [])} + except Exception: + return {} + + +def _made_picture(book_dir, image_id, entries=None, library=None): + """The picture that is already made, if it is still the right one. + + A rebuild that changes nothing should not spend an hour turning the + library's pictures into WebP again: the file beside the reader is + kept only if its hash is the one the manifest names. + """ + if entries is None: + entries = _manifest_entries(book_dir) + entry = entries.get(image_id) + if not entry or entry.get("hosted"): + return None + name = entry.get("derivative_file") or "" + path = os.path.join(book_dir, name) + if not name or not os.path.exists(path): + return None + with open(path, "rb") as fh: + data = fh.read() + if hashlib.sha256(data).hexdigest() != entry.get("derivative_sha256"): + return None + # the picture the derivative was made from must still be the same + # picture: the build key carries the size and the date of the source, + # so a source that moved is read again here and compared by its + # content + source = entry.get("catalogue_file") + if source and library: + path_on_disk = os.path.join(library, source) + try: + info = os.stat(path_on_disk) + except OSError: + return None + recorded = entry.get("original_mtime_ns") + if recorded is not None and info.st_mtime_ns != recorded: + if _sha256(path_on_disk) != entry.get("original_sha256"): + return None # the picture changed: make it again + return (data, entry.get("mime") or "image/webp", + entry.get("pixels"), entry.get("derivative_sha256"), + os.path.basename(name), entry) + + +def _image_bytes(path, edge=MAX_EDGE, quality=WEBP_QUALITY, method=4): + """The image, made ready for a browser: a WebP at a sane size. + + Without Pillow the picture cannot be made smaller, and a picture that + is not smaller is not what the reader wants. So this says so rather + than passing the original through. + """ + try: + from PIL import Image + except ImportError: + raise RuntimeError( + "Pillow is needed to make the pictures small: pip install pillow") + with Image.open(path) as image: + if image.mode not in ("RGB", "RGBA"): + image = image.convert("RGBA" if "A" in image.mode else "RGB") + if max(image.size) > edge: + image.thumbnail((edge, edge), Image.LANCZOS) + buffer = io.BytesIO() + image.save(buffer, format="WEBP", quality=quality, method=method) + size = image.size + return buffer.getvalue(), "image/webp", size + + +def _escape(text): + """Text safe to put in an attribute and in the body. + + The quotes matter: a description that contains one would otherwise end + the attribute early, and the reader would lose the picture. + """ + return ("" if text is None else str(text)).replace("&", "&").replace("<", "<") .replace(">", ">").replace('"', """).replace("'", "'") + + +def _slug(text, limit=40): + out = re.sub(r"[^A-Za-z0-9]+", "-", text or "").strip("-").lower() + return out[:limit] or "x" + + +MD_HEADING_RE = re.compile(r"^(#{1,3})\s+(.*)$") +TOC_LINE_RE = re.compile(r"^(.*?)(\s*\.{4,}\s*)((?:\d{1,4})|(?:[IVXLC]{1,6}))\s*$") +# Emphasis is only read where it cannot change the words: the opening star +# must not sit between two word characters, and neither must the closing +# one. A formula such as "=B4*B9" and a name such as "Niedzw*wien*ska" +# are left exactly as they are. +STRONG_RE = re.compile(r"(?" + match.group(1) + "" + def emphasis(match): + if not re.search(r"[A-Za-z0-9]", match.group(1)): + return match.group(0) + return "" + match.group(1) + "" + out = STRONG_RE.sub(strong, out) + out = EMPHASIS_RE.sub(emphasis, out) + return out + + +TABLE_SEPARATOR_RE = re.compile(r"^:?-{2,}:?$") + + +def _table_rows(lines): + """The rows of a markdown table, and where the header ends. + + A markdown table is a run of lines that begin with a pipe; the row + that is only dashes and colons is the rule under the header. The + words are not changed - only the marks around them - so the reader + still shows the notes as they were written. + """ + rows = [] + for line in lines: + stripped = line.strip() + if not stripped.startswith("|"): + return None + rows.append([cell.strip() for cell in stripped.strip("|").split("|")]) + if rows and all(all(TABLE_SEPARATOR_RE.match(cell or "") for cell in row) + for row in rows): + return [], [] # a rule on its own carries no words + for index, row in enumerate(rows): + if index and all(TABLE_SEPARATOR_RE.match(cell or "") for cell in row): + return rows[:index], rows[index + 1:] + return [], rows + + +def _table_html(lines): + """A markdown table, as a table.""" + found = _table_rows(lines) + if found is None: + return "" + header, body = found + out = [""] + if header: + out.append("") + for row in header: + for cell in row: + out.append("\n" % _inline(cell)) + out.append("\n") + if body: + out.append("") + for row in body: + out.append("\n") + for cell in row: + out.append("\n" % _inline(cell)) + out.append("\n") + out.append("\n") + out.append("\n
%s
%s
") + return "".join(out) + + +def _is_table(block): + """Does this block of the notes carry a table?""" + if not block or block.get("kind") != "paragraph": + return False + return any(line.strip().startswith("|") for line in (block.get("text") or "").split("\n")) + + +def _markdown_block(text): + """A paragraph of the notes: the element that carries it, and its words. + + Most paragraphs are prose. Some carry a table the notes wrote in + markdown, and those are shown as tables, in a block of their own so + that the browser has somewhere to put a table. + """ + if os.environ.get("B2C_MD", "on").strip().lower() == "off": + cls, inner = _markdown(text) + return "p", cls, inner + lines = (text or "").split("\n") + parts = [] + prose = [] + table = [] + for line in lines: + if line.strip().startswith("|"): + if prose: + parts.append(("prose", prose)) + prose = [] + table.append(line) + continue + if table: + parts.append(("table", table)) + table = [] + prose.append(line) + if table: + parts.append(("table", table)) + if prose: + parts.append(("prose", prose)) + if not any(kind == "table" for kind, _ in parts): + cls, inner = _markdown(text) + return "p", cls, inner + out = [] + for kind, payload in parts: + if kind == "prose": + cls, inner = _markdown("\n".join(payload)) + out.append('

%s

' % (cls, inner)) + else: + out.append(_table_html(payload)) + return "div", "ptext pblock", "".join(out) + + +def _markdown(text): + """The notes carry a little of the markdown they were written in. + + A line that begins with # is a heading, *word* is italics, and a line + with a run of dots is the book's own contents line. Rendering them + keeps the reader from showing "# NOTICE" as if it were the book's + text, and keeps the dot leaders out of the prose. + + The words are not changed - only the marks around them - so the + reader still shows the notes as they were written, and the gate, + which compares the reader with the notes letter by letter, still + holds. B2C_MD=off brings the older behaviour back. + """ + if os.environ.get("B2C_MD", "on").strip().lower() == "off": + return "ptext", _inline(text) + heading = MD_HEADING_RE.match(text) + if heading: + level = len(heading.group(1)) + cls = "mdhead" if level == 1 else "mdhead mdh%d" % level + return cls, _inline(heading.group(2)) + toc = TOC_LINE_RE.match(text) + if toc: + title, dots, page = toc.groups() + return ("tocline", + '%s' + '' + '%s' + % (_escape(title.strip()), _escape(dots.strip()), _escape(page.strip()))) + return "ptext", _inline(text) + + +CAPTION_NUMBER_RE = re.compile(r"^\s*(fig(?:ure)?|table)\s*\.?\s*([0-9][0-9.\-]*)\s*[:.\-]?\s*", re.I) + + +def _caption_without_number(caption, label): + """The printed caption without the figure number it repeats. + + The book prints "FIGURE 1.1 Key aspects of ..." and the reader shows + the number on a line of its own above, so the number is taken out of + the caption. The words are the book's; only the number that is + already shown is dropped. + """ + text = (caption or "").strip() + found = CAPTION_NUMBER_RE.match(text) + if not found: + return text + number = found.group(2).replace("-", ".").rstrip(".") + label_number = re.sub(r"[^0-9.]", "", label or "").rstrip(".") + if not number or number != label_number: + return text + return text[found.end():].strip() + + +TIER_PHRASE = { + "numbered": "the figure's own number", + "verified": "the printed caption", + "description-match": "the two written descriptions", + "probable": "a similar caption", + "inferred": "the position on the page", + "ordinal": "the order on the page", +} + + +def _figure_block(book, chapter_index, block_index, block, figure_dir, + claimed=None): + """One figure, and one state. + + A figure is in one of three states, and the reader says which: + + matched the picture is shown, and the line under it says why it + was chosen: the figure's own number, the printed + caption, the two written descriptions, or the position + on the page + unconfirmed no picture is claimed; the candidates are shown small, + so that the reader can judge for himself + absent the notes mark a figure here and no picture was found + + A picture that another figure has already claimed is never offered + again as a candidate: the reader has just seen it. + """ + claimed = claimed or set() + fields = block.get("fields", {}) + tier = block.get("tier") or "none" + label = (block.get("label") or "").strip() + kind = (fields.get("TYPE") or "").strip() + caption = _caption_without_number(fields.get("CAPTION"), label) + content = (fields.get("CONTENT") or "").strip() + in_figure = (fields.get("TEXT IN FIGURE") or "").strip() + fid = block.get("figure_id") or ("f-%02d-%04d" % (chapter_index, block_index)) + image = block.get("image") + has_image = bool(image and image.get("derivative")) + candidates = [c for c in (block.get("candidates") or []) + if c.get("id") and c.get("id") not in claimed] + if has_image: + state = "matched" + elif candidates: + state = "unconfirmed" + else: + state = "absent" + if tier in ("candidate", "ordinal") and not candidates: + # every picture this figure could have had is already shown under + # another figure, so there is nothing left to offer it + tier = "none" + + out = ['
' + % (fid, _escape((image or {}).get("id", "")), state, _escape(tier))] + if has_image: + entry = image["derivative"] + src = image.get("embed_src") or entry["derivative_file"] + alt = (content or caption or label or "figure") + out.append('%s' + % (src, _escape(alt))) + numbered = bool(label) and label.lower() not in ("unnumbered", "none") + + # the caption: the figure's own number and the caption the book printed. + # Nothing else belongs here: the words printed inside the picture and + # the kind of figure are the picture's own business. + head = ['
Figure'] + if numbered: + head.append(' %s' % _escape(label)) + head.append("") + if caption and caption.lower() != "none": + head.append('%s' + % _escape(caption)) + head.append("
") + out.append("".join(head)) + + # the line that says what happened, in the open + if state == "matched": + phrase = TIER_PHRASE.get(tier, "the evidence") + where = figures.KEY_NAME.get(block.get("key") or "", "") + extra = "" + similarity = (block.get("detail") or {}).get("similarity") + if tier in ("description-match", "probable") and similarity is not None: + # the score means something here: it is the similarity the + # two descriptions reached + extra = ' · score %.2f' % similarity + out.append('

Matched by %s%s%s.

' + % (_escape(phrase), + (", on %s" % _escape(where)) if where else "", + extra)) + elif state == "unconfirmed": + refusal = block.get("refusal") + if refusal: + # the claim was refused, and the line says why: a tie, or a + # rival that was nearly as good + if refusal.get("tie"): + out.append('

Two pictures matched equally ' + 'well, so neither is claimed.

') + else: + detail = "" + if (refusal.get("score") is not None + and refusal.get("rival_score") is not None): + detail = (" (%.2f against %.2f)" + % (refusal["score"], refusal["rival_score"])) + elif refusal.get("rival_number"): + detail = (" (the picture numbered %s)" + % _escape(str(refusal["rival_number"]))) + out.append('

Another picture matched nearly ' + 'as well%s, so neither is claimed.

' % detail) + else: + out.append('

Picture not confirmed.

') + else: + out.append('

The notes mark a figure here; ' + 'no picture was found.

') + + # what the figure is, for a reader who cannot see the picture or who + # wants to know what a model made of it + details = [] + if content and content.lower() != "none": + details.append('
What the picture shows
' + '
%s
' + % _escape(content)) + if in_figure and in_figure.lower() != "none": + details.append('
Words printed in the picture
' + '
%s
' + % _escape(in_figure)) + if kind and kind.lower() != "none": + details.append('
Kind
' + '
%s
' + % _escape(kind)) + if not numbered: + details.append('
Number in the notes
' + '
%s
' + % _escape(label or "")) + + if state == "unconfirmed": + # the candidates, as small pictures: the reader can judge for himself + # whether one of them is the figure + out.append('
    ') + for cand in candidates[:4]: + thumb = cand.get("thumb") + # a candidate is not a picture of this figure, and it is not an + # : the gate forbids a figure that shows a picture it has + # not claimed, and that rule must stay exact + picture = ('' + % _escape(thumb)) if thumb else "" + out.append('
  • %s%s
  • ' + % (picture, _escape(cand.get("id", "")))) + out.append("
") + + if details: + out.append('
Picture details' + '
%s
' % "".join(details)) + out.append("
") + return "".join(out) + + +def render_html(built, book_meta, template_dir, index_payload=None): + """The reader, as a string.""" + head = open(os.path.join(template_dir, "reader.head.html"), encoding="utf-8").read() + tail = open(os.path.join(template_dir, "reader.tail.html"), encoding="utf-8").read() + chapters = built["chapters"] + paragraphs = sum(1 for c in chapters for b in c["blocks"] if b["kind"] == "paragraph") + figures = [b for c in chapters for b in c["blocks"] if b["kind"] == "figure"] + images = sum(1 for b in figures if b.get("image")) + # the pictures that are already claimed: a figure is never offered a + # picture the reader has just seen under another figure + claimed = set(entry.get("id") for entry in built.get("manifest") or []) + + nav = [] + for index, chapter in enumerate(chapters): + count = sum(1 for b in chapter["blocks"] if b["kind"] == "paragraph") + figs = sum(1 for b in chapter["blocks"] if b["kind"] == "figure") + items = [] + for position, block in enumerate(chapter["blocks"]): + if block["kind"] != "figure": + continue + label = (block.get("label") or "").strip() + if not label or label.lower() == "unnumbered": + label = "figure %d" % (position + 1) + fid = block.get("figure_id") or ("f-%02d-%04d" % (index + 1, position)) + items.append('%s' + % (_escape(fid), _escape(label))) + nav.append('
' + '%d' + '%s' + '%d · %d fig' + '
%d figure%s' + '
%s
' + % (index + 1, " open" if index == 0 else "", index + 1, + index + 1, + _escape(chapter["title"] or chapter["stem"]), count, figs, + figs, "" if figs == 1 else "s", "".join(items))) + body = [] + for index, chapter in enumerate(chapters): + body.append('
' + % (index + 1, _escape(chapter["stem"]))) + body.append('
%s
' + % _escape(chapter["title"] or chapter["stem"])) + body.append('
') + para_index = 0 + for block_index, block in enumerate(chapter["blocks"]): + if block["kind"] == "page": + # the book's own page label, when it printed one: a page + # with no number says so by saying only where it is + printed = (block.get("page") or "").strip() + if printed.lower() in ("unnumbered", "none", ""): + printed = "" + body.append('
%s' + 'PDF %s
' + % (index + 1, _escape(block.get("pdf_page") or "0"), + _escape(printed), + _escape(block.get("pdf_page") or ""))) + continue + if block["kind"] == "paragraph": + para_index += 1 + tag, cls, inner = _markdown_block(block["text"]) + if "pblock" in cls: + # a table: it may continue the one before it, and it + # may be continued by the one after it + before = chapter["blocks"][block_index - 1] if block_index else None + after = (chapter["blocks"][block_index + 1] + if block_index + 1 < len(chapter["blocks"]) else None) + if _is_table(before): + cls += " mdtable-cont" + if _is_table(after): + cls += " mdtable-more" + body.append('<%s class="%s" id="t-%02d-%04d">%s' + % (tag, cls, index + 1, para_index, inner, tag)) + continue + if block["kind"] == "placeholder": + body.append('

The notes mark another figure on this ' + 'page, and do not describe it.

') + continue + if block["kind"] == "figure": + body.append(_figure_block(built, index + 1, block_index, block, None, + claimed=claimed)) + body.append("
") + + if built.get("picture_base"): + body.append('

This copy of the reader carries no ' + 'pictures of its own: each one is loaded from %s, where the ' + 'pictures of this corpus live.

' + % _escape(built["picture_base"])) + + index_rows = [] + index_groups = [] + for index, chapter in enumerate(chapters): + for block in chapter["blocks"]: + if block["kind"] != "figure": + continue + label = block.get("label") or "Figure" + kind = (block.get("fields", {}).get("TYPE") or "").strip() + caption = (block.get("fields", {}).get("CAPTION") or "").strip() + if caption.lower() == "none": + caption = (block.get("fields", {}).get("CONTENT") or "")[:90] + fid = block.get("figure_id") or ("f-%02d-%04d" % (index + 1, chapter["blocks"].index(block))) + index_rows.append('
  • %s %s' + ' %s %s
  • ' + % (_escape(fid), _escape(label), + _escape(kind), _escape(caption), + _escape(block.get("page") or ""))) + if index_rows: + # the list says which chapter each figure belongs to, so it + # says it: the figures of a chapter are under its name + index_groups.append('

    %d · %s

    ' + '
      %s
    ' + % (index + 1, _escape(chapter["title"] or chapter["stem"]), + "".join(index_rows))) + index_rows = [] + body.append('
    ' + 'Figures
    ' + '

    Every figure the notes record, with the chapter it belongs to ' + 'and the page it is on.

    %s
    ' + % "".join(index_groups)) + + first_page = last_page = "" + for chapter in chapters: + for block in chapter["blocks"]: + if block["kind"] == "page": + if not first_page: + first_page = (block.get("pdf_page") or "").strip() + last_page = (block.get("pdf_page") or "").strip() + pages = "" + if first_page and last_page and first_page != last_page: + pages = "PDF pages %s to %s" % (first_page, last_page) + elif first_page: + pages = "PDF page %s" % first_page + + counts = counts_line.to_html(counts_line.notes(len(chapters), paragraphs, + len(figures), images)) + note = ("These are study notes: the book's own text, page by page, with the pictures " + "matched to their figures.") + note_more = ("The notes are the corpus: the text is reproduced exactly, and every figure " + "the notes record is here. The pictures are the book's own, taken from its " + "PDF; the descriptions were written by a vision model reading the page. " + "Where a picture could not be matched to its figure on evidence, the figure " + "says so and names the candidates it could not claim. A sampled audit " + "estimates how often a match is right: the text is exact, the match is an " + "estimate.") + doc = head + tail + doc = doc.replace("{{TITLE}}", _escape(book_meta.get("title") or built["book"])) + doc = doc.replace("{{SUBTITLE}}", _escape(pages)) + citation = re.split(r",\s*PDF pages", book_meta.get("citation") or "")[0].strip() + if citation == (book_meta.get("title") or ""): + citation = "" + doc = doc.replace("{{CITATION}}", _escape(citation)) + if not citation: + doc = doc.replace('

    ', "") + doc = doc.replace("{{COUNTS}}", counts) + doc = doc.replace("{{KIND}}", "notes") + doc = doc.replace("{{SEARCH}}", "Search the book (press / )") + doc = doc.replace("{{JUMP}}", "page C12 or Fig 15.2") + doc = doc.replace("{{NAV}}", "".join(nav)) + doc = doc.replace("{{BODY}}", "\n".join(body)) + doc = doc.replace("{{ORPHANS}}", "") + doc = doc.replace("{{INDEX}}", index_block.render(index_payload)) + doc = doc.replace("{{NOTE}}", note) + doc = doc.replace("{{NOTE_MORE}}", "

    %s

    " % note_more) + return doc + + +def picture_policy(corpus_root): + """The policy that decides which tiers may show a picture. + + It lives in the corpus, beside the evidence it was computed from, so + the numbers are never written into the code: a re-audit changes the + decisions by itself. + """ + path = os.path.join(os.path.abspath(corpus_root), "picture-policy.json") + if not os.path.exists(path): + return None + try: + with open(path, encoding="utf-8") as fh: + return json.load(fh) + except Exception: + return None + + +def canonical_order(): + """Is the canonical order in force? + + The canonical order writes every list in the same way whatever order + the inputs came in: the manifest by picture id, a figure's candidates + by picture id. B2C_ORDER=legacy turns it off, which is the switch + that brings the older behaviour back. + """ + return os.environ.get("B2C_ORDER", "canonical").strip().lower() != "legacy" + + +def build_book(book_dir, library, out_dir=None, embed=True, level=None, + picture_base=None): + """Build one book: the reader, the figures and the record of what was used. + + With a picture_base the reader borrows its pictures from another + host - the mirror keeps the corpus on one side and the pictures on + the other - and the book carries no pictures of its own. + """ + book = os.path.basename(book_dir.rstrip("/")) + level = level or LEVELS[0] + chapters_dir = os.path.join(book_dir, "chapters") + out_dir = out_dir or book_dir + figures_dir = os.path.join(out_dir, "figures") + if not os.path.isdir(chapters_dir): + return None + names = sorted(n for n in os.listdir(chapters_dir) if n.endswith(".md")) + chapters = [] + blocks = [] + for name in names: + stem = name[:-3] + parsed = parse_chapter(os.path.join(chapters_dir, name)) + for block in parsed["blocks"]: + block["stem"] = stem + blocks.extend(parsed["blocks"]) + parsed["file"] = name + parsed["stem"] = stem + chapters.append(parsed) + # one matching run over the whole book: a picture is free only if no + # figure in any chapter has claimed it + match_figures(blocks, records_for(library, book), library) + + # what the audit asked for: a picture the judge found to be the wrong + # one is not shown, and the figure says why it has no picture + demotions = {} + demotion_path = os.path.join(book_dir, "demotions.json") + if os.path.exists(demotion_path): + with open(demotion_path, encoding="utf-8") as fh: + demotions = (json.load(fh) or {}).get("demoted") or {} + + # the policy: a tier that does not clear the bar does not show a + # picture, and a book whose catalogue is not sound does not show a + # text-only picture. The picture is released and offered back as a + # candidate, so the reader can see what was found and why it was not + # claimed. + policy = picture_policy(os.path.dirname(os.path.abspath(book_dir))) + if policy: + tiers_ok = set(t for t, info in (policy.get("gate_b", {}).get("tiers") or {}).items() + if info.get("shows_picture")) + gate_a = set(policy.get("gate_a", {}).get("pass") or []) + text_only = set(policy.get("text_only_tiers") or []) + for chapter in chapters: + for block in chapter["blocks"]: + if block.get("kind") != "figure" or not block.get("image"): + continue + tier = block.get("tier") + allowed = tier in tiers_ok + if allowed and tier in text_only and book not in gate_a: + allowed = False + if allowed: + continue + image = block.get("image") + block["candidates"] = [dict(image)] + [ + c for c in (block.get("candidates") or []) if c.get("id") != image.get("id")] + block["image"] = None + block["tier"] = "candidate" + block["released"] = tier + + for index, chapter in enumerate(chapters): + for position, block in enumerate(chapter["blocks"]): + if block.get("kind") != "figure": + continue + figure_id = "f-%02d-%04d" % (index + 1, position) + block["figure_id"] = figure_id + if figure_id in demotions: + image = block.get("image") + if image: + block["candidates"] = [dict(image)] + block["image"] = None + block["tier"] = "candidate" + block["demoted"] = demotions[figure_id] + + # the panels of one figure share one picture, and the sharing is + # declared: the gate checks the declaration against the notes + for chapter in chapters: + for block in chapter["blocks"]: + if block.get("kind") != "figure": + continue + shared = block.get("shared_with") + if shared: + block["shared_with"] = [other.get("figure_id") + for other in shared + if other.get("figure_id")] + + # every picture a figure claims, with that figure's own notes about + # it: one picture may serve two figures, the panels of one figure + used = [] + claiming = {} + for chapter in chapters: + for block in chapter["blocks"]: + image = block.get("image") + if image: + fields = block.get("fields", {}) + image["tier"] = block.get("tier") + image["chapter"] = chapter["stem"] + image["notes_caption"] = (fields.get("CAPTION") or "").strip() + image["notes_description"] = (fields.get("CONTENT") or "").strip() + image["notes_type"] = (fields.get("TYPE") or "").strip() + image["notes_text_in_figure"] = (fields.get("TEXT IN FIGURE") or "").strip() + used.append(image) + claiming.setdefault(image["id"], []).append(block) + + # the manifest of the last build is read once, not once per picture + made_entries = _manifest_entries(book_dir) + + if not picture_base: + # the pictures that are already made are kept until the build has + # decided which of them it wants; the rest go at the end + os.makedirs(figures_dir, exist_ok=True) + manifest = [] + total = 0 + # one picture file per distinct original: the same diagram often appears + # in several chapters, and it is the same file + by_digest = {} + entries = {} + embeds = {} + written = set() + local = {} + if picture_base: + # the pictures live elsewhere, and their names there were decided + # by the build that made them: the hosted reader must use those + # names, not make its own + local_path = os.path.join(book_dir, "figures.json") + if os.path.exists(local_path): + with open(local_path, encoding="utf-8") as fh: + for entry in (json.load(fh) or {}).get("figures", []): + local[entry.get("id")] = entry + for image in used: + image_id = image["id"] + if image_id in entries: + # the same picture, claimed by two figures + image["derivative"] = entries[image_id] + image["embed_src"] = embeds[image_id] + continue + source = os.path.join(library, image["file"]) + if picture_base and image_id in local: + entry = dict(local[image_id]) + entry["hosted"] = True + entry["hosted_url"] = "%s/%s/%s" % (picture_base.rstrip("/"), book, + entry["derivative_file"]) + manifest.append(entry) + entries[image_id] = entry + embeds[image_id] = entry["hosted_url"] + image["derivative"] = entry + image["embed_src"] = entry["hosted_url"] + continue + made = _made_picture(book_dir, image_id, made_entries, library) + if made is not None: + data, mime, size, digest, made_name, made_entry = made + written.add(made_name) + # the original's hash is already written down: reading the file + # again out of the cloud costs a minute a book for nothing + original_hash = made_entry.get("original_sha256") + original_bytes = made_entry.get("original_bytes") + else: + data = mime = size = digest = None + original_hash = original_bytes = None + for attempt in (range(3) if data is None else ()): + try: + data, mime, size = _image_bytes(source, *level) + break + except Exception: + # a picture in the library that is not there, or that the + # cloud has not fetched yet: the figure must not claim a + # picture it cannot show + data = None + if data is None: + for block in claiming.get(image_id, []): + block["candidates"] = [dict(image)] + block["image"] = None + block["tier"] = "candidate" + block["unreadable"] = True + continue + if digest is None: + digest = hashlib.sha256(data).hexdigest() + name = by_digest.get(digest) + if name is None: + name = image_id + ".webp" + by_digest[digest] = name + if not picture_base: + with open(os.path.join(figures_dir, name), "wb") as fh: + fh.write(data) + written.add(name) + if original_hash is None: + original_hash = _sha256(source) + original_bytes = os.path.getsize(source) + try: + original_stat = os.stat(source) + # the second, not the nanosecond: the cloud filesystem reads + # the same file with a slightly different clock each time, and + # a manifest that changes on every build is not a manifest + original_mtime = original_stat.st_mtime_ns // 1000000000 + except OSError: + original_mtime = None + entry = {"id": image_id, "catalogue_file": image["file"], + "original_sha256": original_hash, + "original_bytes": original_bytes, + "original_mtime_ns": original_mtime, + "derivative_file": "figures/" + name, + "derivative_sha256": digest, + "derivative_bytes": len(data), "mime": mime, + "pixels": size, "kind": image.get("kind"), + "chapter": image.get("chapter"), + "caption": image.get("caption"), + "description": image.get("description"), + "printed_page": image.get("printed_page")} + if picture_base: + entry["hosted"] = True + entry["hosted_url"] = "%s/%s/%s" % (picture_base.rstrip("/"), book, + entry["derivative_file"]) + manifest.append(entry) + entries[image_id] = entry + if picture_base: + embeds[image_id] = entry["hosted_url"] + elif embed: + embeds[image_id] = ("data:%s;base64,%s" + % (mime, base64.b64encode(data).decode("ascii"))) + else: + embeds[image_id] = "figures/" + name + image["derivative"] = entry + image["embed_src"] = embeds[image_id] + total += len(data) + # the pictures this build does not use are listed, not removed: a + # build whose reader fails its gate must leave the corpus as it was + stale = [] + if not picture_base and os.path.isdir(figures_dir): + for name in sorted(os.listdir(figures_dir)): + if name not in written: + stale.append(name) + for chapter in chapters: + for block in chapter["blocks"]: + if block.get("image"): + block["image"]["embed"] = embed and total <= EMBED_BUDGET + # the pictures a figure could not claim are shown small, so that the + # reader can judge for himself whether one of them is the figure. + # A picture that several figures offer is made once. + thumbs = {} + cache_dir = os.path.expanduser("~/.cache/book2corpus/thumbs") + for chapter in chapters: + for block in chapter["blocks"]: + if block.get("kind") != "figure" or block.get("image"): + continue + for cand in block.get("candidates") or []: + cid = cand.get("id") + if not cid or cid in thumbs or not cand.get("file"): + continue + path = os.path.join(library, cand["file"]) + if not os.path.exists(path): + continue + # the thumb is made once and kept: the same picture is + # offered by many figures, and a rebuild must not spend + # an encoder on it again + cache_path = os.path.join(cache_dir, cid + ".webp") + data = None + if os.path.exists(cache_path): + try: + with open(cache_path, "rb") as fh: + data = fh.read() + except Exception: + data = None + if data is None: + try: + data, _, _ = _image_bytes(path, 72, 50, method=0) + except Exception: + continue + try: + os.makedirs(cache_dir, exist_ok=True) + with open(cache_path, "wb") as fh: + fh.write(data) + except Exception: + pass + thumbs[cid] = ("data:image/webp;base64," + + base64.b64encode(data).decode("ascii")) + if thumbs: + for chapter in chapters: + for block in chapter["blocks"]: + for cand in block.get("candidates") or []: + if cand.get("id") in thumbs: + cand["thumb"] = thumbs[cand["id"]] + + if canonical_order(): + # one order everywhere: the manifest by picture id, and a figure's + # candidates by picture id + for chapter in chapters: + for block in chapter["blocks"]: + if block.get("kind") == "figure" and block.get("candidates"): + block["candidates"].sort(key=lambda c: c.get("id") or "") + manifest.sort(key=lambda entry: entry.get("id") or "") + figure_map = [] + for index, chapter in enumerate(chapters): + for position, block in enumerate(chapter["blocks"]): + if block.get("kind") != "figure": + continue + image = block.get("image") + figure_map.append({ + "id": block.get("figure_id"), + "chapter": chapter["stem"], + "label": block.get("label"), + "index": position, + "tier": block.get("tier"), + "key": block.get("key"), + "image": image.get("id") if image else None, + "demoted": block.get("demoted"), + "shared_with": block.get("shared_with") or [], + "refusal": block.get("refusal"), + "caption": (block.get("fields", {}).get("CAPTION") or "").strip(), + "description": (block.get("fields", {}).get("CONTENT") or "").strip(), + "candidates": [c.get("id") for c in block.get("candidates", [])], + }) + return {"book": book, "chapters": chapters, "manifest": manifest, + "figure_map": figure_map, "picture_base": picture_base, + "stale_derivatives": stale, + "embedded_bytes": total, "embed": embed and total <= EMBED_BUDGET} + + +class _Scan(HTMLParser): + """The reader, read back: its ids, its texts and its figures.""" + + def __init__(self): + HTMLParser.__init__(self, convert_charrefs=True) + self.ids = [] + self.texts = {} + self.figures = {} + self.links = [] + self._open = None + self._tag = None + self._figure = None + self._figure_class = None + self._buf = None + + def handle_starttag(self, tag, attrs): + found = dict(attrs) + if found.get("id"): + self.ids.append(found["id"]) + href = found.get("href") or "" + if href.startswith("#"): + self.links.append(href[1:]) + classes = (found.get("class") or "").split() + if tag == "figure": + self._figure = found.get("id") + self._figure_class = "" + self.figures[self._figure] = {} + if self._figure and found.get("data-para") is None and classes: + self._figure_class = classes[0] + if self._open is None and (found.get("id") or "").startswith("t-"): + self._open = {"id": found["id"], "text": []} + self._tag = tag + + def handle_endtag(self, tag): + if self._open is not None and tag == self._tag: + self.texts.setdefault(self._open["id"], "".join(self._open["text"])) + self._open = None + self._tag = None + if tag == "figure" and self._figure: + self._figure = None + + def handle_data(self, data): + if self._open is not None: + self._open["text"].append(data) + elif self._figure and self._figure_class: + key = self._figure_class + self.figures[self._figure][key] = (self.figures[self._figure].get(key, "") + data).strip() + + +def verify(book_dir, out_dir, built, html_text): + """Check the reader against the notes it was made from. + + The source is read again here, line by line, with a grammar of its own: + a line that fits no bucket fails loudly rather than being passed over. + """ + problems = [] + chapters_dir = os.path.join(book_dir, "chapters") + source_lines = 0 + source_paragraphs = [] + source_figures = [] + source_pages = 0 + for name in sorted(n for n in os.listdir(chapters_dir) if n.endswith(".md")): + with io.open(os.path.join(chapters_dir, name), encoding="utf-8") as fh: + lines = fh.read().splitlines() + paragraph = [] + in_figure = False + fields = {} + last_field = None + for line in lines: + stripped = line.strip() + if not stripped: + if paragraph: + source_paragraphs.append(chr(10).join(paragraph)) + paragraph = [] + if in_figure: + in_figure = False + source_figures.append(fields) + fields = {} + continue + source_lines += 1 + if PAGE_RE.match(line): + if paragraph: + source_paragraphs.append(chr(10).join(paragraph)) + paragraph = [] + source_pages += 1 + continue + if FIGURE_RE.search(line): + if paragraph: + source_paragraphs.append(chr(10).join(paragraph)) + paragraph = [] + in_figure = True + fields = {} + continue + if in_figure: + if stripped == "--": + in_figure = False + source_figures.append(fields) + fields = {} + continue + if ":" in stripped: + key, value = stripped.split(":", 1) + if key.strip().upper() in FIELDS: + fields.setdefault(key.strip().upper(), value.strip()) + last_field = key.strip().upper() + continue + if fields and last_field: + fields[last_field] = (fields[last_field] + " " + stripped).strip() + continue + problems.append("a line inside a figure block fits no field: %s" + % stripped[:60]) + continue + if stripped.startswith("# ") or CITATION_RE.match(stripped): + continue + paragraph.append(stripped) + if paragraph: + source_paragraphs.append(chr(10).join(paragraph)) + if in_figure: + source_figures.append(fields) + + scan = _Scan() + scan.feed(html_text) + rendered_paragraphs = [scan.texts[k] for k in sorted(scan.texts) if k.startswith("t-")] + # a line that carries no words - the rule under a table's header - is + # not text, and the reader may show it or leave it out + wanted = [p for p in source_paragraphs if _norm(p)] + shown_words = [p for p in rendered_paragraphs if _norm(p)] + if len(shown_words) != len(wanted): + problems.append("the reader shows %d paragraphs, the notes have %d" + % (len(shown_words), len(wanted))) + else: + for index, (got, want) in enumerate(zip(shown_words, wanted)): + if _norm(got) != _norm(want): + problems.append("paragraph %d differs between the notes and the reader" % index) + break + rendered_figures = [scan.figures[k] for k in sorted(scan.figures)] + if len(rendered_figures) != len(source_figures): + problems.append("the reader shows %d figures, the notes have %d" + % (len(rendered_figures), len(source_figures))) + else: + for index, (got, want) in enumerate(zip(rendered_figures, source_figures)): + for key, cls in (("TYPE", "figtype"), ("CAPTION", "figcaption"), + ("CONTENT", "figdesc"), ("TEXT IN FIGURE", "figtext")): + source_value = (want.get(key) or "").strip() + shown = (got.get(cls) or "").strip() + if source_value.lower() in ("none", ""): + if shown: + problems.append("figure %d shows a %s the notes do not have" % (index, key)) + elif _norm(shown) != _norm(source_value): + problems.append("figure %d: the %s differs between the notes and the reader" + % (index, key)) + break + if len(scan.ids) != len(set(scan.ids)): + problems.append("the reader has an id that appears twice") + missing = sorted(set(scan.links) - set(scan.ids)) + if missing: + problems.append("%d links in the reader point at ids that are not there" % len(missing)) + for marker in ("http://", "https://", "file://", "/Users/"): + if marker in html_text: + problems.append("the reader refers to %s - it must stand on its own" % marker) + break + for entry in built["manifest"]: + path = os.path.join(out_dir, entry["derivative_file"]) + if not os.path.exists(path): + problems.append("a figure file is missing: %s" % entry["derivative_file"]) + continue + if _sha256(path) != entry["derivative_sha256"]: + problems.append("a figure file does not match its hash: %s" % entry["derivative_file"]) + return problems diff --git a/pipeline/book2corpus/notes_gate.py b/pipeline/book2corpus/notes_gate.py new file mode 100644 index 00000000..33213f7e --- /dev/null +++ b/pipeline/book2corpus/notes_gate.py @@ -0,0 +1,821 @@ +"""The gate: is the reader the notes it was made from? + +This is a second, independent reading of the source. It is a line +classifier, not a paragraph builder: every line of every chapter file is +sorted into exactly one bucket, and the buckets must add up. Where the +builder's rules and this one's disagree, the disagreement is the finding. + +The rules, stated once: + + blank a line with nothing on it + heading the chapter title, "# something" + citation the line that says which book this is + page marker "=== PAGE 61 (PDF page 87) ===" + figure header a line that ends with "[FIGURE ...]" + figure field a "KEY: value" line inside a figure block, or a + continuation of the field above it + prose anything else, and prose is gathered into a segment that + ends at the next line that is not prose + unclassified anything that fits no bucket - a failure, never a shrug +""" +import io +import json +import os +import re +import unicodedata +from html.parser import HTMLParser + +from . import counts_line + +# the marker comes bare or with a note of how the page was read; both are +# the same marker, and a marker the gate does not know is a line that fits +# no bucket +PAGE_MARKER_RE = re.compile(r"^=== PAGE (.+?) \(PDF page (\d+)(?:;[^)]*)?\) ===\s*$") +FIGURE_HEADER_RE = re.compile(r"\[FIGURE ([^\]]*)\]\s*$") +CITATION_RE = re.compile(r"^Source:\s*(.+?)\s*$") +FIELDS = ("TYPE", "CAPTION", "CONTENT", "TEXT IN FIGURE", "SOURCE") +# the tags that never close: they must not be counted as nesting +VOID_TAGS = frozenset(("area", "base", "br", "col", "embed", "hr", "img", + "input", "link", "meta", "param", "source", "track", "wbr")) +FIELD_LABELS = {"LABEL": "Figure", "TYPE": "Type", "CAPTION": "Caption", + "CONTENT": "Description", "TEXT IN FIGURE": "Text printed in the figure"} +# what counts is a reference, not the word: a URL quoted in the book's own +# text is the book, not a reach-out of the reader +EXTERNAL_MARKERS = ('src="http', 'href="http', 'srcset="http', "url(http", + "@import", "file://", 'href="/Users', 'src="/Users', + " + + diff --git a/pipeline/book2corpus/terms.py b/pipeline/book2corpus/terms.py new file mode 100644 index 00000000..8e71751c --- /dev/null +++ b/pipeline/book2corpus/terms.py @@ -0,0 +1,535 @@ +#!/usr/bin/env python3 +"""book2corpus/terms.py - the terms of a book, and the rules they must pass. + +Written 26 Nov 2026 by MCode, following the ruling of Claude Opus 5.5 on +the corpus-wide term index (briefs 12, 13 and 14), and the coding practice +of the s2n repository: a header that says what the file is and where the +idea came from, output that is byte-for-byte the same on every run, and the +old file kept beside the new one. + +The principle under all of it: THE MODEL PROPOSES, CODE PROVES. A model +may say that a phrase is a term; every location, every definition span and +every occurrence in the index is found here, in the actual text, by code. +Nothing a model says is written into the index without a span this module +located. + +Three objects, and they are kept apart on purpose: + + a term a phrase as used in one book: its surface form, its + canonical form, where it was named, what kind it is + an occurrence where the term appears in its own book + a concept a set of terms in different books judged to be one sense + +The per-book list is the ground truth. A wrong merge in the concept layer +must never corrupt a book's own index. + +Two lists that are NOT terms, and are kept apart on purpose: + + the seeds what a book's own text offers: its headings, its captions + and its recurring phrases. They are hints for the model and + nothing else. A seed is never admitted to the index. + the rejected the names the model gave that did not survive the code: the + reason is written down with every one of them. +""" +import json +import os +import re + +from . import debris + +# the rules version. It is part of every key the stages compute, so a +# change to the rules invalidates what the rules produced, and nothing else. +RULES_VERSION = 4 + +# the corpus's own words, and the ones that are never terms +STOPWORDS = frozenset(""" +the a an and or but of in on at to for with without from by as is are was +were be been being it its this that these those there here their his her +our your my me him them us they he she we you i not no nor so if then than +because while when where which who whom whose what how why all any both each +few more most other some only own same too very can could may might must +will would shall should do does did done have has had having +one two three four five six seven eight nine ten first second third next +last new old good better best bad worse worst large small long short high +low early late full empty able unable +about per versus vs eg ie etc +figure table page chapter section part note notes source text see also +caption content type none placeholder value data +example examples definition definitions however therefore thus hence +""".split()) + +# the words that may not end a term: a term is "duty of care", not "care of", +# and it is not "bottom right" +HEAD_BLOCK = frozenset(""" +right left top bottom centre center middle front back side end edge +point points number numbers line lines list lists name names +area areas part parts kind kinds type types form forms order orders +""".split()) + +# the phrases that are a publisher, a place, or the furniture of a book +NON_TERM_PATTERNS = ( + "university press", " press ", " ltd", " inc", " publishing", + "routledge", "palgrave", "macmillan", "springer", "wiley", "oxford", + "harvard", "yale", "princeton", "cambridge", " et al", + "chapter ", "volume ", "edition ", "appendix ", "preface ", + "foreword ", "acknowledg", "glossary", "bibliograph", "references", +) + +# the words that carry a definition in a law code +DEFINITION_PATTERNS = ( + re.compile(r"\bmeans\b", re.I), + re.compile(r"\bhas the meaning (?:given|assigned)\b", re.I), + re.compile(r"\bincludes\b", re.I), + re.compile(r"\bfor the purposes of\b", re.I), + re.compile(r"\bshall (?:be deemed to|mean)\b", re.I), +) + +# a term is a phrase of one to six words +MAX_TERM_WORDS = 6 + + +def canonical(text): + """The form a term is compared by: folded, joined, without its ends.""" + text = debris.normalise(text) + for article in ("the ", "a ", "an "): + if text.startswith(article): + text = text[len(article):] + break + return text + + +IRREGULAR_PLURALS = { + # the Latin and Greek plurals, and the English families that no suffix + # rule can carry. Every entry is a plural the corpus holds; the + # singular is the one the book writes. The table is checked against + # the corpus own labels, and the pairs it closes are counted. + "analyses": "analysis", "theses": "thesis", "crises": "crisis", + "bases": "basis", "axes": "axis", "hypotheses": "hypothesis", + "diagnoses": "diagnosis", "parentheses": "parenthesis", + "syntheses": "synthesis", "oases": "oasis", "emphases": "emphasis", + "phenomena": "phenomenon", "epiphenomena": "epiphenomenon", + "criteria": "criterion", "curricula": "curriculum", + "symposia": "symposium", "strata": "stratum", "ganglia": "ganglion", + "referenda": "referendum", "ova": "ovum", "dicta": "dictum", + "mitochondria": "mitochondrion", "bacteria": "bacterium", + "millennia": "millennium", "aquaria": "aquarium", + "larvae": "larva", "formulae": "formula", "antennae": "antenna", + "papillae": "papilla", "pinnae": "pinna", "lacunae": "lacuna", + "vertebrae": "vertebra", "indices": "index", "appendices": "appendix", + "matrices": "matrix", "vertices": "vertex", "cortices": "cortex", + "apices": "apex", "stimuli": "stimulus", "foci": "focus", + "nuclei": "nucleus", "radii": "radius", "cacti": "cactus", + "syllabi": "syllabus", "alumni": "alumnus", "thesauri": "thesaurus", + "fungi": "fungus", "termini": "terminus", "uteri": "uterus", + "genera": "genus", "corpora": "corpus", "opera": "opus", + "leaves": "leaf", "knives": "knife", "wives": "wife", + "lives": "life", "wolves": "wolf", "shelves": "shelf", + "thieves": "thief", "calves": "calf", "selves": "self", + "loaves": "loaf", "halves": "half", "elves": "elf", + "scarves": "scarf", "hooves": "hoof", "echoes": "echo", + "potatoes": "potato", "heroes": "hero", "vetoes": "veto", + "volcanoes": "volcano", "tornadoes": "tornado", + "torpedoes": "torpedo", "mosquitoes": "mosquito", + "tomatoes": "tomato", "cargoes": "cargo", "embargoes": "embargo", + "haloes": "halo", "buffaloes": "buffalo", "scrapies": "scrapie", + # the "ses" plurals whose stem ends in a single s: the rule would cut + # the s and leave "biase" behind, and the corpus holds "bias" + "biases": "bias", "gases": "gas", "atlases": "atlas", + "viruses": "virus", "atlanta": "atlanta", +} + + +def singular(word): + """The plain singular of a word, so plurals are one term. + + The rules are careful with the words that end in s and are not + plurals - "bias", "analysis", "stimulus", "hypothesis" - because + cutting their s made keys that the text could never match: + "adenovirus" was filed as "adenoviru" and "corpus callosum" as + "corpu callosum". A word that ends in "is", "us" or "ss" is left + alone, and so is one that ends in "as", because its plural takes an + "es" ("biases", "atlases"). + + The "es" family needs a rule for every ending, because one rule + cannot carry it: "biases" is "bias", "synapses" is "synapse", + "processes" is "process", "approaches" is "approach" and + "reflexes" is "reflex". The plural of a word that ends in s, x, z, + ch or sh takes "es"; the plural of a word that ends in e takes "s". + + The irregular plurals are in the table above, and the table is read + first: a word in it is not touched by the rules. + """ + irregular = IRREGULAR_PLURALS.get(word) + if irregular: + return irregular + if len(word) > 4 and word.endswith("ies"): + return word[:-3] + "y" + if len(word) > 4 and word.endswith("sses"): + return word[:-2] + if len(word) > 4 and word.endswith("ches"): + return word[:-2] + if len(word) > 4 and word.endswith("shes"): + return word[:-2] + if len(word) > 4 and word.endswith("xes"): + return word[:-2] + if len(word) > 3 and word.endswith("ses"): + return word[:-1] + if len(word) > 3 and word.endswith("s") and not word.endswith("ss"): + if word.endswith("is") or word.endswith("us") or word.endswith("as"): + return word + return word[:-1] + return word + + +def canonical_form(text): + """The canonical form of a term: folded, singular, no punctuation.""" + words = canonical(text).split() + return " ".join(singular(word) for word in words) + + +def rule_filter(phrase): + """The last word. The model names a term; the rules decide. + + An empty string means the phrase passes. Anything else is the reason + it does not, and the reason is written down with the rejection. + """ + original = (phrase or "").strip() + if not original: + return "empty" + words = original.split() + if len(words) > MAX_TERM_WORDS: + return "length" + # the article is stripped for the comparison, but not for the rule: + # "the journal" is not a term and "journal" is + tokens = debris.normalise(original).split() + if not tokens: + return "empty" + if all(token in STOPWORDS for token in tokens): + return "rule_filter" + if tokens[0] in STOPWORDS: + return "rule_filter" + if tokens[-1] in STOPWORDS or tokens[-1] in HEAD_BLOCK: + return "rule_filter" + for token in tokens: + if token not in STOPWORDS and len(token) < 3: + # "al", "ir", "b", "e": the debris of a scan, not a term + return "rule_filter" + folded = " %s " % debris.normalise(original) + if debris.normalise(original) in debris.FIGURE_BOILERPLATE: + return "rule_filter" + for pattern in NON_TERM_PATTERNS: + if pattern in folded: + return "rule_filter" + return "" + + +def clean_caption(caption): + """The caption's own words, without the label in front of them. + + A caption names a concept (FIGURE 11.2 Speech problems in Broca's + aphasia), and the words after the label are the seed. How much of the + caption is the term is for the model to narrow and for the code to + check, so the seed keeps the caption's own words. + """ + text = (caption or "").strip() + folded = text.lower() + if folded in ("none", "caption none", "caption: none", "n/a", "not given"): + return "" + text = re.sub(r"^(?:caption|figure|table|fig|chart|plate)\s*[:.\-]\s*", "", + text, flags=re.I) + text = re.sub(r"^(?:FIGURE|TABLE|FIG|Chart|Plate)\s*\d+(?:[.\-]\d+)*\s*[:.\-]?\s*", + "", text, flags=re.I) + text = re.sub(r"\s+", " ", text).strip() + if not text or text.lower() in ("none", "caption none"): + return "" + words = [] + for word in text.split()[:8]: + stripped = word.strip(".,;:()\"'") + if stripped: + words.append(stripped) + return " ".join(words) + + +def ngrams(text, size=4): + """The phrases of a text, shortest first.""" + words = re.findall(r"[A-Za-z][A-Za-z'-]*", text or "") + out = [] + for start in range(len(words)): + for length in range(1, size + 1): + if start + length > len(words): + break + phrase = " ".join(words[start:start + length]) + out.append((phrase, start, length)) + return out + + +def frequent_phrases(text, minimum=3, limit=60): + """The phrases a book uses often: the seeds, never the terms. + + A seed is a hint. It is written to index/seeds/ and shown to the model + as a hint, and it is never admitted to the index on its own. + """ + counts = {} + for phrase, _start, length in ngrams(text): + if length < 2: + continue + words = phrase.lower().split() + if words[0] in STOPWORDS: + continue + if words[-1] in STOPWORDS: + continue + counts[phrase] = counts.get(phrase, 0) + 1 + ranked = [(count, phrase) for phrase, count in counts.items() if count >= minimum] + ranked.sort(key=lambda pair: (-pair[0], pair[1])) + return [(phrase, count) for count, phrase in ranked[:limit]] + + +# the sentences that define, even when the term is not in quotes +DEFINITION_MARKERS = ( + re.compile(r"\bin this (?:act|context|section|schedule|part|article|order)\b", re.I), + re.compile(r"\bfor the purposes of\b", re.I), + re.compile(r"\bherein\b", re.I), + re.compile(r"\bin this book\b", re.I), +) + + +# a sentence is not cut after an abbreviation: "Art. 212" is one sentence +ABBREVIATIONS = re.compile( + r"\b(?:Art|Sec|No|Rep|Sen|Col|Pp|Vol|Ch|Cl|Rr|Ord|Reg)\.$", re.I) + + +def sentences_of(text): + """The sentences of a paragraph, with where each one begins.""" + out = [] + at = 0 + for piece in re.split(r"(?<=[.;])\s+", text or ""): + out.append((piece, at)) + at += len(piece) + 1 + # the pieces that follow an abbreviation are put back together + merged = [] + for piece, start in out: + if merged and ABBREVIATIONS.search(merged[-1][0].rstrip()): + previous, previous_at = merged.pop() + merged.append((previous + " " + piece, previous_at)) + else: + merged.append((piece, start)) + return merged + + +def definition_span(sentence): + """Where the defined term sits in the sentence that defines it. + + A law code defines a term by quoting it and saying what it means: the + term "strike" means a cessation of work. A sentence that merely uses + the word "means" is not a definition, and the words before it are not + a term - "it is by no means a handmaiden of the law" defines nothing. + """ + found = re.search( + r"[\"\u201c\u2018]([A-Za-z][A-Za-z' \-]{1,60}?)[\"\u201d\u2019']\s+(?:herein\s+)?means\b", + sentence, re.I) + if found: + return found.group(1).strip(), found.start(1), found.end(1) + if any(marker.search(sentence) for marker in DEFINITION_MARKERS): + found = re.search( + r"\b([A-Za-z][A-Za-z' \-]{1,60}?)\s+(?:herein\s+)?means\b", + sentence, re.I) + if found: + return found.group(1).strip(), found.start(1), found.end(1) + return None, None, None + + +def law_terms(paragraphs): + """The terms of a law code: the ones it defines. + + A law code defines its terms, so the code alone knows them. The + phrases a code uses often are the same noise a study-notes book has, + and they are not admitted. + """ + defined = {} + for record in paragraphs: + body = (record.get("text") or "") + if record.get("kind") not in (None, "body"): + continue + scope = " / ".join(record.get("section_path") or []) + for sentence, at in sentences_of(body): + if not any(pattern.search(sentence) for pattern in DEFINITION_PATTERNS): + continue + term, start, end = definition_span(sentence) + if not term: + continue + term = term.strip() + if len(term) < 3 or len(term.split()) > MAX_TERM_WORDS: + continue + key = canonical_form(term) + if not key: + continue + if rule_filter(term): + # the rules have the last word here as well: a span that + # is not a term is not a term, whatever the code said + continue + defined.setdefault(key, { + "term_id": "law:%s" % key, + "label": term, + "canonical": key, + "kind": "defined", + "scope": scope, + "definition": { + "paragraph": record.get("id"), + "chapter": record.get("chapter"), + "page": record.get("page_start"), + "span": [at + start, at + end], + "sentence": sentence.strip()[:400], + }, + }) + return sorted(defined.values(), key=lambda row: row["term_id"]) + + + +def label_words(row): + """The book's own words for a term, as the scan reads them. + + The canonical is singular and drops the leading article; the book's + own spelling is neither, and the text is written in the book's own + spelling. The words are taken with the tokeniser the text is read + with, so the two sides of a match agree on what a word is: a letter + the book writes with a combining mark, or a possessive, is one word + and not two. + """ + return tuple(debris.words_of(row.get("label") or "")) + + +# the routes a term is looked for under, and the order they are tried +ROUTE_RANK = {"canonical": 0, "surface": 1, "head": 2} + +# the gap between two words of a term may hold punctuation, but not a +# word, not a line break and not much of anything +GAP_MAX = 12 +WORDY = re.compile(r"[^\W_]|\d", re.UNICODE) +ONE_LETTER = re.compile(r"^[^\W\d]$", re.UNICODE) +DIGITS = re.compile(r"^\d+$") + + +def term_table(rows): + """The terms of a book as a table: first word -> the phrases and their terms. + + A term is looked for under three phrases: its canonical one, which + is singular; the book's own spelling; and the head phrase, which is + the canonical without its parenthetical alias. The order is fixed, so + the route that found a term is the first one that matched anywhere. + + A phrase maps to every term that has it, so "acetylcholine" and + "acetylcholine (ACh)" do not overwrite each other. + """ + table = {} + for row in rows: + term_id = row["term_id"] + canonical = row.get("canonical") or "" + seen = set() + for route, text in (("canonical", canonical), + ("surface", row.get("label") or ""), + ("head", canonical.split("(")[0])): + words = tuple(debris.words_of(text)) + if not words or words in seen: + continue + seen.add(words) + table.setdefault(words[0], []).append((words, term_id, route)) + return table + + +def _gap_allows(gap, before): + """May two words of a term stand with this gap between them? + + Punctuation is allowed: an initial ("Donald O. Hebb"), a number + ("Article 17.1"), a comma ("Apex CoVantage, LLC"), a bracket + ("unconditioned stimulus (UCS)"). A word is not: "working. + Memory" is two things and not one, so a full stop that ends a word + of more than one letter is a sentence's end and the gap holds it. + """ + if len(gap) > GAP_MAX: + return False + if "\n" in gap or "\r" in gap: + return False + if WORDY.search(gap): + return False + if "." in gap and not (ONE_LETTER.match(before) or DIGITS.match(before)): + return False + return True + + +def scan_terms(text, table): + """Every place a term is found, with the offset and the route. + + The words of the text are read once, with their offsets, and the table + is looked up at every word. A term is found under the first route + that matches it anywhere in the text, so the route is a property of + the term and not of where it was found. + """ + words = debris.tokenise_spans(text) + found = {} + for start in range(len(words)): + options = table.get(words[start][0]) + if not options: + continue + for phrase, term_id, route in options: + length = len(phrase) + if start + length > len(words): + continue + if not all(words[start + step][0] == phrase[step] + for step in range(length)): + continue + apart = False + for step in range(length - 1): + gap = text[words[start + step][2]:words[start + step + 1][1]] + if not _gap_allows(gap, words[start + step][0]): + apart = True + break + if apart: + continue + found.setdefault(term_id, {}).setdefault(route, []).append( + words[start][1]) + for term_id in sorted(found): + routes = found[term_id] + best = min(routes, key=lambda name: ROUTE_RANK[name]) + for offset in sorted(routes[best]): + yield term_id, offset, best + + +def occurrence_counts(text, terms): + """How often each term appears in its own book. + + The same scan the evidence uses, so the reader's counts and the + judge's passages cannot disagree. + """ + counts = {} + if not terms: + return counts + table = term_table(terms) + for term_id, _offset, _route in scan_terms(text, table): + counts[term_id] = counts.get(term_id, 0) + 1 + return counts + + +def write_terms(path, terms): + """The terms of a book, written the way the corpus writes everything: + sorted, one object a line, the keys in one order.""" + terms = sorted(terms, key=lambda row: row["term_id"]) + directory = os.path.dirname(path) + if directory: + os.makedirs(directory, exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + for row in terms: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + return len(terms) + + +def read_terms(path): + """The terms of a book, read back.""" + if not os.path.exists(path): + return [] + out = [] + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + out.append(json.loads(line)) + return out diff --git a/pipeline/book2corpus/verify.py b/pipeline/book2corpus/verify.py new file mode 100644 index 00000000..3e1a6286 --- /dev/null +++ b/pipeline/book2corpus/verify.py @@ -0,0 +1,411 @@ +"""The checks that need the artefacts, and the list a reviewer should read. + +Three things live here: + +- the index oracle: the book's own tables of cases point at paragraphs, and + the case name should occur in the paragraph they point at. The table is + evidence about the corpus, not authority over it: a name that is not in + the paragraph is a suspect to read, never a paragraph to invent. +- the render gate: the text in the reader must be the text in the corpus, + paragraph for paragraph. +- the suspect report: everything the gates found, in one ordered list, so + that a reviewer reads tens of items and not thousands. +""" +import json +import os +import re +from collections import Counter +from html.parser import HTMLParser + +from . import counts_line +from . import tables + +STOPWORDS = {"the", "and", "case", "re", "of", "in", "on", "at", "to", "a", "an", + "vs", "v"} +# the tags that never close: they must not be counted as nesting +VOID_TAGS = frozenset(("area", "base", "br", "col", "embed", "hr", "img", + "input", "link", "meta", "param", "source", "track", "wbr")) +SEVERITY = {"fail": 3, "warn": 2, "pass": 1, "reported": 0, "skip": 0} +MIN_PARSE_RATE = 0.5 +CONFIRMED_RATE = 0.9 +NEAR_RATE = 0.75 +TRUSTWORTHY_RATE = 0.9 + + +def _norm(text): + norm = (text or "").lower() + norm = re.sub(r"[^a-z0-9' ]+", " ", norm) + return re.sub(r"\s+", " ", norm).strip() + + +NAME_RE = re.compile(r"^(.*?)(?=\s*\[|\s*\(\s*\d|\s+\d{4}\b|\s*\d{1,2}\s+[A-Z]{2,3}\b)") +DOT_LEADERS = re.compile(r"\.{2,}") + + +def _name_of(entry): + """The case name in a table entry, without its citation.""" + found = NAME_RE.match(entry or "") + return (found.group(1) if found else (entry or "")).strip() + + +def _key_words(entry): + """The words of a table entry that identify the case it names. + + Only the name counts: the citation beside it ("[1993] 1 IR 359") says + where the case was reported, not which case it is. + """ + words = [] + for word in re.findall(r"[a-z][a-z'-]{3,}", _name_of(entry).lower()): + if word in STOPWORDS or word in words: + continue + words.append(word) + return words[:3] + + +def _legible(entry): + """Can this entry be read as a case name at all? + + A line the scan turned into dot leaders and fragments names nothing, + and cannot judge anything. + """ + if DOT_LEADERS.search(entry or ""): + return False + return bool(_key_words(entry)) + + +def index_oracle(book): + """Do the names in the book's own tables occur in the paragraphs they cite?""" + from . import qa + lines = tables.table_lines(book) + rows = tables.table_rows(book) + known = {} + for para in book.paragraphs: + marker = getattr(para, "native_marker", None) + if para.kind == "body" and marker: + known[marker] = para + order = [p for p in book.paragraphs if p.kind == "body"] + position = {id(p): i for i, p in enumerate(order)} + checked = confirmed = near = absent = unresolved = skipped = 0 + suspects = [] + for row in rows: + keys = _key_words(row["entry"]) + if not _legible(row["entry"]): + skipped += 1 + continue + for ref in row["refs"]: + checked += 1 + para = known.get(ref) + if para is None: + unresolved += 1 + suspects.append({"entry": row["entry"], "ref": ref, + "why": "no paragraph carries that number"}) + continue + text = _norm(para.text) + if all(key in text for key in keys): + confirmed += 1 + continue + here = any(key in text for key in keys) + index = position.get(id(para), 0) + beside = False + close = False + for step in (1, 2, 3): + for other in (order[max(0, index - step):index] + + order[index + 1:index + 1 + step]): + if any(key in _norm(other.text) for key in keys): + if step == 1: + beside = True + else: + close = True + break + if beside or close: + break + if here or beside: + near += 1 + suspects.append({"entry": row["entry"], "ref": ref, + "why": "the name is in the paragraph or beside it"}) + elif close: + # a few paragraphs away: the reference may be off, or a + # paragraph may have been split in the wrong place + absent += 1 + suspects.append({"entry": row["entry"], "ref": ref, + "why": "the name is a few paragraphs away"}) + else: + absent += 1 + suspects.append({"entry": row["entry"], "ref": ref, + "why": "the name is not in the paragraph"}) + parsed_lines = len({(id(page), line.text) for page, line in lines + if tables.parse_table_line(line.text)}) + parse_rate = (parsed_lines / len(lines)) if lines else 0.0 + value = {"table_lines": len(lines), "rows": len(rows), + "parsed_lines": parsed_lines, "parse_rate": round(parse_rate, 4), + "rows_without_a_readable_name": skipped, + "checked": checked, "confirmed": confirmed, "near": near, + "absent": absent, "unresolved": unresolved} + if not checked: + return qa.Gate("index_oracle", value, {"confirmed_rate": CONFIRMED_RATE}, + "skip", 0, + "the book has no table of cases to check the paragraphs against", + suspects=suspects, suspect_count=len(suspects)) + rate = (confirmed + near) / checked + value["rate"] = round(rate, 4) + if rate < TRUSTWORTHY_RATE: + # the table's own reading is too poor to hold the conversion to a + # rate: it is reported, not gated. On a scan of a book of case + # tables about half the names sit in the paragraph the table points + # at, and the misses are the table's reading rather than the + # conversion's. + return qa.Gate("index_oracle", value, {"confirmed_rate": CONFIRMED_RATE}, + "reported", checked, + "the tables of cases are read too badly to judge the " + "paragraphs: %d of %d cited names are in the paragraph " + "they cite, so the measure is reported, not gated" + % (confirmed + near, checked), + suspects=suspects, suspect_count=len(suspects)) + status = "pass" if rate >= CONFIRMED_RATE else ("warn" if rate >= NEAR_RATE else "fail") + return qa.Gate("index_oracle", value, {"confirmed_rate": CONFIRMED_RATE}, + status, checked, + "%d of %d cited names were found in the paragraph they cite" + % (confirmed + near, checked), + suspects=suspects, suspect_count=len(suspects)) + + +class _ReaderScan(HTMLParser): + """What the reader actually shows: its frame and its blocks. + + The frame matters as much as the text. A reader with the right + paragraphs and the wrong title, or with an empty contents list, is + broken in a way that a comparison of the text alone cannot see. + """ + + def __init__(self): + super().__init__(convert_charrefs=True) + self.title = "" + self.counts = [] # one entry per data-gate="counts" element + self.nav_hrefs = [] + self.ids = [] + self.hrefs = [] + self.units = [] # (id, text) + self.classes = Counter() + self.tags = Counter() + self._in_title = False + self._gate_depth = 0 + self._buf = None + self._open = None + self._open_tag = None + + def handle_starttag(self, tag, attrs): + found = dict(attrs) + self.tags[tag] += 1 + classes = (found.get("class") or "").split() + for name in classes: + self.classes[name] += 1 + if found.get("id"): + self.ids.append(found["id"]) + href = found.get("href") or "" + if href.startswith("#"): + self.hrefs.append(href[1:]) + if "navitem" in classes: + self.nav_hrefs.append(href[1:]) + if tag == "title": + self._in_title = True + if self._gate_depth: + if tag not in VOID_TAGS: + self._gate_depth += 1 + elif found.get("data-gate") == "counts": + # the counts are bound by an attribute, not by a class name: + # the gate must not break when the styling changes + self._gate_depth = 1 + self._buf = [] + if "data-para" in found and self._open is None: + self._open = {"id": found["data-para"], "text": []} + self._open_tag = tag + + def handle_endtag(self, tag): + if self._open is not None and tag == self._open_tag: + self.units.append((self._open["id"], "".join(self._open["text"]))) + self._open = None + self._open_tag = None + if tag == "title": + self._in_title = False + if self._gate_depth: + self._gate_depth -= 1 + if self._gate_depth == 0: + self.counts.append(" ".join("".join(self._buf).split())) + self._buf = None + + def handle_data(self, data): + if self._in_title: + self.title += data + if self._gate_depth and self._buf is not None: + self._buf.append(data) + if self._open is not None: + self._open["text"].append(data) + + +def _markdown_units(corpus_dir): + """The paragraphs the chapter files carry, by id, and their headings. + + A heading is written as a heading line, not as a numbered paragraph, + so it is counted by its text. + """ + found = {} + headings = set() + chapters = os.path.join(corpus_dir, "chapters") + if not os.path.isdir(chapters): + return found, headings + for name in sorted(os.listdir(chapters)): + if not name.endswith(".md"): + continue + with open(os.path.join(chapters, name), encoding="utf-8") as fh: + for line in fh: + if line.startswith("#"): + headings.add(line.lstrip("#").strip()) + continue + if not line.startswith("["): + continue + end = line.find("]") + if end < 0: + continue + found[line[1:end]] = line[end + 1:].strip() + return found, headings + + +def _outline_paragraph_ids(outline): + """The paragraphs the contents list is made of, in order.""" + out = [] + for ch in (outline or {}).get("chapters", []): + out.extend(p["id"] for p in ch.get("paragraphs", [])) + for div in ch.get("divisions", []): + out.extend(p["id"] for p in div.get("paragraphs", [])) + for sub in div.get("subsections", []): + out.extend(p["id"] for p in sub.get("paragraphs", [])) + return out + + +def render_conservation(book, html_text, records, book_meta, counts, outline, + corpus_dir=None): + """The reader must show the corpus: its text, its frame and its blocks. + + The text is compared paragraph by paragraph, not by length: a + concatenation hides a dropped paragraph balanced by a duplicated one. + The frame is compared too - the title, the counts, the contents list, + the kinds of block - because a reader with the right text and an empty + contents list is broken in a way that comparing the text cannot see. + """ + from . import qa + scan = _ReaderScan() + scan.feed(html_text) + rendered = {} + for pid, text in scan.units: + rendered.setdefault(pid, _norm(text)) + problems = [] + + for rec in records: + want = _norm(rec.get("text")) + got = rendered.get(rec["id"]) + if got is None: + problems.append({"id": rec["id"], "why": "not in the reader"}) + elif got != want: + problems.append({"id": rec["id"], "why": "the text differs in the reader"}) + + title = (book_meta or {}).get("title") or "" + if not scan.title.strip(): + problems.append({"id": "reader", "why": "the reader has no title"}) + elif scan.title.strip() != title.strip(): + problems.append({"id": "reader", + "why": "the reader's title is not the book's title"}) + counts = counts or {} + want_counts = counts_line.law(counts) + if len(scan.counts) != 1: + problems.append({"id": "reader", + "why": "the reader shows %d counts lines, it should show one" + % len(scan.counts)}) + elif scan.counts[0] != want_counts: + problems.append({"id": "reader", + "why": "the reader's counts are not the corpus's counts"}) + + expected_nav = _outline_paragraph_ids(outline) + if scan.nav_hrefs != expected_nav: + problems.append({"id": "reader", + "why": "the contents list does not match the outline: " + "%d entries against %d" % (len(scan.nav_hrefs), + len(expected_nav))}) + known = set(scan.ids) + missing = sorted(set(t for t in scan.hrefs if t not in known)) + if missing: + problems.append({"id": "reader", + "why": "%d links point at ids that are not there" % len(missing)}) + duplicates = sorted(set(i for i in scan.ids if scan.ids.count(i) > 1)) + if duplicates: + problems.append({"id": "reader", + "why": "%d ids appear twice" % len(duplicates)}) + + quotations = sum(1 for r in records if r.get("block_kind") == "quotation") + tables = sum(1 for r in records if r.get("block_kind") == "table") + if scan.tags.get("blockquote", 0) != quotations: + problems.append({"id": "reader", + "why": "the reader shows %d quotations, the corpus has %d" + % (scan.tags.get("blockquote", 0), quotations)}) + if scan.classes.get("tl", 0) != tables: + problems.append({"id": "reader", + "why": "the reader shows %d table lines, the corpus has %d" + % (scan.classes.get("tl", 0), tables)}) + notes = len(getattr(book, "footnotes", [])) + owned = sum(len(rec.get("footnote_ids", []) or []) for rec in records) + if scan.classes.get("note", 0) != notes: + problems.append({"id": "reader", + "why": "the reader shows %d notes, the corpus has %d" + % (scan.classes.get("note", 0), notes)}) + if scan.classes.get("note-back", 0) != owned: + problems.append({"id": "reader", + "why": "%d notes have no way back to their paragraph" + % (owned - scan.classes.get("note-back", 0))}) + + chapter_records = 0 + if corpus_dir: + markdown, headings = _markdown_units(corpus_dir) + chapter_records = len(markdown) + for rec in records: + if rec.get("kind") == "heading": + if rec.get("text") not in headings: + problems.append({"id": rec["id"], + "why": "the heading is not in the chapter files"}) + continue + got_md = markdown.get(rec["id"]) + if got_md is None: + problems.append({"id": rec["id"], "why": "not in the chapter files"}) + elif _norm(got_md) != _norm(rec.get("text")): + problems.append({"id": rec["id"], + "why": "the text differs in the chapter files"}) + + value = {"records": len(records), "reader_units": len(rendered), + "reader_title": scan.title.strip(), + "reader_counts": scan.counts[0] if scan.counts else "", + "contents_entries": len(scan.nav_hrefs), + "quotations": scan.tags.get("blockquote", 0), + "table_lines": scan.classes.get("tl", 0), + "notes_shown": scan.classes.get("note", 0), + "links": len(scan.hrefs), + "chapter_records": chapter_records, + "problems": len(problems)} + status = "pass" if not problems else "fail" + return qa.Gate("render_conservation", value, {"mismatches": 0}, status, + len(records), + "" if not problems else + "%d things about the reader do not match the corpus" % len(problems), + suspects=problems[:50], suspect_count=len(problems)) + + +def collect_suspects(gates): + """Everything the gates found, worst first.""" + out = [] + for gate in gates: + items = getattr(gate, "suspects", None) or [] + count = getattr(gate, "suspect_count", None) or len(items) + if not count: + continue + out.append({"gate": gate.name, "status": gate.status, + "severity": SEVERITY.get(gate.status, 1), + "count": count, "items": items[:50]}) + out.sort(key=lambda row: (-row["severity"], -row["count"])) + return out diff --git a/pipeline/file-manifest.json b/pipeline/file-manifest.json new file mode 100644 index 00000000..5e9d9834 --- /dev/null +++ b/pipeline/file-manifest.json @@ -0,0 +1,753 @@ +{ + "files": [ + { + "bytes": 936, + "path": ".minimax-plugin/plugin.json", + "sha256": "8a7819cdf8adcb9bb25f2ed4342b425e3abafa2a73a527685d04bd697605af57" + }, + { + "bytes": 3544, + "path": "PROVENANCE.md", + "sha256": "ada612ed16ba6d726d251d5b95083d431a23f260107212ed11943f91a5e89d22" + }, + { + "bytes": 2777, + "path": "agents/library-builder.md", + "sha256": "7e4e05f79974e2d46b3960191874ed640afc874f6c273d8c5b7c7a4a0148c8a2" + }, + { + "bytes": 1512, + "path": "examples/build-example.sh", + "sha256": "2b85c6b1b3b441958a2fa2d9b048b0cb7864e9cc60b93bd4edd0f7d16e6e18bd" + }, + { + "bytes": 666, + "path": "examples/coffee-library/espresso-2024/chapters/01-The-shot.md", + "sha256": "94ad6b4b0b878e2a53e09e8681e2386535cb33e97f5b0832e970a0e7354d1ecf" + }, + { + "bytes": 338, + "path": "examples/coffee-library/espresso-2024/chapters/02-The-puck.md", + "sha256": "bf939af666ff43901c8fe59bcc5ece9a670a64bd7639129a5485c35206573faf" + }, + { + "bytes": 449, + "path": "examples/coffee-library/filter-2025/chapters/01-The-brew.md", + "sha256": "f67e0e7436f5c5580322b1f1398aa222f4750f2fa5fb09d1a8d68f484c97a186" + }, + { + "bytes": 295, + "path": "examples/coffee-library/filter-2025/chapters/02-The-water.md", + "sha256": "71fe997b5bca36fb960db3fce8b0955fc8b5d07324c54f31371532cb2c7af55a" + }, + { + "bytes": 774, + "path": "examples/coffee-library/index/terms/espresso-2024.jsonl", + "sha256": "62ee97bafb4e9c14c34cbbf50ba77c4b1646f8fa2fd43b926bd70d24341ef937" + }, + { + "bytes": 879, + "path": "examples/coffee-library/index/terms/filter-2025.jsonl", + "sha256": "ccb8893ade4ab1c4a4b71b79593080fe24ff7d135ac3dfac2e0538e24f779a54" + }, + { + "bytes": 1003, + "path": "examples/coffee-library/index/terms/roast-2023.jsonl", + "sha256": "501ed80d75506504de1582b66f80649ee3e9935316df23ca494732f4df0358d1" + }, + { + "bytes": 368, + "path": "examples/coffee-library/paper-filter-2019/manifest.json", + "sha256": "5a7007f1666bc915e66c45aa17c96ed6d7a6e25458521b9ab909a673677198a3" + }, + { + "bytes": 971, + "path": "examples/coffee-library/paper-filter-2019/outline.json", + "sha256": "957ded37795f0b2ea72957ff8f1270a8baca7563b1ccab08b92e36c6bba5f560" + }, + { + "bytes": 1383, + "path": "examples/coffee-library/paper-filter-2019/paragraphs.jsonl", + "sha256": "a7fd0bf317e4b12d4208b28e56a50f19996051580778f446d979c174dc971876" + }, + { + "bytes": 316, + "path": "examples/coffee-library/roast-2023/chapters/01-The-roast.md", + "sha256": "6412fbbb3eb9c54e40b9ecf1005fc536db4558c1ac8722700ef43beb47a05ca9" + }, + { + "bytes": 233, + "path": "examples/coffee-library/roast-2023/chapters/02-The-cup.md", + "sha256": "35da743e5668feda8a8e3827b07339c2d5d833274681029732fbb3f06d34a7ac" + }, + { + "bytes": 158049, + "path": "icon-dark.png", + "sha256": "0fd55e85743af48e878be6f1a8e2b6198c967570026aee73132561f24c2712ac" + }, + { + "bytes": 127527, + "path": "icon.png", + "sha256": "888547c34c661e12f25a98252a25b8745d80b0a836861cc71ab67e5908d0d088" + }, + { + "bytes": 99, + "path": "pipeline/book2corpus/__init__.py", + "sha256": "867d36fb3d5bc07341819ab6059874971f197b08e03b3c38fa7cf7ccd41fd59e" + }, + { + "bytes": 24235, + "path": "pipeline/book2corpus/admission.py", + "sha256": "559fcb4513497c0a1f10f1c26d3a18de8730213e67a082517b343c4026d561a4" + }, + { + "bytes": 6112, + "path": "pipeline/book2corpus/assignment.py", + "sha256": "12a5f9341c3edcb173ca94992fbeecd3a59574689b2015ffc597c177086e8817" + }, + { + "bytes": 5919, + "path": "pipeline/book2corpus/batch.py", + "sha256": "33c679c99abdda6c6f542a6f64b77f1b882a078908ffce20f13b78dc9eada373" + }, + { + "bytes": 16722, + "path": "pipeline/book2corpus/book.py", + "sha256": "ad88074c922fdd6384f7a4f94033c1aac98e7d5951574dc5e2014188a68c1301" + }, + { + "bytes": 17835, + "path": "pipeline/book2corpus/cli.py", + "sha256": "090af9dddbfcf981bfbdb8af54f6d1ef4f3d0b4a054fd6d89b0aedbb77911f4e" + }, + { + "bytes": 1626, + "path": "pipeline/book2corpus/counts_line.py", + "sha256": "f58ae9210f31489b08f7bc20c7a9f0317dc619a8c6e62ce44bad39ada7f6ea14" + }, + { + "bytes": 10262, + "path": "pipeline/book2corpus/debris.py", + "sha256": "7276348347d5c33807656340eb93f3aa92e7b59d9f92a6b0cd8f06260d8e9104" + }, + { + "bytes": 23644, + "path": "pipeline/book2corpus/digital.py", + "sha256": "fa5f502a31370111be58c1195ce7dafb8ae6022fa514f4c0b7fc9d05426fda9e" + }, + { + "bytes": 18109, + "path": "pipeline/book2corpus/emit.py", + "sha256": "23e05df29a4b0fba2e6b964dcc4f1fadb17ed209a800c5c55ac8da6e5b5608da" + }, + { + "bytes": 35137, + "path": "pipeline/book2corpus/figures.py", + "sha256": "9a591fb20f807260a0d34bdbbac8c9498de2e061a1dfdd88e4ce1907111dc321" + }, + { + "bytes": 16949, + "path": "pipeline/book2corpus/html.py", + "sha256": "6454f88d91a8c6d90c448a2dafd92873f3493c7c8f919231f41e8f452b06c654" + }, + { + "bytes": 4584, + "path": "pipeline/book2corpus/ids.py", + "sha256": "4e4ce63f8197d1d53c9675ca5657058375db64f1df8d05f31680101ea8a0458a" + }, + { + "bytes": 4504, + "path": "pipeline/book2corpus/index_block.py", + "sha256": "f080438eba3d1cbd6ed444c1400251e3fbeb9841c5dd0bb5071193eae099a275" + }, + { + "bytes": 5951, + "path": "pipeline/book2corpus/ingest.py", + "sha256": "b4401324a8e3cd6f9fd4e92b2bc3b629a6045d2a9fc529add139731c1828521c" + }, + { + "bytes": 2584, + "path": "pipeline/book2corpus/ir.py", + "sha256": "b5704fc03fb528b2698505edc50976934eeb114ccc1124b707ad611a6c92b633" + }, + { + "bytes": 31777, + "path": "pipeline/book2corpus/judge.py", + "sha256": "fff93271d94e220ae7d77ca2d4cef680d5bcbf4cf573c3668cea62f7424641ff" + }, + { + "bytes": 7000, + "path": "pipeline/book2corpus/layout.py", + "sha256": "957d77de7ecad834f6a0b1ec1996e9f0fea3d6e49b4304c84be88180a39b6b68" + }, + { + "bytes": 57976, + "path": "pipeline/book2corpus/notes.py", + "sha256": "b7b610f18d430654ac733cff25974dbd7f6c44ebb21a09d0bce3ff4c5763a10f" + }, + { + "bytes": 36446, + "path": "pipeline/book2corpus/notes_gate.py", + "sha256": "28a9949d560b86673b7118df838291efe242839a6060a4ecbde8ef18a61e9921" + }, + { + "bytes": 15465, + "path": "pipeline/book2corpus/pipeline.py", + "sha256": "a64f62779becf10a0948cddb254ad64d314d0d53d5bf1d03b48f1cf3260de4d7" + }, + { + "bytes": 6788, + "path": "pipeline/book2corpus/profile.py", + "sha256": "638a4abf3b519dd9d4f6da49a54b89e2d2805b2b5d9d464d131ac678927d6a24" + }, + { + "bytes": 25348, + "path": "pipeline/book2corpus/projection.py", + "sha256": "8bdb12cd8c99c1aeb5c71bf7eba88554b9036f788786b888bfdc245661a94393" + }, + { + "bytes": 1913, + "path": "pipeline/book2corpus/provenance.py", + "sha256": "9ae314eaa61a7d0ab3c116d9f852d8bf59b2a3b86ecb3978cdb24c8b0ea41a23" + }, + { + "bytes": 25894, + "path": "pipeline/book2corpus/qa.py", + "sha256": "94f0ca73815c9a59b68a603bbdf0346e89f95775e4ca46acc6cf79463a736765" + }, + { + "bytes": 4827, + "path": "pipeline/book2corpus/readscore.py", + "sha256": "356cadd0f6423f0b787118c4106f27d116770a1c12572056d7e405771e49d025" + }, + { + "bytes": 2648, + "path": "pipeline/book2corpus/scrub.py", + "sha256": "9e28553cfbacb89cf2e00b52c7ff270b41f9b9e91807587719682d7067f8b966" + }, + { + "bytes": 7859, + "path": "pipeline/book2corpus/selfcheck.py", + "sha256": "6a14614b04e67a430b5e482df329769eebe254cc953fc17c4a0955cdbe30f17b" + }, + { + "bytes": 7443, + "path": "pipeline/book2corpus/stamp.py", + "sha256": "c7476a15ecda077e01817a0e133a6bbfc2c1c7fc805f6ea9feef859e57950986" + }, + { + "bytes": 10975, + "path": "pipeline/book2corpus/structure.py", + "sha256": "458bd8773a92246699e39d108cd3e4a64bca3de286d2f0dabc0ee32e0ff0016a" + }, + { + "bytes": 2900, + "path": "pipeline/book2corpus/tables.py", + "sha256": "9a5a8e54e7129905a46b90fd02fda878ae16303b868af08d442e66a936555edc" + }, + { + "bytes": 22332, + "path": "pipeline/book2corpus/templates/reader.head.html", + "sha256": "1f520513877c905d3a13736ee4d74fba06dfec12965dce3296d99c6c89dde6f9" + }, + { + "bytes": 14631, + "path": "pipeline/book2corpus/templates/reader.tail.html", + "sha256": "a792f18057cd2be929906115e38e6af45797d595085011d117df0706534b3e74" + }, + { + "bytes": 21342, + "path": "pipeline/book2corpus/terms.py", + "sha256": "18df83471b26205d62fd95a381a4863b5521438b24c21deb940e427fa644b664" + }, + { + "bytes": 17350, + "path": "pipeline/book2corpus/verify.py", + "sha256": "d32182c966048f4011dae1c8c41baaf724855ee18875b3ed234c280049edfaf2" + }, + { + "bytes": 2549, + "path": "pipeline/scripts/adjudicate_mismatches.py", + "sha256": "57428fb586cfc5a9e9b461c158c5cd1f3e2cabe72743cb6b738dd07d7f9c0e5d" + }, + { + "bytes": 5480, + "path": "pipeline/scripts/agy_corpus.py", + "sha256": "3735cd5527fed7948639ab1907573e64cef27ad8b00e9640a85c231da057fc5f" + }, + { + "bytes": 7267, + "path": "pipeline/scripts/apply_admission.py", + "sha256": "aa998d32d8ecbdec80606b0f5285ce2517b6bc86160488980a818e0d239f50b3" + }, + { + "bytes": 13257, + "path": "pipeline/scripts/assemble_index.py", + "sha256": "85ee7e20144b9ff725b4bd3e682ba2c0e8f05ac9dbd375d0a0ea619df6eec844" + }, + { + "bytes": 6992, + "path": "pipeline/scripts/audit_agreement.py", + "sha256": "762f540a8f8722130274ded7bd4f619c150536a1542b0e297202b8c3b5118304" + }, + { + "bytes": 2753, + "path": "pipeline/scripts/audit_all.py", + "sha256": "956ffa51aa1fe92576e76cfe5b7b192201debe20012af6a3d914e621da118d1a" + }, + { + "bytes": 14406, + "path": "pipeline/scripts/audit_decide.py", + "sha256": "fe2508ec9526ff99edbe69b23102cf8eff67490b44b336e647ce14f322be3fa1" + }, + { + "bytes": 23278, + "path": "pipeline/scripts/audit_figures.py", + "sha256": "52762a0069d80002142eb82e5a6b37ad6e6508097a3e9e6ab1668d0e8178feee" + }, + { + "bytes": 6475, + "path": "pipeline/scripts/audit_label.py", + "sha256": "056ae080e21fed098c01e19deb9bc8d7f22bf060982ca84322fc5c6e1abcf93b" + }, + { + "bytes": 9279, + "path": "pipeline/scripts/audit_links.py", + "sha256": "69b31324e7c9858b6c1eb3e2e3954a0a0a59f3782ee20271af29766825a42ca1" + }, + { + "bytes": 4375, + "path": "pipeline/scripts/audit_plant.py", + "sha256": "6f2d0cb4f3bd02863b1d7c7a6290d369bff005c97940e6b9d4966e5996eb5519" + }, + { + "bytes": 8570, + "path": "pipeline/scripts/audit_sample.py", + "sha256": "0db6fe4cf48f30278c14204654d735d5648d5e0bf80a6cd38fdae750f5c6181d" + }, + { + "bytes": 10684, + "path": "pipeline/scripts/build_database.py", + "sha256": "06194aa0a9df79a741b9340f42240508c7cd25a0ba2c529fc596b61b7485e7ff" + }, + { + "bytes": 40365, + "path": "pipeline/scripts/build_inventory.py", + "sha256": "c5f308506b9dc3e56270b6dc5e5757c96025f7a6432d53e00b5e375b838b1bbc" + }, + { + "bytes": 9961, + "path": "pipeline/scripts/build_read_packets.py", + "sha256": "5788975aa4f39018915d65bf96a95102d0ee1fc3975c5879f8e8279dc1c9be6b" + }, + { + "bytes": 8441, + "path": "pipeline/scripts/calibrate_figures.py", + "sha256": "8f73e90d3ad28e1fb65ffc195747d4527f19a3268ffb2cf7e9dd39e4dab6d89e" + }, + { + "bytes": 4107, + "path": "pipeline/scripts/check_answers_reproduced.py", + "sha256": "b342131f71c379d74394b956928dd09cca4795ed6f313ead2403a00240a328d7" + }, + { + "bytes": 7572, + "path": "pipeline/scripts/check_history_traces.py", + "sha256": "949209c6a1c06e861105780c3c3b85ac0a4a29278a2ab63255142b859a5f707b" + }, + { + "bytes": 10231, + "path": "pipeline/scripts/check_inventory.py", + "sha256": "97380ba6d32e90891b7bcc2e9b0577e3210850e479887b17fdba16816734c565" + }, + { + "bytes": 6890, + "path": "pipeline/scripts/check_minimal.py", + "sha256": "db48c0e4ee5589dbcca4f2546495e17b56d719c4f0a0d8e8857c52253d17a9c6" + }, + { + "bytes": 5751, + "path": "pipeline/scripts/check_reader_browser.py", + "sha256": "27a6c39691830cd5f83ec534881ad3b66456686d398234e137c37e803e3409c3" + }, + { + "bytes": 6859, + "path": "pipeline/scripts/check_readers.py", + "sha256": "252629afa2ac11ea7a7a07fcf300775faf867db2af78d52d52f234efd681dc79" + }, + { + "bytes": 22969, + "path": "pipeline/scripts/check_reproducible.py", + "sha256": "730d8904e6accf199a0562a9f1efade2c5ef4a551f40f064576d3c36a3ea4ac5" + }, + { + "bytes": 1412, + "path": "pipeline/scripts/check_settings.py", + "sha256": "4aa9399870c3aec8d46e1607ef3aa2a4715e788de3995d170a9ec6839eff7b9c" + }, + { + "bytes": 5733, + "path": "pipeline/scripts/check_source_traces.py", + "sha256": "3c60315c6d14ee98012b08801a003ad3568ab0dc8bcdb807a1e210deba5eaa9b" + }, + { + "bytes": 63393, + "path": "pipeline/scripts/judge_forms.py", + "sha256": "142a5ab92a2f78a9f90040b0c6a45ed53781dd7cdb7760cff248be70f2ab5a51" + }, + { + "bytes": 23034, + "path": "pipeline/scripts/link_read.py", + "sha256": "2aac3950627fd1c3428a447a74d182fdd4b9ee1fdfac1a8b0171b0ef90198955" + }, + { + "bytes": 10240, + "path": "pipeline/scripts/make_candidates_spacy.py", + "sha256": "5867eba9874e5de244c137c9ebc950e88d2508a6d238ea528f69074c78d2b6ba" + }, + { + "bytes": 7016, + "path": "pipeline/scripts/make_corpus_index.py", + "sha256": "a2ebcc554adff3c4cb85266a8e00c562ee974c854aa3ee9a200affadfd915a59" + }, + { + "bytes": 20297, + "path": "pipeline/scripts/make_gold.py", + "sha256": "823a626e67db2de905041152e4430bd9b741b9f9e1d1a333d4537fc42bbf8faf" + }, + { + "bytes": 5015, + "path": "pipeline/scripts/make_heldout.py", + "sha256": "6e127d8579d8ba24c6dfa92161ebca849b18b73042f047f59655c25eb718bf05" + }, + { + "bytes": 11794, + "path": "pipeline/scripts/make_index.py", + "sha256": "5d9208360e173a4b8a43a42114bec147754974b5b8a38d5d45f117d3f2c0d06d" + }, + { + "bytes": 10894, + "path": "pipeline/scripts/make_policy.py", + "sha256": "7ef6ddfada66813b331da3c8081eb1a31afd591e7357a94ef5710b4a2ab1f300" + }, + { + "bytes": 5498, + "path": "pipeline/scripts/make_search_index.py", + "sha256": "a7ff4b22b8207582bd07870bfc7a4075a0fdaffd13a04de1b93d8553cd213772" + }, + { + "bytes": 41063, + "path": "pipeline/scripts/make_terms.py", + "sha256": "1fb3d1a8ca4a5e8c9aa530c0215f920299ab9d80be15f208691cb1191a44a4e8" + }, + { + "bytes": 29120, + "path": "pipeline/scripts/md_corpus2html.py", + "sha256": "c1a0e6b8424096a7272a63cf54d2aeda617380473952bddb3b44661444f02e40" + }, + { + "bytes": 10736, + "path": "pipeline/scripts/measure_candidates.py", + "sha256": "3a65570a706822bfce6c39dfc2507fad62ddfed35c44fd10922e4c5e4c0bacdf" + }, + { + "bytes": 16475, + "path": "pipeline/scripts/measure_termhood.py", + "sha256": "c4ececa9977f59fa28a34078cc728ddcaf912dfbe248dfb036bddfccb8646690" + }, + { + "bytes": 24328, + "path": "pipeline/scripts/pipeline.py", + "sha256": "283ac684d47a6fd12e0aa30b01822c313b1bc29071a4e0f847e2b6e9d11cfbfd" + }, + { + "bytes": 4271, + "path": "pipeline/scripts/rebuild_all.sh", + "sha256": "1ce6fcabf8a983aa58bce95b13dac1892391d0159dc8a88174a8e69ba2be6ebf" + }, + { + "bytes": 15420, + "path": "pipeline/scripts/render_database_view.py", + "sha256": "959b0e09265ca711ad49796d4042d630e8c40083549c235a1e1d010b25a0c69d" + }, + { + "bytes": 5900, + "path": "pipeline/scripts/render_machine_reader.py", + "sha256": "e0419e8d4edd3a63977afabc46c4075336f6eafdaf5545b661334531745bc908" + }, + { + "bytes": 8814, + "path": "pipeline/scripts/reocr_lines.py", + "sha256": "6a7920962bb5c3c8a7a2c1c4aa9ca55d26494a9e52f4bf46c1cd1b8e2885f677" + }, + { + "bytes": 20335, + "path": "pipeline/scripts/replay_admission.py", + "sha256": "1760b222cd04bd421ef9276dbd26eaba959b61bf76b074dcb0620893f89f56c0" + }, + { + "bytes": 776, + "path": "pipeline/scripts/run_read_wide.sh", + "sha256": "94ebe8e00f0def46cd5722d2ba130558f4a9b2f495a7eb3c17335ea9661942c1" + }, + { + "bytes": 8942, + "path": "pipeline/scripts/score_read.py", + "sha256": "177a234348aa6b7ca41f86fde0752e328184623e95af8c842443fc5edf25c8bd" + }, + { + "bytes": 17402, + "path": "pipeline/scripts/score_reread.py", + "sha256": "b45732bb30fdf20177b85b0f2d13e31ab126fbb0db10595240314e896d5e59a4" + }, + { + "bytes": 13669, + "path": "pipeline/scripts/score_terms.py", + "sha256": "1d3cbc153325ed64d7eb55d748b3750dfd1423d90d35e3cf76a87b46d8a15ffe" + }, + { + "bytes": 1000, + "path": "pipeline/scripts/score_the_read.sh", + "sha256": "02e3bb0a64ed500f1773e18a22ea103ad18b2717412d79e18c32246684d76f8a" + }, + { + "bytes": 6288, + "path": "pipeline/scripts/scrub_source_traces.py", + "sha256": "cd29c2f617685265b06ff64a8bba061d11befb19df9c0d5b7a37c95d9969cd7c" + }, + { + "bytes": 4697, + "path": "pipeline/scripts/ship_corpus.py", + "sha256": "c81507394c5385fe56eb2ab216fb016f27b3c02d7fb504f8ca470b53433deecf" + }, + { + "bytes": 5203, + "path": "pipeline/scripts/termhood_jate.py", + "sha256": "8c909287a7bd3cd21fa1b38866f08320edde286a9dc609c7b74143df2d923458" + }, + { + "bytes": 3372, + "path": "pipeline/scripts/warm_picture_cache.py", + "sha256": "04aada3b9fabd587001e36625a323d1d861f42d2d0f14fc25c7edabc43945b13" + }, + { + "bytes": 14188, + "path": "pipeline/scripts/write_run_record.py", + "sha256": "58dd6bf1ae37566c04870448ff7d1cf0dc5d23548df2b343e9f353628b32ab63" + }, + { + "bytes": 24956, + "path": "pipeline/settings/pipeline.json", + "sha256": "218adc281e52a7342138175a971594444b2a0ad3effd4796b32b31b08e6cc8f6" + }, + { + "bytes": 0, + "path": "pipeline/tests/__init__.py", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "bytes": 4471, + "path": "pipeline/tests/fixtures.py", + "sha256": "e9f3a7218e71e0af052c6bc0a039fec2db246b6185329cb77bcc29f490496306" + }, + { + "bytes": 54313, + "path": "pipeline/tests/fixtures/citation_tier_labels.json", + "sha256": "98c7dba0046149fa863d18206c3e79e097b8a1b9b0290e637afaba4f2c7adabb" + }, + { + "bytes": 5339, + "path": "pipeline/tests/fixtures/pilot_adjudication.json", + "sha256": "213c4940e516ecc1b1939e35c4a6da104230763542607433243928f36fbce811" + }, + { + "bytes": 20665, + "path": "pipeline/tests/fixtures/pilot_handread-2026-11-28.json", + "sha256": "a828609aa0f117700a90f87a6b80fd8b67171beefccc4e2dab76b99bb82ed4e7" + }, + { + "bytes": 22116, + "path": "pipeline/tests/test_admission.py", + "sha256": "8c6aabd1c64da9985790fea562193f636c5a584b8a660b75a77d22a607d75325" + }, + { + "bytes": 4554, + "path": "pipeline/tests/test_answers_reproduced.py", + "sha256": "0b53164ad19c5e455f349191798fb4f0ecc49078b1b73d5a9a85fc9607f61593" + }, + { + "bytes": 3493, + "path": "pipeline/tests/test_build.py", + "sha256": "b3fcb73b158bf376f3bd213aa6140b91e7b0204771598448371923de5e4d3741" + }, + { + "bytes": 8681, + "path": "pipeline/tests/test_citation_tier.py", + "sha256": "96661cb8760d008535437d8886f153370a690155012572574d2811d9498b8be1" + }, + { + "bytes": 5063, + "path": "pipeline/tests/test_corpus.py", + "sha256": "90bcd9786dd328489dc04df4a62f80a1c99580c6d58e51a7a43ef1fbfc107f16" + }, + { + "bytes": 10672, + "path": "pipeline/tests/test_corpus_pipeline.py", + "sha256": "b516022491fa557b4e397be2048da322552a06ac0f829a1c3714b5b6fadacd25" + }, + { + "bytes": 7263, + "path": "pipeline/tests/test_debris.py", + "sha256": "ee977207cd6d987c8942d4616bbb876d4b2bda8fe60ec61c6547bb24424d32cb" + }, + { + "bytes": 8091, + "path": "pipeline/tests/test_forms.py", + "sha256": "f138142bcd5b5c1892ed3fef0d2ed9cb1295ca7d6367ab2f45306847d89ed101" + }, + { + "bytes": 12061, + "path": "pipeline/tests/test_index.py", + "sha256": "16a4079c2c2df4e5c20096e8d949bafb07475a90835a0d69f918bf02652786dc" + }, + { + "bytes": 25220, + "path": "pipeline/tests/test_inventory_identity.py", + "sha256": "52778edeb11bf1f042bb5765e92707329b48a86b9b06fa2f8fe2f9d23178416a" + }, + { + "bytes": 16695, + "path": "pipeline/tests/test_judge_escalation.py", + "sha256": "22b65ad3731da0700a813c2585d1fbec251065a0c497d562742fbd910c6a6630" + }, + { + "bytes": 8114, + "path": "pipeline/tests/test_judge_reuse.py", + "sha256": "f3a4b42f18171285381bc085b5aa3f763e3947c1267a45ca249ddfac1f453a0b" + }, + { + "bytes": 5372, + "path": "pipeline/tests/test_judge_routes.py", + "sha256": "0825b97bb721c499857ba70793024b09c8ae261d9ce332ff8a462d1759eb8878" + }, + { + "bytes": 1349, + "path": "pipeline/tests/test_line_occurrence.py", + "sha256": "65549b7e269e86258c2f70c691503268fe36e444a4d18ce38de817d1d3337754" + }, + { + "bytes": 5563, + "path": "pipeline/tests/test_matching.py", + "sha256": "7129ac93cad153f0a629589bf7e67cfa57afe3eed19cf27712886e772937a2b7" + }, + { + "bytes": 5478, + "path": "pipeline/tests/test_missing_forms.py", + "sha256": "d4eb4ee121f4c12f20ad07d4de541d879cb222ce66458bac85d5d3343ff2c789" + }, + { + "bytes": 3825, + "path": "pipeline/tests/test_pipeline.py", + "sha256": "31dfcd27355639a0d2923f1ced2ac760818e48fb2aa6e1b4dfbfecf77632fdab" + }, + { + "bytes": 23198, + "path": "pipeline/tests/test_projection.py", + "sha256": "338e12731fc518f774f2db430f0f5cab81125cbf2293e979c7cfaedb7725b847" + }, + { + "bytes": 4929, + "path": "pipeline/tests/test_read_packets.py", + "sha256": "bce97b6bd6aca4b998b02fd1ea58b36d894d3df72349b11ec855dacaee2cb413" + }, + { + "bytes": 5607, + "path": "pipeline/tests/test_read_score.py", + "sha256": "e7760513b2f0dab7d4ef8332388bed0b1f0c4358b6f8a7a64ff35e341176d257" + }, + { + "bytes": 1564, + "path": "pipeline/tests/test_scrub.py", + "sha256": "4106d9f190fcb83b6275113e8c91240c10460b46df4855781ff6f0db68e67031" + }, + { + "bytes": 5206, + "path": "pipeline/tests/test_stamp.py", + "sha256": "76fedb6044f80910a05cc0e15ab7712a09d420f72e6c96fe9417dbc71ea0a67d" + }, + { + "bytes": 2363, + "path": "pipeline/tests/test_terms_singular.py", + "sha256": "1fa7d1dc11d65bfd965e6f3973778d199bc6682d04526bc655fbc01e78bcbbe6" + }, + { + "bytes": 628, + "path": "pipeline/tests/test_tool.py", + "sha256": "a58464903faef59a0e27c4bfb5f36423403c82b02abf09fa3111a5d7d537e166" + }, + { + "bytes": 6010, + "path": "pipeline/tools/doctor.py", + "sha256": "1b9596d3a1f087f6a4ce3704d62954dac54ecd2e96a8034d3517690fd72dd9ab" + }, + { + "bytes": 1944, + "path": "pipeline/tools/register_prompt.py", + "sha256": "63a627b8deb41154b77550bd97eeeb6e2476356bfdcebcc8a3402fbebfbd3666" + }, + { + "bytes": 6190, + "path": "pipeline/tools/scaffold_library.py", + "sha256": "dc8264e2e2e3582189b6c4c72433199d653c8afcbf31be1d9a16b6e2409aafa7" + }, + { + "bytes": 2962, + "path": "pipeline/tools/verify_vendored.py", + "sha256": "57aada8fec455696674ab85ca14194d220c6b22aaf157d1ad3b7a999c12f5ff6" + }, + { + "bytes": 2870, + "path": "pipeline/tools/write_manifest.py", + "sha256": "37ebfb6e0c4b551fdb97ddd1a6327daf21d8dc0ec599be2a37a5f00cca8e6e12" + }, + { + "bytes": 3367, + "path": "pipeline/tools/write_readme.py", + "sha256": "eb1c22f9fbd35cd390e0476352bc214be7f3bbe195ee6da4b5504ad7f685b30c" + }, + { + "bytes": 8346, + "path": "server.py", + "sha256": "1bc5b50b627dc6d7f5d2bf16695164f2ffe3f902a039e963ed256c956b29014f" + }, + { + "bytes": 407, + "path": "servers.mcp.json", + "sha256": "bd1781dab4d7e597014f1847d5fbf40832108e4c3ee881bab5ae0642b38605cc" + }, + { + "bytes": 7317, + "path": "skills/document-library/SKILL.md", + "sha256": "4c5d17646f422f22f17fb7db5f52e15beea88c7237f2f8e9c94bd4594bba0d18" + }, + { + "bytes": 3680, + "path": "skills/document-library/references/document-contract.md", + "sha256": "05c2ff2d6d7267d16a1fb79aac7f4ed28fe4a0a1515fddb5be7101ac5712ca69" + }, + { + "bytes": 4231, + "path": "skills/document-library/references/identities-and-claims.md", + "sha256": "996162c572d03806659234508b9593f0e42e5c67fe808baa83946899e6f37734" + }, + { + "bytes": 4712, + "path": "skills/document-library/references/settings.md", + "sha256": "6912d28699fd9d40dea43c60923d0788803886cee5d4f10953408dcf3d5afb79" + } + ], + "source": "vochic03/book2corpus", + "source_commit": "216bb4aa4b621f92e4cc484108e2b31cb21cafa8", + "source_repository": "https://gitlab.com/vochic03/book2corpus", + "vendored": "the pipeline and the tests that cover it; the audits of one corpus are not here" +} diff --git a/pipeline/scripts/adjudicate_mismatches.py b/pipeline/scripts/adjudicate_mismatches.py new file mode 100644 index 00000000..53af0744 --- /dev/null +++ b/pipeline/scripts/adjudicate_mismatches.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Sample the judge's mismatches for a second opinion. + +A tier whose mismatch rate is high is held: before its demotions are +applied, a sample of the mismatches is read by someone else. If the +mismatches are real, the pictures go; if the judge is wrong, the +demotions are held and the tier stays as it is. + +This prints the sample; the verdicts come back as a JSON file: + + {"numbered": {"checked": 30, "judge_errors": 2}, ...} + + python3 scripts/adjudicate_mismatches.py --corpus-root \\ + --out /tmp/mismatch-cases.txt +""" +import argparse +import json +import os +import random +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + + +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--per-tier", type=int, default=30) + parser.add_argument("--seed", type=int, default=20261124) + args = parser.parse_args(argv) + root = os.path.abspath(os.path.expanduser(args.corpus_root)) + random.seed(args.seed) + + cases = [] + for book in sorted(os.listdir(root)): + path = os.path.join(root, book, "figure-audit.json") + if not os.path.exists(path): + continue + with open(path, encoding="utf-8") as fh: + report = json.load(fh) + for tier, row in report.get("tiers", {}).items(): + for mismatch in row.get("mismatches", []): + cases.append({"case": "%s|%s|%s" % (book, tier, mismatch.get("id")), + "book": book, "tier": tier, + "id": mismatch.get("id"), + "reason": (mismatch.get("reason") or "").strip()}) + + by_tier = {} + for case in cases: + by_tier.setdefault(case["tier"], []).append(case) + + lines = [] + picked = [] + for tier, group in sorted(by_tier.items()): + sample = random.sample(group, min(args.per_tier, len(group))) + picked.extend(sample) + for case in sample: + lines.append("%s :: %s" % (case["case"], case["reason"][:400])) + with open(args.out, "w", encoding="utf-8") as fh: + fh.write("\n".join(lines)) + print("cases written: %s (%d cases over %d tiers)" + % (args.out, len(picked), len(by_tier))) + for tier, group in sorted(by_tier.items()): + print(" %-18s %d mismatches in all" % (tier, len(group))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/agy_corpus.py b/pipeline/scripts/agy_corpus.py new file mode 100644 index 00000000..2122b4dd --- /dev/null +++ b/pipeline/scripts/agy_corpus.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""scripts/agy_corpus.py - the corpus job, stepped through the Antigravity CLI. + +The job is the work the corpus still owes: the blind read of the links, the +re-judge by the Argon model, the rebuild that applies both fixes, and the +record that says what the corpus then carries. Each step is run once, in +order, and a step that has run is not run again. The steps are paced by the +door: one step at a time, and a step that fails because the door has no +allowance left is waited out, not retried into. + + python3 scripts/agy_corpus.py --corpus-root [--step ] + python3 scripts/agy_corpus.py --corpus-root --status +""" +import argparse +import json +import os +import subprocess +import sys +import time + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOL = HERE +LOG = os.path.join(HERE, "runs", "agy_corpus", "job-log.jsonl") +LOCK = os.path.join(HERE, "runs", "agy_corpus", "job.lock") +ARGON = "gemini-4-carbon-high" +CARBON = "gemini-4-neon-xhigh" +READ = os.path.join(os.path.expanduser("~"), ".minimax", "sessions", + "mvs_20afcbb9507247ef9f8b758aa7dfd2a7", "workspace", + "read-2026-11-30") + + +def steps_for(corpus): + """The job, in order: each step is a command and the marker it leaves.""" + read = READ + return [ + {"name": "read-narrow-argon", + "marker": os.path.join(read, "argon", "narrow", "done"), + "command": ["python3", os.path.join(TOOL, "scripts", "link_read.py"), + "run", "--packets", read, "--out", os.path.join(read, "argon"), + "--model", ARGON, "--stage", "narrow", + "--workers", "1", "--timeout", "2400"]}, + {"name": "read-narrow-carbon", + "marker": os.path.join(read, "carbon", "narrow", "done"), + "command": ["python3", os.path.join(TOOL, "scripts", "link_read.py"), + "run", "--packets", read, "--out", os.path.join(read, "carbon"), + "--model", CARBON, "--stage", "narrow", + "--workers", "1", "--timeout", "2400"]}, + {"name": "read-wide", + "marker": os.path.join(read, "wide", "done"), + "command": ["bash", os.path.join(TOOL, "scripts", "run_read_wide.sh"), + read]}, + {"name": "read-scored", + "marker": os.path.join(corpus, "index", "manifest", + "link-read-2026-12-01.json"), + "command": ["bash", os.path.join(TOOL, "scripts", "score_the_read.sh"), + corpus, read]}, + {"name": "re-judge", + "marker": os.path.join(corpus, "index", "manifest", "link-run-2026-12-01.json"), + "command": ["python3", os.path.join(TOOL, "scripts", "judge_forms.py"), + "--corpus-root", corpus]}, + {"name": "rebuild", + "marker": os.path.join(corpus, "index", "manifest", "inventory.json"), + "command": ["bash", os.path.join(TOOL, "scripts", "rebuild_all.sh"), + "--corpus-root", corpus, "--with-links"]}, + ] + + +def log(step, state, detail): + os.makedirs(os.path.dirname(LOG), exist_ok=True) + with open(LOG, "a", encoding="utf-8") as handle: + handle.write(json.dumps({"step": step, "state": state, + "detail": detail, "when": time.time()}, + ensure_ascii=False) + chr(10)) + + +def claim_the_lock(): + os.makedirs(os.path.dirname(LOCK), exist_ok=True) + try: + handle = os.open(LOCK, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + os.write(handle, str(os.getpid()).encode()) + os.close(handle) + return True + except FileExistsError: + return False + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="agy_corpus.py") + parser.add_argument("--corpus-root", default="") + parser.add_argument("--step", default="") + parser.add_argument("--status", action="store_true") + parser.add_argument("--wait", type=int, default=600) + args = parser.parse_args(argv) + corpus = os.path.abspath(os.path.expanduser(args.corpus_root)) + steps = steps_for(corpus) + if args.status: + for step in steps: + done = os.path.exists(os.path.join(os.path.dirname(LOG), "done-" + step["name"])) + print("%-20s %s" % (step["name"], "done" if done else "to do")) + return 0 + if not claim_the_lock(): + print("another run holds the lock; the door serves one job at a time") + return 0 + try: + for step in steps: + if args.step and step["name"] != args.step: + continue + done = os.path.join(os.path.dirname(LOG), "done-" + step["name"]) + if os.path.exists(done): + continue + print("==> %s" % step["name"]) + log(step["name"], "start", " ".join(step["command"][:4])) + code = subprocess.call(step["command"], cwd=TOOL) + log(step["name"], "end", "the command returned %d" % code) + if code == 0: + with open(done, "w", encoding="utf-8") as handle: + handle.write(step["name"] + chr(10)) + if code != 0: + print(" the step did not finish; the door may have no allowance") + print(" waiting %d seconds" % args.wait) + time.sleep(args.wait) + finally: + if os.path.exists(LOCK): + os.remove(LOCK) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/apply_admission.py b/pipeline/scripts/apply_admission.py new file mode 100644 index 00000000..d1d05fa9 --- /dev/null +++ b/pipeline/scripts/apply_admission.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""scripts/apply_admission.py - write the terms files from the replay. + +Written 27 Nov 2026 by MCode, after the ruling of Claude Fable 5.2 on the +systematic admission of terms (the ruling that the index must be rebuilt +from the replayed output, not merely re-scored). + +WHAT IT DOES +The replay decides, for every name the model ever proposed, whether the +new rules admit it. This script writes that decision back into the +corpus: the terms file of each book is rebuilt from the names the new +rules admit, the names they refuse are taken out, and the names that were +refused by the old rules and are admitted by the new ones are put in, +with the chapter they were named in. + +Nothing here calls a model. The names are already stored; this is the +bookkeeping. + + python3 scripts/apply_admission.py --corpus-root --dry-run + python3 scripts/apply_admission.py --corpus-root + +What it writes: + + index/terms/.jsonl the terms of one book, under the new rules + index/admission/apply.json what was added, what was taken out, and why +""" +import argparse +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from book2corpus import admission +from book2corpus import terms as old_terms + + +def read_jsonl(path): + if not os.path.exists(path): + return [] + out = [] + with open(path, encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def write_jsonl(path, rows): + tmp = path + ".tmp" + with open(tmp, "w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + os.replace(tmp, path) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args(argv) + + corpus = args.corpus_root + admission_dir = os.path.join(corpus, "index", "admission") + report_path = os.path.join(admission_dir, "replay.json") + if not os.path.exists(report_path): + print("no replay at index/admission/replay.json - run replay_admission.py") + return 1 + with open(report_path, encoding="utf-8") as handle: + replay = json.load(handle) + + # the names the new rules admit, per book, with the chapter they + # were named in + admitted = {} + folder = os.path.join(admission_dir, "admitted") + if os.path.isdir(folder): + for name in sorted(os.listdir(folder)): + if not name.endswith(".jsonl"): + continue + book = name[:-6] + admitted[book] = set() + for row in read_jsonl(os.path.join(folder, name)): + if row.get("term"): + admitted[book].add(row["term"]) + + # the chapter each name was named in, from the stored calls + scopes = {} + for record in read_jsonl(os.path.join(corpus, "index", "cache", "terms.jsonl")): + book = record.get("book", "") + chapter = record.get("chapter", "") + for name in record.get("admitted") or []: + scopes.setdefault(book, {}).setdefault(name, set()).add(chapter) + for item in record.get("rejected") or []: + name = item.get("term") if isinstance(item, dict) else str(item) + if name: + scopes.setdefault(book, {}).setdefault(name, set()).add(chapter) + + # what the replay decided for every name it scored + decisions = {} + folder = os.path.join(admission_dir, "decisions") + if os.path.isdir(folder): + for name in sorted(os.listdir(folder)): + if not name.endswith(".jsonl"): + continue + book = name[:-6] + decisions[book] = {} + for row in read_jsonl(os.path.join(folder, name)): + if row.get("label"): + decisions[book][row["label"]] = row.get("verdict") + + summary = {} + changed_books = [] + for book in sorted(admitted): + path = os.path.join(corpus, "index", "terms", book + ".jsonl") + rows = read_jsonl(path) + if not rows: + continue + keep, dropped = [], [] + seen = set() + seen_canon = set() + for row in rows: + label = row.get("label", "") + verdict = decisions.get(book, {}).get(label) + if verdict is None: + # a record the replay never scored: the law books' defined + # terms and the like. The rules decide it, without the + # verbatim check, so nothing is lost by accident. + verdict = admission.admit(label).get("verdict") + if verdict == admission.ADMIT or label in admitted[book]: + keep.append(row) + seen.add(label) + seen_canon.add(old_terms.canonical_form(label)) + else: + dropped.append({"term": label, + "reason": "the new rules do not admit it"}) + added = [] + for label in sorted(admitted[book]): + if label in seen: + continue + canonical = old_terms.canonical_form(label) + if canonical in seen_canon: + continue + chapters = sorted(scopes.get(book, {}).get(label, [])) + added.append({"canonical": canonical, "definition": None, + "kind": "named", "label": label, + "scope": chapters[0] if chapters else "", + "term_id": "%s:%s" % (book, canonical)}) + summary[book] = {"kept": len(keep), "added": len(added), + "dropped": len(dropped)} + if added or dropped: + changed_books.append(book) + if not args.dry_run: + write_jsonl(path, keep + added) + with open(os.path.join(admission_dir, "dropped-%s.jsonl" % book), + "w", encoding="utf-8") as handle: + for row in dropped: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + + totals = { + "books": len(summary), + "kept": sum(v["kept"] for v in summary.values()), + "added": sum(v["added"] for v in summary.values()), + "dropped": sum(v["dropped"] for v in summary.values()), + "rules_version": admission.RULES_VERSION, + "dry_run": bool(args.dry_run), + } + out = os.path.join(admission_dir, "apply.json") + if not args.dry_run: + with open(out, "w", encoding="utf-8") as handle: + json.dump({"totals": totals, "per_book": summary}, handle, + indent=1, ensure_ascii=False) + print("%s: kept %d, added %d, dropped %d across %d books" + % ("DRY RUN" if args.dry_run else "written", totals["kept"], + totals["added"], totals["dropped"], totals["books"])) + for book in changed_books[:12]: + s = summary[book] + print(" %-26s +%-5d -%d" % (book, s["added"], s["dropped"])) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/assemble_index.py b/pipeline/scripts/assemble_index.py new file mode 100644 index 00000000..5ec572e3 --- /dev/null +++ b/pipeline/scripts/assemble_index.py @@ -0,0 +1,329 @@ +#!/usr/bin/env python3 +"""scripts/assemble_index.py - the assemble stage: pure code, no model. + +Written 26 Nov 2026 by MCode, after the ruling of Claude Opus 5.5 on the +corpus-wide term index (briefs 12, 13 and 14). + +This stage asks nothing of any model. It takes the terms the terms stage +admitted and the links the link stage judged, and it works out where those +terms are, which books share them, and what each book's reader should say +about the others. + + python3 scripts/assemble_index.py --corpus-root + +What it writes: + + index/occurrences/.jsonl where the terms of one book are + index/slices/.json what that book's reader says of others +""" +import argparse +import hashlib +import json +import os +import re +import sys +import time + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus import debris, projection, terms # noqa: E402 + +ASSEMBLER_VERSION = 3 + +# the most other books one term may name in the full slice +MAX_BOOKS_PER_TERM = 20 + +# the most places of one term the reader may link to +MAX_ANCHORS = 5 + + +def _file_hash(path): + """The hash of a file, or nothing when there is no file.""" + if not os.path.exists(path): + return "" + digest = hashlib.sha256() + with open(path, "rb") as fh: + digest.update(fh.read()) + return digest.hexdigest() + + +def _body_hash(units): + """The hash of the text a book's slice was made from.""" + digest = hashlib.sha256() + for _anchor, _title, body in units: + digest.update(body.encode("utf-8")) + return digest.hexdigest() + + +def read_jsonl(path): + """A file of objects, one a line.""" + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + rows.append(json.loads(line)) + return rows + + +def _title_from_source(text): + """The book's own name, from the source line its notes carry. + + The line reads "Author, The Book's Title, 5th edition (2025), PDF pages + 1 to 1". The title is what is between the author and the edition, + and when the author is the only name before the pages, the title is + what comes before the year. + """ + parts = [part.strip() for part in text.split(",")] + if len(parts) > 1 and not parts[1].lower().startswith("pdf pages"): + title = ", ".join(parts[1:]) + else: + title = parts[0] + title = re.split(r"\s+\d+(st|nd|rd|th) edition|\s*\(\d{4}\)", title)[0] + title = title.strip().rstrip(",").strip() + return title if len(title) > 2 else "" + + +def book_title(corpus, book): + """The book's own title, as the reader shows it. + + A reader whose title is a folder name names the wrong thing, so the + title is taken from the book itself: the manifest when there is one, + and otherwise the source line the notes carry at the top of their + first chapter. + """ + manifest = os.path.join(corpus, book, "manifest.json") + if os.path.exists(manifest): + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + found = (data.get("book") or {}).get("title") + if found: + return found + chapters = os.path.join(corpus, book, "chapters") + if os.path.isdir(chapters): + for name in sorted(os.listdir(chapters)): + if not name.endswith(".md"): + continue + with open(os.path.join(chapters, name), encoding="utf-8") as fh: + for line in fh: + if line.startswith("Source:"): + found = _title_from_source(line.split(":", 1)[1].strip()) + if found: + return found + break + break + return book + + +def chapter_title(name, body): + """The title of a chapter: its own heading, or the name of its file.""" + for head in debris.headings(body): + if head["level"] == 1 and head["text"]: + return head["text"] + stem = re.sub(r"\.md$", "", name) + stem = re.sub(r"^\d+\s*", "", stem) + return stem.strip() or name + + +def chapters_of(book_dir): + """The chapters of a notes book, in the order the reader shows them.""" + folder = os.path.join(book_dir, "chapters") + out = [] + for index, name in enumerate(sorted(n for n in os.listdir(folder) + if n.endswith(".md")), 1): + with open(os.path.join(folder, name), encoding="utf-8") as fh: + body = fh.read() + out.append(("ch-%02d" % index, chapter_title(name, body), body)) + return out + + +def paragraphs_of(book_dir): + """The paragraphs of a law code, with the ids the reader gives them.""" + path = os.path.join(book_dir, "paragraphs.jsonl") + out = [] + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + record = json.loads(line) + if record.get("kind") not in (None, "body"): + continue + title = " / ".join(record.get("section_path") or []) + if not title and record.get("chapter"): + title = "chapter %s" % record["chapter"] + out.append((record.get("id") or "", title, record.get("text") or "")) + return out + + +def locate(units, rows, furniture=None): + """Where each term is, in its own book: how often, and where. + + One pass over the words, with the terms in a table, so a book is read + once and not once per term. The tokenizer is the one in debris, so + "occurs" means the same thing here and in the terms stage. + """ + table = terms.term_table(rows) + counts = {} + places = {} + for anchor, title, body in units: + # the page furniture and the running heads are not the book's + # words, so they are not counted + body = projection.strip_furniture(body, furniture) + for term_id, _offset, _route in terms.scan_terms(body, table): + counts[term_id] = counts.get(term_id, 0) + 1 + seen = places.setdefault(term_id, []) + if len(seen) < MAX_ANCHORS and (anchor, title) not in seen: + seen.append((anchor, title)) + return counts, places + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="assemble_index.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args(argv) + + corpus = args.corpus_root + index_root = os.path.join(corpus, "index") + started = time.time() + books = sorted(d for d in os.listdir(corpus) + if not d.startswith(".") + and os.path.isdir(os.path.join(corpus, d)) + and (os.path.isdir(os.path.join(corpus, d, "chapters")) + or os.path.exists(os.path.join(corpus, d, + "paragraphs.jsonl")))) + titles = {name: book_title(corpus, name) for name in books} + + concepts = read_jsonl(os.path.join(index_root, "concepts.jsonl")) + member_of = {} + shared = {} + for concept in concepts: + members = concept.get("members") or [] + for member in members: + member_of[member] = concept["concept_id"] + names = sorted(set(member.split("|", 1)[0] for member in members)) + for i in range(len(names)): + for j in range(i + 1, len(names)): + pair = (names[i], names[j]) + shared[pair] = shared.get(pair, 0) + 1 + + found = {} + for name in books: + rows = terms.read_terms(os.path.join(index_root, "terms", "%s.jsonl" % name)) + if not rows: + continue + book_dir = os.path.join(corpus, name) + if os.path.exists(os.path.join(book_dir, "paragraphs.jsonl")): + units = paragraphs_of(book_dir) + else: + units = chapters_of(book_dir) + furniture = projection.furniture_lines("\n".join(body for _a, _t, body in units)) + counts, places = locate(units, rows, furniture) + found[name] = {"rows": rows, "counts": counts, "places": places} + + written = 0 + for name in sorted(found): + rows = found[name]["rows"] + places = found[name]["places"] + slice_rows = [] + for row in rows: + canonical = row["canonical"] + mine = "%s|%s" % (name, canonical) + concept_id = member_of.get(mine) + also = [] + if concept_id: + for other in books: + if other == name or other not in found: + continue + if member_of.get("%s|%s" % (other, canonical)) != concept_id: + continue + # the other book's own term: the id carries the book + seen = found[other]["places"].get( + "%s:%s" % (other, canonical), []) + anchor, title = seen[0] if seen else ("", "") + also.append({"book": other, "title": titles.get(other, other), + "anchor": anchor, "chapter": title, + "count": found[other]["counts"].get(row["term_id"], 0), + "shared": shared.get(tuple(sorted((name, other))), 0), + "concept_id": concept_id}) + also.sort(key=lambda item: (-item["shared"], item["book"])) + also = also[:MAX_BOOKS_PER_TERM] + seen = places.get(row["term_id"], []) + slice_rows.append({ + "term_id": row["term_id"], "label": row["label"], + "canonical": canonical, "kind": row.get("kind") or "", + "scope": row.get("scope") or "", + "count": found[name]["counts"].get(row["term_id"], 0), + "anchors": [item[0] for item in seen], + "chapter": seen[0][1] if seen else "", + "concept_id": concept_id or "", + "also": also, + }) + slice_rows.sort(key=lambda row: row["term_id"]) + if not args.dry_run: + path = os.path.join(index_root, "slices", "%s.json" % name) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + json.dump({"book": name, "title": titles.get(name, name), + "terms": slice_rows}, fh, indent=1, sort_keys=True, + ensure_ascii=False) + fh.write("\n") + occurrences = [] + for row in slice_rows: + occurrences.append({ + "term_id": row["term_id"], "label": row["label"], + "canonical": row["canonical"], "kind": row["kind"], + "scope": row["scope"], "count": row["count"], + "anchors": row["anchors"], "chapter": row["chapter"], + "concept_id": row["concept_id"], + }) + path = os.path.join(index_root, "occurrences", "%s.jsonl" % name) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + for row in occurrences: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + written += 1 + + # the manifest: one row per book, with the hash of what it holds + old_manifest = {} + old_keys = set() + old_path = os.path.join(index_root, "manifest", "assemble.jsonl") + for row in read_jsonl(old_path): + old_manifest[row["unit"]] = row + old_keys.add(row["key"]) + manifest = [] + for name in sorted(found): + path = os.path.join(index_root, "slices", "%s.json" % name) + payload = hashlib.sha256() + with open(path, "rb") as fh: + payload.update(fh.read()) + # the key is the hash of what this book was made from, so it + # changes exactly when the book does + terms_path = os.path.join(index_root, "terms", "%s.jsonl" % name) + material = {"book": name, "version": ASSEMBLER_VERSION, + "terms": _file_hash(terms_path), + "concepts": _file_hash(os.path.join(index_root, "concepts.jsonl")), + "text": _body_hash(units)} + key = hashlib.sha256( + json.dumps(material, sort_keys=True).encode("utf-8")).hexdigest() + status = "reused" if key in old_keys else "computed" + manifest.append({"unit": name, "key": key, "status": status, + "output": payload.hexdigest(), + "terms": len(found[name]["rows"])}) + if not args.dry_run: + path = os.path.join(index_root, "manifest", "assemble.jsonl") + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + for row in sorted(manifest, key=lambda item: item["unit"]): + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + print("books: %d | concepts: %d | slices: %d | %.1f s" + % (written, len(concepts), written, time.time() - started)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/audit_agreement.py b/pipeline/scripts/audit_agreement.py new file mode 100644 index 00000000..26dc31f9 --- /dev/null +++ b/pipeline/scripts/audit_agreement.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Does the judge agree with a person? + +The judge is a model, and a model that is trusted without being checked +is not evidence. This reads the sheet the sampler wrote, once a person +has filled in the verdicts, and says three things: + + agreement how often the judge and the person say the same thing, + weighted so that the enriched part of the sample does not + distort the answer, with the lower bound of that number + sensitivity of the pairs the person calls wrong, how many the judge + calls wrong too - a judge that says "yes" to everything + agrees with nobody but is no use + kappa the chance that two judges agree by accident, which is a + diagnostic and not a gate + +The judge may be trusted when the lower bound of the agreement is at +least 0.95 and the lower bound of the sensitivity is at least 0.80 over +at least thirty pairs. + + python3 scripts/audit_agreement.py --sheet +""" +import argparse +import json +import os +import sys + +AGREEMENT_BAR = 0.95 +SENSITIVITY_BAR = 0.80 +MIN_SENSITIVITY = 30 + + +def wilson_lower(k, n, z=1.959964): + if n <= 0: + return 0.0 + p = k / n + d = 1 + z * z / n + centre = p + z * z / (2 * n) + spread = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) + return (centre - spread) / d + + +def kappa(pairs): + """Cohen's kappa over the pairs both judged.""" + counts = {} + for human, judge in pairs: + counts[(human, judge)] = counts.get((human, judge), 0) + 1 + total = len(pairs) + if not total: + return 0.0 + humans = {} + judges = {} + for (human, judge), count in counts.items(): + humans[human] = humans.get(human, 0) + count + judges[judge] = judges.get(judge, 0) + count + same = sum(count for (human, judge), count in counts.items() + if human == judge) + chance = 0.0 + for label, count in humans.items(): + chance += (count / total) * (judges.get(label, 0) / total) + if chance >= 1: + return 1.0 + return (same / total - chance) / (1 - chance) + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="audit_agreement.py") + ap.add_argument("--sheet", required=True) + args = ap.parse_args(argv) + with open(args.sheet, encoding="utf-8") as fh: + sheet = json.load(fh) + pairs = sheet.get("pairs") or [] + labelled = [p for p in pairs if (p.get("verdict") or "").strip()] + if not labelled: + print("no pair has a verdict yet: the sheet is", args.sheet) + print("%d pairs are waiting" % len(pairs)) + return 1 + # the pairs both could judge: "cannot_tell" is not a disagreement, and + # a judge that failed says nothing at all + RIGHT = ("match", "partial") + judged = [] + for pair in labelled: + human = (pair.get("verdict") or "").strip().lower() + judge = (pair.get("judge") or "").strip().lower() + if human not in RIGHT + ("mismatch",): + continue + if judge not in RIGHT + ("mismatch",): + continue + judged.append((pair, human, judge)) + if not judged: + print("none of the verdicts can be compared") + return 1 + def side(verdict): + return "right" if verdict in RIGHT else "wrong" + + agree = [(p, h, j) for p, h, j in judged if side(h) == side(j)] + weights = [float(p.get("weight") or 1.0) for p, _h, _j in judged] + agree_weights = [float(p.get("weight") or 1.0) for p, _h, _j in agree] + total_weight = sum(weights) or 1.0 + weighted = sum(agree_weights) / total_weight + # the effective sample size of the weighted mean, so the lower bound + # is not flattered by the weights + square = sum(w * w for w in weights) or 1.0 + effective = (total_weight ** 2) / square + lower = wilson_lower(weighted * effective, effective) + # sensitivity: of the pairs the person calls wrong, how many the judge + # calls wrong + wrong = [(p, h, j) for p, h, j in judged if h == "mismatch"] + caught = [(p, h, j) for p, h, j in wrong if j == "mismatch"] + sensitivity = len(caught) / len(wrong) if wrong else 0.0 + sensitivity_lower = wilson_lower(len(caught), len(wrong)) if wrong else 0.0 + + print("Judge against a person") + print() + print("| Measure | Value | Bar | Holds |") + print("| --- | --- | --- | --- |") + print("| Pairs in the sheet | %d | | |" % len(pairs)) + print("| Pairs labelled | %d | | |" % len(labelled)) + print("| Pairs both could judge | %d | | |" % len(judged)) + print("| Agreement | %.3f | | |" % weighted) + print("| Agreement, lower bound | %.3f | %.2f | %s |" + % (lower, AGREEMENT_BAR, "yes" if lower >= AGREEMENT_BAR else "no")) + print("| Sensitivity | %.3f | | |" % sensitivity) + print("| Sensitivity, lower bound | %.3f | %.2f | %s |" + % (sensitivity_lower, SENSITIVITY_BAR, + "yes" if (sensitivity_lower >= SENSITIVITY_BAR + and len(wrong) >= MIN_SENSITIVITY) else "no")) + print("| Pairs a person called wrong | %d | %d | %s |" + % (len(wrong), MIN_SENSITIVITY, + "enough" if len(wrong) >= MIN_SENSITIVITY else "too few")) + print("| Cohen's kappa | %.3f | | |" % kappa([(side(h), side(j)) for _p, h, j in judged])) + print() + # the judge's own error, written where the policy can correct for it + right_pairs = [(p, h, j) for p, h, j in judged if h != "mismatch"] + specificity = (len([1 for _p, _h, j in right_pairs if j != "mismatch"]) / + float(len(right_pairs))) if right_pairs else 0.0 + measured = {"agreement": round(weighted, 4), "lower_bound": round(lower, 4), + "sensitivity": round(sensitivity, 4), + "sensitivity_lower_bound": round(sensitivity_lower, 4), + "specificity": round(specificity, 4), + "judged": len(judged), "wrong_pairs": len(wrong), + "labelled_by": (labelled[0].get("labelled_by") or "unknown"), + "judge": (judged[0][0].get("judge_model") or "unknown")} + out_path = os.path.splitext(args.sheet)[0] + "-judge-error.json" + with open(out_path, "w", encoding="utf-8") as fh: + json.dump(measured, fh, indent=1, sort_keys=True) + print("the judge's measured error is written to %s" % out_path) + print() + if lower < AGREEMENT_BAR: + print("FAILED: the agreement does not reach the bar.") + print("The judge is not certified: label more pairs, or judge the", + "unreliable books by hand.") + return 1 + if len(wrong) < MIN_SENSITIVITY: + print("FAILED: too few pairs a person called wrong to measure the", + "judge's eye for a wrong picture.") + return 1 + if sensitivity_lower < SENSITIVITY_BAR: + print("FAILED: the judge misses too many of the wrong pictures.") + return 1 + print("The judge may be trusted on the books it has judged.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/audit_all.py b/pipeline/scripts/audit_all.py new file mode 100644 index 00000000..16aa89be --- /dev/null +++ b/pipeline/scripts/audit_all.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Audit every book that has a reader. + +One book at a time, each with its own sample: the tiers that carry a +picture are judged in full where they are small, and by a fixed-seed +sample where they are large. The books that are not built yet are left +alone, so this can run while the readers are still being made. + + python3 scripts/audit_all.py --corpus-root --workers 8 +""" +import argparse +import os +import subprocess +import sys +import time + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--sample", type=int, default=25) + parser.add_argument("--census", default="description-match,probable,inferred") + parser.add_argument("--candidates", type=int, default=10) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument("--judge", default="gemini") + parser.add_argument("--controls", type=int, default=12) + parser.add_argument("--only", default="", help="comma separated books") + args = parser.parse_args(argv) + root = os.path.abspath(os.path.expanduser(args.corpus_root)) + + wanted = [b.strip() for b in args.only.split(",") if b.strip()] + books = sorted(name for name in os.listdir(root) + if os.path.isdir(os.path.join(root, name, "chapters"))) + if wanted: + books = [b for b in books if b in wanted] + + for book in books: + reader = os.path.join(root, book, "index.html") + manifest = os.path.join(root, book, "figures.json") + if not os.path.exists(reader) or not os.path.exists(manifest): + print("skip %s: no reader yet" % book) + continue + started = time.time() + out = subprocess.run( + [sys.executable, os.path.join(HERE, "scripts", "audit_figures.py"), + "--corpus-root", root, "--book", book, + "--sample", str(args.sample), "--census", args.census, + "--candidates", str(args.candidates), + "--workers", str(args.workers), "--judge", args.judge, + "--controls", str(args.controls)], + capture_output=True, text=True) + if out.returncode: + print("FAILED %s: %s" % (book, out.stderr.strip()[-300:])) + continue + print("%-28s %5.1fs" % (book, time.time() - started)) + for line in out.stdout.splitlines(): + if line.startswith(("numbered", "verified", "description-match", + "probable", "inferred", "candidates", + "control", "judge")): + print(" ", line) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/audit_decide.py b/pipeline/scripts/audit_decide.py new file mode 100644 index 00000000..38d71965 --- /dev/null +++ b/pipeline/scripts/audit_decide.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""Turn the audit's verdicts into decisions about which pictures to show. + +The rules, fixed before the audit ran: + + per pair a pair the judge calls a mismatch is demoted: that figure + loses its picture and names it as a candidate + per book-tier a book-tier is demoted whole only when its Wilson UPPER + bound is under the bar - failing to prove a book good + never demotes it + per tier a tier is demoted across the corpus only when its POOLED + Wilson LOWER bound is under the bar + the gate if the judge's false-accept rate on the hard controls is + too high, the audit certifies nothing and no decision is + taken + the tripwire a tier whose mismatch rate is over 10% has its demotions + held, and 30 of its mismatches are printed for a second + pair of eyes + +The bars: numbered 0.90, verified 0.90, description-match 0.85, probable +0.85, inferred 0.85. + + python3 scripts/audit_decide.py --corpus-root +""" +import argparse +import json +import os +import random +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +BARS = {"numbered": 0.90, "verified": 0.90, "description-match": 0.85, + "probable": 0.85, "inferred": 0.85} +SAMPLED = ("numbered", "verified") +CONTROL_LIMIT = 0.10 # the judge's false-accept ceiling +MISMATCH_TRIPWIRE = 0.10 +CANNOT_TELL_LIMIT = 0.15 + + +def wilson(k, n, z=1.96): + if not n: + return 0.0, 1.0 + p = k / float(n) + d = 1 + z * z / n + centre = p + z * z / (2 * n) + spread = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) + return max(0.0, (centre - spread) / d), min(1.0, (centre + spread) / d) + + +def load(root): + books = {} + for name in sorted(os.listdir(root)): + path = os.path.join(root, name, "figure-audit.json") + if not os.path.exists(path): + continue + with open(path, encoding="utf-8") as fh: + books[name] = json.load(fh) + return books + + +def tier_sizes(root): + """How many figures each tier really has, and which ones they are.""" + sizes = {} + figures = {} + for name in sorted(os.listdir(root)): + path = os.path.join(root, name, "figures.json") + if not os.path.exists(path): + continue + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + for figure in data.get("figure_map", []): + tier = figure.get("tier") + if tier in BARS: + sizes.setdefault(name, {}).setdefault(tier, 0) + sizes[name][tier] += 1 + figures.setdefault(name, {}).setdefault(tier, []).append( + figure.get("id")) + return sizes, figures + + +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--seed", type=int, default=20261124) + parser.add_argument("--write", action="store_true", + help="write the demotions files") + parser.add_argument("--adjudication", default="", + help="the second opinion on the judge's mismatches") + parser.add_argument("--hold-tier", default="", + help="tiers whose corpus-wide demotion is held, with the reason") + args = parser.parse_args(argv) + root = os.path.abspath(os.path.expanduser(args.corpus_root)) + random.seed(args.seed) + + books = load(root) + sizes, tier_figures = tier_sizes(root) + if not books: + print("no audits found") + return 1 + + # ---- the gate: can the judge be believed at all? -------------------- + hard = [] + for report in books.values(): + hard.extend(report.get("controls", {}).get("control-hard", {}).get("verdicts", [])) + accepted = sum(1 for r in hard if r["verdict"] in ("match", "partial")) + low, high = wilson(accepted, len(hard)) + certified = high <= CONTROL_LIMIT + print("judge: %d hard controls, false-accept %s, wilson upper %.3f -> %s" + % (len(hard), round(accepted / len(hard), 4) if hard else 0, high, + "certifies" if certified else "CERTIFIES NOTHING")) + + # ---- pooled rates per tier ----------------------------------------- + pooled = {} + for tier, bar in BARS.items(): + weighted_pass = 0.0 + weighted_n = 0 + plain_pass = 0 + plain_n = 0 + cannot = 0 + mismatches = [] + for book, report in books.items(): + row = report.get("tiers", {}).get(tier) + if not row or not row.get("effective"): + continue + size = sizes.get(book, {}).get(tier, row["n"]) + rate = row["passed_lenient"] / float(row["effective"]) + weighted_pass += size * rate + weighted_n += size + plain_pass += row["passed_lenient"] + plain_n += row["effective"] + cannot += row["cannot_tell"] + mismatches.extend(row.get("mismatches", [])) + if not plain_n: + continue + if tier in SAMPLED: + rate = weighted_pass / weighted_n if weighted_n else 0.0 + else: + rate = plain_pass / float(plain_n) + low, high = wilson(int(round(rate * plain_n)), plain_n) + pooled[tier] = { + "bar": bar, "rate": round(rate, 4), "n": plain_n, + "wilson": [round(low, 4), round(high, 4)], + "cannot_tell_rate": round(cannot / float(plain_n + cannot), 4) if (plain_n + cannot) else 0, + "mismatch_rate": round(len(mismatches) / float(plain_n), 4), + "mismatches": mismatches, + "passes_needed": int(bar * plain_n) + 1, + } + print("%-16s pooled n=%-5d rate=%.3f wilson=%s bar=%.2f -> needs %d passes %s" + % (tier, plain_n, rate, [round(low, 4), round(high, 4)], bar, + pooled[tier]["passes_needed"], + "OK" if low >= bar else "FAILS")) + + # ---- decisions ------------------------------------------------------ + demotions = {} + reasons = {} + tier_failed = set() + tier_held = set() + + # a book-tier is broken when even its best case fails: the upper + # bound under the bar. Those books lose their pictures, whatever the + # tier is called. + broken_books = {} + for book, report in books.items(): + for tier, row in report.get("tiers", {}).items(): + bar = BARS.get(tier) + if bar is None or not row.get("effective"): + continue + if row["wilson_lenient"][1] < bar: + broken_books.setdefault(tier, set()).add(book) + + # the tier-wide question is asked of the books whose own data is + # sound: a tier that fails only because some books have broken + # pictures is not a broken tier, and demoting it everywhere would + # throw away pictures the audit says are right + for tier, bar in BARS.items(): + passes = 0 + total = 0 + for book, report in books.items(): + if book in broken_books.get(tier, ()): + continue + row = report.get("tiers", {}).get(tier) + if not row or not row.get("effective"): + continue + passes += row["passed_lenient"] + total += row["effective"] + if not total: + continue + low, high = wilson(passes, total) + pooled.setdefault(tier, {})["sound_books"] = { + "n": total, "rate": round(passes / float(total), 4), + "wilson": [round(low, 4), round(high, 4)], "bar": bar} + if low < bar: + tier_failed.add(tier) + print("tier %-16s over the books whose data is sound: %d of %d (%.3f) wilson=%s bar=%.2f -> %s" + % (tier, passes, total, passes / float(total), + [round(low, 4), round(high, 4)], bar, + "FAILS" if low < bar else "holds")) + + # the tripwire: a tier whose mismatch rate is over ten per cent has + # its demotions held until somebody else has read a sample of those + # mismatches. The second opinion decides: if the judge was right, + # the demotions go ahead; if the judge was wrong, the tier stays. + opinion = {} + if args.adjudication and os.path.exists(args.adjudication): + with open(args.adjudication, encoding="utf-8") as fh: + opinion = json.load(fh) + for tier, row in pooled.items(): + if row["mismatch_rate"] <= MISMATCH_TRIPWIRE: + continue + checked = (opinion.get(tier) or {}).get("checked") or 0 + errors = (opinion.get(tier) or {}).get("judge_errors") or 0 + if not checked: + tier_held.add(tier) + print("tripwire: %-18s needs a second opinion; none has been read yet" % tier) + continue + share = errors / float(checked) + print("adjudication: %-18s %d of %d sampled mismatches were the judge's fault (%.0f%%) -> %s" + % (tier, errors, checked, 100.0 * share, + "the demotions go ahead" if share <= 0.20 else "the demotions are held")) + if share > 0.20: + tier_held.add(tier) + for tier in sorted(tier_failed): + print("tier %s fails its bar: %s" % (tier, pooled[tier]["wilson"])) + for tier in sorted(tier_held): + print("tier %s is held: its mismatch rate is %s" + % (tier, pooled[tier]["mismatch_rate"])) + + # a tier can be held on purpose: when it misses its bar by a hair over + # the books whose data is sound, the pairs the judge called wrong are + # demoted one by one, and the tier-wide demotion would take away + # pictures the audit says are right + held_by_hand = set(t.strip() for t in args.hold_tier.split(",") if t.strip()) + for tier in sorted(held_by_hand & tier_failed): + print("tier %s is held on purpose: %s" % (tier, tier_failed)) + + # a tier that fails its bar, and is not held, is demoted everywhere: + # the rule is the rule, not the book it was measured in + for tier in sorted(tier_failed - tier_held - held_by_hand): + count = 0 + for book, by_tier in tier_figures.items(): + for figure_id in by_tier.get(tier, []): + if not figure_id: + continue + demotions.setdefault(book, set()).add(figure_id) + reasons.setdefault(book, {})[figure_id] = ( + "the audit found the %s tier unreliable across the corpus" % tier) + count += 1 + print("tier %s demoted everywhere: %d figures" % (tier, count)) + + for book, report in books.items(): + for tier, row in report.get("tiers", {}).items(): + book_failed = row["wilson_lenient"][1] < BARS.get(tier, 0.85) + if tier in tier_held: + continue # the tripwire holds this tier's demotions + for mismatch in row.get("mismatches", []): + figure_id = mismatch.get("figure_id") + if not figure_id: + continue + demotions.setdefault(book, set()).add(figure_id) + reasons.setdefault(book, {})[figure_id] = ( + "the audit judged this picture the wrong figure") + if book_failed: + # the whole book-tier goes: every figure the reader shows + # with that tier loses its picture + for verdict in row.get("verdicts", []): + if verdict.get("figure_id"): + demotions.setdefault(book, set()).add(verdict["figure_id"]) + reasons.setdefault(book, {})[verdict["figure_id"]] = ( + "the audit found the %s tier unreliable in this book" % tier) + # the escalation: a sampled book-tier with two mismatches needs a + # census before anything is demoted + for tier in SAMPLED: + row = report.get("tiers", {}).get(tier) + if row and len(row.get("mismatches", [])) >= 2: + print("escalate: %s %s has %d mismatches - census it before demoting" + % (book, tier, len(row["mismatches"]))) + + # the tripwire: 30 mismatches of a held tier, for a second opinion + for tier in sorted(tier_held): + mismatches = pooled.get(tier, {}).get("mismatches", []) + if len(mismatches) > 30: + sample = random.sample(mismatches, 30) + print("tripwire: 30 of %d %s mismatches for review" % (len(mismatches), tier)) + for row in sample: + print(" %-22s %-14s %s" % (row.get("book"), row.get("id"), + (row.get("reason") or "")[:80])) + + # ---- what the corpus is leaving on the table ------------------------ + left = [] + for report in books.values(): + row = report.get("candidates") + if row and row.get("effective"): + left.append(row) + if left: + total = sum(r["n"] for r in left) + good = sum(r["passed_lenient"] for r in left) + print("unclaimed candidates judged: %d, of which %d would have been right (%.1f%%)" + % (total, good, 100.0 * good / total if total else 0)) + + # ---- write ---------------------------------------------------------- + if args.write: + for book, figures in demotions.items(): + path = os.path.join(root, book, "demotions.json") + with open(path, "w", encoding="utf-8") as fh: + json.dump({"book": book, "demoted": reasons.get(book, {})}, + fh, indent=1, ensure_ascii=False) + print("demotions written:", path) + print() + print("figures to demote: %d across %d books" + % (sum(len(v) for v in demotions.values()), len(demotions))) + # the decision, written down: what this run decided, with the reason, so + # that the reading which releases it is given the right set + pending = os.path.join(args.corpus_root, "index", "manifest", + "figure-demotions.json") + os.makedirs(os.path.dirname(pending), exist_ok=True) + with open(pending, "w", encoding="utf-8") as fh: + json.dump({"decided": reasons, + "count": sum(len(v) for v in demotions.values()), + "books": len(demotions)}, fh, indent=1, ensure_ascii=False) + print("the decision written to:", pending) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/audit_figures.py b/pipeline/scripts/audit_figures.py new file mode 100644 index 00000000..426e8d4d --- /dev/null +++ b/pipeline/scripts/audit_figures.py @@ -0,0 +1,546 @@ +#!/usr/bin/env python3 +"""Ask a model whether the picture on the page is the picture the book printed. + +The matcher works on evidence - a figure's number, a caption, a written +description - and this is the check on that evidence: a second model, +which has not seen the matcher's reasoning, is shown the picture, the +caption the book printed and the description the notes carry, and is asked +whether they are the same figure. + +It also measures the model that does the asking. A control set of pairs +that are known to be wrong says how often it says yes to a wrong picture; +without that number, a pass rate means nothing. + +What it reports, per tier: the sample size, the verdicts, the pass rate +under both readings of "partial" (partial as a pass, partial as a fail), +the rate of "cannot tell", and the Wilson 95% interval on each. + + python3 scripts/audit_figures.py --corpus-root --book \\ + --sample 25 --census description-match,probable,inferred +""" +import argparse +import json +import os +import random +import re +import sys +import threading +import urllib.request +import base64 + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +API = "https://api.anthropic.com/v1/messages" +KEY_FILE = os.path.expanduser("~/claude-keys/anthropic.header") +MODEL = "claude-sonnet-5-5" # this model has deprecated the temperature parameter +GEMINI_API = "https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s" +GEMINI_MODEL = "gemini-3.8-flash" +GEMINI_KEY_FILE = os.path.expanduser("~/claude-keys/gemini.header") +CENSUS_DEFAULT = "description-match,probable,inferred" + +SYSTEM = """You check whether a picture from a textbook is the picture a note describes. +You are given the picture itself, the caption the book printed under it, and a +written description of what the note says the figure shows. Answer whether the +picture and the text are about the same figure. +Reply with one JSON object and nothing else: +{"verdict": "match" | "partial" | "mismatch" | "cannot_tell", "reason": "one sentence"} +"match" means the picture shows what the text describes. +"partial" means it is the same figure but the text describes something the +picture does not show, or shows something extra. +"mismatch" means they are different figures. +"cannot_tell" means the picture is too small, blank or unclear to judge.""" + +QUESTION = """The caption the book printed: {caption} +The written description of the figure: {description} +The kind of figure: {kind} +Is the picture the same figure as the text describes?""" + + +def wilson(k, n, z=1.96): + if not n: + return 0.0, 1.0 + p = k / float(n) + d = 1 + z * z / n + centre = p + z * z / (2 * n) + spread = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) + return max(0.0, (centre - spread) / d), min(1.0, (centre + spread) / d) + + +def api_key(): + with open(KEY_FILE, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line.lower().startswith("x-api-key:"): + return line.split(":", 1)[1].strip() + if ":" in line: + return line.split(":", 1)[1].strip() + raise SystemExit("no key in %s" % KEY_FILE) + + +def gemini_key(): + path = os.path.expanduser("~/claude-keys/gemini.header") + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if ":" in line: + return line.split(":", 1)[1].strip() + if line: + return line.strip() + raise SystemExit("no key in %s" % path) + + +def gemini_judge(image_path, kind, caption, description, timeout=180): + """One judgement from Gemini. + + The judge has to be one judge for the whole corpus: a tier measured + with one model and a tier measured with another are not the same + measurement. + """ + with open(image_path, "rb") as fh: + data = base64.b64encode(fh.read()).decode("ascii") + body = {"contents": [{"parts": [ + {"inline_data": {"mime_type": "image/webp", "data": data}}, + {"text": SYSTEM + "\n\nThe caption the book printed: " + (caption or "none") + + "\nThe written description of the figure: " + (description or "none") + + "\nThe kind of figure: " + (kind or "unknown") + + "\nIs the picture the same figure as the text describes?"}]}], + # the thinking budget has to be off: a model that thinks for two + # hundred tokens never reaches its answer + "generationConfig": {"maxOutputTokens": 900, "temperature": 0, + "thinkingConfig": {"thinkingBudget": 0}}} + url = GEMINI_API % (GEMINI_MODEL, gemini_key()) + request = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), + headers={"content-type": "application/json"}) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + answer = json.load(response) + except Exception as exc: + raise JudgeError(exc) + try: + text = "".join(part.get("text", "") + for part in answer["candidates"][0]["content"]["parts"]) + except Exception: + raise JudgeError(RuntimeError(str(answer)[:120])) + parsed = _parse_verdict(text) + if parsed is None: + return {"verdict": "error", "reason": text[:120]} + parsed["usage"] = {"judge": GEMINI_MODEL} + return parsed + + +class JudgeError(Exception): + """A call that did not come back.""" + + def __init__(self, exc): + Exception.__init__(self, str(exc)) + self.cause = exc + + @property + def kind(self): + from book2corpus.pipeline import classify_error + return classify_error(self.cause) + + +def ask_with_retries(ask, image_path, kind, caption, description, + attempts=5, base=2.0, cap=60.0, on_wait=None): + """One judgement, with the failures handled. + + A rate limit is waited out, a server error is tried again a few times, + and a request that is wrong is not tried again at all: a failed call is + missing data, not a verdict, and the run has to know which it was. + """ + import time + from book2corpus.pipeline import backoff_delay + for attempt in range(1, attempts + 1): + try: + return ask(image_path, kind, caption, description) + except JudgeError as exc: + kind_of = exc.kind + if kind_of == "fatal" or attempt >= attempts: + return {"verdict": "error", "reason": str(exc)[:120], + "failed_kind": kind_of, "attempts": attempt} + wait = getattr(exc.cause, "headers", None) and \ + exc.cause.headers.get("retry-after") + if not wait: + wait = backoff_delay(attempt, base, cap) + if on_wait: + on_wait(kind_of, attempt, float(wait)) + time.sleep(float(wait)) + return {"verdict": "error", "reason": "the judge gave up", + "failed_kind": "fatal", "attempts": attempts} + + +def _parse_verdict(text): + """The JSON the judge wrote, if it wrote one.""" + match = re.search(r"\{.*\}", text, re.S) + if not match: + return None + try: + return json.loads(match.group(0)) + except ValueError: + return None + + +def judge(image_path, kind, caption, description, timeout=180): + """One judgement from the API.""" + with open(image_path, "rb") as fh: + data = base64.b64encode(fh.read()).decode("ascii") + body = { + "model": MODEL, "max_tokens": 200, + "system": SYSTEM, + "messages": [{"role": "user", "content": [ + {"type": "image", "source": {"type": "base64", + "media_type": "image/webp", "data": data}}, + {"type": "text", "text": QUESTION.format( + kind=kind or "unknown", caption=caption or "none", + description=description or "none")}]}], + } + request = urllib.request.Request( + API, data=json.dumps(body).encode("utf-8"), + headers={"x-api-key": api_key(), "content-type": "application/json", + "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + answer = json.load(response) + except Exception as exc: + raise JudgeError(exc) + text = "".join(block.get("text", "") for block in answer.get("content", []) + if block.get("type") == "text") + match = re.search(r"\{.*\}", text, re.S) + if not match: + return {"verdict": "error", "reason": text[:120]} + try: + parsed = json.loads(match.group(0)) + except ValueError: + return {"verdict": "error", "reason": text[:120]} + parsed["usage"] = answer.get("usage", {}) + return parsed + + +_PAIRS_CACHE = {} + + +def pairs_for(book_dir): + """Every figure the reader shows, with the notes' own words. + + The reader is the thing under audit, so the pairs come from it: the + tier it shows, and the description it prints. The picture files come + from the manifest that names them. + """ + key = os.path.abspath(book_dir) + if key in _PAIRS_CACHE: + return _PAIRS_CACHE[key] + from book2corpus import notes_gate + with open(os.path.join(book_dir, "index.html"), encoding="utf-8") as fh: + html = fh.read() + scan = notes_gate.Scan() + scan.feed(html) + with open(os.path.join(book_dir, "figures.json"), encoding="utf-8") as fh: + data = json.load(fh) + entries = {e["id"]: e for e in data["figures"]} + chapters = {} + for row in data.get("figure_map", []): + if row.get("image"): + chapters.setdefault(row["image"], row.get("chapter")) + out = [] + for figure_id, figure in scan.figures.items(): + catalogue = figure.get("catalogue") or "" + entry = entries.get(catalogue) + if entry is None: + continue + description = (figure.get("fields", {}).get("CONTENT") or "").strip() + if not description or description.lower() == "none": + continue + out.append({ + "id": catalogue, + "figure_id": figure_id, + "tier": figure.get("tier"), + "book": os.path.basename(book_dir.rstrip("/")), + "chapter": entry.get("chapter") or chapters.get(catalogue), + "kind": (figure.get("fields", {}).get("TYPE") or "").strip(), + "caption": (figure.get("fields", {}).get("CAPTION") or "").strip(), + "description": description, + "image": os.path.join(book_dir, entry["derivative_file"]), + }) + _PAIRS_CACHE[key] = out + return out + + +def candidate_pairs(book_dir, limit=1): + """The pictures a figure named but did not claim. + + These are the ones the matcher would not stand behind. Judging them + says how much the corpus is leaving on the table: a picture that was + right and was not shown. + """ + from book2corpus import notes_gate + path = os.path.join(book_dir, "figures.json") + if not os.path.exists(path): + return [] + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + entries = {e["id"]: e for e in data["figures"]} + out = [] + for figure in data.get("figure_map", []): + if figure.get("tier") not in ("candidate", "ordinal"): + continue + description = (figure.get("description") or "").strip() + if not description or description.lower() == "none": + continue + for catalogue in (figure.get("candidates") or [])[:limit]: + entry = entries.get(catalogue) + if entry is None: + continue + out.append({ + "id": catalogue, + "figure_id": figure.get("id"), + "tier": "candidate", + "book": os.path.basename(book_dir.rstrip("/")), + "chapter": figure.get("chapter"), + "kind": "", + "caption": (figure.get("caption") or "").strip(), + "description": description, + "image": os.path.join(book_dir, entry["derivative_file"]), + }) + return out + + +def controls_for(pairs, count): + """Pairs that are known to be wrong: the judge's false-accept rate. + + A hard negative is the same kind of figure from another chapter: that + is the realistic failure, a wrong but plausible picture. An easy + negative is a different kind of figure from another book: a judge that + passes those is broken. + """ + by_book = {} + for pair in pairs: + by_book.setdefault(pair["book"], []).append(pair) + hard = [] + easy = [] + for book, group in by_book.items(): + for pair in group: + # a hard negative is another picture from the same book, from + # another chapter, whose caption shares no words with this + # one: the realistic failure, a wrong but plausible picture + for other in group: + if other["id"] == pair["id"]: + continue + if other["chapter"] == pair["chapter"]: + continue + if set((other["caption"] or "").lower().split()) & \ + set((pair["caption"] or "").lower().split()): + continue + hard.append({"pair": pair, "image_of": other}) + break + for pair in pairs: + # an easy negative is a picture from another book: a judge that + # passes those is broken + for other in pairs: + if other["book"] == pair["book"]: + continue + easy.append({"pair": pair, "image_of": other}) + break + return hard[:count], easy[:count] + + +def tier_row(group): + """One tier's numbers, under both readings of "partial".""" + n = len(group) + cannot = sum(1 for r in group if r["verdict"] == "cannot_tell") + errors = sum(1 for r in group if r["verdict"] == "error") + effective = n - cannot - errors + lenient = sum(1 for r in group if r["verdict"] in ("match", "partial")) + strict = sum(1 for r in group if r["verdict"] == "match") + low_l, high_l = wilson(lenient, effective) + low_s, high_s = wilson(strict, effective) + return {"n": n, "effective": effective, + "passed_lenient": lenient, "passed_strict": strict, + "cannot_tell": cannot, "errors": errors, + "pass_rate_lenient": round(lenient / effective, 4) if effective else 0, + "pass_rate_strict": round(strict / effective, 4) if effective else 0, + "cannot_tell_rate": round(cannot / n, 4) if n else 0, + "wilson_lenient": [round(low_l, 4), round(high_l, 4)], + "wilson_strict": [round(low_s, 4), round(high_s, 4)], + "mismatches": [r for r in group if r["verdict"] == "mismatch"], + "verdicts": group} + + +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--book", required=True) + parser.add_argument("--tiers", default="numbered,verified,description-match,probable,inferred") + parser.add_argument("--census", default=CENSUS_DEFAULT, + help="tiers that are audited in full") + parser.add_argument("--sample", type=int, default=25) + parser.add_argument("--candidates", type=int, default=0, + help="how many unclaimed candidates to judge") + parser.add_argument("--seed", type=int, default=20261124) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--judge", default="gemini", choices=("gemini", "sonnet")) + parser.add_argument("--controls", type=int, default=12, + help="how many wrong pairs of each kind to judge") + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--fresh", action="store_true", + help="ask again about every pair, even the answered ones") + args = parser.parse_args(argv) + + book_dir = os.path.join(os.path.abspath(os.path.expanduser(args.corpus_root)), + args.book) + random.seed(args.seed) + wanted = [t.strip() for t in args.tiers.split(",") if t.strip()] + census = [t.strip() for t in args.census.split(",") if t.strip()] + + pairs = pairs_for(book_dir) + samples = {} + for tier in wanted: + group = [p for p in pairs if p["tier"] == tier] + if tier in census: + samples[tier] = group + elif len(group) <= args.sample: + samples[tier] = group + else: + samples[tier] = random.sample(group, args.sample) + + jobs = [] + for tier, group in samples.items(): + for item in group: + jobs.append(("tier:" + tier, item, item["image"])) + if args.candidates: + for item in candidate_pairs(book_dir)[:args.candidates]: + jobs.append(("candidate", item, item["image"])) + + root = os.path.abspath(os.path.expanduser(args.corpus_root)) + pool = [] + for other in sorted(os.listdir(root)): + other_dir = os.path.join(root, other) + if other == args.book or not os.path.isdir(other_dir): + continue + if not os.path.exists(os.path.join(other_dir, "figures.json")): + continue + try: + pool.extend(pairs_for(other_dir)) + except Exception: + continue + hard, easy = controls_for(pool + pairs, args.controls) + for item in hard: + jobs.append(("control-hard", item["pair"], item["image_of"]["image"])) + for item in easy: + jobs.append(("control-easy", item["pair"], item["image_of"]["image"])) + + # the verdicts of the last run are worth keeping: a call that came + # back is an answer, and a correction elsewhere does not make it + # wrong. Only the pairs that never came back are asked again. + kept = [] + answered = set() + if not args.fresh: + previous = os.path.join(args.corpus_root, args.book, "figure-audit.json") + if os.path.exists(previous): + try: + with open(previous, encoding="utf-8") as fh: + old = json.load(fh) + except Exception: + old = {} + wanted_model = GEMINI_MODEL if args.judge == "gemini" else MODEL + if old.get("model") and old.get("model") != wanted_model: + # another judge answered these pairs: they are not answers + # to this judge questions, so they are asked again + old = {} + for tier, block in (old.get("tiers") or {}).items(): + for verdict in block.get("verdicts") or []: + if verdict.get("verdict") == "error": + # a call that never came back is missing data, + # not an answer: it is asked again + continue + kept.append(verdict) + answered.add(("tier:" + tier, verdict.get("id"), + verdict.get("figure_id"))) + for label, block in (old.get("controls") or {}).items(): + for verdict in block.get("verdicts") or []: + if verdict.get("verdict") == "error": + continue + kept.append(verdict) + answered.add((label, verdict.get("id"), verdict.get("figure_id"))) + jobs = [job for job in jobs + if (job[0], job[1].get("id"), job[1].get("figure_id")) not in answered] + + if args.dry_run: + for label, pair, image_path in jobs: + print("%-16s %-28s %s" % (label, pair["id"], os.path.basename(image_path))) + print("jobs:", len(jobs), "| kept from the last run:", len(kept)) + return 0 + + results = list(kept) + lock = threading.Lock() + + ask = gemini_judge if args.judge == "gemini" else judge + + def work(job): + label, pair, image_path = job + verdict = ask_with_retries(ask, image_path, pair["kind"], pair["caption"], + pair["description"]) + with lock: + results.append({"label": label, "id": pair["id"], + "figure_id": pair.get("figure_id"), + "tier": pair["tier"], "book": pair["book"], + "chapter": pair.get("chapter"), + "verdict": verdict.get("verdict"), + "reason": verdict.get("reason"), + "usage": verdict.get("usage")}) + + threads = [] + for job in jobs: + thread = threading.Thread(target=work, args=(job,)) + thread.start() + threads.append(thread) + while len([t for t in threads if t.is_alive()]) >= args.workers: + threads[0].join(0.2) + threads = [t for t in threads if t.is_alive()] + for thread in threads: + thread.join() + + report = {"book": args.book, + "model": GEMINI_MODEL if args.judge == "gemini" else MODEL, + "judge": args.judge, "seed": args.seed, + "sample": args.sample, "census": census, "tiers": {}, "controls": {}} + for tier in wanted: + group = [r for r in results if r["label"] == "tier:" + tier] + report["tiers"][tier] = tier_row(group) + candidates = [r for r in results if r["label"] == "candidate"] + if candidates: + report["candidates"] = tier_row(candidates) + for label in ("control-hard", "control-easy"): + group = [r for r in results if r["label"] == label] + accepted = sum(1 for r in group if r["verdict"] in ("match", "partial")) + strict = sum(1 for r in group if r["verdict"] == "match") + low, high = wilson(accepted, len(group)) + low_s, high_s = wilson(strict, len(group)) + report["controls"][label] = {"n": len(group), "accepted": accepted, + "accepted_strict": strict, + "false_accept_rate": round(accepted / len(group), 4) if group else 0, + "false_accept_rate_strict": round(strict / len(group), 4) if group else 0, + "wilson_95": [round(low, 4), round(high, 4)], + "wilson_95_strict": [round(low_s, 4), round(high_s, 4)], + "verdicts": group} + out = os.path.join(book_dir, "figure-audit.json") + with open(out, "w", encoding="utf-8") as fh: + json.dump(report, fh, indent=1, ensure_ascii=False) + print("audit written to", out) + for tier, row in report["tiers"].items(): + print("%-16s n=%-4d lenient=%.3f strict=%.3f cannot_tell=%.3f wilson=%s" + % (tier, row["n"], row["pass_rate_lenient"], row["pass_rate_strict"], + row["cannot_tell_rate"], row["wilson_lenient"])) + if "candidates" in report: + row = report["candidates"] + print("%-16s n=%-4d lenient=%.3f strict=%.3f" % ("candidates", row["n"], + row["pass_rate_lenient"], row["pass_rate_strict"])) + for label, row in report["controls"].items(): + print("%-16s n=%-4d false-accept=%.3f wilson=%s" % (label, row["n"], + row["false_accept_rate"], row["wilson_95"])) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/audit_label.py b/pipeline/scripts/audit_label.py new file mode 100644 index 00000000..4f224476 --- /dev/null +++ b/pipeline/scripts/audit_label.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Label the sample: a second model, from another family, looks at the pairs. + +The judge that made the corpus's verdicts is one model. A model checked +against itself proves nothing, so the sheet of pairs is labelled by +another one - a different family, so a mistake in one is unlikely to be +made in the other - and the two are compared. The labels are written +back into the sheet, and + + python3 scripts/audit_agreement.py --sheet + +says whether the judge may be trusted. + +A person labelling the same sheet is better than this, and the sheet is +the same either way. + + python3 scripts/audit_label.py --sheet [--jobs 8] +""" +import argparse +import base64 +import json +import os +import re +import sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from concurrent.futures import ThreadPoolExecutor + +import audit_figures + + +def media_type(path): + lower = path.lower() + if lower.endswith(".png"): + return "image/png" + if lower.endswith(".webp"): + return "image/webp" + if lower.endswith(".gif"): + return "image/gif" + return "image/jpeg" + + +CATALOGUE = {} + + +def catalogue(library): + """Every picture the library holds, by its id. + + The catalogue, not the manifest: a pair the audit saw may not be a + picture the reader shows now, and the label is about the pair, not + about what the reader does with it. + """ + if CATALOGUE: + return CATALOGUE + path = os.path.join(library, "agent-index.jsonl") + if os.path.exists(path): + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except Exception: + continue + if row.get("id"): + CATALOGUE[row["id"]] = row + return CATALOGUE + + +def label(pair, corpus, library): + """One label, from the other model.""" + book = pair.get("book") + figure_id = pair.get("figure_id") + picture = pair.get("picture") + manifest_path = os.path.join(corpus, book, "figures.json") + try: + with open(manifest_path, encoding="utf-8") as fh: + manifest = json.load(fh) + except Exception as exc: + return {"verdict": "error", "reason": str(exc)[:120]} + figures = {entry.get("id"): entry for entry in manifest.get("figure_map") or []} + figure = figures.get(figure_id) + entry = catalogue(library).get(picture) + if not entry or not figure: + return {"verdict": "error", "reason": "the pair is not in the corpus"} + source = entry.get("file") + if not source: + return {"verdict": "error", "reason": "the picture has no file"} + path = os.path.join(library, source) + if not os.path.exists(path): + return {"verdict": "error", "reason": "the picture is not there"} + with open(path, "rb") as fh: + data = base64.b64encode(fh.read()).decode("ascii") + import urllib.request + body = {"model": audit_figures.MODEL, "max_tokens": 1500, + "thinking": {"type": "adaptive"}, + "output_config": {"effort": "low"}, + "system": audit_figures.SYSTEM, + "messages": [{"role": "user", "content": [ + {"type": "image", "source": {"type": "base64", + "media_type": media_type(path), + "data": data}}, + {"type": "text", "text": audit_figures.QUESTION.format( + kind=figure.get("type") or "unknown", + caption=figure.get("caption") or "none", + description=figure.get("description") or "none")}]}]} + request = urllib.request.Request( + audit_figures.API, data=json.dumps(body).encode("utf-8"), + headers={"x-api-key": audit_figures.api_key(), + "content-type": "application/json", + "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(request, timeout=180) as response: + answer = json.load(response) + except Exception as exc: + return {"verdict": "error", "reason": str(exc)[:120]} + text = "".join(block.get("text", "") for block in answer.get("content", []) + if block.get("type") == "text") + parsed = audit_figures._parse_verdict(text) + if parsed is None: + # the model may have written more than one object; the last one is + # its answer + found = re.findall(r"\{.*?\}", text, re.S) + for piece in reversed(found): + try: + parsed = json.loads(piece) + break + except ValueError: + continue + if parsed is None: + return {"verdict": "error", "reason": (text or "no answer")[:120]} + return parsed + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="audit_label.py") + ap.add_argument("--sheet", required=True) + ap.add_argument("--corpus-root", default=os.path.expanduser( + "~/Documents/GitHub/textbooks")) + ap.add_argument("--library", default=os.path.expanduser( + "~/Library/Mobile Documents/com~apple~CloudDocs/Textbooks")) + ap.add_argument("--jobs", type=int, default=8) + ap.add_argument("--limit", type=int, default=0) + args = ap.parse_args(argv) + with open(args.sheet, encoding="utf-8") as fh: + sheet = json.load(fh) + pairs = sheet.get("pairs") or [] + if args.limit: + pairs = pairs[:args.limit] + done = [0] + + def work(pair): + result = label(pair, args.corpus_root, args.library) + done[0] += 1 + if done[0] % 25 == 0: + print(" %d of %d" % (done[0], len(pairs)), flush=True) + return pair, result + + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + for pair, result in pool.map(work, pairs): + pair["verdict"] = result.get("verdict") or "" + pair["reason"] = (result.get("reason") or "")[:300] + pair["labelled_by"] = audit_figures.MODEL + with open(args.sheet, "w", encoding="utf-8") as fh: + json.dump(sheet, fh, indent=1, ensure_ascii=False, sort_keys=True) + counted = {} + for pair in pairs: + counted[pair.get("verdict")] = counted.get(pair.get("verdict"), 0) + 1 + print("%d pairs labelled: %s" % (len(pairs), counted)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/audit_links.py b/pipeline/scripts/audit_links.py new file mode 100644 index 00000000..cd4e158d --- /dev/null +++ b/pipeline/scripts/audit_links.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +"""scripts/audit_links.py - do two judges agree about the same form? + +Written 26 Nov 2026 by MCode, after the ruling of Claude Opus 5.5 on the +corpus-wide term index, and after the Message Batches API of Anthropic. + +The index's links are decided by a model. When the door one model came +through is spent and another model finishes the work, the index holds the +answers of two judges, and the honest thing is to measure what that costs +rather than to hope it costs nothing. + +This script asks a second model about forms that are already decided, and +compares the two partitions: the same pairs of books in the same group, or +not. The measurement is hundreds of independent questions, which is +exactly what a batch job is for: one submission, half the price, and no +rate limits to wait out. + + python3 scripts/audit_links.py --corpus-root \ + --model claude-haiku-4-5-20251001 --against gemini-3.8-flash \ + --sample 300 --batch + +What it writes: + + index/manifest/link-agreement.json the numbers, and the details +""" +import argparse +import json +import os +import sys +import time +from concurrent.futures import ThreadPoolExecutor + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus.judge import Judge # noqa: E402 +from book2corpus.pipeline import (CircuitBreaker, Ledger, # noqa: E402 + Settings) +from scripts import judge_forms # noqa: E402 + + +def pairs_of(groups): + """The pairs of books a partition puts together.""" + out = set() + for group in groups: + books = sorted(set(group)) + for i in range(len(books)): + for j in range(i + 1, len(books)): + out.add((books[i], books[j])) + return out + + +def all_pairs(books): + out = set() + books = sorted(set(books)) + for i in range(len(books)): + for j in range(i + 1, len(books)): + out.add((books[i], books[j])) + return out + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="audit_links.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--model", required=True) + ap.add_argument("--sample", type=int, default=200) + ap.add_argument("--jobs", type=int, default=8) + ap.add_argument("--against", default="", + help="the model whose answers are in the ledger") + ap.add_argument("--batch", action="store_true", + help="ask the second judge as one batch job") + ap.add_argument("--allow-missing", action="store_true", + help="write the verdict even when answers are missing") + args = ap.parse_args(argv) + + settings = Settings() + judge_settings = dict(settings["judge"]) + prices = settings["money"]["prices"] + judge_settings["model"] = args.model + ledger = Ledger(prices) + judge = Judge(judge_settings, ledger, CircuitBreaker(judge_settings)) + corpus = args.corpus_root + links = os.path.join(corpus, "index", "links") + + forms = {} + for row in judge_forms.read_jsonl(os.path.join(links, "forms.jsonl")): + if len(row.get("books") or []) > 1: + forms[row["canonical"]] = row + judged = {} + for row in judge_forms.read_jsonl(os.path.join(links, "form-judgments.jsonl")): + judged[row["canonical"]] = row + + if args.against: + chosen = [c for c, row in judged.items() + if row.get("model") == args.against] + else: + chosen = list(judged) + # the ledger keeps the history: a form the corpus no longer has is + # not compared + chosen = [c for c in chosen if c in forms] + chosen.sort() + step = max(1, len(chosen) // args.sample) + chosen = chosen[::step][:args.sample] + if not chosen: + print("no forms to compare") + return 1 + + started = time.time() + state = {"same": 0, "pairs": 0.0, "count": 0, "missing": 0, + "asked": 0} + details = [] + # the batch is Anthropic's: a Gemini model in it fails, and a + # failure that is not reported is a measurement of nothing + if args.batch and not args.model.startswith("claude"): + print("REFUSED: the batch route is Anthropic's, and %s is not an" + % args.model) + print("Anthropic model: use the single-call route instead.") + return 2 + + def compare(canonical, groups): + """One form, judged twice.""" + row = judged.get(canonical) + if row is None: + return + mine = pairs_of(groups) + theirs = pairs_of(row["groups"]) + every = all_pairs([item["book"] for item in forms[canonical]["books"]]) + agree = mine == theirs + if agree: + state["same"] += 1 + shared = mine | theirs + if shared: + state["pairs"] += len(mine & theirs) / float(len(shared)) + state["count"] += 1 + details.append({"canonical": canonical, "agree": agree, + "groups": len(groups), "books": len(every)}) + + if args.batch: + items = [] + prompts = {} + for canonical in chosen: + form = forms[canonical] + for chunk in judge_forms.blocks_of(form, corpus): + prompt = judge_forms.prompt_for(form, chunk, corpus) + key = judge_forms.key_for(prompt, args.model) + prompts.setdefault(canonical, []).append((key, chunk)) + items.append((key, prompt)) + rows, batch_id, seconds = judge.text_batch(items, args.model) + print("batch %s: %d questions asked, %.0f s" + % (batch_id, len(items), seconds)) + for canonical, parts in prompts.items(): + groups = [] + for key, chunk in parts: + row = rows.get(key) + if not row or not row.get("ok"): + state["missing"] += 1 + continue + answer = row.get("answer") + if not isinstance(answer, dict): + state["missing"] += 1 + continue + state["asked"] += 1 + try: + found, _missing, _unknown = judge_forms.parse_groups(answer, chunk) + except Exception: + continue + groups.extend(found) + compare(canonical, groups) + else: + def ask(canonical): + form = forms[canonical] + groups = [] + for chunk in judge_forms.blocks_of(form, corpus): + prompt = judge_forms.prompt_for(form, chunk, corpus) + result = judge.text(prompt, + judge_forms.key_for(prompt, args.model), + args.model) + answer = result.get("answer") + if not isinstance(answer, dict): + state["missing"] += 1 + continue + try: + found, _missing, _unknown = judge_forms.parse_groups(answer, chunk) + except Exception: + state["missing"] += 1 + continue + groups.extend(found) + state["asked"] += 1 + return canonical, groups + + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + for canonical, groups in pool.map(ask, chosen): + compare(canonical, groups) + + # an instrument that asked nothing measured nothing, and a verdict + # that says so is worse than no verdict at all + if state["asked"] == 0: + print("REFUSED: the audit asked the model nothing, so there is") + print("nothing to compare. The verdict is not written.") + return 1 + if state["missing"] and not args.allow_missing: + print("REFUSED: %d answer(s) are missing, so the comparison is" + % state["missing"]) + print("not a measurement. The verdict is not written.") + return 1 + total = max(1, state["count"]) + verdict = {"sample": state["count"], "model": args.model, + "against": args.against or "the ledger", + # the same model twice measures the model's steadiness, + # not its rightness + "kind": ("repeatability only" if args.against + and args.against == args.model + else "agreement"), + "asked": state["asked"], "missing": state["missing"], + "same_form": round(state["same"] / float(total), 4), + "same_pair": round(state["pairs"] / float(total), 4), + "cost_usd": round(ledger.usd(), 4), + "seconds": round(time.time() - started, 1), + "details": details} + path = os.path.join(corpus, "index", "manifest", "link-agreement.json") + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + json.dump(verdict, fh, indent=1, sort_keys=True, ensure_ascii=False) + fh.write("\n") + print("link agreement: %d forms | the same partition %.1f%% | " + "the same pairs %.1f%% | cost $%.4f | %.0f s" + % (state["count"], verdict["same_form"] * 100, + verdict["same_pair"] * 100, ledger.usd(), time.time() - started)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/audit_plant.py b/pipeline/scripts/audit_plant.py new file mode 100644 index 00000000..aa8a405f --- /dev/null +++ b/pipeline/scripts/audit_plant.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""The tester that tests the tester: plant the held-out pairs and see. + +The held-out pairs have a known truth - the book's own numbering says +whether a picture is the figure it was shown for. They are planted in a +batch of real pairs, the judge is asked about each of them in the same +words and with the same pictures, and the rate at which it catches the +wrong ones is measured. A judge that accepts a wrong picture eight times +in a hundred makes a tier look eight points better than it is, and this +is where that number comes from. + + python3 scripts/audit_plant.py --heldout calibration/heldout.jsonl +""" +import argparse +import json +import os +import sys +import time + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus.judge import Judge # noqa: E402 +from book2corpus.pipeline import (CircuitBreaker, Ledger, # noqa: E402 + Settings, wilson) + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="audit_plant.py") + ap.add_argument("--heldout", default=os.path.join(HERE, "calibration", "heldout.jsonl")) + ap.add_argument("--library", default=os.path.expanduser( + "~/Library/Mobile Documents/com~apple~CloudDocs/Textbooks")) + ap.add_argument("--corpus-root", default=os.path.expanduser( + "~/Documents/GitHub/textbooks")) + ap.add_argument("--limit", type=int, default=40, help="how many of each") + ap.add_argument("--model", default="") + args = ap.parse_args(argv) + + settings = Settings() + judge_settings = dict(settings["judge"]) + if args.model: + judge_settings["model"] = args.model + ledger = Ledger(settings["money"]["prices"]) + breaker = CircuitBreaker(judge_settings) + judge = Judge(judge_settings, ledger, breaker) + + heldout = [] + with open(args.heldout, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + heldout.append(json.loads(line)) + right = [row for row in heldout if row.get("truth") == "right"][:args.limit] + wrong = [row for row in heldout if row.get("truth") == "wrong"][:args.limit] + + def ask(row): + path = os.path.join(args.library, row["picture"]) + if not os.path.exists(path): + return None + answer = judge.judge(path, "figure", row.get("caption") or "", + row.get("description") or "") + return answer.get("verdict") + + started = time.time() + results = [] + for row in right + wrong: + verdict = ask(row) + results.append((row, verdict)) + print(" %-6s %-22s -> %s" % (row.get("truth"), row.get("picture_id"), verdict), + flush=True) + + caught = [1 for row, verdict in results + if row.get("truth") == "wrong" and verdict in ("mismatch", "cannot_tell")] + missed = [1 for row, verdict in results + if row.get("truth") == "wrong" and verdict not in ("mismatch", "cannot_tell")] + accepted = [1 for row, verdict in results + if row.get("truth") == "right" and verdict in ("match", "partial")] + refused = [1 for row, verdict in results + if row.get("truth") == "right" and verdict not in ("match", "partial")] + print() + print("Planted pairs") + print() + print("| Measure | Value |") + print("| --- | --- |") + print("| Planted wrong pairs | %d |" % len(wrong)) + print("| Caught | %d (%.0f%%) |" % (len(caught), 100.0 * len(caught) / max(1, len(wrong)))) + print("| Missed | %d |" % len(missed)) + print("| Sensitivity, lower bound | %.3f |" % wilson(len(caught), len(wrong))) + print("| Planted right pairs | %d |" % len(right)) + print("| Accepted | %d (%.0f%%) |" % (len(accepted), 100.0 * len(accepted) / max(1, len(right)))) + print("| Refused | %d |" % len(refused)) + print("| Specificity, lower bound | %.3f |" % wilson(len(accepted), len(right))) + print("| Cost | $%.4f |" % ledger.usd()) + print("| Time | %.0f s |" % (time.time() - started)) + floor = judge_settings.get("sensitivity_floor", 0.85) + holds = wilson(len(caught), len(wrong)) >= floor and wilson(len(accepted), len(right)) >= floor + print() + print("the judge %s the floor of %.2f" % ("holds" if holds else "does not hold", floor)) + return 0 if holds else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/audit_sample.py b/pipeline/scripts/audit_sample.py new file mode 100644 index 00000000..d8d6adcb --- /dev/null +++ b/pipeline/scripts/audit_sample.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Which pictures a person should judge, and how much each one counts. + +The audit's judge is a model, and a model that is trusted without being +checked is not evidence. So a sample of its verdicts goes to a person, +and the two are compared: how often they agree, how often the judge +catches what the person calls wrong, and how far the lower bound of the +agreement sits above the bar. + +The sample is drawn in two parts. The first is spread over the tiers and +the books, so every kind of claim is represented; the second is enriched +with the pairs that look hardest - the ones the judge called wrong, the +ones whose margin was thin, the ones the gate suspected - so that the +judge's eye for a wrong picture is measured at all. + + python3 scripts/audit_sample.py --corpus-root --out + +The sheet says what to look at and where to write the answer: "match", +"mismatch" or "cannot_tell". Put the answers back into the same file +under each pair's "verdict", and + + python3 scripts/audit_agreement.py --sheet + +will say whether the judge may be trusted. +""" +import argparse +import json +import os +import random +import sys + +TIER_ORDER = ("numbered", "verified", "description-match", "probable", + "inferred", "ordinal", "candidate", "none") + +# the part of the sample that is spread over the tiers and the books, and +# the part that is enriched with the hard cases +SPREAD = 600 +ENRICHED = 200 +MIN_PER_STRATUM = 15 +MAX_PER_BOOK = 25 +SEED = 20261128 + + +def wilson_lower(k, n, z=1.959964): + if n <= 0: + return 0.0 + p = k / n + d = 1 + z * z / n + centre = p + z * z / (2 * n) + spread = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) + return (centre - spread) / d + + +def load_pairs(corpus): + """Every pair the judge has seen, with what it said about it.""" + pairs = [] + for book in sorted(os.listdir(corpus)): + path = os.path.join(corpus, book, "figure-audit.json") + if not os.path.exists(path): + continue + try: + with open(path, encoding="utf-8") as fh: + audit = json.load(fh) + except Exception: + continue + for tier, block in (audit.get("tiers") or {}).items(): + for verdict in block.get("verdicts") or []: + pairs.append({"book": book, + "figure_id": verdict.get("figure_id"), + "picture": verdict.get("id"), + "tier": tier, + "judge": verdict.get("verdict"), + "chapter": verdict.get("chapter"), + "reason": (verdict.get("reason") or "")[:400]}) + return pairs + + +def load_manifests(corpus): + """What the last build decided about each figure.""" + out = {} + for book in sorted(os.listdir(corpus)): + path = os.path.join(corpus, book, "figures.json") + if not os.path.exists(path): + continue + try: + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + except Exception: + continue + for figure in data.get("figure_map") or []: + out[(book, figure.get("id"))] = figure + return out + + +def book_groups(pairs, manifests): + """Three groups of books, by how many figures they have.""" + counts = {} + for book in set(pair["book"] for pair in pairs): + figures = len([key for key in manifests if key[0] == book]) + counts[book] = figures + order = sorted(counts, key=lambda name: (counts[name], name)) + size = max(1, len(order) // 3) + groups = {} + for index, book in enumerate(order): + groups[book] = min(2, index // size) + return groups, counts + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="audit_sample.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--out", required=True, help="where the sheet is written") + ap.add_argument("--library", default=os.path.expanduser( + "~/Library/Mobile Documents/com~apple~CloudDocs/Textbooks"), + help="where the pictures are") + ap.add_argument("--spread", type=int, default=SPREAD) + ap.add_argument("--enriched", type=int, default=ENRICHED) + args = ap.parse_args(argv) + + pairs = load_pairs(args.corpus_root) + if not pairs: + print("no audited pairs were found") + return 1 + # the judge answered only some of the pairs it was asked about: the + # rest are errors, and a pair the judge did not answer cannot be + # compared with anything + answered = [pair for pair in pairs if pair.get("judge") != "error"] + if not answered: + print("the judge answered none of the pairs it was asked about") + return 1 + pairs = answered + manifests = load_manifests(args.corpus_root) + groups, counts = book_groups(pairs, manifests) + random.seed(SEED) + + # the hard cases: what the judge called wrong, what the gate suspected, + # and what had the thinnest margin + hard = [] + for pair in pairs: + figure = manifests.get((pair["book"], pair["figure_id"])) or {} + refusal = figure.get("refusal") or {} + margin = refusal.get("margin") + reasons = [] + if pair["judge"] not in ("match", None): + reasons.append("the judge did not accept it") + if figure.get("conflict"): + reasons.append("the descriptions contradict the number") + if margin is not None and margin < 1.0: + reasons.append("the margin was thin (%.2f)" % margin) + if reasons: + hard.append((pair, reasons, margin)) + hard.sort(key=lambda item: (item[2] if item[2] is not None else 99)) + + # the spread: a plain stratified draw over the tiers, in proportion to + # how many pairs each tier holds, with a floor for every tier so that + # a rare tier is not left out + strata = {} + for pair in pairs: + strata.setdefault(pair["tier"], []).append(pair) + for key in strata: + random.shuffle(strata[key]) + total = sum(len(group) for group in strata.values()) + chosen = [] + allocation = {} + for key in sorted(strata, key=lambda k: (TIER_ORDER.index(k[0]) + if k[0] in TIER_ORDER else 9)): + room = max(MIN_PER_STRATUM, + int(round(args.spread * len(strata[key]) / float(total)))) + room = min(room, len(strata[key])) + allocation[key] = room + chosen.extend(strata[key][:room]) + chosen = chosen[:args.spread] + + # the enriched part, and what is left over + seen = set((p["book"], p["figure_id"]) for p in chosen) + for pair, reasons, margin in hard: + if len(chosen) >= args.spread + args.enriched: + break + key = (pair["book"], pair["figure_id"]) + if key in seen: + continue + seen.add(key) + pair = dict(pair) + pair["why_it_is_hard"] = reasons + chosen.append(pair) + + # the weight of each pair: how many pairs its stratum holds, over how + # many of them were drawn - so the tiers are weighted as they are, and + # the enriched part does not distort the agreement + universe = {} + for pair in pairs: + universe[pair["tier"]] = universe.get(pair["tier"], 0) + 1 + drawn = {} + for pair in chosen: + drawn[pair["tier"]] = drawn.get(pair["tier"], 0) + 1 + for pair in chosen: + tier = pair["tier"] + count = drawn.get(tier, 1) or 1 + pair["weight"] = round(float(universe.get(tier, count)) / count, 4) + pair["verdict"] = "" + + sheet = {"corpus": os.path.abspath(args.corpus_root), + "library": args.library, + "seed": SEED, + "sampling": {"spread": args.spread, "enriched": args.enriched, + "min_per_stratum": MIN_PER_STRATUM, + "max_per_book": MAX_PER_BOOK, + "strata": len(strata), + "hard_pairs": len(hard), + "books": len(counts)}, + "pairs": chosen} + with open(args.out, "w", encoding="utf-8") as fh: + json.dump(sheet, fh, indent=1, ensure_ascii=False, sort_keys=True) + print("%d pairs written to %s" % (len(chosen), args.out)) + print("of which %d are the hard ones" + % len([p for p in chosen if p.get("why_it_is_hard")])) + print("the next step: look at each picture and write match, mismatch or" + " cannot_tell in its verdict") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/build_database.py b/pipeline/scripts/build_database.py new file mode 100644 index 00000000..69eb4b79 --- /dev/null +++ b/pipeline/scripts/build_database.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +'''scripts/build_database.py - the corpus as a database. + +The corpus is a repository of text files, and it is also a database. This +builds the database from the repository: the books and what each of them +holds, the terms and where they are used, the concepts and the books in +them, the figures, the runs and the inventory, with a full-text index over +the terms, the concepts and the passages. + +It is DERIVED. The repository is the source of truth and the database is +rebuilt from it, so the database is stamped with what it was built from: +the commit, the rule that produced the links, and the hashes of the files +it read. + + python3 scripts/build_database.py --corpus-root + python3 scripts/build_database.py --corpus-root --query amygdala +''' +import argparse +import hashlib +import json +import os +import sqlite3 +import subprocess +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +DATABASE = 'index/corpus.db' + +SCHEMA = ''' +DROP TABLE IF EXISTS books; +DROP TABLE IF EXISTS concept_members; +DROP TABLE IF EXISTS figures; +DROP TABLE IF EXISTS runs; +DROP TABLE IF EXISTS inventory; +DROP TABLE IF EXISTS terms; +DROP TABLE IF EXISTS concepts; +DROP TABLE IF EXISTS passages; +DROP TABLE IF EXISTS meta; +CREATE TABLE books ( + name TEXT PRIMARY KEY, kind TEXT, terms INTEGER, forms INTEGER, + concept_entries INTEGER, figure_blocks INTEGER, paragraphs INTEGER); +CREATE TABLE concept_members ( + concept_id TEXT, book TEXT, canonical TEXT); +CREATE INDEX concept_members_book ON concept_members (book, canonical); +CREATE TABLE figures ( + book TEXT, figure_id TEXT, caption TEXT, description TEXT, tier TEXT, + picture TEXT); +CREATE TABLE runs (id TEXT, what TEXT, detail TEXT); +CREATE TABLE inventory (key TEXT PRIMARY KEY, value TEXT); +CREATE VIRTUAL TABLE terms USING fts5( + book UNINDEXED, canonical UNINDEXED, label, scope, chapter, + tokenize='unicode61 remove_diacritics 2'); +CREATE VIRTUAL TABLE concepts USING fts5( + concept_id UNINDEXED, label, books, + tokenize='unicode61 remove_diacritics 2'); +CREATE VIRTUAL TABLE passages USING fts5( + book UNINDEXED, canonical UNINDEXED, passage, + tokenize='unicode61 remove_diacritics 2'); +CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT); +''' + + +def read_jsonl(path): + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding='utf-8') as fh: + for line in fh: + line = line.strip() + if line: + try: + rows.append(json.loads(line)) + except ValueError: + continue + return rows + + +def read_json(path, default=None): + try: + with open(path, encoding='utf-8') as fh: + return json.load(fh) + except Exception: + return default + + +def sha256_of(path): + digest = hashlib.sha256() + try: + with open(path, 'rb') as fh: + for chunk in iter(lambda: fh.read(1 << 20), b''): + digest.update(chunk) + except OSError: + return '' + return digest.hexdigest() + + +def commit_of(corpus): + try: + out = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=corpus, + capture_output=True, text=True).stdout.strip() + return out + except Exception: + return '' + + +def build(corpus, path): + """The database, built from the repository.""" + directory = os.path.dirname(path) + if directory: + os.makedirs(directory, exist_ok=True) + if os.path.exists(path): + os.remove(path) + con = sqlite3.connect(path) + con.executescript(SCHEMA) + terms = 0 + for name in sorted(os.listdir(os.path.join(corpus, 'index', 'occurrences'))): + if not name.endswith('.jsonl'): + continue + book = name[:-len('.jsonl')] + for row in read_jsonl(os.path.join(corpus, 'index', 'occurrences', name)): + con.execute('INSERT INTO terms VALUES (?,?,?,?,?)', + (book, row.get('canonical') or '', row.get('label') or '', + row.get('scope') or '', row.get('chapter') or '')) + terms += 1 + passages = 0 + for form in read_jsonl(os.path.join(corpus, 'index', 'links', + 'forms.jsonl')): + canonical = form.get('canonical') or '' + for book in form.get('books') or []: + for text in (book.get('use') or '', book.get('wide') or ''): + if not text: + continue + con.execute('INSERT INTO passages VALUES (?,?,?)', + (book.get('book') or '', canonical, text)) + passages += 1 + concepts = 0 + for row in read_jsonl(os.path.join(corpus, 'index', 'concepts.jsonl')): + members = row.get('members') or [] + books = [] + label = '' + for member in members: + book, _sep, canonical = member.partition('|') + books.append('%s: %s' % (book, canonical)) + con.execute('INSERT INTO concept_members VALUES (?,?,?)', + (row.get('concept_id') or '', book, canonical)) + con.execute('INSERT INTO concepts VALUES (?,?,?)', + (row.get('concept_id') or '', label, '; '.join(books))) + concepts += 1 + for book in sorted(os.listdir(corpus)): + path = os.path.join(corpus, book) + if not os.path.isdir(path) or book.startswith('.'): + continue + if not (os.path.isdir(os.path.join(path, 'chapters')) + or os.path.exists(os.path.join(path, 'paragraphs.jsonl'))): + continue + terms_here = len(read_jsonl(os.path.join(corpus, 'index', 'terms', + '%s.jsonl' % book))) + forms_here = len([row for row in read_jsonl(os.path.join(corpus, 'index', + 'links', 'forms.jsonl')) + if any(item.get('book') == book + for item in row.get('books') or [])]) + figures = read_json(os.path.join(path, 'figures.json'), {}) or {} + paragraphs = len(read_jsonl(os.path.join(path, 'paragraphs.jsonl'))) + con.execute('INSERT INTO books VALUES (?,?,?,?,?,?,?)', + (book, 'machine corpus' if paragraphs else 'notes', + terms_here, forms_here, 0, len(figures.get('figure_map') or []), + paragraphs)) + for entry in figures.get('figure_map') or []: + image = entry.get('image') + if isinstance(image, dict): + image = image.get('id') or '' + con.execute('INSERT INTO figures VALUES (?,?,?,?,?,?)', + (book, entry.get('id') or '', + (entry.get('caption') or '')[:300], + (entry.get('description') or '')[:1200], + entry.get('tier') or '', + str(image or ''))) + inventory = read_json(os.path.join(corpus, 'index', 'manifest', + 'inventory.json'), {}) or {} + for key, value in (inventory.get('totals') or {}).items(): + con.execute('INSERT INTO inventory VALUES (?,?)', (key, str(value))) + run = read_json(os.path.join(corpus, 'index', 'manifest', 'link-run.json'), + {}) or {} + judge = run.get('judge') or {} + con.execute('INSERT INTO runs VALUES (?,?,?)', + ('links', 'the run that judged every form', + json.dumps({'model': judge.get('model'), + 'date': (run.get('dates') or {}).get('run'), + 'cost': (run.get('money') or {}).get('links_total'), + 'question_fingerprint': judge.get('question_fingerprint'), + 'forms_answered': (run.get('completion') or {}).get('forms_answered')}, + ensure_ascii=False))) + settings = read_json(os.path.join(HERE, 'settings', 'pipeline.json'), {}) or {} + rule = (settings.get('index') or {}).get('link_rule') or {} + con.execute('INSERT INTO meta VALUES (?,?)', ('commit', commit_of(corpus))) + con.execute('INSERT INTO meta VALUES (?,?)', ('rule_prompt_hash', + str(rule.get('prompt_hash') or ''))) + con.execute('INSERT INTO meta VALUES (?,?)', ('terms', str(terms))) + con.execute('INSERT INTO meta VALUES (?,?)', ('concepts', str(concepts))) + con.execute('INSERT INTO meta VALUES (?,?)', ('passages', str(passages))) + for name, key in (('index/manifest/link.jsonl', 'link'), + ('index/concepts.jsonl', 'concepts'), + ('index/links/forms.jsonl', 'forms')): + con.execute('INSERT INTO meta VALUES (?,?)', + ('hash:' + key, sha256_of(os.path.join(corpus, name)))) + con.commit() + con.close() + return terms, concepts, passages + + +def search(path, query, limit=25): + """What the corpus holds for a word.""" + if not os.path.exists(path): + return None + con = sqlite3.connect(path) + hits = [] + try: + for row in con.execute( + 'SELECT book, label, chapter FROM terms WHERE terms MATCH ? ' + 'ORDER BY rank LIMIT ?', (query, limit)): + hits.append(('term',) + row) + for row in con.execute( + 'SELECT concept_id, label, books FROM concepts ' + 'WHERE concepts MATCH ? ORDER BY rank LIMIT ?', (query, limit)): + hits.append(('concept',) + row) + for row in con.execute( + 'SELECT book, canonical, passage FROM passages ' + 'WHERE passages MATCH ? ORDER BY rank LIMIT ?', (query, limit)): + hits.append(('passage',) + row) + except sqlite3.OperationalError as exc: + print('the query is not one FTS5 understands: %s' % exc) + con.close() + return hits + + +def main(argv=None): + ap = argparse.ArgumentParser(prog='build_database.py') + ap.add_argument('--corpus-root', required=True) + ap.add_argument('--query', default='') + ap.add_argument('--path', default='') + args = ap.parse_args(argv) + path = args.path or os.path.join(args.corpus_root, DATABASE) + if args.query: + hits = search(path, args.query) + for row in hits or []: + print(' | '.join(str(part)[:160] for part in row)) + return 0 + terms, concepts, passages = build(args.corpus_root, path) + print('the database is written to', path) + print('terms: %d | concepts: %d | passages: %d' % (terms, concepts, passages)) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pipeline/scripts/build_inventory.py b/pipeline/scripts/build_inventory.py new file mode 100644 index 00000000..0ee36c40 --- /dev/null +++ b/pipeline/scripts/build_inventory.py @@ -0,0 +1,756 @@ +#!/usr/bin/env python3 +'''scripts/build_inventory.py - the inventory of the corpus. + +What the corpus holds, what it refuses, what it cannot say, and where every +number comes from. The inventory is generated from the artefacts themselves, +so it cannot drift from them: every count is read out of the files it +describes, and the identities that must hold are checked and written down with +the result. An identity that does not hold is written down as a gap, with the +numbers on both sides and what the difference is. + +The bases matter. A name, a book entry, a group and a form are four different +counts, and the corpus has more than one number for the same word. Every +number here says which one it is. + + python3 scripts/build_inventory.py --corpus-root +''' +import argparse +import collections +import glob +import hashlib +import json +import os +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +# the identities the corpus must hold, and that no README may excuse. The +# gate does not trust the inventory to say which ones these are: it reads +# this list. +REQUIRED_IDENTITIES = ( + "the books grouped, the books unplaced and the books unanswered are the books of every form", + "every form of the corpus has exactly one row in the manifest", + "the forms of the corpus are the names the books share", + "the concepts are the groups of the last answer to every form", + "the answers of the manifest are the answers of the ledger", + "the question the corpus asks is the question the rule registers", + "the books of the corpus are the books of the terms and of the terms manifest", + "the evidence of the corpus is the evidence of the run", +) + +# the artefacts each identity needs. An identity whose stage has not run yet +# has nothing to say: it says so, and it does not fail the build. A library +# that has only been indexed is not a broken library, and a reader has to be +# able to see which parts of it are not there yet. +STAGES_THE_IDENTITY_NEEDS = { + "the distinct names proposed are the names of the books added up": + ["index/admission/replay.json"], + "every distinct name was admitted, refused or quarantined": + ["index/admission/replay.json"], + "the names in more than one book are the forms and the held back": + ["index/links/forms.jsonl", "index/links/held-back.jsonl"], + "the gold set adds up": ["index/admission/replay.json"], + "the concepts are the groups of two or more": ["index/concepts.jsonl"], + "the books grouped, the books unplaced and the books unanswered are the books of every form": + ["index/manifest/link.jsonl"], + "every form of the corpus has exactly one row in the manifest": + ["index/manifest/link.jsonl"], + "the forms of the corpus are the names the books share": + ["index/links/forms.jsonl"], + "the concepts are the groups of the last answer to every form": + ["index/links/form-judgments.jsonl"], + "the answers of the manifest are the answers of the ledger": + ["index/manifest/link.jsonl", "index/links/form-judgments.jsonl"], + "the books of the corpus are the books of the terms and of the terms manifest": + ["index/manifest/terms.jsonl"], + "the evidence of the corpus is the evidence of the run": + ["index/manifest/link-run.json"], +} + + +def read_jsonl(path): + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding='utf-8') as fh: + for line in fh: + line = line.strip() + if line: + try: + rows.append(json.loads(line)) + except ValueError: + continue + return rows + + +def read_json(path, default=None): + try: + with open(path, encoding='utf-8') as fh: + return json.load(fh) + except Exception: + return default + + +def sha256_of(path): + digest = hashlib.sha256() + try: + with open(path, 'rb') as fh: + for chunk in iter(lambda: fh.read(1 << 20), b''): + digest.update(chunk) + except OSError: + return '' + return digest.hexdigest() + + +def main(argv=None): + ap = argparse.ArgumentParser(prog='build_inventory.py') + ap.add_argument('--corpus-root', required=True) + ap.add_argument('--out', default='') + args = ap.parse_args(argv) + corpus = os.path.abspath(os.path.expanduser(args.corpus_root)) + out_path = args.out or os.path.join(corpus, 'index', 'manifest', + 'inventory.json') + + books = [] + for name in sorted(os.listdir(corpus)): + path = os.path.join(corpus, name) + if not os.path.isdir(path) or name.startswith('.'): + continue + machine = os.path.exists(os.path.join(path, 'paragraphs.jsonl')) + notes = os.path.isdir(os.path.join(path, 'chapters')) + if not (machine or notes): + continue + books.append(name) + + terms = [] + for path in sorted(glob.glob(os.path.join(corpus, 'index', 'terms', + '*.jsonl'))): + terms.extend(read_jsonl(path)) + occurrences = 0 + for path in sorted(glob.glob(os.path.join(corpus, 'index', 'occurrences', + '*.jsonl'))): + occurrences += len(read_jsonl(path)) + forms = read_jsonl(os.path.join(corpus, 'index', 'links', 'forms.jsonl')) + held = read_jsonl(os.path.join(corpus, 'index', 'links', + 'held-back.jsonl')) + concepts = read_jsonl(os.path.join(corpus, 'index', 'concepts.jsonl')) + manifest_rows = read_jsonl(os.path.join(corpus, 'index', 'manifest', + 'link.jsonl')) + rejected = read_jsonl(os.path.join(corpus, 'index', + 'terms_rejected.jsonl')) + replay = read_json(os.path.join(corpus, 'index', 'admission', + 'replay.json'), {}) or {} + run = read_json(os.path.join(corpus, 'index', 'manifest', + 'link-run.json'), {}) or {} + figure_read = read_json(os.path.join(corpus, 'index', 'manifest', + 'figure-read.json'), {}) or {} + # the settings of the library are its own, and the environment names + # them; without that, the ones of the tool are read + try: + from book2corpus.pipeline import Settings as _Settings + settings = _Settings().values + except Exception: + settings = read_json(os.path.join(HERE, 'settings', 'pipeline.json'), {}) or {} + index_settings = settings.get('index') or {} + + names = collections.Counter(row.get('canonical') for row in terms) + books_per_name = collections.defaultdict(set) + for row in terms: + books_per_name[row.get('canonical')].add(row.get('term_id', '').split(':')[0]) + shared_names = [name for name, books in books_per_name.items() if len(books) > 1] + form_names = set(form.get('canonical') for form in forms) + held_names = set() + for row in held: + if isinstance(row, dict): + held_names.add(row.get('canonical')) + else: + held_names.add(row) + reasons = collections.Counter(row.get('reason') for row in rejected) + groups = sum(1 for concept in concepts if concept.get('size', 0) > 1) + members = set() + for concept in concepts: + for member in concept.get('members') or []: + members.add(member) + + identities = [] + + def identity(name, left, right, note='', base_left='', base_right='', + waivable=True): + identities.append({'name': name, 'left': left, 'right': right, + 'holds': left == right, 'note': note, + 'base_left': base_left, 'base_right': base_right, + 'waivable': waivable}) + + identity('the term entries and the occurrence entries are the same set', + len(terms), occurrences, + 'a book entry is a term in a book, counted the same way in both', + 'book entries', 'book entries') + identity('the distinct names proposed are the names of the books added up', + replay.get('unique_names'), + sum((row.get('names') or 0) + for row in (replay.get('per_book') or {}).values()), + 'a name is proposed once per book, and the distinct names are counted once', + 'distinct names', 'the sum of the names of the books') + tiers = replay.get('tiers') or {} + identity('every distinct name was admitted, refused or quarantined', + replay.get('unique_names'), sum(tiers.values()), + 'the admission tiers cover every distinct name', + 'distinct names', 'distinct names') + identity('the names in more than one book are the forms and the held back', + len(shared_names), len(form_names) + len(held_names), + 'a name in two books is a form, unless it is a name and not a sense', + 'distinct names in more than one book', + 'the forms plus the held back') + exceptions = read_jsonl(os.path.join(corpus, 'index', 'gold', + 'exceptions.jsonl')) + identity('the gold set adds up', + replay.get('gold_terms'), + (replay.get('gold_admitted_by_the_new_rules') or 0) + + (replay.get('gold_held_for_a_person') or 0) + + (replay.get('gold_rejected_by_the_new_rules') or 0) + + len(exceptions), + 'the gold set is the books own terms, ruled on by the same rules, with the exceptions a person reviewed', + 'gold terms', 'gold terms') + identity('the concepts are the groups of two or more', + len(concepts), groups, + 'a concept is a group of two or more books', + 'concepts', 'groups of two or more') + # the sources. A name in two or more books is a form of the corpus, + # unless it is a name and not a sense, and the books of that form are the + # books that carry the name. The terms are written by the stage that + # reads the books, so a check anchored here cannot be fooled by a later + # stage that drops a row: the corpus lost 2,955 forms once, and every + # check that was built on the manifest held. + books_of_name = collections.defaultdict(set) + for row in terms: + books_of_name[row.get('canonical')].add(row.get('term_id', '').split(':')[0]) + expected_forms = set(name for name, books in books_of_name.items() + if len(books) > 1) - held_names + books_of_every_form = sum(len(books_of_name.get(name, set())) + for name in expected_forms) + attestations = {} + for form in forms: + books_of_form = set() + for item in form.get("books") or []: + books_of_form.add(item.get("book")) + attestations[form.get("canonical")] = books_of_form + # the books of every form, one form at a time: the books the judge + # grouped and the books it left unplaced are exactly the books that + # carry the name. The forms are compared one by one and not added up, + # because one form losing a book and another gaining one would cancel + # in a total. + forms_exact = 0 + forms_short = 0 + forms_over = 0 + books_double = 0 + forms_with_a_double = 0 + books_grouped = 0 + books_unplaced = 0 + forms_checked = 0 + books_unanswered = 0 + for row in manifest_rows: + canonical = row.get("unit") + books_of_form = books_of_name.get(canonical) + if books_of_form is None or canonical not in expected_forms: + continue + forms_checked += 1 + placed = set(row.get("books") or []) + unplaced = set(row.get("unplaced") or []) + # a book the judge did not name even after the form was asked again + # is not unplaced: it is a third state, and it is counted here + unanswered = set(row.get("unanswered") or []) + both = placed | unplaced | unanswered + books_grouped += len(placed) + books_unplaced += len(unplaced) + books_unanswered += len(unanswered) + double = ((placed & unplaced) | (placed & unanswered) + | (unplaced & unanswered)) + if both == books_of_form and not double: + forms_exact += 1 + elif len(both) < len(books_of_form): + forms_short += 1 + else: + forms_over += 1 + if double: + forms_with_a_double += 1 + books_double += len(double) + identity("the books grouped, the books unplaced and the books unanswered are the books of every form", + forms_exact, len(expected_forms), + "for every form the books the judge grouped, the books it left unplaced and the books it did not name even when it was asked again are exactly the books that carry the name, form by form", + "the forms whose books add up", "the forms of the corpus", + waivable=False) + seventh = identities[-1] + seventh["forms_checked"] = forms_checked + seventh["forms_in_the_corpus"] = len(expected_forms) + seventh["books_grouped_and_unplaced"] = books_grouped + books_unplaced + seventh["books_unanswered"] = books_unanswered + seventh["books_of_every_form"] = books_of_every_form + seventh["forms_with_a_book_missing"] = forms_short + seventh["forms_with_a_book_extra"] = forms_over + seventh["books_in_two_groups"] = books_double + seventh["forms_with_a_double_book"] = forms_with_a_double + if forms_short or forms_over or books_double: + seventh["holds"] = False + seventh["note"] = (seventh["note"] + + "; a form is short or over, or a book is both grouped and unplaced") + # the forms of the corpus against the rows of the manifest. The names are + # compared and not the counts: one form can have two rows, and a duplicate + # can hide a form that is missing. + manifest_unit_list = [row.get("unit") for row in manifest_rows] + manifest_units = set(manifest_unit_list) + duplicate_units = sorted(unit for unit, number + in collections.Counter(manifest_unit_list).items() + if number > 1) + forms_with_a_row = len(expected_forms & manifest_units) + missing_forms = sorted(expected_forms - manifest_units) + rows_with_no_form = sorted(manifest_units - expected_forms) + identity("every form of the corpus has exactly one row in the manifest", + forms_with_a_row, len(expected_forms), + "the forms of the corpus and the rows of the manifest are the same names, one row each", + "the forms of the corpus the manifest carries", "the forms of the corpus", + waivable=False) + coverage = identities[-1] + coverage["forms_missing_from_the_manifest"] = len(missing_forms) + coverage["rows_with_no_form"] = len(rows_with_no_form) + coverage["duplicate_rows"] = len(duplicate_units) + coverage["manifest_rows"] = len(manifest_rows) + coverage["manifest_units"] = len(manifest_units) + coverage["missing_forms"] = missing_forms[:50] + coverage["rows_named"] = rows_with_no_form[:50] + coverage["duplicate_units"] = duplicate_units[:50] + if missing_forms or rows_with_no_form or duplicate_units: + coverage["holds"] = False + coverage["note"] = (coverage["note"] + + "; a form is missing, a row has no form, or a row is there twice") + # the forms of the corpus against the books that carry the name. The + # attestations are checked against the terms, so a form that is lost in + # the attestations shows here and not only in the manifest. + forms_matching = 0 + forms_mismatching = [] + for name in sorted(expected_forms): + have = attestations.get(name) + if have is not None and have == books_of_name.get(name, set()): + forms_matching += 1 + else: + forms_mismatching.append(name) + identity("the forms of the corpus are the names the books share", + forms_matching, len(expected_forms), + "every name the books share, and not held back, is a form of the corpus with the books that carry the name", + "the forms that match the books", "the names the books share", + waivable=False) + anchors = identities[-1] + anchors["forms_in_the_attestations"] = len(attestations) + anchors["forms_that_do_not_match"] = len(forms_mismatching) + anchors["names_named"] = forms_mismatching[:50] + if forms_mismatching: + anchors["holds"] = False + anchors["note"] = (anchors["note"] + + "; a name the books share is not a form of the corpus, or its books differ") + # the concepts against the ledger. The concepts are the groups of the + # last answer to every form, and the ledger is where they are read from, + # so a concept that is lost shows here. + ledger_rows = read_jsonl(os.path.join(corpus, 'index', 'links', + 'form-judgments.jsonl')) + judge_model = (run.get('judge') or {}).get('model') or '' + last_answer = {} + for row in ledger_rows: + if judge_model and row.get('model') and row.get('model') != judge_model: + continue + canonical = row.get('canonical') + if canonical is None: + continue + last_answer[canonical] = row + expected_groups = set() + for canonical, row in last_answer.items(): + for group in row.get('groups') or []: + group_members = frozenset("%s|%s" % (book, canonical) + for book in group) + if len(group_members) >= 2: + expected_groups.add(group_members) + actual_groups = [frozenset(concept.get('members') or []) + for concept in concepts] + actual_set = set(actual_groups) + # the groups are sets of members, and a set of sets has no order of + # its own, so they are sorted by what they hold + groups_not_expected = sorted(expected_groups - actual_set, + key=lambda group: sorted(group)) + concepts_not_expected = sorted(actual_set - expected_groups, + key=lambda group: sorted(group)) + duplicated_concepts = [group for group, number + in collections.Counter(actual_groups).items() + if number > 1] + small_concepts = [group for group in actual_set if len(group) < 2] + identity("the concepts are the groups of the last answer to every form", + len(expected_groups), len(actual_groups), + "the concepts of the corpus are the groups of the last answer to every form, and the ledger is where they are read from", + "the groups of the last answers", "the concepts", + waivable=False) + concepts_identity = identities[-1] + concepts_identity["groups_not_in_the_concepts"] = len(groups_not_expected) + concepts_identity["concepts_not_in_the_groups"] = len(concepts_not_expected) + concepts_identity["duplicate_concepts"] = len(duplicated_concepts) + concepts_identity["concepts_with_fewer_than_two_members"] = len(small_concepts) + if groups_not_expected or concepts_not_expected or duplicated_concepts or small_concepts: + concepts_identity["holds"] = False + concepts_identity["note"] = (concepts_identity["note"] + + "; a concept is lost, or there is one that is not a group") + # the answers of the manifest against the answers of the ledger. The + # manifest names the answer it carries by its hash, so a row the ledger + # loses, or a row the ledger holds twice, is named here. + ledger_by_key = collections.defaultdict(list) + for row in ledger_rows: + ledger_by_key[row.get("key")].append(row) + answers_pinned = 0 + answers_missing = [] + answers_twice = [] + answers_not_the_last = [] + for row in manifest_rows: + key = row.get("key") + hits = [item for item in (ledger_by_key.get(key) or []) + if item.get("canonical") == row.get("unit")] + if len(hits) != 1: + if not hits: + answers_missing.append(row.get("unit")) + else: + answers_twice.append(row.get("unit")) + continue + # and it is the last answer the ledger holds for that form: a row + # the ledger lost would leave an earlier answer as the last one + last = last_answer.get(row.get("unit")) + if last is None or last.get("key") != key: + answers_not_the_last.append(row.get("unit")) + continue + answers_pinned += 1 + # and the ledger holds no answer for a form the manifest does not carry: + # an answer that points at nothing is a lost form + carried = set(row.get("unit") for row in manifest_rows) + answers_for_nothing = sorted(set(row.get("canonical") for row in ledger_rows + if row.get("model") == (run.get("judge") or {}).get("model") + and row.get("canonical") not in carried)) + identity("the answers of the manifest are the answers of the ledger", + answers_pinned, len(manifest_rows), + "every answer the manifest carries is an answer of the ledger, is there once, and is the last answer the ledger holds for that form", + "the answers of the manifest the ledger holds", "the answers of the manifest", + waivable=False) + answers_identity = identities[-1] + answers_identity["answers_not_in_the_ledger"] = len(answers_missing) + answers_identity["answers_in_the_ledger_twice"] = len(answers_twice) + answers_identity["answers_that_are_not_the_last"] = len(answers_not_the_last) + answers_identity["forms_named"] = (answers_missing + answers_twice + + answers_not_the_last)[:50] + answers_identity["answers_for_a_form_the_manifest_does_not_carry"] = len(answers_for_nothing) + answers_identity["forms_not_carried"] = answers_for_nothing[:50] + if answers_missing or answers_twice or answers_not_the_last or answers_for_nothing: + answers_identity["holds"] = False + answers_identity["note"] = (answers_identity["note"] + + "; an answer of the manifest is not in the ledger, is there twice, or is not the last one") + # the question the corpus asks against the question the rule registers. + # The rule is a prompt template in the code and a hash in the settings, + # and a corpus that is judged under a question the settings do not name is + # a corpus whose links belong to another rule. + import hashlib as _hashlib + import importlib.util as _util + _judge_path = os.path.join(HERE, "scripts", "judge_forms.py") + templates = [] + try: + _spec = _util.spec_from_file_location("judge_forms_for_hash", _judge_path) + _module = _util.module_from_spec(_spec) + _spec.loader.exec_module(_module) + templates = [("the prompt", _module.FORM_PROMPT), + ("the escalation prompt", _module.ESCALATE_PROMPT)] + except Exception: + templates = [] + rule = index_settings.get("link_rule") or {} + registered = [("the prompt", rule.get("prompt_hash")), + ("the escalation prompt", rule.get("escalate_prompt_hash"))] + question_matches = 0 + question_changed = [] + for (name, template), (_label, wanted) in zip(templates, registered): + got = _hashlib.sha256(template.encode("utf-8")).hexdigest() + if wanted and got == wanted: + question_matches += 1 + else: + question_changed.append(name) + identity("the question the corpus asks is the question the rule registers", + question_matches, len(templates), + "the prompt the judge is given is the prompt the rule registers by its hash, so a corpus judged under another question is named", + "the questions that match the registration", "the questions the rule names", + waivable=False) + question_identity = identities[-1] + question_identity["questions_changed"] = question_changed + if question_changed: + question_identity["holds"] = False + question_identity["note"] = (question_identity["note"] + + "; the question the corpus asks is not the question the rule registers") + # the books of the corpus against the books of the terms. The books are + # the folders the corpus is made of, and the terms are what the stage + # that reads those books wrote, so a book that is lost between the two + # shows here. + term_books = set() + for path in glob.glob(os.path.join(corpus, 'index', 'terms', '*.jsonl')): + term_books.add(os.path.basename(path)[:-len('.jsonl')]) + # and the books the terms manifest names: the manifest of the stage that + # read the books is a third account of them, and a book that is lost + # from the folders and from the terms is still in it + manifest_books = set() + for row in read_jsonl(os.path.join(corpus, 'index', 'manifest', + 'terms.jsonl')): + unit = str(row.get('unit') or '') + if unit: + manifest_books.add(unit.split('/')[0]) + identity("the books of the corpus are the books of the terms and of the terms manifest", + len(manifest_books), len(books), + "every book of the corpus has its terms, every set of terms has a book of the corpus, and the terms manifest names the same books", + "the books of the terms manifest", "the books of the corpus", + waivable=False) + books_identity = identities[-1] + books_identity["books_without_terms"] = sorted(set(books) - term_books) + books_identity["terms_without_a_book"] = sorted(term_books - set(books)) + books_identity["books_not_in_the_terms_manifest"] = sorted(set(books) - manifest_books) + books_identity["books_in_the_manifest_without_a_book"] = sorted(manifest_books - set(books)) + books_identity["books_with_terms"] = len(term_books) + if (books_identity["books_without_terms"] or books_identity["terms_without_a_book"] + or books_identity["books_not_in_the_terms_manifest"] + or books_identity["books_in_the_manifest_without_a_book"]): + books_identity["holds"] = False + books_identity["note"] = (books_identity["note"] + + "; a book of the corpus has no terms, the terms have no book, or the terms manifest names another book") + # the evidence of the run: the cache of the answers, the ledger and the + # forms. The run record names them by their hash, and the run record is + # written by the stage that judged and not by the build, so a cache that + # is swapped after the run is named here. + evidence = run.get("evidence") or {} + evidence_matching = 0 + evidence_changed = [] + for name, path in (("cache", "index/links/form-answers.jsonl"), + ("ledger", "index/links/form-judgments.jsonl"), + ("forms", "index/links/forms.jsonl")): + wanted = (evidence.get(name) or {}).get("sha256") + if not wanted: + continue + if sha256_of(os.path.join(corpus, path)) == wanted: + evidence_matching += 1 + else: + evidence_changed.append(path) + identity("the evidence of the corpus is the evidence of the run", + evidence_matching, 3, + "the cache of the answers, the ledger and the forms are the ones the run was made on, named by their hash in the run record", + "the evidence that matches the run", "the files the run names", + waivable=False) + evidence_identity = identities[-1] + evidence_identity["files_changed"] = evidence_changed + if evidence_changed or evidence_matching < 3: + evidence_identity["holds"] = False + evidence_identity["note"] = (evidence_identity["note"] + + "; the evidence of the corpus is not the evidence of the run") + # the stages that have not run yet: an identity that needs one of them + # has nothing to say, and says so, and does not fail the build + not_built = [] + for item in identities: + needed = STAGES_THE_IDENTITY_NEEDS.get(item["name"]) + missing = [] + if needed: + missing = [path for path in needed + if not os.path.exists(os.path.join(corpus, path))] + if missing: + item["state"] = "not_built" + item["left"] = None + item["right"] = None + item["note"] = (item["note"] + "; the stage that answers this has not" + " run yet: " + ", ".join(missing)) + not_built.append(item["name"]) + else: + item["state"] = "holds" if item["holds"] else "gap" + # the identities that no README may excuse. A form the manifest does not + # carry, or a form whose books do not add up, is a broken corpus and not + # a gap a reader can be told about. + broken = [item for item in identities + if item["name"] in REQUIRED_IDENTITIES and item["state"] == "gap"] + gaps = [] + for item in identities: + if item["state"] == "gap": + gaps.append({'name': item['name'], 'left': item['left'], + 'right': item['right'], + 'difference': (item['left'] or 0) - (item['right'] or 0), + 'note': item['note']}) + + per_book = [] + for name in books: + book_terms = len(read_jsonl(os.path.join(corpus, 'index', 'terms', + '%s.jsonl' % name))) + book_forms = len([form for form in forms + if any(item.get('book') == name + for item in form.get('books') or [])]) + book_members = len([member for member in members + if member.startswith(name + '|')]) + figures = read_json(os.path.join(corpus, name, 'figures.json'), {}) or {} + paragraphs = len(read_jsonl(os.path.join(corpus, name, + 'paragraphs.jsonl'))) + per_book.append({'book': name, + 'kind': 'machine corpus' if paragraphs else 'notes', + 'terms': book_terms, + 'forms': book_forms, + 'concept_entries': book_members, + 'figure_blocks': len(figures.get('figure_map') or []), + 'paragraphs': paragraphs}) + + # the evidence: how much of it is cut off, at the narrow window the + # judge reads first and at the wide one it asks for when the narrow + # one shows no sense. A passage sitting exactly at the wide cap is + # evidence the builder could not keep whole. + narrow = 0 + wide_at_cap = 0 + evidence_books = 0 + for form in forms: + for book in form.get('books') or []: + evidence_books += 1 + passage = book.get('use') or '' + if len(passage) >= 300: + narrow += 1 + wider = book.get('wide') or '' + if wider and len(wider) >= 2400: + wide_at_cap += 1 + evidence = {'books': evidence_books, + 'at_the_narrow_cap': narrow, + 'share_at_the_narrow_cap': round(narrow / float(evidence_books), 4) if evidence_books else 0.0, + 'at_the_wide_cap': wide_at_cap, + 'share_at_the_wide_cap': round(wide_at_cap / float(evidence_books), 4) if evidence_books else 0.0} + + rule = index_settings.get('link_rule') or {} + inventory = { + 'what': 'the inventory of the corpus: what it holds, what it refuses, and where every number comes from', + 'generated': '2026-11-28', + 'bases': 'a name, a book entry, a group and a form are four different counts, and every number here says which one it is', + 'books': per_book, + 'totals': {'books': len(books), + 'book_entries': len(terms), + 'distinct_names': len(names), + 'names_in_more_than_one_book': len(shared_names), + 'forms': len(forms), + 'held_back': len(held), + 'concepts': len(concepts), + 'concept_entries': len(members), + 'refused_entries': len(rejected), + 'figure_blocks': sum(row['figure_blocks'] for row in per_book), + 'paragraphs': sum(row['paragraphs'] for row in per_book)}, + 'identities': identities, + 'not_built': not_built, + 'evidence': evidence, + 'gaps': gaps, + 'rule': {'registered': rule.get('registered'), + 'outcomes': rule.get('outcomes'), + 'evidence_window': rule.get('evidence_window'), + 'prompt_hash': rule.get('prompt_hash'), + 'why': rule.get('why'), + 'read': index_settings.get('link_read') or {}}, + 'runs': [{'what': 'the run that judged every form', + 'model': (run.get('judge') or {}).get('model'), + 'date': (run.get('dates') or {}).get('run'), + 'cost': (run.get('money') or {}).get('links_total'), + 'question_fingerprint': (run.get('judge') or {}).get('question_fingerprint'), + 'forms_answered': (run.get('completion') or {}).get('forms_answered'), + 'forms_unanswered': (run.get('completion') or {}).get('forms_unanswered')}, + {'what': 'the read of the ninety demotions', + 'demotions': (figure_read.get('result') or {}).get('demotions'), + 'confirmed': (figure_read.get('result') or {}).get('confirmed'), + 'controls': (figure_read.get('result') or {}).get('controls'), + 'outcome': (figure_read.get('result') or {}).get('outcome')}], + 'refusals_by_reason': dict(reasons), + 'gold_exceptions': exceptions, + 'admission_by_book': replay.get('per_book') or {}, + 'admission_totals': {'names_proposed': replay.get('names_replayed'), + 'distinct_names': replay.get('unique_names'), + 'admitted': (tiers or {}).get('admit'), + 'refused': (tiers or {}).get('reject'), + 'quarantined': (tiers or {}).get('quarantine'), + 'gold_terms': replay.get('gold_terms'), + 'gold_admitted': replay.get('gold_admitted_by_the_new_rules'), + 'gold_held': replay.get('gold_held_for_a_person'), + 'gold_refused': replay.get('gold_rejected_by_the_new_rules')}, + 'input_hashes': {'index/manifest/link.jsonl': sha256_of(os.path.join(corpus, 'index', 'manifest', 'link.jsonl')), + 'index/concepts.jsonl': sha256_of(os.path.join(corpus, 'index', 'concepts.jsonl')), + 'index/links/forms.jsonl': sha256_of(os.path.join(corpus, 'index', 'links', 'forms.jsonl')), + 'index/admission/replay.json': sha256_of(os.path.join(corpus, 'index', 'admission', 'replay.json'))}, + 'lineage': {'computed_from_the_lineage': [ + 'the books and what each of them holds', + 'the counts of terms, entries, forms, concepts and refusals', + 'the identities that must sum, and the gaps that do not', + 'the rule, the window and the hash of the prompt', + 'the runs: the model, the date, the cost and the question fingerprint'], + 'needs_a_label': [ + 'how good the links are: a rate needs a judge and a reader that agree, and the readers do not', + 'whether the concept count is above or below the number of shared senses: that needs the senses themselves', + 'whether a picture is the figure the text names: that needs a reader of the pictures', + 'whether the demotions are right: the read did not confirm them']}, + 'never_claims': ['a judge error rate or accuracy', + 'that the concept count is a bound on the shared senses', + 'that anything in the corpus is verified', + 'that no placement is waiting for a person, because the placements are right', + 'that one judge is better than another by more than the readers differ']} + + with open(out_path, 'w', encoding='utf-8') as fh: + json.dump(inventory, fh, indent=1, ensure_ascii=False, sort_keys=True) + fh.write(chr(10)) + print('the inventory is written to', out_path) + print('the books:', len(books), '| the book entries:', len(terms), + '| the forms:', len(forms), '| the concepts:', len(concepts)) + for item in identities: + state = item.get('state') or ('holds' if item['holds'] else 'gap') + if state == 'not_built': + shown = 'not built yet' + elif state == 'holds': + shown = 'holds' + else: + shown = 'GAP %s vs %s' % (item['left'], item['right']) + print(' %-54s %s' % (item['name'][:54], shown)) + if gaps: + print('the gaps:', len(gaps), '- the inventory names them and the README must too') + if broken: + # the inventory that was written is the failing one, so the corpus + # never keeps the old inventory that passed + print('FAILED: the corpus does not hold the identity it must hold,') + print(' and a README that names the gap does not excuse it') + for item in broken: + print(' ', item['name']) + print(' the two sides:', item['left'], 'against', item['right']) + for name in item.get('missing_forms') or []: + print(' the form the manifest does not carry:', name) + if len(item.get('missing_forms') or []) < item.get('forms_missing_from_the_manifest', 0): + print(' and %d more' + % (item['forms_missing_from_the_manifest'] + - len(item['missing_forms']))) + for name in item.get('rows_named') or []: + print(' the row the corpus has no form for:', name) + for name in item.get('forms_named') or []: + print(' the answer of the manifest is not the ledger own:', name) + for name in item.get('forms_not_carried') or []: + print(' the ledger answers a form the manifest does not carry:', name) + for name in item.get('books_without_terms') or []: + print(' the book of the corpus without its terms:', name) + for name in item.get('books_not_in_the_terms_manifest') or []: + print(' the book of the corpus that the terms manifest does not name:', name) + for name in item.get('books_in_the_manifest_without_a_book') or []: + print(' the book the terms manifest names and the corpus does not hold:', name) + for name in item.get('terms_without_a_book') or []: + print(' the terms with no book of the corpus:', name) + for name in item.get('duplicate_units') or []: + print(' the row that is there twice:', name) + for name in item.get('names_named') or []: + print(' the name the books share that is not a form:', name) + if item.get('concepts_not_in_the_groups'): + print(' the concepts that are not a group of any answer:', + item['concepts_not_in_the_groups']) + if item.get('groups_not_in_the_concepts'): + print(' the groups of the answers that are not a concept:', + item['groups_not_in_the_concepts']) + if item.get('duplicate_concepts'): + print(' the concepts that are there twice:', + item['duplicate_concepts']) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) + diff --git a/pipeline/scripts/build_read_packets.py b/pipeline/scripts/build_read_packets.py new file mode 100755 index 00000000..50e32ddd --- /dev/null +++ b/pipeline/scripts/build_read_packets.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +"""scripts/build_read_packets.py - the packets a blind read is given. + +A blind read of the figures needs a packet per figure: the description the +book gives, and the picture the figure claims. The picture has to be a file +that exists, or the reader is asked about nothing. The packet therefore +resolves the picture id to a file, and says where it found it. + +The pictures live in the library's catalogue (`agent-index.jsonl`), which names +the file of every picture the extraction made - the corpus keeps only the +pictures it claims, and the pictures a demotion names are usually among the +ones the corpus does not keep. A picture that is in the corpus's own figures +directory is used from there. + +A picture that cannot be resolved is not written into a packet: it is named in +`unresolved.jsonl` and the run exits 2, so that a read cannot be scored over +forms nobody saw. + +The figures to read are the demotions the audit decided and has not applied +(`index/manifest/figure-demotions.json`) and a matched number of kept +pictures from the same books, drawn with the seed the rule names. + + python3 scripts/build_read_packets.py --corpus-root \ + --library --out [--batches 6] [--seed 20261128] +""" +import argparse +import collections +import json +import os +import random +import sys + + +def read_jsonl(path): + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + try: + rows.append(json.loads(line)) + except ValueError: + continue + return rows + + +def catalogue(library): + """Every picture the library holds, by its id.""" + out = {} + for row in read_jsonl(os.path.join(library, "agent-index.jsonl")): + if row.get("id"): + out[row["id"]] = row + return out + + +def resolve(picture, book, corpus, catalogue, library): + """The file of a picture, or nothing: where it is, and whether it is there.""" + if not picture: + return "", "no picture named" + name = picture + ".webp" + local = os.path.join(corpus, book, "figures", name) + if os.path.exists(local): + return local, "the corpus" + entry = catalogue.get(picture) + if entry and entry.get("file"): + path = os.path.join(library, entry["file"]) + if os.path.exists(path): + return path, "the library" + return "", "the catalogue names a file that is not there" + return "", "the catalogue does not hold it" + + +def figure_map(corpus, books): + blocks = {} + for book in books: + path = os.path.join(corpus, book, "figures.json") + if not os.path.exists(path): + continue + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + for entry in data.get("figure_map") or []: + blocks[(book, entry.get("id"))] = entry + return blocks + + +def audited_pictures(corpus, books): + """The picture the audit judged for each figure, from the audit's own record. + + A demotion names the figure, and the figure may name no picture any more: + the corpus keeps the pictures it claims, and a demoted figure's picture + is often among the ones it does not keep. The audit's verdict names both, + so that is where the picture comes from. + """ + out = {} + for book in books: + path = os.path.join(corpus, book, "figure-audit.json") + if not os.path.exists(path): + continue + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + for tier, block in (data.get("tiers") or {}).items(): + for verdict in block.get("verdicts") or []: + figure_id = verdict.get("figure_id") + picture = verdict.get("id") + if figure_id and picture: + out[(book, figure_id)] = picture + return out + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="build_read_packets.py") + ap.add_argument("--corpus-root", default=os.path.expanduser( + "")) + ap.add_argument("--library", default=os.path.expanduser( + "~/Library/Mobile Documents/com~apple~CloudDocs/Textbooks")) + ap.add_argument("--out", required=True) + ap.add_argument("--batches", type=int, default=6) + ap.add_argument("--seed", type=int, default=20261128) + ap.add_argument("--controls", type=int, default=0, + help="how many kept pictures to read beside the demotions") + ap.add_argument("--only", default="both", + choices=("both", "demotions", "controls"), + help="which packets to write") + args = ap.parse_args(argv) + corpus = os.path.abspath(os.path.expanduser(args.corpus_root)) + library = os.path.abspath(os.path.expanduser(args.library)) + out_dir = os.path.abspath(os.path.expanduser(args.out)) + os.makedirs(out_dir, exist_ok=True) + + manifest_path = os.path.join(corpus, "index", "manifest", + "figure-demotions.json") + with open(manifest_path, encoding="utf-8") as fh: + manifest = json.load(fh) + demoted = manifest.get("decided") or {} + books = sorted(demoted) + blocks = figure_map(corpus, books) + audited = audited_pictures(corpus, books) + cat = catalogue(library) + + items = [] + for book in books: + for figure_id in sorted(demoted[book]): + entry = blocks.get((book, figure_id)) + if entry is None: + continue + candidates = entry.get("candidates") or [] + picture = candidates[0] if candidates else "" + if not picture: + picture = audited.get((book, figure_id)) or "" + items.append({"book": book, "figure": figure_id, + "picture": picture, + "caption": entry.get("caption") or "none", + "description": entry.get("description") or "none", + "tier": entry.get("tier"), "kind": "demotion"}) + + # the controls: pictures the corpus keeps, in the tiers the demotions + # are in, from figures the audit did not demote. A control is a picture + # the reader shows, so that "judged demotable" means the judge would + # have taken a good picture away. + demoted_figures = set((row["book"], row["figure"]) for row in items) + tiers = set(row["tier"] for row in items) + per_book = collections.Counter(row["book"] for row in items) + kept = collections.defaultdict(list) + for (book, figure_id), entry in blocks.items(): + image = entry.get("image") + if not image or (book, figure_id) in demoted_figures: + continue + if entry.get("tier") not in tiers: + continue + kept[book].append((figure_id, image, entry)) + controls = [] + for book, count in per_book.items(): + pool = sorted(kept.get(book) or []) + random.Random(args.seed).shuffle(pool) + for figure_id, image, entry in pool[:count]: + controls.append({"book": book, "figure": figure_id, + "picture": image, + "caption": entry.get("caption") or "none", + "description": entry.get("description") or "none", + "tier": entry.get("tier"), "kind": "control"}) + + unresolved = [] + for row in items + controls: + path, where = resolve(row["picture"], row["book"], corpus, cat, library) + row["image"] = path + row["where"] = where + if not path: + unresolved.append({"book": row["book"], "figure": row["figure"], + "picture": row["picture"], "reason": where}) + print("the demotions: %d | the controls: %d | unresolved: %d" + % (len(items), len(controls), len(unresolved))) + where = collections.Counter(row["where"] for row in items + controls) + print("where the pictures came from:", dict(where)) + if unresolved: + with open(os.path.join(out_dir, "unresolved.jsonl"), "w", + encoding="utf-8") as fh: + for row in unresolved: + fh.write(json.dumps(row, ensure_ascii=False) + "\n") + print("the figures whose picture could not be found are written to:", + os.path.join(out_dir, "unresolved.jsonl")) + return 2 + + rows = items + controls + if args.only == "demotions": + rows = items + elif args.only == "controls": + rows = controls + random.Random(args.seed).shuffle(rows) + batches = max(1, args.batches) + size = (len(rows) + batches - 1) // batches + number = 0 + for start in range(0, len(rows), size): + chunk = rows[start:start + size] + number += 1 + path = os.path.join(out_dir, "batch %d of %d.jsonl" % (number, batches)) + with open(path, "w", encoding="utf-8") as fh: + for row in chunk: + # the packet does not say which figures the judge wanted + # demoted and which are the controls: that is in labels.json, + # and a reader that can tell them apart is not blind + packet = {key: row[key] for key in + ("book", "figure", "picture", "image", "caption", + "description", "tier")} + fh.write(json.dumps(packet, ensure_ascii=False) + "\n") + print("wrote", path, len(chunk), "figures") + with open(os.path.join(out_dir, "labels.json"), "w", encoding="utf-8") as fh: + json.dump({"demotions": [[row["book"], row["figure"]] for row in items], + "controls": [[row["book"], row["figure"]] for row in controls], + "seed": args.seed}, fh, indent=1) + print("the labels are written to", os.path.join(out_dir, "labels.json")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/calibrate_figures.py b/pipeline/scripts/calibrate_figures.py new file mode 100644 index 00000000..b58cc679 --- /dev/null +++ b/pipeline/scripts/calibrate_figures.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Measure the matcher's thresholds against blocks that are already known. + +A threshold that is a guess is a threshold that will be wrong somewhere. +The blocks a page key or a figure number already resolves give an answer +that does not depend on the threshold: the picture the key names is the +right one. Those blocks are the yardstick. + +What this measures: + * the description rule - when it fires, how often it names that same + picture (precision), and how many of the known blocks it reaches + (recall), once the catalogue's duplicate extractions are collapsed + * the caption rule - measured only on blocks a *number* resolved, so + the caption is not scored against itself + * the precision by pool type, because a page pool and a chapter pool + are not the same kind of question + * the page numbering - how often the catalogue's PDF page carries the + printed page the notes give + + python3 scripts/calibrate_figures.py --corpus-root --library +""" +import argparse +import collections +import glob +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from book2corpus import figures, notes + + +def load_records(library): + records = collections.defaultdict(list) + index = os.path.join(library, notes.FIGURE_INDEX + ".jsonl") + with open(index, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + record = json.loads(line) + records[record.get("book", "")].append(record) + return records + + +def book_blocks(book_dir): + blocks = [] + for path in sorted(glob.glob(os.path.join(book_dir, "chapters", "**", "*.md"), + recursive=True)): + parsed = notes.parse_chapter(path) + stem = os.path.splitext(os.path.basename(path))[0] + for block in parsed["blocks"]: + block["stem"] = stem + blocks.extend(parsed["blocks"]) + return blocks + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--library", required=True) + args = parser.parse_args() + library = os.path.abspath(os.path.expanduser(args.library)) + corpus = os.path.abspath(os.path.expanduser(args.corpus_root)) + records = load_records(library) + + known = [] + page_agreement = collections.Counter() + page_totals = collections.Counter() + for book in sorted(records): + book_dir = os.path.join(corpus, book) + if not os.path.isdir(book_dir): + continue + blocks = book_blocks(book_dir) + matcher = figures.Matcher(blocks, records[book], library) + matcher.pass_number({"pdf-page", "printed-page"}) + matcher.pass_caption({"pdf-page", "printed-page"}) + matcher.pass_number({"chapter", "book"}) + matcher.pass_caption({"chapter", "book"}) + for block in matcher.figures: + label = figures.norm(block.get("page") or "") + if label and label not in figures.GENERIC_PAGE: + page_totals[book] += 1 + if any(figures.norm(r.get("printed_page") or "") == label + for r in block["_pool"]): + page_agreement[book] += 1 + if block.get("tier") in ("numbered", "verified"): + known.append((book, block, block["image"], block["_pool"], + block["_key"], block.get("tier"))) + + print("known blocks (a key resolved them): %d" % len(known)) + print() + print("page numbering: the catalogue's PDF page carries the notes' page label") + print("%-30s %8s %8s %8s" % ("book", "blocks", "agree", "share")) + for book in sorted(page_totals): + total = page_totals[book] + agree = page_agreement[book] + print("%-30s %8d %8d %7.1f%%" % (book, total, agree, 100.0 * agree / total)) + total = sum(page_totals.values()) + agree = sum(page_agreement.values()) + print("%-30s %8d %8d %7.1f%%" % ("ALL", total, agree, 100.0 * agree / (total or 1))) + print() + + # --- the description rule, with the duplicates collapsed ----------- + scores = [] + matchers = {} + for book, block, truth, pool, key, tier in known: + matcher = matchers.get(book) + if matcher is None: + matcher = matchers[book] = figures.Matcher([], records[book], library) + score, top, second, rival = matcher.top_two(block, pool) + collapsed = bool(second > figures.DESCRIPTION_LO + and top is not None and rival is not None + and matcher.same_picture(top, rival)) + scores.append({ + "book": book, "key": key, "tier": tier, + "truth": truth.get("id"), + "top": top.get("id") if top else None, + "top_score": score, "second": second, + "collapsed": bool(collapsed), + "correct": bool(top and top.get("id") == truth.get("id")), + }) + print("description rule, precision and recall over the known blocks") + print("%6s %6s %7s %8s %8s %8s" % ("HI", "LO", "fires", "correct", "prec", "recall")) + for hi in (0.80, 0.85, 0.90): + for lo in (0.15, 0.20, 0.30): + fired = [s for s in scores if s["top_score"] >= hi and s["second"] <= lo] + correct = [s for s in fired if s["correct"]] + print("%6.2f %6.2f %7d %8d %8.4f %8.3f" + % (hi, lo, len(fired), len(correct), + len(correct) / float(len(fired) or 1), + len(correct) / float(len(scores) or 1))) + print() + print("the same, with byte-identical pictures collapsed into one rival") + for hi in (0.80, 0.85, 0.90): + for lo in (0.15, 0.20, 0.30): + fired = [s for s in scores if s["top_score"] >= hi + and (s["second"] <= lo or s["collapsed"])] + correct = [s for s in fired if s["correct"]] + print("%6.2f %6.2f %7d %8d %8.4f %8.3f" + % (hi, lo, len(fired), len(correct), + len(correct) / float(len(fired) or 1), + len(correct) / float(len(scores) or 1))) + print() + print("precision by pool type, at HI 0.85 / LO 0.20 with the collapse") + for key in ("pdf-page", "printed-page", "chapter", "book"): + subset = [s for s in scores if s["key"] == key] + fired = [s for s in subset if s["top_score"] >= 0.85 + and (s["second"] <= 0.20 or s["collapsed"])] + correct = [s for s in fired if s["correct"]] + print(" %-14s known %5d fires %5d correct %5d precision %.4f" + % (key, len(subset), len(fired), len(correct), + len(correct) / float(len(fired) or 1))) + print() + print("the caption rule, measured only on blocks a number resolved") + cap = [] + for book, block, truth, pool, key, tier in known: + if tier != "numbered" or not block["_caption_tokens"]: + continue + matcher = matchers[book] + best, best_score = None, 0.0 + for record in pool: + printed = record.get("caption_clean") or record.get("caption") or "" + if not printed: + continue + score = figures.jaccard(block["_caption_tokens"], figures.tokens(printed)) + if score > best_score: + best_score, best = score, record + cap.append((best_score, bool(best and best.get("id") == truth.get("id")))) + for th in (0.30, 0.40, 0.50, 0.60, 0.70, 0.80): + fired = [c for c in cap if c[0] >= th] + ok = [c for c in fired if c[1]] + print(" >=%.2f fires %5d correct %5d precision %.4f" + % (th, len(fired), len(ok), len(ok) / float(len(fired) or 1))) + print() + print("the description rule's disagreements at HI 0.85, for eyes") + shown = 0 + for s in scores: + if s["top_score"] >= 0.85 and not s["correct"]: + print(" %-24s key=%-12s tier=%-10s truth=%s top=%s truth_sim=%.2f top_sim=%.2f" + % (s["book"], s["key"], s["tier"], s["truth"], s["top"], + 0.0, s["top_score"])) + shown += 1 + if shown >= 12: + break + json.dump(scores, open("/tmp/calibration-scores.json", "w"), indent=1) + print() + print("written: /tmp/calibration-scores.json") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/check_answers_reproduced.py b/pipeline/scripts/check_answers_reproduced.py new file mode 100644 index 00000000..e18b1da1 --- /dev/null +++ b/pipeline/scripts/check_answers_reproduced.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""scripts/check_answers_reproduced.py - the manifest is what the ledger and +the cache say it is. + +The defect this corpus had was a re-derivation that did not replay the +escalation: the answer the tool read again was not the answer the judge gave, +and 2,955 forms dropped out of the manifest without a word. The fix is tested +on a fixture in the tool own tests. This checks the same thing on the corpus: +every form is read again from the cached evidence, with the escalation +replayed, and the answer that comes out must be the answer the manifest +carries. Nothing is asked of a model, and nothing costs money: the answers +are read out of the cache the judge wrote. + + python3 scripts/check_answers_reproduced.py --corpus-root +""" +import argparse +import json +import os +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.join(HERE, "scripts")) + +import judge_forms # noqa: E402 + + +def read_json(path, default=None): + try: + with open(path, encoding="utf-8") as fh: + return json.load(fh) + except Exception: + return default + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="check_answers_reproduced.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--model", default="") + args = ap.parse_args(argv) + corpus = os.path.abspath(os.path.expanduser(args.corpus_root)) + forms = judge_forms.read_jsonl(os.path.join(corpus, "index", "links", "forms.jsonl")) + history = judge_forms.read_jsonl(os.path.join(corpus, "index", "links", "form-judgments.jsonl")) + cache = judge_forms.read_cache(os.path.join(corpus, "index", "links")) + manifest = judge_forms.read_jsonl(os.path.join(corpus, "index", "manifest", "link.jsonl")) + model = args.model + if not model: + run = read_json(os.path.join(corpus, "index", "manifest", "link-run.json"), {}) or {} + model = (run.get("judge") or {}).get("model") or "" + decided, incomplete = judge_forms.current_rows(history, forms, corpus, cache, model=model) + latest = {} + for canonical in sorted(decided): + latest[canonical] = decided[canonical] + for canonical in sorted(incomplete): + latest.setdefault(canonical, incomplete[canonical]) + committed = dict((row.get("unit"), row) for row in manifest) + problems = [] + for canonical in sorted(latest): + row = latest[canonical] + books = sorted(set(book for group in row["groups"] for book in group)) + unplaced = sorted(row.get("unplaced") or {}) + groups = len(row["groups"]) + was = committed.get(canonical) + if was is None: + problems.append("the manifest does not carry the form: " + canonical) + continue + if (was.get("books") or []) != books: + problems.append("the books read again are not the books of the manifest: " + canonical) + continue + if (was.get("unplaced") or []) != unplaced: + problems.append("the books left unplaced read again are not the books of the manifest: " + canonical) + continue + if was.get("groups") != groups: + problems.append("the groups read again are not the groups of the manifest: " + canonical) + for canonical in sorted(set(committed) - set(latest)): + problems.append("the manifest carries a form the ledger does not answer: " + canonical) + print("the forms read again:", len(latest), "| the forms of the manifest:", len(manifest)) + if problems: + print("FAILED: the answers read again are not the answers of the manifest,") + print(" and a manifest that does not match the evidence is not a build") + for problem in problems[:20]: + print(" ", problem) + if len(problems) > 20: + print(" and %d more" % (len(problems) - 20)) + return 1 + print("every answer read again from the evidence is the answer the manifest") + print(" carries, with the escalation replayed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/check_history_traces.py b/pipeline/scripts/check_history_traces.py new file mode 100644 index 00000000..dc040bca --- /dev/null +++ b/pipeline/scripts/check_history_traces.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Does the history of the corpus carry the traces of the copy? + +A corpus artefact records the book, not the copy, and that holds for the +history as well: a commit that carries the name of the place the file was +downloaded from is the same trace in a different place, and a reader who +knows the hash of the commit can still read the blob. + + python3 scripts/check_history_traces.py --corpus-root [--fresh] + +Every blob of every ref is read once, and the blobs already scanned are +remembered, so that the second run is quick. The commit messages are +read too: a message that names the collection is a trace as well. + +The patterns live here, in the tool, and not in the corpus repository: +the corpus must not carry them, and this file is not part of it. +""" +import argparse +import os +import re +import subprocess +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +# the places a copy is downloaded from +COLLECTIONS = ("Anna's Archive", "Anna\u2019s Archive", "Internet Archive", + "Archive.org", "Z-Library", "Library Genesis", "libgen", + "libgen.li", "z-lib", "Open Library", "HathiTrust") + + +def needles(): + """The patterns, and what each one is called.""" + out = [] + out.append(("a collection name", + re.compile("|".join(re.escape(name) for name in COLLECTIONS) + .encode("utf-8"), re.IGNORECASE))) + out.append(("the stamp of the digitisation", + re.compile(r"digitiz?ed\s+by".encode("utf-8"), re.IGNORECASE))) + # the name of the file the book was read from: only where the line says + # the file came from somewhere, because a book that mentions a file of + # its own is the book + out.append(("the name of the file the book was read from", + re.compile(r"(downloaded?|saved|copied|obtained|retrieved|scraped|" + r"extracted from|source file|the file|read from)[^\n]{0,80}" + r"\.(pdf|epub|djvu|mobi|azw3|rar|zip)\b".encode("utf-8"), + re.IGNORECASE))) + return out + + +NEEDLES = needles() + + +def is_provenance(line): + """Is this line one of the pipeline own headers?""" + body = (line or "").strip() + return body.startswith("Source:") or body.startswith("# ") + + +def which(blob): + """The patterns a blob carries.""" + out = [] + for label, pattern in NEEDLES: + match = pattern.search(blob) + if not match: + continue + if label.startswith("the name of the file"): + start = match.start() + line_start = blob.rfind(b"\n", 0, start) + 1 + line_end = blob.find(b"\n", start) + if line_end < 0: + line_end = len(blob) + line = blob[line_start:line_end].decode("utf-8", "replace") + if not is_provenance(line): + # the book own reference list, not the pipeline own header + continue + out.append(label) + return out + + +def object_list(repo): + """Every blob of every ref, with the path it was found at.""" + out = subprocess.run(["git", "-C", repo, "rev-list", "--objects", "--all"], + capture_output=True, text=True) + rows = [] + for line in out.stdout.splitlines(): + parts = line.split(" ", 1) + if len(parts) == 2 and parts[1]: + rows.append((parts[0], parts[1])) + return rows + + +def commit_messages(repo): + """Every commit message in the history.""" + out = subprocess.run(["git", "-C", repo, "log", "--all", "--format=%H%x00%B%x00"], + capture_output=True, text=True) + return out.stdout.split("\x00") + + +def scan_blobs(repo, shas): + """The blobs that carry a trace, read through one batch process.""" + hits = [] + proc = subprocess.Popen(["git", "-C", repo, "cat-file", "--batch"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + chunk = [] + + def read_chunk(chunk): + for sha in chunk: + header = proc.stdout.readline().decode("utf-8", "replace").split() + if len(header) < 3: + continue + size = int(header[2]) + blob = proc.stdout.read(size) + proc.stdout.read(1) + labels = which(blob) + if labels: + hits.append((sha, labels)) + + for sha in shas: + chunk.append(sha) + if len(chunk) >= 500: + proc.stdin.write(("\n".join(chunk) + "\n").encode("ascii")) + proc.stdin.flush() + read_chunk(chunk) + chunk = [] + if chunk: + proc.stdin.write(("\n".join(chunk) + "\n").encode("ascii")) + proc.stdin.flush() + read_chunk(chunk) + proc.stdin.close() + proc.stdout.read() + proc.wait() + return hits + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="check_history_traces.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--fresh", action="store_true", + help="read the blobs again, even the ones already scanned") + ap.add_argument("--record", action="store_true", + help="record the traces found as the known ones and pass") + args = ap.parse_args(argv) + repo = os.path.abspath(os.path.expanduser(args.corpus_root)) + cache_dir = os.path.join(HERE, "runs", "history-scan") + os.makedirs(cache_dir, exist_ok=True) + cache = os.path.join(cache_dir, "scanned.txt") + seen = set() + if os.path.exists(cache) and not args.fresh: + with open(cache, encoding="utf-8") as fh: + seen = set(line.strip() for line in fh if line.strip()) + rows = object_list(repo) + todo = [(sha, path) for sha, path in rows if sha not in seen] + hits = scan_blobs(repo, [sha for sha, _path in todo]) + paths = dict((sha, path) for sha, path in todo) + hit_shas = [sha for sha, _labels in hits] + known = os.path.join(cache_dir, "known-traces.txt") + recorded = set() + if os.path.exists(known): + with open(known, encoding="utf-8") as fh: + recorded = set(line.strip().split(" ", 1)[0] for line in fh + if line.strip()) + new_hits = [sha for sha in hit_shas if sha not in recorded] + for sha, labels in hits: + mark = "known" if sha in recorded else "NEW" + print("%-5s %s %s %s" % (mark, sha[:12], paths.get(sha, ""), + ", ".join(labels))) + message_hits = [] + for chunk in commit_messages(repo): + if chunk and which(chunk.encode("utf-8", "replace")): + message_hits.append(chunk.strip().splitlines()[0][:80]) + for line in message_hits: + print("commit message: %s" % line) + with open(cache, "a", encoding="utf-8") as fh: + for sha, _path in todo: + fh.write(sha + "\n") + if args.record and hits: + with open(known, "a", encoding="utf-8") as fh: + for sha in hit_shas: + fh.write("%s %s\n" % (sha, paths.get(sha, ""))) + print("recorded %d traces as the known ones" % len(hit_shas)) + print("blobs: %d | scanned now: %d | already scanned: %d | traces: %d new, %d known" + % (len(rows), len(todo), len(rows) - len(todo), len(new_hits), + len(hit_shas) - len(new_hits))) + if new_hits or message_hits: + print("FAILED: the history carries a trace of the copy that is not recorded") + return 1 + print("the history carries no new trace of the copy") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/check_inventory.py b/pipeline/scripts/check_inventory.py new file mode 100644 index 00000000..cafd5e0c --- /dev/null +++ b/pipeline/scripts/check_inventory.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +'''scripts/check_inventory.py - the README must say what the inventory says. + +The inventory is generated from the artefacts, so it cannot drift from them. +The README is written by hand, so it can. This gate reads the marked section +of the README and checks every number in it against the inventory, and checks +that the gaps the inventory names are the gaps the README names. + + python3 scripts/check_inventory.py --corpus-root +''' +import argparse +import json +import os +import re +import sys +import tempfile + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.join(HERE, 'scripts')) + +import build_inventory # noqa: E402 + + +def read_json(path, default=None): + try: + with open(path, encoding='utf-8') as fh: + return json.load(fh) + except Exception: + return default + +BEGIN = '' +END = '' + + +def required_problems(inventory, text=''): + """The identities the corpus must hold, and that no README may excuse. + + The list is the tool own, and not the one the inventory carries: an + inventory that left an identity out must not be able to say that the + identity was not needed. + """ + present = dict((item.get('name'), item) + for item in inventory.get('identities') or []) + problems = [] + for name in build_inventory.REQUIRED_IDENTITIES: + item = present.get(name) + if item is None: + problems.append('the inventory does not carry the identity: ' + name) + continue + state = item.get('state') + if state is None: + state = 'holds' if item.get('holds') else 'gap' + if state == 'gap': + problems.append('the identity does not hold: ' + name) + # the stages that have not run yet: the README has to say so, or a reader + # takes a library that is half built for a whole one + if inventory.get('not_built') and 'not built' not in text.lower(): + problems.append('the inventory has stages that have not run yet, and the' + ' README does not say so') + return problems + +# the labels the README uses, and the key of the inventory they carry +LABELS = [('books', 'books'), + ('book entries', 'book_entries'), + ('distinct names', 'distinct_names'), + ('names in more than one book', 'names_in_more_than_one_book'), + ('forms', 'forms'), + ('held back', 'held_back'), + ('concepts', 'concepts'), + ('concept entries', 'concept_entries'), + ('refused entries', 'refused_entries'), + ('figure blocks', 'figure_blocks'), + ('numbered paragraphs', 'paragraphs')] + + +def books_named_in_readme(text): + """The books the README names, out of the table of the books. + + The README is written by hand, so it is the one account of the books + that a build cannot rewrite: a book lost by the stage that reads the + books is still named here, and the gate says so. + """ + names = [] + lines = text.splitlines() + start = None + for index, line in enumerate(lines): + if line.strip().startswith('| Folder |'): + start = index + break + if start is None: + return names + for line in lines[start + 1:]: + stripped = line.strip() + if not stripped: + continue + if not stripped.startswith('|'): + break + cells = [cell.strip() for cell in stripped.strip('|').split('|')] + first = cells[0] + if first == 'Folder' or set(first) <= set('-:'): + continue + names.append(first) + return names + + +def number(text): + text = text.strip().replace(',', '') + match = re.search(r'-?[0-9]+', text) + return int(match.group(0)) if match else None + + +def main(argv=None): + ap = argparse.ArgumentParser(prog='check_inventory.py') + ap.add_argument('--corpus-root', required=True) + ap.add_argument('--readme', default='') + args = ap.parse_args(argv) + corpus = os.path.abspath(os.path.expanduser(args.corpus_root)) + readme_path = args.readme or os.path.join(corpus, 'README.md') + if not os.path.exists(readme_path): + print('FAILED: the corpus has no README, and the README is where the' + ' inventory is shown') + return 1 + with open(readme_path, encoding='utf-8') as fh: + readme = fh.read() + if BEGIN not in readme or END not in readme: + print('FAILED: the README has no marked inventory section') + return 1 + section = readme.split(BEGIN, 1)[1].split(END, 1)[0] + handle, path = tempfile.mkstemp(prefix='inventory-', suffix='.json') + os.close(handle) + code = build_inventory.main(['--corpus-root', corpus, '--out', path]) + with open(path, encoding='utf-8') as fh: + inventory = json.load(fh) + os.remove(path) + # the identities that no README may excuse: the corpus either holds them + # or it is broken, and a README that names the gap does not make it whole + broken = required_problems(inventory, readme) + if broken or code: + for problem in broken: + print('FAILED:', problem) + for item in inventory.get('identities') or []: + state = item.get('state') + if state is None: + state = 'holds' if item.get('holds') else 'gap' + if item.get('name') in build_inventory.REQUIRED_IDENTITIES \ + and state == 'gap': + print(' ', item['name'], ':', item['left'], 'against', item['right']) + for name in item.get('missing_forms') or []: + print(' the form the manifest does not carry:', name) + if not broken: + print('FAILED: the corpus does not hold the identity it must hold') + print(' and a README that names the gap does not excuse it') + return 1 + stated = {} + gaps = None + for line in section.splitlines(): + if '|' not in line: + continue + cells = [cell.strip() for cell in line.strip().strip('|').split('|')] + if len(cells) < 2: + continue + label = cells[0].split('(')[0].strip().lower() + value = cells[1].strip() + if label == 'gaps': + gaps = value + continue + stated[label] = number(value) + problems = [] + for label, key in LABELS: + if label not in stated: + problems.append('the README does not say the ' + label) + continue + expected = inventory['totals'].get(key) + if stated[label] != expected: + problems.append('the README says %s %s and the inventory says %s' + % (label, stated[label], expected)) + # the identities: the README names each one and gives the two numbers + # it holds between, so a drift in either is a gate failure and not a + # thing a reader has to notice + for item in inventory.get('identities') or []: + left = item.get('left') + right = item.get('right') + if left is None or right is None: + continue + # the README gives each identity its own line, and the line names + # the identity and carries its numbers, so the gate reads that line + name = item.get('name') or '' + line = None + for candidate in section.splitlines(): + if name and name in candidate: + line = candidate + break + if line is None: + problems.append('the README does not name the identity: ' + name) + continue + # a number is written with commas or with spaces, and the README may + # write it either way, so both forms are accepted + def forms(value): + return [str(value), ('{:,}'.format(value)), + ('{:,}'.format(value)).replace(',', ' ')] + wanted = forms(left) + if left != right: + wanted += forms(right) + if not any(one in line for one in wanted): + problems.append('the README does not give the numbers of %s' + % name) + named = [gap['name'] for gap in inventory.get('gaps') or []] + if not named: + if gaps is None or 'none' not in gaps.lower(): + problems.append('the inventory has no gaps and the README does not say so') + else: + if gaps is None: + problems.append('the inventory names gaps and the README does not') + else: + for name in named: + if name.split(' ')[0].lower() not in gaps.lower(): + problems.append('the README does not name the gap: ' + name) + # the evidence: a passage that sits exactly at the wide cap is evidence + # the builder could not keep whole, and the gate says so + settings = read_json(os.path.join(HERE, 'settings', 'pipeline.json'), {}) or {} + rule = (settings.get('index') or {}).get('link_rule') or {} + limit = rule.get('evidence_wide_cap_share_max') + share = (inventory.get('evidence') or {}).get('share_at_the_wide_cap') + if limit is not None and share is not None and share > limit: + problems.append('%.1f per cent of the passages sit exactly at the wide cap,' + ' and the limit is %.1f per cent' % (100 * share, 100 * limit)) + # the books the README names against the books of the corpus: the + # README is written by hand, so it is the one account of the books that + # a build cannot rewrite + named = books_named_in_readme(readme) + have = [row.get('book') for row in inventory.get('books') or []] + if named and set(named) != set(have): + problems.append('the books the README names and the books of the corpus' + ' are not the same') + problems.append('the README names: %s' % ', '.join(sorted(set(named) - set(have)))) + problems.append('the corpus holds: %s' % ', '.join(sorted(set(have) - set(named)))) + for problem in problems: + print('FAILED:', problem) + if problems: + return 1 + print('the README and the inventory agree:', + ', '.join('%s %s' % (label, stated[label]) for label, _ in LABELS)) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pipeline/scripts/check_minimal.py b/pipeline/scripts/check_minimal.py new file mode 100644 index 00000000..20e7c9bb --- /dev/null +++ b/pipeline/scripts/check_minimal.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""scripts/check_minimal.py - the proof that a rerun does the least. + +Written 26 Nov 2026 by MCode, after the ruling of Claude Opus 5.5 on the +corpus-wide term index (brief 13). + +"Provably minimal" is not a promise, it is a check. This script compares +the manifest of a stage now against the manifest of that stage as it was +committed, and it fails the run when the work was not the least it could +be. + +The three rules: + + * a unit whose key did not change must have the same output it had. + The same inputs gave different bytes, and that is never right. + * a unit whose key is new is a unit that had to be made: for the links + it must be a form that touches a book the corpus did not have, or a + form whose judge changed. Anything else is work that was not asked + for. + * a unit whose key is new must carry an output of its own: a unit that + was made for nothing is a unit that was not needed. + + python3 scripts/check_minimal.py --corpus-root --ref HEAD +""" +import argparse +import json +import os +import subprocess +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +STAGES = ("terms", "link", "assemble") + + +def read_jsonl(text): + rows = [] + for line in (text or "").splitlines(): + line = line.strip() + if line: + try: + rows.append(json.loads(line)) + except ValueError: + continue + return rows + + +def git(corpus, *args): + result = subprocess.run(["git"] + list(args), cwd=corpus, + capture_output=True, text=True) + return result.stdout + + +def old_manifest(corpus, stage, ref): + """The manifest of the stage as it was committed.""" + return read_jsonl(git(corpus, "show", "%s:index/manifest/%s.jsonl" + % (ref, stage))) + + +def old_books(corpus, ref): + """The books the corpus had before the change.""" + names = set() + for line in git(corpus, "ls-tree", "--name-only", ref).splitlines(): + path = os.path.join(corpus, line) + if os.path.isdir(path) and (os.path.isdir(os.path.join(path, "chapters")) + or os.path.exists(os.path.join(path, + "paragraphs.jsonl"))): + names.add(line) + return names + + +def new_books(corpus): + """The books the corpus has now.""" + names = set() + for line in os.listdir(corpus): + path = os.path.join(corpus, line) + if os.path.isdir(path) and not line.startswith("."): + if (os.path.isdir(os.path.join(path, "chapters")) + or os.path.exists(os.path.join(path, "paragraphs.jsonl"))): + names.add(line) + return names + + +def check_stage(corpus, stage, ref): + """The check for one stage.""" + path = os.path.join(corpus, "index", "manifest", "%s.jsonl" % stage) + if not os.path.exists(path): + return {"stage": stage, "ok": True, "note": "no manifest yet", + "problems": []} + with open(path, encoding="utf-8") as fh: + new_rows = read_jsonl(fh.read()) + old_rows = old_manifest(corpus, stage, ref) + if not old_rows: + # there is nothing to compare with: this is the first build of this + # stage, and everything is new. The next build is the one the + # check can hold to account. + return {"stage": stage, "ok": True, "old": 0, "new": len(new_rows), + "computed": len(new_rows), "reused": 0, + "note": "first build: no manifest to compare with", + "problems": []} + old_by_key = {} + old_by_unit = {} + for row in old_rows: + old_by_key[row["key"]] = row + old_by_unit[row.get("unit")] = row + new_by_key = {row["key"]: row for row in new_rows} + computed = set(new_by_key) - set(old_by_key) + reused = set(new_by_key) & set(old_by_key) + problems = [] + for key in sorted(reused): + before = old_by_key[key] + after = new_by_key[key] + if (before.get("content") or "") != (after.get("content") or ""): + # the question changed, so the answer may change with it + continue + if (before.get("output") or "") != (after.get("output") or ""): + problems.append("the same question gave different bytes: %s" + % after.get("unit")) + break + if stage == "link": + fresh = new_books(corpus) - old_books(corpus, ref) + for key in sorted(computed): + row = new_by_key[key] + books = row.get("books") or [] + if [name for name in books if name in fresh]: + continue + before = old_by_unit.get(row.get("unit")) + if before is None: + continue + if before.get("model") != row.get("model"): + # the judge changed, so every answer had to be given again + continue + if sorted(before.get("books") or []) != sorted(row.get("books") or []): + # the books the form is in changed, so the question is not + # the question that was asked before, even when the passages + # that carry it are the same + continue + if (before.get("content") or "") != (row.get("content") or ""): + # the question itself changed, so the answer had to be + # given again + continue + problems.append("a form was judged that no new book is in, " + "that no judge changed and whose terms did not " + "change: %s" % row.get("unit")) + break + return {"stage": stage, "ok": not problems, "old": len(old_by_key), + "new": len(new_by_key), "computed": len(computed), + "reused": len(reused), "problems": problems} + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="check_minimal.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--ref", default="HEAD") + ap.add_argument("--stage", default="") + args = ap.parse_args(argv) + corpus = args.corpus_root + stages = [args.stage] if args.stage else list(STAGES) + failed = 0 + for stage in stages: + report = check_stage(corpus, stage, args.ref) + print("%-9s old %4d | new %4d | computed %4d | reused %4d | %s%s" + % (stage, report.get("old", 0), report.get("new", 0), + report.get("computed", 0), report.get("reused", 0), + "ok" if report["ok"] else "FAILED", + (" (%s)" % report["note"]) if report.get("note") else "")) + for problem in report.get("problems") or []: + print(" %s" % problem) + if not report["ok"]: + failed += 1 + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/check_reader_browser.py b/pipeline/scripts/check_reader_browser.py new file mode 100755 index 00000000..79b263ad --- /dev/null +++ b/pipeline/scripts/check_reader_browser.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Drive a reader in a real browser and report what happened. + +The reader's search, its jump, its filter and its progress bar are +JavaScript, and a screenshot cannot show whether they work. This copies a +reader, adds a script that drives them, and asks a headless browser what +the result was. +""" +import json, os, re, subprocess, sys, tempfile + +CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" + +TEST = r""" + +""" + + +def main(argv): + if not os.path.exists(CHROME): + # a machine with no browser cannot run it; the check is not a + # failure there, it is simply not available + print("skipped: no Chrome at %s" % CHROME) + return 0 + reader = argv[0] if argv else os.path.expanduser( + "//index.html") + if not os.path.exists(reader): + print("skipped: no reader at %s" % reader) + return 0 + # the number of pictures the book declares, so that a check which + # examined nothing cannot pass: the reader must show the pictures the + # manifest says the book has + expected = 0 + manifest = os.path.join(os.path.dirname(reader), "figures.json") + if os.path.exists(manifest): + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + expected = len(data.get("figures") or []) + work = tempfile.mkdtemp(prefix="reader-browser-") + copy = os.path.join(work, "reader.html") + html = open(reader, encoding="utf-8").read() + # the word to search for comes from the book itself, so the check means + # something on every book and not only on the ones that happen to + # contain a common word + word = "" + title = re.search(r"(.*?)", html, re.S) + if title: + for candidate in re.findall(r"[A-Za-z]{8,}", title.group(1)): + word = candidate.lower() + break + if not word: + word = "the" + html = html.replace("", TEST.replace("SEARCHWORD", word) + "", 1) + with open(copy, "w", encoding="utf-8") as fh: + fh.write(html) + profile = os.path.join(work, "profile") + result = subprocess.run( + [CHROME, "--headless", "--disable-gpu", "--user-data-dir=" + profile, + "--virtual-time-budget=15000", "--dump-dom", "file://" + copy], + capture_output=True, text=True) + match = re.search(r"(.*?)", result.stdout, re.S) + if not match or not match.group(1).startswith("RESULT"): + print("the reader did not answer; the browser said:") + print(result.stdout[:400]) + print(result.stderr[:400]) + return 1 + print(match.group(1).replace(" | ", "\n")) + # a check that examined nothing has proved nothing: the reader must + # show the pictures the manifest declares + found = re.search(r"pictures=(\d+)", match.group(1)) + pictures = int(found.group(1)) if found else 0 + if expected and pictures < expected: + print("FAILED: the reader shows %d pictures and the manifest declares %d" + % (pictures, expected)) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/pipeline/scripts/check_readers.py b/pipeline/scripts/check_readers.py new file mode 100644 index 00000000..532d95b6 --- /dev/null +++ b/pipeline/scripts/check_readers.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Check the committed readers against the notes they were made from. + +The build needs the picture library; this check does not. It reads the +reader, the notes and the manifest that names the pictures, and asks the +gate the same questions it asks at build time: is this reader still the +notes, are the pictures there, is anything pointing outside the book. + + python3 scripts/check_readers.py --corpus-root +""" +import argparse +import json +import os +import re +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from book2corpus import notes_gate +from book2corpus import stamp + +HOSTED_RE = re.compile(r'src="(https?://[^"]+?/figures/)') +ID_RE = re.compile(r'id="([^"]+)"') +HREF_RE = re.compile(r'href="#([^"]+)"') + + +def check_machine_reader(book_dir, reader_path): + """A machine corpus's reader, checked against the corpus it was made from. + + A machine corpus keeps its paragraphs in paragraphs.jsonl. The reader + must carry every one of them, must not be missing a single paragraph + from the corpus it claims to show, and must not point at an id it does + not have. + """ + problems = [] + records = [] + with open(os.path.join(book_dir, "paragraphs.jsonl"), encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + records.append(json.loads(line)) + with open(reader_path, encoding="utf-8") as fh: + html = fh.read() + ids = set(ID_RE.findall(html)) + wanted = {r.get("id") for r in records if r.get("id")} + missing = wanted - ids + if missing: + problems.append("%d paragraphs of the corpus are not in the reader" + % len(missing)) + if "{{" in html: + problems.append("the reader has a placeholder that was never filled in") + broken = {h for h in HREF_RE.findall(html) if h and h not in ids} + if broken: + problems.append("%d links in the reader point at ids that are not there" + % len(broken)) + # and the words: the reader must show the corpus paragraph by paragraph, + # which is the question the machine corpus's own gate asks + try: + from book2corpus import verify + scan = verify._ReaderScan() + scan.feed(html) + rendered = {} + for pid, text in scan.units: + rendered.setdefault(pid, verify._norm(text)) + differing = 0 + for record in records: + want = verify._norm(record.get("text")) + got = rendered.get(record.get("id")) + if got is None or got != want: + differing += 1 + if differing: + problems.append("%d paragraphs of the corpus differ in the reader" + % differing) + except Exception as exc: + problems.append("the reader could not be read back: %s" % exc) + return problems + + +def stamp_difference(found): + """What changed in the tool between the reader and today.""" + today = set(stamp.tool_state(HERE)["files"]) + then = set(found.get("files") or []) + added = sorted(today - then) + gone = sorted(then - today) + if not added and not gone: + return "" + parts = [] + if added: + parts.append("now covered: " + ", ".join(added[:4])) + if gone: + parts.append("no longer covered: " + ", ".join(gone[:4])) + return " (" + "; ".join(parts) + ")" + + +def stamp_problems(html, root, book): + """What the reader's stamp says about it, and what it should say. + + A reader without a stamp cannot be checked, and a reader whose + stamp is older than the index it shows is a reader of another + corpus. Both fail: a stale reader that passes the gate is worse + than no reader at all. + """ + found = stamp.read_stamp(html) + if not found: + return ["the reader has no build stamp"] + problems = [] + if found["index"] != stamp.index_hash(root, book): + problems.append("the reader was built from another index") + if found["tool"] != stamp.tool_hash(HERE): + problems.append("the reader was built by another version of the tool" + + stamp_difference(found)) + return problems + + +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--picture-base", default="", + help="the host the pictures come from, if not the book") + args = parser.parse_args(argv) + root = os.path.abspath(os.path.expanduser(args.corpus_root)) + + failed = [] + checked = 0 + for book in sorted(os.listdir(root)): + book_dir = os.path.join(root, book) + reader = os.path.join(book_dir, "index.html") + manifest = os.path.join(book_dir, "figures.json") + if not os.path.exists(reader) or not os.path.exists(manifest): + continue + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + with open(reader, encoding="utf-8") as fh: + html = fh.read() + base = args.picture_base + if not base: + found = HOSTED_RE.search(html) + if found: + base = found.group(1).rstrip("/") + base = base[: base.rindex("/")] if "/" in base[len("http"):] else base + if os.path.exists(os.path.join(book_dir, "paragraphs.jsonl")): + # a machine corpus: its own reader, its own paragraphs, its own gate + problems = check_machine_reader(book_dir, reader) + else: + built = {"manifest": data.get("figures", []), + "figure_map": data.get("figure_map", [])} + problems = notes_gate.check(book_dir, built, html, picture_base=base or None) + problems.extend(stamp_problems(html, root, book)) + checked += 1 + if problems: + failed.append((book, problems)) + print("%-28s FAILED %s" % (book, problems[0])) + else: + print("%-28s ok" % book) + # the readers and the books the corpus knows about are the same books + terms_dir = os.path.join(root, "index", "terms") + books = set() + if os.path.isdir(terms_dir): + for name in os.listdir(terms_dir): + if name.endswith(".jsonl"): + books.add(name[:-6]) + if books and len(books) != checked: + failed.append(("readers", ["the corpus knows %d books and there" + % len(books)])) + failed[-1][1].append("are %d readers" % checked) + print("ALARM: the corpus knows %d books and there are %d readers" + % (len(books), checked)) + print() + print("readers checked: %d | failed: %d" % (checked, len(failed))) + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/check_reproducible.py b/pipeline/scripts/check_reproducible.py new file mode 100755 index 00000000..b47b5c56 --- /dev/null +++ b/pipeline/scripts/check_reproducible.py @@ -0,0 +1,539 @@ +#!/usr/bin/env python3 +"""Is the build reproducible? Build the same book twice and compare. + +The readers are committed to a repository, so the build that makes them +has to give the same bytes every time: on any machine, under any hash +seed, with the folders listed in any order, with the parse cache warm or +cold. This test builds a small book of notes against a small catalogue of +pictures, twice, and compares the two readers byte for byte. + +It also proves the test can see a difference: a control that must differ, +and a planted fault that must be caught. + + python3 scripts/check_reproducible.py +""" +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +BUILD = os.path.join(HERE, "scripts", "md_corpus2html.py") + +NOTES = { + "01 The first chapter.md": """# The first chapter + +Source: A Test Book (2026) + +=== PAGE 7 (PDF page 9) === + +The first paragraph of the test book, long enough to be a sentence of its own. + +[FIGURE 1] +TYPE: diagram +CAPTION: Figure 1.1 A test diagram +CONTENT: A box with an arrow pointing at another box, which is what a test diagram is. +TEXT IN FIGURE: none +-- + +=== PAGE 8 (PDF page 10) === + +A second paragraph, with a figure that has no number. + +[FIGURE unnumbered] +TYPE: illustration +CAPTION: A picture of a lamp +CONTENT: A lamp on a table, lit, standing next to a window. +TEXT IN FIGURE: none +-- + +[FIGURE unnumbered] +TYPE: photograph +CAPTION: A photograph of a chair +CONTENT: A wooden chair by a door, seen from the side, with a coat on its back. +TEXT IN FIGURE: none +-- + +[FIGURE unnumbered] +TYPE: diagram +CAPTION: A diagram of a door +CONTENT: A rectangle with an arrow pointing at it, which the catalogue does not describe. +TEXT IN FIGURE: none +-- +""", + "02 The second chapter.md": """# The second chapter + +Source: A Test Book (2026) + +=== PAGE 11 (PDF page 13) === + +A third paragraph, and a figure that the catalogue also holds. + +[FIGURE 2] +TYPE: diagram +CAPTION: Figure 2.1 Another test diagram +CONTENT: Two circles joined by a line, which is what another test diagram is. +TEXT IN FIGURE: none +-- + +[FIGURE 2.2] +TYPE: diagram +CAPTION: Figure 2.2 A third test diagram +CONTENT: A circle with a dot in the middle, which is what a third test diagram is. +TEXT IN FIGURE: none +-- +""", +} + +# a one pixel PNG, the smallest picture a book can hold +PNG = bytes.fromhex( + "89504e470d0a1a0a0000000d494844520000000100000001080600000" + "01f15c4890000000a49444154789c6300010000050001" + "0d0a2db40000000049454e44ae426082") + + +RECORDS = [ + {"id": "Test-0001", "book": "Test", "file": "Test/chapters/one.png", + "page": "7", "printed_page": "7", "chapter": "01 The first chapter", + "caption": "Figure 1.1 A test diagram", + "description": "A box with an arrow pointing at another box, which is what a test diagram is.", + "figure": "1.1", "kind": "raster"}, + {"id": "Test-0002", "book": "Test", "file": "Test/chapters/two.png", + "page": "8", "printed_page": "8", "chapter": "01 The first chapter", + "caption": "A picture of a lamp", + "description": "A lamp on a table, lit, standing next to a window.", + "figure": "", "kind": "raster"}, + {"id": "Test-0004", "book": "Test", "file": "Test/chapters/four.png", + "page": "8", "printed_page": "8", "chapter": "01 The first chapter", + "caption": "A photograph of a chair", + "description": "A wooden chair by a door, seen from the side, with a coat on its back.", + "figure": "", "kind": "raster"}, + {"id": "Test-0003", "book": "Test", "file": "Test/chapters/three.png", + "page": "11", "printed_page": "11", "chapter": "02 The second chapter", + "caption": "Figure 2.1 Another test diagram", + "description": "Two circles joined by a line, which is what another test diagram is.", + "figure": "2.1", "kind": "raster"}, + {"id": "Test-0005", "book": "Test", "file": "Test/chapters/five.png", + "page": "8", "printed_page": "8", "chapter": "01 The first chapter", + "caption": "A picture of a window", + "description": "A window with the curtains drawn back, showing a garden.", + "figure": "", "kind": "raster"}, + {"id": "Test-0006", "book": "Test", "file": "Test/chapters/six.png", + "page": "8", "printed_page": "8", "chapter": "01 The first chapter", + "caption": "A picture of a tree", + "description": "A tree in a garden, seen against the sky.", + "figure": "", "kind": "raster"}, + {"id": "Test-0007", "book": "Test", "file": "Test/chapters/seven.png", + "page": "11", "printed_page": "11", "chapter": "02 The second chapter", + "caption": "Figure 2.2 A third test diagram", + "description": "A circle with a dot in the middle, which is what a third test diagram is.", + "figure": "2.2", "kind": "raster"}, +] + + +# A book whose two figures the catalogue cannot tell apart: the same +# number, the same description, two pictures. Nothing decides between +# them, so nothing may be claimed. +TIE_NOTES = { + "01 The tie chapter.md": """# The tie chapter + +Source: A Test Book (2026) + +=== PAGE 3 (PDF page 5) === + +Two figures the catalogue cannot tell apart. + +[FIGURE 1.1] +TYPE: diagram +CAPTION: Figure 1.1 A test diagram +CONTENT: A box with an arrow pointing at another box, which is what a test diagram is. +TEXT IN FIGURE: none +-- + +[FIGURE 1.1] +TYPE: diagram +CAPTION: Figure 1.1 A test diagram +CONTENT: A box with an arrow pointing at another box, which is what a test diagram is. +TEXT IN FIGURE: none +-- +"""} + +TIE_RECORDS = [ + {"id": "Tie-0001", "book": "Tie", "file": "Tie/chapters/one.png", + "page": "3", "printed_page": "3", "chapter": "01 The tie chapter", + "caption": "Figure 1.1 A test diagram", + "description": "A box with an arrow pointing at another box, which is what a test diagram is.", + "figure": "1.1", "kind": "raster"}, + {"id": "Tie-0002", "book": "Tie", "file": "Tie/chapters/two.png", + "page": "3", "printed_page": "3", "chapter": "01 The tie chapter", + "caption": "Figure 1.1 A test diagram", + "description": "A box with an arrow pointing at another box, which is what a test diagram is.", + "figure": "1.1", "kind": "raster"}, +] + + +def records_in_order(): + """The catalogue records, in the order they are written by default.""" + return [dict(record) for record in RECORDS] + + +def picture_library(root, order=None): + """A small catalogue: four pictures, one page of the test book holding + two of them, so that one figure has more than one candidate.""" + os.makedirs(os.path.join(root, "book", "chapters"), exist_ok=True) + records = records_in_order() + for record in records: + path = os.path.join(root, record["file"]) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as fh: + fh.write(PNG) + with open(os.path.join(root, "agent-index.jsonl"), "w", encoding="utf-8") as fh: + for record in (order if order is not None else records): + fh.write(json.dumps(record, sort_keys=True) + '\n') + + +def notes_corpus(root, order, mutate=False): + """The notes, written in the order given, so the folder listing differs.""" + book = os.path.join(root, "corpus", "Test") + os.makedirs(os.path.join(book, "chapters"), exist_ok=True) + for name in order: + text = NOTES[name] + if mutate and name.startswith("02"): + text = text.replace("Figure 2.1 Another test diagram", + "Figure 2.1 Another test diagram, changed") + with open(os.path.join(book, "chapters", name), "w", encoding="utf-8") as fh: + fh.write(text) + return os.path.join(root, "corpus") + + +def tie_corpus(root): + """A book whose figures the catalogue cannot tell apart.""" + book = os.path.join(root, "corpus", "Tie") + os.makedirs(os.path.join(book, "chapters"), exist_ok=True) + for name, text in TIE_NOTES.items(): + with open(os.path.join(book, "chapters", name), "w", encoding="utf-8") as fh: + fh.write(text) + return os.path.join(root, "corpus") + + +def tie_library(root, order=None): + """The catalogue of the tie book: two pictures that look the same.""" + os.makedirs(os.path.join(root, "book", "chapters"), exist_ok=True) + for record in TIE_RECORDS: + path = os.path.join(root, record["file"]) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as fh: + fh.write(PNG) + with open(os.path.join(root, "agent-index.jsonl"), "w", encoding="utf-8") as fh: + for record in (order if order is not None else TIE_RECORDS): + fh.write(json.dumps(record, sort_keys=True) + "\n") + + +def build(corpus, library, seed, env=None, order=None, force=True, books="Test", + extra=None): + """Build the book and return the bytes of what it wrote.""" + environment = dict(os.environ) + environment["PYTHONHASHSEED"] = str(seed) + if env: + environment.update(env) + command = [sys.executable, BUILD, "--corpus-root", corpus, "--library", library, + "--books", books, "--jobs", "1"] + if force: + command.append("--force") + if extra: + command.extend(extra) + result = subprocess.run(command, capture_output=True, text=True, + env=environment) + if result.returncode: + raise SystemExit("the build failed:\n%s\n%s" % (result.stdout, result.stderr)) + reader = os.path.join(corpus, books, "index.html") + with open(reader, "rb") as fh: + data = fh.read() + with open(os.path.join(corpus, books, "figures.json"), "rb") as fh: + manifest = fh.read() + return data, manifest, result.stdout + + +def same(a, b): + return hashlib.sha256(a).hexdigest() == hashlib.sha256(b).hexdigest() + + +def swapped_records(): + """The catalogue with two descriptions exchanged: a picture swapped.""" + records = records_in_order() + by_id = {record["id"]: record for record in records} + first = by_id["Test-0003"]["description"] + second = by_id["Test-0007"]["description"] + by_id["Test-0003"]["description"] = second + by_id["Test-0007"]["description"] = first + return records + + +def moved_records(): + """The catalogue with one picture taken from another book's folder.""" + records = records_in_order() + for record in records: + if record["id"] == "Test-0001": + record["file"] = "Elsewhere/chapters/one.png" + return records + + +def build_and_report(corpus, library, books="Test"): + """Build and say what the gate said, without raising.""" + result = subprocess.run( + [sys.executable, BUILD, "--corpus-root", corpus, "--library", library, + "--books", books, "--force", "--jobs", "1"], + capture_output=True, text=True) + return result.returncode, result.stdout + result.stderr + + +def real_corpus(): + """The library the check compares a real book of, if there is one. + + The environment names it, and the settings of the run name it, and a + library that has neither simply does without a real book. + """ + corpus = os.environ.get("B2C_CORPUS_ROOT", "") + if corpus: + return corpus + settings = os.path.join(HERE, "settings", "pipeline.json") + if not os.path.exists(settings): + return "" + try: + with open(settings, encoding="utf-8") as fh: + return (json.load(fh) or {}).get("corpus_root") or "" + except Exception: + return "" + + +def real_book_check(work, corpus, checks): + """A real book, with its pictures, built twice.""" + if not os.path.isdir(corpus): + return + candidates = [] + for name in sorted(os.listdir(corpus)): + reader = os.path.join(corpus, name, "index.html") + manifest = os.path.join(corpus, name, "figures.json") + if not (os.path.exists(reader) and os.path.exists(manifest)): + continue + try: + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + except Exception: + continue + shown = sum(1 for f in data.get("figure_map", []) if f.get("image")) + if shown < 10: + continue + candidates.append((os.path.getsize(reader), name)) + if not candidates: + return + candidates.sort() + name = candidates[0][1] + # the book, its notes and the policy that governs its pictures, copied + # out of the corpus so that the corpus itself is not touched + book_root = os.path.join(work, "real", "corpus", name) + shutil.copytree(os.path.join(corpus, name, "chapters"), + os.path.join(book_root, "chapters")) + for extra in ("picture-policy.json", "picture-verdicts.jsonl"): + source = os.path.join(corpus, extra) + if os.path.exists(source): + shutil.copy(source, os.path.join(work, "real", "corpus", extra)) + library = os.environ.get("B2C_LIBRARY") or os.path.expanduser( + "~/Library/Mobile Documents/com~apple~CloudDocs/Textbooks") + if not os.path.isdir(library): + return + code, output = build_and_report(os.path.join(work, "real", "corpus"), + library, books=name) + ok = code == 0 + checks.append(("A real book passes its own gate", ok, + "passed" if ok else "failed:\n%s" % output[-600:])) + if not ok: + return + reader = os.path.join(work, "real", "corpus", name, "index.html") + with open(reader, "rb") as fh: + data = fh.read() + # every picture file is the file the manifest says it is + with open(os.path.join(work, "real", "corpus", name, "figures.json"), + encoding="utf-8") as fh: + manifest = json.load(fh) + bad = [] + for entry in manifest.get("figures", []): + path = os.path.join(work, "real", "corpus", name, entry["derivative_file"]) + if not os.path.exists(path): + bad.append(entry["derivative_file"]) + continue + with open(path, "rb") as fh: + digest = hashlib.sha256(fh.read()).hexdigest() + if digest != entry.get("derivative_sha256"): + bad.append(entry["derivative_file"]) + checks.append(("Every picture is the file the manifest says", not bad, + "they are" if not bad else "wrong: %s" % ", ".join(bad[:3]))) + # one picture, one figure, unless the sharing is declared + shared = {} + for figure in manifest.get("figure_map", []): + if figure.get("image"): + shared.setdefault(figure["image"], []).append(figure) + undeclared = [image for image, group in shared.items() + if len(group) > 1 and not group[0].get("shared_with")] + checks.append(("A picture is used by one figure, unless it is declared", + not undeclared, + "they are" if not undeclared else + "%d pictures are used twice" % len(undeclared))) + + +def main(argv=None): + work = tempfile.mkdtemp(prefix="book2corpus-repro-") + checks = [] + try: + # two catalogues: the same pictures, written down in the other order + library = os.path.join(work, "library") + library_b = os.path.join(work, "library-b") + picture_library(library) + picture_library(library_b, order=list(reversed(records_in_order()))) + + names = sorted(NOTES) + forward = notes_corpus(os.path.join(work, "a"), names) + backward = notes_corpus(os.path.join(work, "b"), list(reversed(names))) + + reader_a, manifest_a, _ = build(forward, library, 1) + reader_b, manifest_b, _ = build(backward, library, 2) + checks.append(("Hash seeds 1 and 2", same(reader_a, reader_b), + "the readers differ" if not same(reader_a, reader_b) else "the same, byte for byte")) + checks.append(("The manifest, likewise", same(manifest_a, manifest_b), + "the same, byte for byte" if same(manifest_a, manifest_b) else "the manifests differ")) + + # the folders listed in the other order + reader_c, _, _ = build(backward, library_b, 1) + checks.append(("The catalogue in the other order", same(reader_a, reader_c), + "the same, byte for byte" if same(reader_a, reader_c) else "the readers differ")) + + # the control: the test must be able to see a difference + control_a, _, _ = build(forward, library, 1, + env={"B2C_MATCH": "off"}) + checks.append(("Matching off: the control", + not same(reader_a, control_a), + "the readers differ, as they must" if not same(reader_a, control_a) + else "the control did not differ: the test cannot see")) + legacy, _, _ = build(forward, library, 1, env={"B2C_ORDER": "legacy"}) + checks.append(("The old order of the manifest: the control", + not same(manifest_a, legacy), + "the manifest differs, as it must" + if not same(manifest_a, legacy) + else "the control did not differ: the test cannot see")) + + # a planted fault: a caption changed must change the reader + planted_corpus = notes_corpus(os.path.join(work, "c"), names, mutate=True) + reader_d, _, _ = build(planted_corpus, library, 1) + checks.append(("A planted change to a caption", not same(reader_a, reader_d), + "found" if not same(reader_a, reader_d) else "not found: the test is blind")) + + # an incremental build must give the same bytes as a clean one + clean_corpus = notes_corpus(os.path.join(work, "inc-clean"), names) + clean_reader, clean_manifest, _ = build(clean_corpus, library, 1) + inc_corpus = notes_corpus(os.path.join(work, "inc"), names) + build(inc_corpus, library, 1, force=False) + chapter = os.path.join(inc_corpus, "Test", "chapters", + "02 The second chapter.md") + os.utime(chapter, None) + inc_reader, inc_manifest, output = build(inc_corpus, library, 1, force=False) + checks.append(("An incremental build equals a clean one", + same(clean_reader, inc_reader) + and same(clean_manifest, inc_manifest), + "the same, byte for byte" + if same(clean_reader, inc_reader) else "the readers differ")) + checks.append(("A book whose notes were touched is left alone", + "unchanged" in output, + "left alone" if "unchanged" in output + else "it was rebuilt: the key followed the date")) + + # the reader must not depend on the locale or the timezone + for name, env in (("the locale", {"LC_ALL": "C"}), + ("the locale, in UTF-8", {"LC_ALL": "en_US.UTF-8"}), + ("the timezone", {"TZ": "UTC"}), + ("the timezone, east of it", {"TZ": "Pacific/Auckland"})): + reader_x, _, _ = build(forward, library, 1, env=env) + checks.append(("The reader does not depend on %s" % name, + same(reader_a, reader_x), + "it does not" if same(reader_a, reader_x) + else "the readers differ")) + + # a tie is a coin toss, and nothing may be claimed + tie_lib = os.path.join(work, "tie-library") + tie_library(tie_lib) + tie_book = tie_corpus(os.path.join(work, "tie")) + tie_reader, tie_manifest, _ = build(tie_book, tie_lib, 1, books="Tie") + with open(os.path.join(tie_book, "Tie", "figures.json"), + encoding="utf-8") as fh: + tie_map = json.load(fh) + refusals = [f for f in tie_map.get("figure_map", []) if f.get("refusal")] + tied = (len(refusals) == 2 + and all(r["refusal"].get("tie") for r in refusals) + and all(r["refusal"].get("margin") == 0 for r in refusals)) + checks.append(("A tie is left unclaimed, with the margin written down", + tied, + "it is" if tied else "the figures claimed: %s" + % [f.get("tier") for f in tie_map.get("figure_map", [])])) + orders = [] + for index, order in enumerate((TIE_RECORDS, list(reversed(TIE_RECORDS))), 1): + lib = os.path.join(work, "tie-library-%d" % index) + tie_library(lib, order=order) + reader_x, _, _ = build(tie_book, lib, 1 + index, books="Tie") + orders.append(reader_x) + checks.append(("A tie gives the same reader whatever the order", + same(orders[0], orders[1]), + "it does" if same(orders[0], orders[1]) + else "the readers differ")) + + # the planted faults: a picture swapped, and a picture moved + swap_library = os.path.join(work, "swap-library") + picture_library(swap_library, order=swapped_records()) + code, output = build_and_report(forward, swap_library) + # the number the book printed stands against a description that + # reads differently, so a swap is a finding for the audit and not + # a failure of the book: it must be written down all the same + suspects = [] + try: + with open(os.path.join(forward, "Test", "notes-report.json"), + encoding="utf-8") as fh: + suspects = json.load(fh).get("suspects") or [] + except Exception: + suspects = [] + found = [s for s in suspects if "swapped" in s] + checks.append(("A swapped picture is found and written down", + bool(found), + "found: %s" % found[0] if found + else "not found:\n%s" % output[-600:])) + move_library = os.path.join(work, "move-library") + picture_library(move_library, order=moved_records()) + code, output = build_and_report(forward, move_library) + checks.append(("A picture moved from another book is caught", + code != 0 and "another book" in output, + "caught" if (code != 0 and "another book" in output) + else "not caught:\n%s" % output[-600:])) + + # and a real book, with its pictures: the library that is being + # built, so that the check is not tied to one corpus + real_book_check(work, os.path.expanduser(real_corpus()), checks) + + print("Reproducible build check") + print() + print("| Check | Result |") + print("| --- | --- |") + for name, ok, detail in checks: + print("| %s | %s |" % (name, detail)) + print() + failed = [name for name, ok, _ in checks if not ok] + if failed: + print("FAILED: %s" % ", ".join(failed)) + return 1 + print("every check held.") + return 0 + finally: + shutil.rmtree(work, ignore_errors=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/check_settings.py b/pipeline/scripts/check_settings.py new file mode 100644 index 00000000..26a11cbc --- /dev/null +++ b/pipeline/scripts/check_settings.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""scripts/check_settings.py - the settings name a library. + + python3 scripts/check_settings.py --corpus-root + +The settings of a library are its own, and the build reads them from the +environment variable B2C_SETTINGS. A settings file that still carries the +placeholders of the template has not been filled in, and a build that read it +would build nothing and say nothing. This says it instead. +""" +import argparse +import os +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus.pipeline import Settings # noqa: E402 + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="check_settings.py") + ap.add_argument("--corpus-root", required=True) + args = ap.parse_args(argv) + settings = Settings() + problem = settings.problem() + if problem: + print("FAILED:", problem) + print(" the settings that were read are in:", settings.path) + return 2 + root = os.path.abspath(os.path.expanduser(args.corpus_root)) + named = os.path.abspath(os.path.expanduser(settings.values.get("corpus_root"))) + if named != root: + print("FAILED: the settings name another library:", named) + print(" and this build is of:", root) + return 2 + print("the settings name this library:", root) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/check_source_traces.py b/pipeline/scripts/check_source_traces.py new file mode 100644 index 00000000..d9b892e1 --- /dev/null +++ b/pipeline/scripts/check_source_traces.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""The gate for the traces of the copy: does a corpus name where it came from? + +A corpus artefact records the book, not the copy. The name of the place +the file was downloaded from, the name of that file and the hash of that +file identify a copy, and a corpus that carries them points at where a +copy can be found. So they are not allowed, and this is the gate that +looks for them: a corpus with a trace in it does not pass. + + python3 scripts/check_source_traces.py + +WHAT IT READS: every .md, .jsonl, .json and .html file in the tree, and +the search index. The number of files examined of each type is printed, +because a gate that examined nothing has proved nothing: if a type that +was expected held no file at all, the run fails. + +WHAT IT LOOKS FOR: the name of a place a copy is downloaded from, the +digitisation stamp that says who scanned the book, the hash of the file +the book was read from standing on its own, and the name of that file. + +The rewriter is the other script: scripts/scrub_source_traces.py takes the +old download headers out. A manifest that names the copy is not rewritten +blindly - the tool writes that field, so the build writes it again. +""" +import argparse +import collections +import os +import re +import sys + +# the places a copy is downloaded from +COLLECTIONS = ("Anna's Archive", "Anna\u2019s Archive", "Internet Archive", + "Archive.org", "Z-Library", "Library Genesis", "libgen", + "libgen.li", "z-lib", "Open Library", "HathiTrust") + +# a book that mentions a file of its own is the book: the name of a file +# is a trace only where the line says the file was read from somewhere +FILE_NAME_RE = re.compile( + rb"(?i)(downloaded?|saved|copied|obtained|retrieved|scraped|extracted from|" + rb"source file|the file|read from)[^\n]{0,80}" + rb"\.(pdf|epub|djvu|mobi|azw3|rar|zip)\b") + +# the hash of the file the book was read from, standing on its own: not +# part of a longer token, and not part of an address +FILE_HASH_RE = re.compile(rb"(? + +What it writes: + + index/links/forms.jsonl the forms: one row per canonical form + index/links/form-judgments.jsonl the ledger: one row per form + index/concepts.jsonl the concepts: the groups + index/review.jsonl the books the model could not place + index/manifest/link.jsonl one row per form: key, status +""" +import argparse +import collections +import hashlib +import json +import os +import random +import sys +import threading +import time +from concurrent.futures import ThreadPoolExecutor + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus.judge import Judge # noqa: E402 +from book2corpus.pipeline import (CircuitBreaker, Ledger, # noqa: E402 + Settings, hash_of) + +# the most books one call may carry +MAX_BOOKS_PER_CALL = 20 + +# the passage a book is shown in the first place: the sentence that has +# the term, cut here. A book whose passage shows no sense is asked again +# with the wide window, and only then is it unplaced. +EVIDENCE_NARROW = 300 + +# the passage a book is shown, and the window the judge reads it in. The +# window is the one the blind readers are given, so that a read of the judge +# is a read of the same evidence: a judge that sees less cannot be measured +# against a reader that sees more. +EVIDENCE_WINDOW = 2000 + +# what an answer is assumed to cost: the measured mean of a link answer is +# 41 tokens and the measured worst is under 200, and the pre-flight must +# not be a guess +OUTPUT_TOKENS = 120 + +FORM_PROMPT = """You are given one term and every book in a corpus that uses it. + +Book | the term as the book writes it | the passage the code found it in +%s + +THE QUESTION: in how many different senses do these books use this term? + +Every book gets one of three answers. + +* The same sense as another book: put it in that group. +* A different sense from the others: put it in a group of its own. +* No sense at all: the passage does not show which sense the book means. + +A passage that gives no sense is a contents line, a key-terms list, an index +entry, a heading with no sentence around it, or a passage that names the term +without using it. Such a book is UNPLACED: it is not a sense of its own, and +it is not the same sense as anything either. Do not group it and do not +separate it. + +PLACING A BOOK. Place a book only if the passage has a sentence that uses the +term and says what it is or does. Write the gloss using words from the +passage. Do not use what you already know about the term. If the passage does +not support a gloss, the book is unplaced. + +SAME SENSE OR DIFFERENT SENSE. Two books use the term in different senses only +if their glosses cannot both describe the same thing. If one book gives more +detail, stresses a different aspect, or uses a different example of the same +thing, that is the same sense. Before you put a book in a group of its own, +write one line: "Book A means X, Book B means Y, and both cannot be true of one +thing." If you cannot write that line, put the books in the same group. + +Before you answer, say for each book in your own words what the sense is, from +that passage alone. If you cannot write that gloss, the book is unplaced. + +Answer with one JSON object and nothing else: +{"groups": [["Book A", "Book B"], ["Book C"]], "unplaced": ["Book D"], "why": {"Book D": "the passage is a contents line"}} + +Use the book names exactly as they are given. Every book appears exactly once: +in a group or in the unplaced list. +""" + + +def read_jsonl(path): + """A file of objects, one a line.""" + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + rows.append(json.loads(line)) + return rows + + +def append_jsonl(path, row): + """One row, on the disk, now.""" + directory = os.path.dirname(path) + if directory: + os.makedirs(directory, exist_ok=True) + with open(path, "a", encoding="utf-8") as fh: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + fh.flush() + os.fsync(fh.fileno()) + + +def key_for(prompt, model): + """The hash of the question: the same question is asked once.""" + return hashlib.sha256(prompt.encode("utf-8") + model.encode("utf-8")).hexdigest() + + +def book_title(corpus, book): + """The book's own title, for the model.""" + manifest = os.path.join(corpus, book, "manifest.json") + if os.path.exists(manifest): + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + found = (data.get("book") or {}).get("title") + if found: + return found + return book + + +def blocks_of(form, corpus): + """The books of a form, in chunks that share an anchor book. + + A form with many books is split, so that no call carries more than + MAX_BOOKS_PER_CALL books. The anchor book is in every chunk, so the + chunks can be put back together. + + Every item carries the book's title as well as its key: the question + shows the title, and the answer has to be read back to the key. + """ + books = [] + for item in form["books"]: + entry = dict(item) + entry["title"] = book_title(corpus, item["book"]) + books.append(entry) + if len(books) <= MAX_BOOKS_PER_CALL: + return [books] + anchor = books[0] + chunks = [] + rest = books[1:] + for start in range(0, len(rest), MAX_BOOKS_PER_CALL - 1): + chunk = [anchor] + rest[start:start + MAX_BOOKS_PER_CALL - 1] + chunks.append(chunk) + return chunks + + +def prompt_for(form, chunk, corpus, must_place=None): + """The question asked about one chunk of a form. + + When the model left books out, the question is asked again with those + books named. It is not told which group they belong to: it is told + that it has to say. + """ + lines = [] + for item in chunk: + lines.append("%s | %s | %s" + % (book_title(corpus, item["book"]), + item["label"], + (item.get("use") or "not given")[:EVIDENCE_NARROW])) + if must_place: + lines.append("") + lines.append("Every one of these books must appear in exactly one " + "group: %s." % ", ".join(must_place)) + return FORM_PROMPT % "\n".join(lines) + + +ESCALATE_PROMPT = """You are given one term and the books of a corpus that use it. + +%s + +The passage of some of these books was too short to show which sense they mean. +Here is each of those books with the same passage and more of it around the term. + +Book | the term as the book writes it | the passage in full +%s + +THE QUESTION: which of these books show a sense now? + +* the same sense as the books already grouped here: +%s + Put such a book in that group. +* a different sense from every other book: put it in a group of its own. +* still no sense: it stays unplaced, and say why. + +PLACING A BOOK. Place a book only if the passage has a sentence that uses the +term and says what it is or does. Write the gloss using words from the +passage. Do not use what you already know about the term. If the passage does +not support a gloss, the book is unplaced. + +SAME SENSE OR DIFFERENT SENSE. Two books use the term in different senses only +if their glosses cannot both describe the same thing. If one book gives more +detail, stresses a different aspect, or uses a different example of the same +thing, that is the same sense. Before you put a book in a group of its own, +write one line: "Book A means X, Book B means Y, and both cannot be true of one +thing." If you cannot write that line, put the books in the same group. + +Answer with one JSON object and nothing else: +{"groups": [["Book A", "Book B"]], "unplaced": ["Book C"], "why": {"Book C": "the passage still gives no sense"}} +""" + + +def escalate_prompt(form, chunk, groups, unplaced, corpus): + """The books whose narrow passage showed no sense, with more of it.""" + lines = [] + for item in chunk: + if item.get("book") not in unplaced: + continue + wide = (item.get("wide") or "").strip() + if not wide: + wide = (item.get("use") or "not given")[:EVIDENCE_NARROW] + lines.append("%s | %s | %s" + % (book_title(corpus, item["book"]), item["label"], wide)) + placed = [] + for group in groups: + names = [book_title(corpus, book) for book in group] + if names: + placed.append(" " + ", ".join(names) + " (one sense)") + if not placed: + placed.append(" (no other book is placed yet)") + return ESCALATE_PROMPT % ("The term is: %s" % form.get("canonical"), + "\n".join(lines), "\n".join(placed)) + + +def forms_to_complete(rows, model=None, selector="manifest"): + """The forms that have to be asked again, and the books with them. + + A form that left a book out, or whose escalated answer dropped a book, + is asked again with that book named. The rows are the rows the + manifest carries, one for each form: the completion pass and the + manifest read the same rows, so the two cannot disagree about which + form has a hole. A form this judge has already asked again is not + asked a third time: an answer that keeps moving costs money and + settles nothing. + """ + if selector == "legacy": + return forms_to_complete_legacy(rows) + unplaced = {} + dropped = {} + asked_once = set() + for row in rows: + canonical = row.get("canonical") + if not canonical: + continue + if row.get("retry"): + # this form has already been asked again by this judge: + # asking it a third time would cost money for an answer that + # keeps moving + if model is None or (row.get("model") or model) == model: + asked_once.add(canonical) + continue + if row.get("left"): + unplaced[canonical] = row["left"] + continue + escalated = row.get("escalated") or [] + if not escalated: + continue + # the wide window was asked for these books, and the second + # answer may have dropped one of them: the answer then covers + # fewer books than the form has, and the form would leave the + # manifest. The book is noticed here and the form is asked + # again with it named. + named = set() + for group in row.get("groups") or []: + named.update(group) + named.update(row.get("unplaced") or {}) + gone = sorted(set(escalated) - named) + if gone: + dropped[canonical] = gone + return unplaced, dropped, asked_once + + +def forms_to_complete_legacy(rows): + """The completion pass of the first shape, kept for the switch. + + It reads the ledger in the order it was written and takes the first + row it finds for a form, so an answer from another judge or another + question can hide the row that answers the question now. The + selector "legacy" turns this on, and the test proves that the two + paths agree wherever the old one could see the hole. + """ + by_canonical = {} + for row in rows: + canonical = row.get("canonical") + if canonical and canonical not in by_canonical: + by_canonical[canonical] = row + unplaced = {} + dropped = {} + asked_once = set() + for canonical, row in sorted(by_canonical.items()): + if row.get("retry"): + # this form has already been asked again: asking it a third + # time would cost money for an answer that keeps moving + asked_once.add(canonical) + elif row.get("left"): + unplaced[canonical] = row["left"] + elif row.get("escalated"): + named = set() + for group in row.get("groups") or []: + named.update(group) + named.update(row.get("unplaced") or {}) + gone = sorted(set(row.get("escalated") or []) - named) + if gone: + dropped[canonical] = gone + return unplaced, dropped, asked_once + + +def merge_escalation(groups, escalation, escalated): + """The escalated books join the groups the first pass made. + + A book the second answer put with a book that is already placed joins + that group; a book it put on its own is a sense of its own; a book it + left unplaced stays unplaced. + """ + known = {} + for index, group in enumerate(groups): + for book in group: + known[book] = index + out = [list(group) for group in groups] + for group in escalation: + target = None + for book in group: + if book in known: + target = known[book] + break + if target is None: + out.append(list(group)) + continue + for book in group: + if book not in known and book in escalated: + out[target].append(book) + return [sorted(set(group)) for group in out] + + +def parse_groups(parsed, books): + """The answer: the books, grouped by sense. + + The question shows a book by its title, so the answer names it by its + title; a title is read back to the key the corpus uses. A book the + model left out, or put in two groups, is not guessed at: it goes to + the review queue, where a person settles it. + """ + if isinstance(parsed, str): + import re + match = re.search(r"\{.*\}", parsed or "", re.S) + if not match: + raise ValueError("the model wrote no object") + parsed = json.loads(match.group(0)) + groups = parsed.get("groups") + if not isinstance(groups, list): + raise ValueError("the answer has no groups") + keys = set(item["book"] for item in books) + # the names a book may be answered by: its key, and its title + aliases = {} + for item in books: + key = item["book"] + aliases.setdefault(key, key) + title = (item.get("title") or "").strip() + if title: + aliases.setdefault(title.casefold(), key) + clean = [] + placed = set() + extra = [] + for group in groups: + if not isinstance(group, list): + continue + members = [] + for book in group: + name = (book or "").strip() + key = aliases.get(name) or aliases.get(name.casefold()) + if key is None: + extra.append(book) + continue + if key in placed: + # the model put this book in two groups: it is placed in + # the first, and it is not counted twice + continue + placed.add(key) + members.append(key) + if members: + clean.append(sorted(members)) + # the books the answer names as unplaced: the passage gave no sense, so + # the book is neither a sense of its own nor the same sense as anything + unplaced = {} + why = parsed.get("why") or {} + if not isinstance(why, dict): + why = {} + for name in parsed.get("unplaced") or []: + key = aliases.get((name or "").strip()) + if key is None: + key = aliases.get((name or "").strip().casefold()) + if key is None: + extra.append(name) + continue + unplaced[key] = str(why.get(name) or why.get(key) + or "the passage gives no sense")[:200] + left = sorted(keys - placed - set(unplaced)) + return clean, left, sorted(set(extra)), unplaced + + +def content_for(form, corpus, must=None): + """The hash of the questions asked about a form. + + Two forms with the same books and the same evidence are the same + question, and a form whose books or evidence changed is a + different question. The hash is what tells them apart. + """ + questions = [prompt_for(form, chunk, corpus, must) + for chunk in blocks_of(form, corpus)] + return hash_of("\n".join(questions)) + + +def form_key(form, model): + """The key of the question about a form: the same question, the same key.""" + return hash_of({"canonical": form["canonical"], "model": model, + "books": [item["book"] for item in form["books"]], + "content": form["_content"]}) + + +def answers_this_form(row, form, corpus, groups=None, left=None): + """True when the row answers the question the corpus is asking now. + + The row has to be about the same books and about the same + question: the books the term is in, and the text the question + shows. A row without the hash of the question is taken on trust: + it was written before the hash was kept, and it answered the + question the corpus would ask. + """ + if groups is None: + groups = row.get("groups") or [] + if left is None: + left = row.get("left") or [] + covered = set() + for group in groups: + covered.update(group) + covered.update(left) + # a book the answer names as unplaced is answered for: it is not a + # sense, and not the same sense as anything, and the row says so + covered.update(row.get("unplaced") or {}) + if covered != set(item["book"] for item in form["books"]): + return False + content = row.get("content") + if not content: + return True + if content == form["_content"]: + return True + if left and content == content_for(form, corpus, left): + return True + # the retry asked the form again with the books it left out named, + # so its question is the form with those books named, and the answer + # may leave none of them out + if row.get("retry"): + named = set() + for group in row.get("groups") or []: + named.update(group) + named.update(row.get("unplaced") or {}) + for book in sorted(named): + if content == content_for(form, corpus, [book]): + return True + return False + + +def current_rows(history, forms, corpus, cache=None, model=None): + """The rows that answer the questions the corpus is asking now. + + The ledger keeps the history: a row for another question is + history, not an answer. The rows are read in the order they were + written, so the last answer to a form is the answer. Every answer + is read again with the parser of today, so a rule about the names + does not stay in the index for ever. + + A row answered by another judge is history as well: the corpus is + judged by one judge, and an answer from another model does not + answer the question this corpus is asking. + """ + by_canonical = {form["canonical"]: form for form in forms} + decided = {} + incomplete = {} + for row in history: + if model and row.get("model") and row.get("model") != model: + # another judge answered this form: its answer is not the + # answer this corpus is asking for + continue + form = by_canonical.get(row.get("canonical")) + if form is None: + continue + if "_content" not in form: + form["_content"] = content_for(form, corpus) + groups = row.get("groups") or [] + left = row.get("left") or [] + extra = row.get("extra") or [] + fresh = reparse_row(row, form, corpus, cache) if cache else None + if fresh is not None: + groups = fresh["groups"] + left = fresh["left"] + extra = fresh["extra"] + if not answers_this_form(row, form, corpus, groups=groups, left=left): + continue + entry = dict(row) + entry["groups"] = groups + entry["left"] = left + entry["extra"] = extra + if left: + incomplete[row["canonical"]] = entry + else: + decided[row["canonical"]] = entry + return decided, incomplete + + +def manifest_rows(history, forms, corpus, cache=None, model=None): + """The rows the manifest carries, one for each form. + + The rows that answer the questions the corpus is asking now, with the + form that has a complete answer ahead of the form that has not: a + form that was asked again and got a complete answer is carried, and + the form that is still short a book is carried as it is. The + completion pass reads this too, so the two cannot disagree about + which form has a hole. + """ + decided, incomplete = current_rows(history, forms, corpus, cache, + model=model) + latest = {} + for canonical in sorted(decided): + latest[canonical] = decided[canonical] + for canonical in sorted(incomplete): + latest.setdefault(canonical, incomplete[canonical]) + return latest + + +def read_cache(links): + """The answers the judge has already paid for, by the question.""" + cache = {} + for row in read_jsonl(os.path.join(links, "form-answers.jsonl")): + key = row.get("key") + if key: + cache[key] = row + return cache + + +def reparse_row(row, form, corpus, cache): + """The row's answer, read again with the parser of today. + + The ledger keeps the decision and the cache keeps the evidence: the + model said which books go together, and the parser says which book + names it used. When the parser changes, the answer is read again + from the evidence, so a rule about the names does not stay in the + index for ever. + """ + if row.get("retry"): + # the retry asked a different question, and the books it named + # are not in the row: the row's own answer is what there is + return None + model = row.get("model") or "" + groups = [] + left = [] + extra = [] + unplaced = {} + for chunk in blocks_of(form, corpus): + prompt = prompt_for(form, chunk, corpus) + cached = cache.get(key_for(prompt, model)) + if not cached or not cached.get("ok"): + return None + answer = cached.get("answer") + if not isinstance(answer, dict): + return None + try: + found, missing, unknown, none_placed = parse_groups(answer, chunk) + except Exception: + return None + for member in found: + groups.append(member) + left.extend(missing) + extra.extend(unknown) + unplaced.update(none_placed) + if none_placed: + # the run asked again with the wide window for the books that + # showed no sense, and the second answer is merged into the + # groups gathered so far, this chunk included. The re-read has + # to replay that, or the answer it derives covers fewer books + # than the form has, and the form drops out of the manifest. + escalated = set(none_placed) + eprompt = escalate_prompt(form, chunk, groups, escalated, corpus) + ecached = cache.get(key_for(eprompt, model)) + if not ecached or not ecached.get("ok"): + # the escalated answer is missing: the row cannot be + # re-derived, and saying so is better than a silent drop + return None + eanswer = ecached.get("answer") + if not isinstance(eanswer, dict): + return None + try: + efound, el, _eu, eunplaced = parse_groups(eanswer, chunk) + except Exception: + return None + efound = [group for group in efound + if any(book in escalated for book in group)] + groups = merge_escalation(groups, efound, escalated) + # the books the second answer left out are books the answer did + # not cover: they go to the review queue, and the completion + # pass asks the form again with them named. Dropping them here + # loses the book from the manifest, and the form drops with it. + left.extend(book for book in el if book in escalated) + for book in escalated: + unplaced.pop(book, None) + for book, reason in (eunplaced or {}).items(): + if book in escalated: + unplaced[book] = reason + return {"groups": groups, "left": sorted(set(left)), + "extra": sorted(set(extra)), "unplaced": unplaced} + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="judge_forms.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--jobs", type=int, default=0, + help="how many forms to ask at once") + ap.add_argument("--model", default="") + ap.add_argument("--strong-model", default="") + ap.add_argument("--batch", action="store_true", + help="ask every form as one batch job instead of one at a time") + ap.add_argument("--pilot", action="store_true") + ap.add_argument("--plain", action="store_true", + help="the pilot samples the corpus evenly, with nothing" + "chosen for it") + ap.add_argument("--sample-offset", type=int, default=0, + help="move the sample, so a second pilot is a fresh one") + ap.add_argument("--seed", type=int, default=20261127, + help="the seed of the draw, so the sample can be drawn again") + ap.add_argument("--exclude-sample", default="", + help="a manifest whose sample is left out of the draw") + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args(argv) + + settings = Settings() + index_settings = settings.get("index") or {} + prices = settings["money"]["prices"] + model = args.model or index_settings.get("link_model", "gemini-3.8-flash") + strong_model = args.strong_model or index_settings.get("strong_model", + "gemini-3.8-flash") + allocation = index_settings.get("link_cap_usd", 1.4) + preflight = index_settings.get("link_preflight_usd", 1.05) + if allocation is None or preflight is None: + # a stage with no cap is stopped before the first call + print("REFUSED: the link stage has no money cap. A stage that has not") + print(" been given a cap is stopped before the first call.") + return 2 + allocation = float(allocation) + preflight = float(preflight) + corpus = args.corpus_root + links = os.path.join(corpus, "index", "links") + + forms = read_jsonl(os.path.join(links, "forms.jsonl")) + forms = [form for form in forms if len(form.get("books") or []) > 1] + if args.limit: + forms = forms[:args.limit] + if args.dry_run: + # what the run would cost: a question the cache already holds + # is free, and the rest is a call + for form in forms: + form["_content"] = content_for(form, corpus) + form["key"] = form_key(form, model) + history = read_jsonl(os.path.join(links, "form-judgments.jsonl")) + decided, _incomplete = current_rows(history, forms, corpus, model=model) + known = set(row["key"] for row in history) + paid = set(row.get("key") for row in + read_jsonl(os.path.join(links, "form-answers.jsonl"))) + to_ask = 0 + fresh = 0 + cached = 0 + prompt_tokens = 0 + for form in forms: + if form["canonical"] in decided or form["key"] in known: + continue + to_ask += 1 + for chunk in blocks_of(form, corpus): + prompt = prompt_for(form, chunk, corpus) + if key_for(prompt, model) in paid: + cached += 1 + continue + fresh += 1 + prompt_tokens += len(prompt) // 4 + price = prices.get(model) or {} + estimate = (prompt_tokens * price.get("in", 0.0) + + fresh * OUTPUT_TOKENS * price.get("out", 0.0)) + print("forms: %d | to ask: %d | fresh calls: %d | already paid: %d" + % (len(forms), to_ask, fresh, cached)) + print("estimated $%.4f of the $%.2f pre-flight line and the $%.2f cap" + % (estimate, preflight, allocation)) + return 0 + + judge_settings = dict(settings["judge"]) + judge_settings["model"] = model + # the door the link stage is asked through. Empty means the model name + # decides, which is how the corpus has always been judged. The model + # keeps its name whatever the door is, so an answer the corpus already + # paid for still answers the question it was asked. + judge_settings["route"] = index_settings.get("link_judge_route", "") + # the widest forms make the model think, and thinking is spent out of + # the same budget as the answer + judge_settings["max_output_tokens"] = int(index_settings.get( + "link_max_output_tokens", 2048)) + ledger = Ledger(prices) + breaker = CircuitBreaker(judge_settings) + judge = Judge(judge_settings, ledger, breaker, + cache_path=os.path.join(links, "form-answers.jsonl")) + strong_settings = dict(judge_settings) + strong_settings["model"] = strong_model + strong_settings["route"] = index_settings.get( + "link_strong_judge_route", index_settings.get("link_judge_route", "")) + # a model that thinks spends its output on the thinking, so it + # needs more room than the cheap one + strong_settings["max_output_tokens"] = int( + index_settings.get("strong_max_output_tokens", 8192)) + # the strong judge spends from the same ledger, so the cap covers + # both, and it keeps its own answers, so a pilot that is run again + # does not pay for the same question twice + strong_judge = Judge(strong_settings, ledger, + CircuitBreaker(strong_settings), + cache_path=os.path.join(links, + "form-answers-strong.jsonl")) + + if args.pilot: + history = read_jsonl(os.path.join(links, "form-judgments.jsonl")) + rows = {} + for row in history: + rows[row["canonical"]] = row + cap = float(index_settings.get("pilot_cap_usd", 2.0)) + exclude = set() + if args.exclude_sample and os.path.exists(args.exclude_sample): + with open(args.exclude_sample, encoding="utf-8") as fh: + exclude = set(json.load(fh).get("sample") or []) + return run_pilot(forms, judge, strong_judge, model, strong_model, + corpus, rows=rows, ledger=ledger, cap=cap, + plain=args.plain, offset=args.sample_offset, + seed=args.seed, exclude=exclude, + rule=index_settings.get("pilot") or {}) + + ledger_path = os.path.join(links, "form-judgments.jsonl") + # the ledger in the order it was written: the history is what says + # which answer came last + history = read_jsonl(ledger_path) + known = {} + for row in history: + known[row["key"]] = row + + lock = threading.Lock() + max_call_cost = [0.0] + state = {"asked": 0, "reused": 0} + asked = set() + # the forms that got no answer: a failed call is missing data, + # not a verdict, and a form with no answer is not decided + missing = [] + + def ask(form): + """One form: the books, grouped by sense.""" + groups = [] + left = [] + extra = [] + unplaced = {} + escalated_books = set() + calls = 0 + tokens_in = 0 + tokens_out = 0 + failed = False + questions = [] + for chunk in blocks_of(form, corpus): + prompt = prompt_for(form, chunk, corpus) + questions.append(prompt) + key = key_for(prompt, model) + result = judge.text(prompt, key, model) + calls += 1 + tokens_in += result.get("tokens_in", 0) + tokens_out += result.get("tokens_out", 0) + answer = result.get("answer") + if not isinstance(answer, dict) or not isinstance(answer.get("groups"), list): + # the model wrote something else: the call is missing data, + # not a verdict, and this form is not decided + failed = True + break + try: + found, missing, unknown, none_placed = parse_groups(answer, chunk) + except Exception: + found, missing, unknown, none_placed = [], [], [], {} + for member in found: + groups.append(member) + left.extend(missing) + extra.extend(unknown) + unplaced.update(none_placed) + if none_placed: + # the passage was too short to show a sense: ask again with + # more of it around the term, and only then is the book + # unplaced. One rule, applied the same way to every form. + escalated = set(none_placed) + eprompt = escalate_prompt(form, chunk, groups, escalated, + corpus) + questions.append(eprompt) + eresult = judge.text(eprompt, key_for(eprompt, model), model) + calls += 1 + tokens_in += eresult.get("tokens_in", 0) + tokens_out += eresult.get("tokens_out", 0) + eanswer = eresult.get("answer") + if not isinstance(eanswer, dict): + # the second question was not answered: the form is + # not decided, and the run says so + failed = True + break + try: + efound, _el, _eu, eunplaced = parse_groups(eanswer, chunk) + except Exception: + efound, eunplaced = [], {} + efound = [group for group in efound + if any(book in escalated for book in group)] + groups = merge_escalation(groups, efound, escalated) + for book in escalated: + unplaced.pop(book, None) + for book, reason in (eunplaced or {}).items(): + if book in escalated: + unplaced[book] = reason + escalated_books.update(escalated) + out = {"groups": groups, "left": sorted(set(left)), + "extra": sorted(set(extra)), "unplaced": unplaced, + "escalated": sorted(escalated_books), + "failed": failed, + "calls": calls, "tokens_in": tokens_in, "tokens_out": tokens_out} + price = prices.get(model) or {} + cost = (tokens_in * price.get("in", 0.0) + + tokens_out * price.get("out", 0.0)) + with lock: + if cost > max_call_cost[0]: + max_call_cost[0] = cost + return form, out + + started = time.time() + # the question about a form, and the key of that question: the same + # question asked twice is the same question, and a form whose books + # or whose evidence changed is a different question + for form in forms: + form["_content"] = content_for(form, corpus) + form["key"] = form_key(form, model) + + # the rows that answer the questions the corpus is asking now: the + # ledger keeps the history, and a row for another question is not an + # answer to this one + decided, incomplete = current_rows(history, forms, corpus, judge.cache, + model=model) + + todo = [] + for form in forms: + canonical = form["canonical"] + done = decided.get(canonical) + if done is not None: + form["key"] = done["key"] + form["model"] = done.get("model") or model + state["reused"] += 1 + continue + row = known.get(form["key"]) + if row is not None: + # this exact question was asked before and the answer left + # books out: asking it again would pay for the same answer, + # and those books wait for a person + form["key"] = row["key"] + form["model"] = row.get("model") or model + incomplete[canonical] = row + state["reused"] += 1 + continue + todo.append(form) + + # the pre-flight: what the run will cost, before it starts + calls = sum(len(blocks_of(form, corpus)) for form in todo) + prompt_tokens = 0 + for form in todo: + for chunk in blocks_of(form, corpus): + prompt_tokens += len(prompt_for(form, chunk, corpus)) // 4 + estimate = (prompt_tokens * (prices.get(model) or {}).get("in", 0.0) + + calls * OUTPUT_TOKENS * (prices.get(model) or {}).get("out", 0.0)) + if estimate > preflight: + print("REFUSED: the link stage is estimated at $%.4f, and the " + "pre-flight line is $%.2f" % (estimate, preflight)) + return 2 + print("link stage: %d forms (%d to ask, %d reused), %d calls, estimated $%.4f" + % (len(forms), len(todo), state["reused"], calls, estimate)) + + # the rate the judge is given, and never faster than the settings + # ask for: a model asked past its rate fails the calls, and a + # failed call is missing data + workers = max(1, args.jobs) if args.jobs else max(1, judge_settings.get("workers", 3)) + queue = list(todo) + pending = [] + stopped = False + results = {} + if args.batch: + # the bulk route: every form is asked in one job, and the answers + # come back together + items = [] + for form in todo: + for chunk in blocks_of(form, corpus): + prompt = prompt_for(form, chunk, corpus) + items.append((key_for(prompt, model), prompt)) + rows, batch_id, seconds = judge.text_batch(items, model) + for form in todo: + groups = [] + left = [] + unplaced = {} + for chunk in blocks_of(form, corpus): + prompt = prompt_for(form, chunk, corpus) + row = rows.get(key_for(prompt, model)) + if not row or not row.get("ok"): + continue + answer = row.get("answer") + if not isinstance(answer, dict): + continue + try: + found, missing, _unknown, none_placed = parse_groups(answer, chunk) + except Exception: + continue + groups.extend(found) + left.extend(missing) + unplaced.update(none_placed) + record = {"key": form["key"], "canonical": form["canonical"], + "groups": groups, "left": sorted(set(left)), "extra": [], + "unplaced": unplaced, + "model": model, "calls": len(blocks_of(form, corpus)), + "tokens_in": 0, "tokens_out": 0, "batch": batch_id} + with lock: + known[form["key"]] = record + history.append(record) + asked.add(form["key"]) + append_jsonl(ledger_path, record) + print("batch %s: %d forms asked, %.0f s" % (batch_id, len(todo), seconds)) + return write_results(known, history, corpus, ledger, + time.time() - started, model, asked) + with ThreadPoolExecutor(max_workers=workers) as pool: + while queue or pending: + while queue and len(pending) < workers and not stopped: + with lock: + spent = ledger.usd() + if spent + 1.5 * max_call_cost[0] >= allocation: + stopped = True + break + form = queue.pop(0) + pending.append(pool.submit(ask, form)) + if not pending: + break + form, out = pending.pop(0).result() + results[form["key"]] = (form, out) + if out["failed"]: + with lock: + missing.append(form["canonical"]) + continue + # the hash of the question itself, so a change in the text + # that was asked is visible even when the key is the same + questions = [prompt_for(form, chunk, corpus) + for chunk in blocks_of(form, corpus)] + row = {"key": form["key"], "canonical": form["canonical"], + "groups": out["groups"], "left": out["left"], + "extra": out["extra"], "unplaced": out["unplaced"], + "escalated": out["escalated"], + "model": model, + "calls": out["calls"], "tokens_in": out["tokens_in"], + "tokens_out": out["tokens_out"], + "content": hash_of("\n".join(questions))} + with lock: + known[form["key"]] = row + history.append(row) + asked.add(form["key"]) + state["asked"] += 1 + append_jsonl(ledger_path, row) + if len(known) % 200 == 0: + print(" %d judged | %d to go | $%.4f" + % (len(known), len(queue), ledger.usd()), flush=True) + # the completion pass: a form that left books out is asked again with + # those books named, so that the index does not carry a hole that one + # careless answer made + by_canonical = {} + for form in forms: + by_canonical[form["canonical"]] = form + # the rows the manifest carries: the completion pass and the manifest + # read the same rows, so they cannot disagree about which form has a + # hole. A row from another judge or another question is history, and + # it cannot hide the row that answers the question now. + selector = index_settings.get("link_completion_selector", "manifest") + if selector == "legacy": + rows = (list(known.values()) + list(decided.values()) + + list(incomplete.values())) + else: + rows = list(manifest_rows(history, forms, corpus, judge.cache, + model=model).values()) + unplaced, dropped, asked_once = forms_to_complete( + rows, model=model, selector=selector) + if unplaced or dropped: + retries = [] + for canonical in sorted(set(unplaced) | set(dropped)): + if canonical in asked_once: + continue + form = by_canonical.get(canonical) + if form is None: + continue + must = list(unplaced.get(canonical) or []) + must += list(dropped.get(canonical) or []) + retries.append((form, sorted(set(must)))) + + def complete(item): + form, must = item + groups = [] + left = [] + none_placed_books = {} + calls = 0 + tokens_in = 0 + tokens_out = 0 + questions = [] + for chunk in blocks_of(form, corpus): + prompt = prompt_for(form, chunk, corpus, must) + questions.append(prompt) + result = judge.text(prompt, key_for(prompt, model), model) + calls += 1 + tokens_in += result.get("tokens_in", 0) + tokens_out += result.get("tokens_out", 0) + answer = result.get("answer") + if not isinstance(answer, dict): + continue + try: + found, missing, _unknown, none_placed = parse_groups(answer, chunk) + except Exception: + continue + groups.extend(found) + none_placed_books.update(none_placed) + left.extend(missing) + content = hash_of("\n".join(questions)) + return (form, groups, sorted(set(left)), calls, tokens_in, + tokens_out, content, none_placed_books) + + with ThreadPoolExecutor(max_workers=workers) as pool: + for (form, groups, left, calls, tokens_in, tokens_out, + content, none_placed_books) in pool.map(complete, retries): + # the retry asks a different question, so it has its + # own key: the two answers cannot be confused + retry_key = hash_of({"canonical": form["canonical"], + "model": model, + "books": [item["book"] for item in form["books"]], + "content": content}) + row = {"key": retry_key, "canonical": form["canonical"], + "groups": groups, "left": left, "extra": [], + "unplaced": none_placed_books, + "model": model, "calls": calls, "tokens_in": tokens_in, + "tokens_out": tokens_out, "retry": True, + "content": content} + with lock: + known[retry_key] = row + history.append(row) + asked.add(retry_key) + append_jsonl(ledger_path, row) + print("completion pass: %d form(s) asked again" % len(retries)) + if stopped: + print("STOPPED at the cap: $%.4f of $%.2f" % (ledger.usd(), allocation)) + + # a form that got no answer is not decided: the run says so, and the + # forms are written down, so that a silent loss cannot pass for a build + if missing: + path = os.path.join(corpus, "index", "links", "missing-forms.jsonl") + with open(path, "w", encoding="utf-8") as fh: + for canonical in sorted(missing): + fh.write(json.dumps({"canonical": canonical, + "reason": "the judge did not answer"}, + ensure_ascii=False) + "\n") + print("MISSING: %d form(s) got no answer and are not decided" % len(missing)) + print("the forms are written to:", path) + + write_results(known, history, corpus, ledger, + time.time() - started, model, asked, + missing=set(missing)) + return 2 if missing else 0 + + +def write_results(known, history, corpus, ledger, seconds, model, + asked=None, missing=None): + """The concepts, the review queue and the manifest.""" + concepts = [] + review = [] + # the question a form asks now, as a hash: the manifest says what was + # asked, and not only what it was called + forms = {} + for row in read_jsonl(os.path.join(corpus, "index", "links", "forms.jsonl")): + forms[row["canonical"]] = row + # the rows that answer the questions the corpus is asking now: the + # ledger keeps the history, and a row for another question is not an + # answer to this one + latest = manifest_rows( + history, list(forms.values()), corpus, + read_cache(os.path.join(corpus, "index", "links")), model=model) + for key in sorted(latest): + row = latest[key] + for group in row["groups"]: + # a book is in a group once: the ledger is written by older + # runs too, and a member twice is not two members + members = sorted(set("%s|%s" % (book, row["canonical"]) + for book in group)) + if len(members) < 2: + continue + concepts.append({ + "concept_id": "c:%s" % hashlib.sha256( + "|".join(members).encode("utf-8")).hexdigest()[:16], + "members": members, "size": len(members), + }) + for book in row["left"]: + review.append({"term": "%s|%s" % (book, row["canonical"]), + "reason": "the model did not place this book"}) + for book in row["extra"]: + review.append({"term": book, + "reason": "the model named a book that does not have " + "the term"}) + concepts.sort(key=lambda row: row["concept_id"]) + review.sort(key=lambda row: (row["term"], row["reason"])) + with open(os.path.join(corpus, "index", "concepts.jsonl"), "w", + encoding="utf-8") as fh: + for row in concepts: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + with open(os.path.join(corpus, "index", "review.jsonl"), "w", + encoding="utf-8") as fh: + for row in review: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + # the status is measured against the manifest that was committed, not + # against the last run: a form that was decided two runs ago and not + # since is still reused + before = {} + for row in read_jsonl(os.path.join(corpus, "index", "manifest", "link.jsonl")): + before[row["key"]] = row + manifest = [] + for key in sorted(latest): + row = latest[key] + form = forms.get(row["canonical"]) + if form is None: + # the corpus does not have this form any more: the ledger + # keeps its history, the manifest describes what is here + continue + placed = sorted(set(book for group in row["groups"] for book in group)) + output = hash_of(sorted(row["groups"])) + status = "reused" if key in before else "computed" + questions = [prompt_for(form, chunk, corpus) + for chunk in blocks_of(form, corpus)] + content = hash_of("\n".join(questions)) + # a book the judge did not name even after the form was asked + # again is not unplaced: unplaced is a book whose passage gives no + # sense. It is a third state, and the identity counts it + unanswered = sorted(row.get("left") or []) if row.get("retry") else [] + manifest.append({"unit": row["canonical"], "key": row["key"], + "status": status, + "model": row.get("model") or "", + "content": content, + "output": output, + "groups": len(row["groups"]), + "unplaced": sorted(row.get("unplaced") or {}), + "unanswered": unanswered, + "books": placed}) + # a builder that drops a row without failing is the root defect this + # corpus had, so a form the ledger answers but the manifest does not + # carry is an error, not a quiet omission + carried = set(row["unit"] for row in manifest) + # a form that got no answer is already written down and named; + # a form the ledger answers and the manifest does not carry is the + # silent error this check is for + dropped = sorted(set(forms.keys()) - carried - (missing or set())) + if dropped: + raise SystemExit("the manifest is missing %d form(s) the ledger" + " answers, and a manifest that drops a form is a" + " silent error: %s" + % (len(dropped), ", ".join(dropped[:12]))) + with open(os.path.join(corpus, "index", "manifest", "link.jsonl"), "w", + encoding="utf-8") as fh: + for row in manifest: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + wide = max([row["size"] for row in concepts] or [0]) + # the grouping is over-splitting when a form carries more concepts + # than one: a term two books share is usually one sense, and a count + # of concepts on its own says nothing about that + split = len([key for key in latest + if len([row for row in concepts + if any(member.endswith("|" + key) + for member in row["members"])]) > 1]) + per_form = (len(concepts) / float(len(latest))) if latest else 0.0 + print("forms: %d | concepts: %d | widest: %d | review: %d | cost $%.4f | %.0f s" + % (len(known), len(concepts), wide, len(review), ledger.usd(), seconds)) + print("a form carries %.2f concepts on average | %d form(s) carry more than one" + % (per_form, split)) + if per_form > 1.15: + print("ALARM: %.2f concepts a form; the grouping is over-splitting" + % per_form) + return 0 + + +def run_pilot(forms, judge, strong_judge, model, strong_model, corpus, + rows=None, ledger=None, cap=2.0, plain=False, offset=0, + seed=0, exclude=(), rule=None): + """The link pilot: is the cheap model good enough to decide a sense? + + The terms pilot measured a different job, so it does not carry over. + Here both models partition the same forms, and the cheap model is + ruled good enough only if it agrees with the strong one on at least + 95% of the forms and catches at least 90% of the splits the strong + model makes. + + The rule is pre-registered, in the settings and in the manifest of the + runs: 95% and 90%, one run, no rerun, no new seed and no change to a + threshold, and a fail means the two-model agreement is not fit to certify + these links - the disagreements are adjudicated by hand and a hand-read + sample of the agreements is read beside them. The pilot spends at most the + cap, and the cap is checked against what was really spent. + """ + chosen = pilot_forms(forms, rows, plain=plain, offset=offset, + seed=seed, exclude=exclude) + agree = 0 + strong_splits = 0 + caught = 0 + details = [] + empty = 0 + stopped = [False] + def both(form): + if stopped[0]: + return form, None, None + lite = partition(judge, form, model, corpus) + strong = partition(strong_judge, form, strong_model, corpus) + if ledger is not None and ledger.usd() >= cap: + stopped[0] = True + return form, lite, strong + + with ThreadPoolExecutor(max_workers=8) as pool: + for form, lite, strong in pool.map(both, chosen): + if lite is None: + continue + same = _same_partition(lite, strong) + if same: + agree += 1 + splits = _apart(strong) + strong_splits += len(splits) + caught += len(splits & _apart(lite)) + if not strong: + # the strong model said nothing: the instrument failed + # on this form, and there is nothing to compare + empty += 1 + details.append({"canonical": form["canonical"], + "books": len(form["books"]), + "lite_groups": len(lite), "strong_groups": len(strong), + "agree": same}) + print(" %-40s %2d books | lite %2d groups | strong %2d groups | %s" + % (form["canonical"][:40], len(form["books"]), len(lite), + len(strong), "same" if same else "different"), flush=True) + # the breakdown: by the route that found the passage, and by whether + # the form carries a passage at all + by_canonical = {form["canonical"]: form for form in forms} + by_route = collections.defaultdict(lambda: [0, 0]) + by_evidence = collections.defaultdict(lambda: [0, 0]) + for detail in details: + form = by_canonical.get(detail["canonical"]) + route = "none" + has = True + if form is not None: + route = "/".join(sorted(set(m.get("route") or "none" + for m in form["books"]))) + has = all((m.get("use") or "").strip() for m in form["books"]) + by_route[route][0] += 1 + by_evidence["with a passage" if has else "without a passage"][0] += 1 + if detail["agree"]: + by_route[route][1] += 1 + by_evidence["with a passage" if has else "without a passage"][1] += 1 + total = len(details) or 1 + agreement = agree / float(total) + catches = (caught / float(strong_splits)) if strong_splits else 1.0 + lost = (agreement < 0.95) or (catches < 0.90) or (empty > 0) + print() + print("link pilot: %d forms | agreement %.1f%% | splits caught %.1f%% | empty %d" + % (total, agreement * 100, catches * 100, empty)) + print("VERDICT: the cheap model is %s" % ("LOST" if lost else "good enough")) + if stopped[0]: + print("the pilot stopped at the cap: $%.4f of $%.2f" + % (ledger.usd(), cap)) + os.makedirs(os.path.join(corpus, "index", "manifest"), exist_ok=True) + import time + path = os.path.join(corpus, "index", "manifest", "link-pilot.json") + payload = {} + if os.path.exists(path): + with open(path, encoding="utf-8") as fh: + payload = json.load(fh) + # the manifest is the history of the runs and not the last run alone: a + # pilot that failed is evidence, and a run that was void has to be + # marked void with its reason + runs = payload.get("runs") or [] + provider = "google" if model.startswith("gemini") else ( + "anthropic" if model.startswith("claude") else "openrouter") + run = { + "id": "%s, seed %s" % (time.strftime("%Y-%m-%d"), seed), + "date": time.strftime("%Y-%m-%d"), + "status": "failed" if lost else "passed", + "reason": ("the agreement or the splits caught fell short of the rule" + if lost else "the rule was met"), + "models": {"cheap": model, "strong": strong_model}, + "provider": provider, + "seed": seed, + "sample": len(chosen), + "strata": "book", + "sample_hash": hash_of([form["canonical"] for form in chosen]), + "excluded": len(exclude), + "rule": rule or {}, + "thresholds": {"agreement": 0.95, "splits_caught": 0.9}, + "results": {"agreement": round(agreement, 4), + "splits_caught": round(catches, 4), + "empty": empty}, + "cost_usd": round(ledger.usd(), 4) if ledger else 0, + "cap_usd": cap, + } + runs.append(run) + payload["runs"] = runs + payload["rule"] = rule or payload.get("rule") or {} + payload.update({"forms": total, "agreement": round(agreement, 4), + "sample": [form["canonical"] for form in chosen], + "splits_caught": round(catches, 4), + "lite": model, "strong": strong_model, + "empty": empty, + "seed": seed, + "excluded": len(exclude), + "by_route": {name: {"forms": cell[0], "agree": cell[1]} + for name, cell in by_route.items()}, + "by_evidence": {name: {"forms": cell[0], "agree": cell[1]} + for name, cell in by_evidence.items()}, + "cost_usd": round(ledger.usd(), 4) if ledger else 0, + "cap_usd": cap, + "threshold_agreement": 0.95, + "threshold_splits_caught": 0.9, + "lite_lost": bool(lost), + "blocks_corpus_mr": bool(lost), + "details": details}) + with open(path, "w", encoding="utf-8") as fh: + json.dump(payload, fh, indent=1, sort_keys=True, ensure_ascii=False) + fh.write(chr(10)) + return 0 + +# the words that mean different things in different books: the forms +# where the sense has to be decided rather than assumed +HOMONYMS = ("bank", "issue", "capital", "action", "attention", + "treatment", "process", "party", "term", "state", + "nature", "object", "power", "right", "case", "rule", + "scale", "measure", "value", "form", "unit", "field", + "level", "order", "point", "line", "model", "market", + "labour", "labor", "development", "structure") + + +def pilot_forms(forms, rows=None, size=250, plain=False, offset=0, + seed=0, exclude=()): + """The pilot's forms: a seeded random draw, stratified by book. + + Every book gets the same share of the sample, so the sample is not + the alphabet of the corpus, and the draw is seeded, so the same + sample can be drawn again and a fresh one can be drawn on purpose. + The forms of an earlier pilot are left out. + """ + if plain: + # an even sample of the corpus, with nothing chosen for it; the + # offset moves the sample, so a second pilot can be a fresh one + step = max(1, len(forms) // size) + return forms[offset::step][:size] + by_book = collections.defaultdict(list) + for form in forms: + by_book[form["books"][0]["book"]].append(form) + books = sorted(by_book) + share = max(1, size // len(books)) if books else size + rng = random.Random(seed) + picks = [] + rest = [] + for book in books: + pool = [form for form in by_book[book] + if form["canonical"] not in exclude] + rng.shuffle(pool) + picks.extend(pool[:share]) + rest.extend(pool[share:]) + rng.shuffle(rest) + picks.extend(rest[:max(0, size - len(picks))]) + rng.shuffle(picks) + return picks[:size] + + +def partition(judge, form, model, corpus): + """The groups of a form, from one model.""" + groups = [] + for chunk in blocks_of(form, corpus): + prompt = prompt_for(form, chunk, corpus) + result = judge.text(prompt, key_for(prompt, model), model) + try: + found, _missing, _unknown, _none = parse_groups(result.get("answer"), chunk) + except Exception: + found = [] + groups.extend(found) + return groups + + +def _same_partition(left, right): + """Do the two partitions put the books in the same groups?""" + def pairs(groups): + out = set() + for group in groups: + for i in range(len(group)): + for j in range(i + 1, len(group)): + out.add(frozenset((group[i], group[j]))) + return out + return pairs(left) == pairs(right) + + +def _splits(groups): + """How many pairs the partition puts apart.""" + return len(_apart(groups)) + + +def _apart(groups): + """The pairs of books the partition puts apart. + + A pair of books that ended up in different groups is a "different" + verdict, and this is how many of them the partition makes. A group of + three makes no split: the three are one sense. + """ + books = set() + for group in groups: + books.update(group) + within = set() + for group in groups: + members = sorted(set(group)) + for i in range(len(members)): + for j in range(i + 1, len(members)): + within.add(frozenset((members[i], members[j]))) + apart = set() + names = sorted(books) + for i in range(len(names)): + for j in range(i + 1, len(names)): + pair = frozenset((names[i], names[j])) + if pair not in within: + apart.add(pair) + return apart + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/link_read.py b/pipeline/scripts/link_read.py new file mode 100644 index 00000000..70866d23 --- /dev/null +++ b/pipeline/scripts/link_read.py @@ -0,0 +1,560 @@ +#!/usr/bin/env python3 +"""scripts/link_read.py - the blind read of the links under the current rule. + +Five jobs, one instrument: + + build the draw, the packets and the registration + wide-packets the second pass, for the books that came back with no sense + run the readers are asked, through the door the settings name + merge the two passes are put together, one answer per form + pair the two readers are put side by side, for the convergence + +A blind read of the links is the corpus own check on the judge: a reader is +shown the same evidence the judge was shown and answers the same question, +blind to the judge and to the stratum. The instrument is registered in +settings/pipeline.json before the read is scored, and the rule the reader is +given is the rule the judge was given, read from that same file. + + python3 scripts/link_read.py build --corpus-root --out \ + --size 600 --seed 20261202 --batches 20 --exclude + python3 scripts/link_read.py wide-packets --corpus-root \ + --packets --verdicts + python3 scripts/link_read.py run --packets --out \ + --model gemini-4-carbon-high --stage narrow --workers 4 + python3 scripts/link_read.py merge --out --stage narrow + python3 scripts/link_read.py pair --out --a --b +""" +import argparse +import collections +import json +import os +import random +import subprocess +import sys +import tempfile +import threading +import time + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +AGY = os.path.expanduser("~/.local/bin/agy") +NARROW = 300 +WIDE = 2400 +LOCK = threading.Lock() +STOP = [] + + +def read_jsonl(path): + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + try: + rows.append(json.loads(line)) + except ValueError: + pass + return rows + + +def read_json(path, default=None): + try: + with open(path, encoding="utf-8") as fh: + return json.load(fh) + except Exception: + return default + + +def write_json(path, data): + with open(path, "w", encoding="utf-8") as fh: + json.dump(data, fh, indent=1, ensure_ascii=False, sort_keys=True) + fh.write(chr(10)) + + +def settings_of(): + path = os.environ.get("B2C_SETTINGS") or os.path.join(HERE, "settings", "pipeline.json") + return read_json(path, {}) or {} + + +def registration_of(settings): + return ((settings.get("index") or {}).get("link_read_2026_11_30") or {}) + + +def book_title(corpus, book): + data = read_json(os.path.join(corpus, book or "", "manifest.json"), {}) or {} + found = (data.get("book") or {}).get("title") + return found or book + + +def stratum_of(form): + n = len(form.get("books") or []) + if n <= 2: + return "2 books" + if n == 3: + return "3 books" + return "4 or more books" + + +def excluded(path): + out = set() + if not path: + return out + data = read_json(path, None) + if isinstance(data, list): + return set(str(x) for x in data) + for row in read_jsonl(path): + if isinstance(row, dict): + name = row.get("canonical") + if name: + out.add(name) + elif isinstance(row, str): + out.add(row) + return out + + +def packet_row(corpus, form, key, wide_books=None): + books = [] + for item in form.get("books") or []: + passage = (item.get("use") or "")[:NARROW] + if wide_books and item.get("book") in wide_books: + passage = (item.get("wide") or "").strip() or passage + books.append({"book": item.get("book"), + "title": book_title(corpus, item.get("book")), + "label": item.get("label") or "", + "passage": passage}) + return {"id": key, "canonical": form.get("canonical"), "books": books} + + +def cmd_build(args): + settings = settings_of() + reg = registration_of(settings) + draw = reg.get("the_draw") or {} + size = int(args.size or draw.get("size") or 0) + seed = int(args.seed or draw.get("seed") or 0) + batches = int(args.batches or draw.get("batches") or 0) + corpus = os.path.abspath(os.path.expanduser(args.corpus_root)) + out = os.path.abspath(os.path.expanduser(args.out)) + forms = read_jsonl(os.path.join(corpus, "index", "links", "forms.jsonl")) + skip = excluded(args.exclude) + population = [f for f in forms if f.get("canonical") not in skip] + strata = collections.defaultdict(list) + for form in population: + strata[stratum_of(form)].append(form) + total = len(population) + drawn = [] + for name in ["2 books", "3 books", "4 or more books"]: + group = sorted(strata.get(name) or [], key=lambda f: f.get("canonical") or "") + random.Random(seed + len(name)).shuffle(group) + share = len(group) / float(total) if total else 0.0 + take = min(int(round(size * share)), len(group)) + drawn.extend(group[:take]) + random.Random(seed).shuffle(drawn) + ids = {} + membership = collections.defaultdict(list) + for number, form in enumerate(drawn, start=1): + key = "r%03d" % number + canonical = form.get("canonical") + ids[canonical] = key + membership[stratum_of(form)].append(canonical) + folder = os.path.join(out, "narrow") + os.makedirs(folder, exist_ok=True) + for stale in sorted(os.listdir(folder)): + if stale.endswith(".jsonl"): + os.remove(os.path.join(folder, stale)) + count = max(1, int(batches)) + size_of = (len(drawn) + count - 1) // count + written = [] + for index, start in enumerate(range(0, len(drawn), size_of), start=1): + chunk = drawn[start:start + size_of] + path = os.path.join(folder, "batch %02d of %02d.jsonl" % (index, count)) + with open(path, "w", encoding="utf-8") as fh: + for form in chunk: + row = packet_row(corpus, form, ids[form.get("canonical")]) + fh.write(json.dumps(row, ensure_ascii=False) + chr(10)) + written.append(path) + registration = {"the_read": "the blind read of the links under the rule of 29 November 2026", + "seed": seed, "size": len(drawn), "batches": count, + "ids": ids, "membership": dict(membership), + "the_strata": dict((k, len(v)) for k, v in membership.items()), + "the_excluded_forms": sorted(skip), + "the_exclusion_why": "the forms the two pending fixes touch, so the read stays valid when they are applied", + "the_population": len(population), + "the_packets": written} + write_json(os.path.join(out, "registration.json"), registration) + print("the draw: %d forms | %d batches | strata %s | excluded %d" + % (len(drawn), count, registration["the_strata"], len(skip))) + print("the registration is written to", os.path.join(out, "registration.json")) + return 0 + + +def cmd_wide_packets(args): + corpus = os.path.abspath(os.path.expanduser(args.corpus_root)) + packets = os.path.abspath(os.path.expanduser(args.packets)) + verdicts = os.path.abspath(os.path.expanduser(args.verdicts)) + forms = read_jsonl(os.path.join(corpus, "index", "links", "forms.jsonl")) + by_canonical = {} + for form in forms: + by_canonical[form.get("canonical")] = form + registration = read_json(os.path.join(packets, "registration.json"), {}) or {} + ids = registration.get("ids") or {} + answer = {} + for name in sorted(os.listdir(verdicts)): + if name.startswith("verdicts "): + for row in read_jsonl(os.path.join(verdicts, name)): + answer[row.get("id")] = row + folder = os.path.join(packets, "wide") + os.makedirs(folder, exist_ok=True) + for stale in sorted(os.listdir(folder)): + if stale.endswith(".jsonl"): + os.remove(os.path.join(folder, stale)) + rows = [] + for key in sorted(answer): + row = answer[key] + canonical = row.get("canonical") + form = by_canonical.get(canonical) + if form is None: + continue + unplaced = [] + for item in row.get("unplaced") or []: + name = item.get("book") if isinstance(item, dict) else item + if name: + unplaced.append(name) + if not unplaced: + continue + rows.append(packet_row(corpus, form, key, set(unplaced))) + batch = int(args.wide_batch or 25) + count = max(1, (len(rows) + batch - 1) // batch) + written = [] + for index, start in enumerate(range(0, len(rows), batch), start=1): + chunk = rows[start:start + batch] + path = os.path.join(folder, "batch %02d of %02d.jsonl" % (index, count)) + with open(path, "w", encoding="utf-8") as fh: + for row in chunk: + fh.write(json.dumps(row, ensure_ascii=False) + chr(10)) + written.append(path) + print("the wide pass: %d forms in %d batches" % (len(rows), count)) + return 0 + + +def prompt_for(reg, rule, rows, wide): + lines = [] + for line in reg.get("the_protocol") or []: + lines.append(line) + lines.append("") + lines.append("THE RULE, the same rule the corpus judge is given:") + lines.append("") + for key in ["the_gloss_test", "the_same_sense_test", "unplaced_is_not_a_sense"]: + text = (rule.get(key) or "").strip() + if text: + lines.append(text) + lines.append("") + if wide: + lines.append("For some of these books the passage below is the same passage and more of it around the term, because the short passage did not show which sense the book means.") + else: + lines.append("A passage can be a heading, a contents line, an index entry, a key-terms list or a sentence.") + lines.append("") + lines.append("Here are %d forms, one JSON object per line:" % len(rows)) + for row in rows: + lines.append(json.dumps(row, ensure_ascii=False)) + lines.append("") + lines.append("Answer with one JSON object and nothing else, one key per form id:") + lines.append('{"r001": {"groups": [["Book A", "Book B"]], "unplaced": [{"book": "Book C", "reason": "the passage still gives no sense"}]}}') + lines.append("Every book of every form must be in exactly one group or in unplaced. Write the book key exactly as it is written above.") + return chr(10).join(lines) + + +def extract_json(text): + depth = 0 + start = -1 + in_string = False + escaped = False + for index, char in enumerate(text or ""): + if in_string: + if escaped: + escaped = False + elif char == chr(92): + escaped = True + elif char == chr(34): + in_string = False + continue + if char == chr(34): + in_string = True + elif char == "{": + if depth == 0: + start = index + depth += 1 + elif char == "}": + depth -= 1 + if depth == 0 and start >= 0: + try: + return json.loads(text[start:index + 1]) + except ValueError: + start = -1 + return None + + +def problems_of(answers, rows): + problems = [] + for row in rows: + key = row.get("id") + entry = answers.get(key) + if not isinstance(entry, dict): + problems.append("%s: no answer" % key) + continue + books = set(item.get("book") for item in row.get("books") or []) + seen = set() + groups = entry.get("groups") or [] + if not isinstance(groups, list): + problems.append("%s: the groups are not a list" % key) + groups = [] + for group in groups: + if not isinstance(group, list) or not group: + problems.append("%s: a group is not a list of books" % key) + continue + for book in group: + if book not in books: + problems.append("%s: %s is not a book of the form" % (key, book)) + if book in seen: + problems.append("%s: %s is in two groups" % (key, book)) + seen.add(book) + unplaced = entry.get("unplaced") or [] + if not isinstance(unplaced, list): + problems.append("%s: the unplaced books are not a list" % key) + unplaced = [] + for item in unplaced: + name = item.get("book") if isinstance(item, dict) else item + if name not in books: + problems.append("%s: %s is not a book of the form" % (key, name)) + elif name in seen: + problems.append("%s: %s is placed and unplaced" % (key, name)) + else: + seen.add(name) + missing = books - seen + if missing: + problems.append("%s: %d books are neither placed nor unplaced" + % (key, len(missing))) + return problems + + +def call_agy(model, prompt, timeout): + """One reader turn, isolated, with the log kept and read back. + + The reader is an agent with tools, so the turn is given nothing to reach + for: it runs in a fresh empty directory outside the corpus and the tool, + the log is written inside that directory, and the log is read back to see + whether the turn touched anything outside it. A turn that did is a + technical void, and the form is asked again. + """ + work = tempfile.mkdtemp(prefix="agy-read-") + log = os.path.join(work, "agy.log") + cmd = [AGY, "--model", model, "--print", prompt, "--output-format", "json", + "--print-timeout", "%ds" % timeout, "--log-file", log, + "--dangerously-skip-permissions"] + started = time.time() + proc = subprocess.run(cmd, capture_output=True, timeout=timeout + 120, cwd=work) + seconds = round(time.time() - started, 1) + out = (proc.stdout or b"").decode("utf-8", "replace") + err = (proc.stderr or b"").decode("utf-8", "replace") + text = "" + if os.path.exists(log): + with open(log, encoding="utf-8", errors="replace") as fh: + text = fh.read() + # the CLI writes its own configuration into the log, and that + # configuration names the folders it knows about: that is the CLI + # telling us what it is, not the reader reaching for the corpus + told = chr(10).join(line for line in text.split(chr(10)) + if "cli_setting_manager" not in line + and "cli_permission" not in line) + everything = sorted(name for name in os.listdir(work) if name != "agy.log") + # the CLI writes its own state into the working directory, and that is + # the CLI keeping its own notes, not the reader writing anything + left = [name for name in everything if not name.startswith(".")] + audit = {"the_directory": work, + "the_log_bytes": len(text), + "the_log_touched_the_corpus": "/Documents/GitHub/textbooks" in told, + "the_files_left": left, + "the_state_the_cli_left": [name for name in everything if name.startswith(".")]} + return proc.returncode, out, err, seconds, audit + + +def cmd_run(args): + settings = settings_of() + reg = registration_of(settings) + rule = (settings.get("index") or {}).get("link_rule") or {} + packets = os.path.abspath(os.path.expanduser(args.packets)) + out = os.path.abspath(os.path.expanduser(args.out)) + stage = args.stage + folder = os.path.join(out, stage) + os.makedirs(folder, exist_ok=True) + files = sorted(name for name in os.listdir(os.path.join(packets, stage)) + if name.endswith(".jsonl")) + if args.limit: + files = files[:args.limit] + lock = threading.Lock() + results = [] + + def one(name): + target = os.path.join(folder, "verdicts " + name) + if os.path.exists(target) and os.path.getsize(target) > 0: + with lock: + print("%-24s already read" % name) + return + rows = read_jsonl(os.path.join(packets, stage, name)) + prompt = prompt_for(reg, rule, rows, stage == "wide") + attempts = [] + answers = None + for attempt in range(2): + code, out_text, err_text, seconds, audit = call_agy(args.model, prompt, args.timeout) + if audit.get("the_log_touched_the_corpus") or audit.get("the_files_left"): + attempts.append("the turn touched something outside its directory") + answers = None + continue + envelope = read_json(out_text, None) + if not isinstance(envelope, dict): + attempts.append("the answer is not an envelope: %s" % err_text[:120]) + if "quota" in (err_text + out_text).lower(): + STOP.append(True) + return + continue + if envelope.get("status") != "SUCCESS": + status = envelope.get("status") + error = str(envelope.get("error") or "") + attempts.append("the door answered %s" % status) + if any(word in error.lower() for word in + ("quota", "429", "resource_exhausted", "rate limit", + "rate_limit", "too many")): + # the door has no allowance left: asking again spends + # nothing and gains nothing, so the run stops and the + # batches already read are kept + STOP.append(True) + return + continue + answers = extract_json(envelope.get("response") or "") + if answers is None: + attempts.append("the answer holds no JSON object") + continue + problems = problems_of(answers, rows) + if not problems: + break + attempts.append("the answer is not usable: %s" % "; ".join(problems[:4])) + answers = None + with lock: + path = os.path.join(folder, "verdicts " + name) + if answers: + with open(path, "w", encoding="utf-8") as fh: + for row in rows: + entry = answers.get(row.get("id")) or {} + groups = entry.get("groups") or [] + unplaced = entry.get("unplaced") or [] + fh.write(json.dumps({"id": row.get("id"), + "canonical": row.get("canonical"), + "groups": groups, + "unplaced": unplaced}, + ensure_ascii=False, sort_keys=True) + chr(10)) + log = {"batch": name, "model": args.model, "stage": stage, + "forms": len(rows), "ok": bool(answers), + "seconds": seconds, "audit": audit, + "attempts": attempts} + results.append(log) + with open(os.path.join(folder, "run-log.jsonl"), "a", encoding="utf-8") as fh: + fh.write(json.dumps(log, ensure_ascii=False, sort_keys=True) + chr(10)) + print("%-24s %s %s" % (name, "ok" if answers else "VOID", + "; ".join(attempts[:1])[:90])) + + threads = [] + for name in files: + thread = threading.Thread(target=one, args=(name,)) + thread.start() + threads.append(thread) + if len(threads) >= args.workers: + threads[0].join() + threads.pop(0) + for thread in threads: + thread.join() + good = len([r for r in results if r.get("ok")]) + print("batches: %d | usable: %d | voids: %d" + % (len(results), good, len(results) - good)) + if STOP: + print("the door has no allowance left; the batches already read are kept") + return 2 + return 0 if good == len(results) else 1 + + +def cmd_merge(args): + out = os.path.abspath(os.path.expanduser(args.out)) + stage = args.stage + narrow = os.path.join(out, stage) + wide = os.path.join(out, "wide") + answer = {} + for folder in [narrow, wide]: + if not os.path.isdir(folder): + continue + for name in sorted(os.listdir(folder)): + if name.startswith("verdicts "): + for row in read_jsonl(os.path.join(folder, name)): + answer[row.get("id")] = row + final = os.path.join(out, "final") + os.makedirs(final, exist_ok=True) + path = os.path.join(final, "verdicts all.jsonl") + with open(path, "w", encoding="utf-8") as fh: + for key in sorted(answer): + fh.write(json.dumps(answer[key], ensure_ascii=False, sort_keys=True) + chr(10)) + print("the merged verdicts: %d forms -> %s" % (len(answer), path)) + return 0 + + +def cmd_pair(args): + out = os.path.abspath(os.path.expanduser(args.out)) + folder = os.path.join(out, "pair") + os.makedirs(folder, exist_ok=True) + made = 0 + for letter, reader in [("A", args.a), ("B", args.b)]: + source = os.path.join(out, reader, "final") + if not os.path.isdir(source): + source = os.path.join(out, reader, args.stage) + for name in sorted(os.listdir(source)): + if not name.startswith("verdicts "): + continue + link = os.path.join(folder, "verdicts %s %s" % (letter, name[len("verdicts "):])) + if os.path.exists(link): + os.remove(link) + os.symlink(os.path.join(source, name), link) + made += 1 + print("the pair folder holds %d files" % made) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="link_read.py") + parser.add_argument("job", choices=("build", "wide-packets", "run", "merge", "pair")) + parser.add_argument("--corpus-root", default="") + parser.add_argument("--packets", default="") + parser.add_argument("--out", default="") + parser.add_argument("--verdicts", default="") + parser.add_argument("--exclude", default="") + parser.add_argument("--size", type=int, default=0) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--batches", type=int, default=0) + parser.add_argument("--wide-batch", type=int, default=8) + parser.add_argument("--model", default="") + parser.add_argument("--stage", default="narrow") + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--timeout", type=int, default=600) + parser.add_argument("--limit", type=int, default=0) + parser.add_argument("--a", default="") + parser.add_argument("--b", default="") + args = parser.parse_args(argv) + if args.job == "build": + return cmd_build(args) + if args.job == "wide-packets": + return cmd_wide_packets(args) + if args.job == "run": + return cmd_run(args) + if args.job == "merge": + return cmd_merge(args) + return cmd_pair(args) + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/make_candidates_spacy.py b/pipeline/scripts/make_candidates_spacy.py new file mode 100644 index 00000000..3895049d --- /dev/null +++ b/pipeline/scripts/make_candidates_spacy.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +"""scripts/make_candidates_spacy.py - candidates from a part-of-speech pass. + +Written 27 Nov 2026 by MCode, after the ruling of Claude Fable 5.2 on the +first candidate generator to add to this pipeline. + +WHAT IT IS +The pipeline has generated its candidate names from capitalisation: a +capitalised run in the text is a candidate. That cannot see a term the +book writes in lower case - "working memory", "operant conditioning" - +and the books gloss a great many of those. The method the literature +uses is a part-of-speech pass: take the noun phrases, keep the ones that +look like a term, and rank them. + +This is that pass, and nothing more. Every candidate it produces goes +through the same admission rules as every other candidate, and the +admission rules are the ones the gold set has already measured. + +THE PATTERN + (ADJ|NOUN|PROPN|NUM)+ one or more modifiers and a head noun +A determiner or a pronoun at the front is dropped: "the ventral stream" +is a candidate called "ventral stream". + + python3 scripts/make_candidates_spacy.py --corpus-root + +What it writes: + + index/candidates_spacy/.jsonl the terms it adds, with a reason + index/candidates_spacy/summary.json the counts, per book +""" +import argparse +import json +import os +import sys +import time + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus import admission +from book2corpus import debris +from book2corpus import projection + +import re + +# The back matter of a book is its own terms and other books' terms, not +# the text of the chapter. In some books it is a chapter of its own, +# which the file name catches; in others it stands at the end of the +# last chapter, and there it is cut here. Without this the generator +# reads the book's own index, finds every term in it, and the +# measurement becomes circular. +BACK_MATTER_RE = re.compile( + r"^#{0,3}\s*(subject index|name index|author index|index continued|" + r"index|glossary|references|bibliography|works cited|further reading)" + r"\s*$", re.I) + + +def cut_back_matter(text): + 'The text up to where the back matter starts.' + lines = (text or "").split("\n") + for number, line in enumerate(lines): + if BACK_MATTER_RE.match(line.strip()): + return "\n".join(lines[:number]) + return text + +# The lines of a figure that are the figure's own words: the labels inside +# the drawing. They are not the book's words and a term is not in them. +# The caption is the book's, so the caption stays. +FIGURE_NOISE = ( + "TEXT IN FIGURE:", + "CONTENT, by type:", + "TYPE:", + "SOURCE:", +) + + +def defigure(text): + """The text with the inside of the figures taken out. + + A figure in these books is written as a block: its type, its caption, + what is in it, the words drawn inside it and where it came from. The + words drawn inside it are the drawing's words - "top right box", + "\"Input processor\"" - and a noun phrase pass over them finds + phrases like that and calls them terms. The caption is the book's + own and stays. + """ + out = [] + inside = False + for line in (text or "").split("\n"): + stripped = line.strip() + if not inside: + if stripped.startswith("TYPE:"): + inside = True + continue + if stripped.startswith("CAPTION:"): + out.append(stripped[len("CAPTION:"):].strip()) + continue + if any(stripped.startswith(prefix) for prefix in FIGURE_NOISE): + continue + if stripped.startswith("[FIGURE"): + continue + out.append(line) + continue + # inside a figure: the caption is the book's, the rest is the + # drawing's own words + if stripped.startswith("CAPTION:"): + out.append(stripped[len("CAPTION:"):].strip()) + if stripped.startswith("SOURCE:"): + inside = False + continue + return "\n".join(out) + +LAW_BOOKS = ("Law-of-Torts-2013", "McDermott-2001", "Stockard-2020", + "Kelly-2018") +# the words a candidate may not carry at its front +KEEP = ("ADJ", "NOUN", "PROPN", "NUM") + + +def chapter_files(corpus_root, book): + folder = os.path.join(corpus_root, book, "chapters") + if not os.path.isdir(folder): + return [] + return [os.path.join(folder, name) for name in sorted(os.listdir(folder)) + if name.lower().endswith(".md")] + + +def read(path): + with open(path, encoding="utf-8", errors="replace") as handle: + return handle.read() + + +def candidates_from_doc(doc): + """The noun phrases of one document that look like a term.""" + out = [] + for chunk in doc.noun_chunks: + tokens = [t for t in chunk] + if not tokens: + continue + # a chunk that holds a piece of punctuation is a chunk whose + # boundary was wrong: "( e.g. , a button press" and "= = 160" are + # not phrases of the book. A hyphen inside a word is part of the + # word, so "short-term" is untouched. + if any(not any(ch.isalnum() for ch in t.text) for t in tokens): + continue + # the front may not be a determiner or a pronoun + while tokens and tokens[0].pos_ in ("DET", "PRON", "ADV"): + tokens = tokens[1:] + if not tokens: + continue + if not any(t.pos_ in KEEP for t in tokens): + continue + # a candidate is a run of modifiers and nouns, not a whole sentence + if any(t.pos_ in ("VERB", "AUX") for t in tokens): + continue + text = " ".join(t.text for t in tokens).strip() + if len(text) < 3 or len(text) > 80: + continue + if "\n" in text: + continue + out.append(text) + return out + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--jobs", type=int, default=8) + parser.add_argument("--books", default="") + parser.add_argument("--limit", type=int, default=0, + help="only this many books (a trial run)") + args = parser.parse_args(argv) + + try: + import spacy + except ImportError: + print("spaCy is not installed. Use the venv that has it:") + print(" ~/Documents/book2corpus/.venv-term/bin/python " + "scripts/make_candidates_spacy.py ...") + return 1 + + corpus = args.corpus_root + nlp = spacy.load("en_core_web_sm") + nlp.max_length = 2_000_000 + + books = sorted(name for name in os.listdir(corpus) + if os.path.isdir(os.path.join(corpus, name, "chapters"))) + if args.books: + wanted = [b.strip() for b in args.books.split(",") if b.strip()] + books = [b for b in books if b in wanted] + if args.limit: + books = books[:args.limit] + + out_dir = os.path.join(corpus, "index", "candidates_spacy") + os.makedirs(out_dir, exist_ok=True) + summary = {} + started = time.time() + + for book in books: + files = chapter_files(corpus, book) + if not files: + continue + texts = [read(path) for path in files] + # the back matter is made of other books' terms, not this book's: + # an index, a bibliography, a references list. Reading it would + # make the measurement circular, because the gold set is built + # from those very pages. + kept = [] + for path, body in zip(files, texts): + name = os.path.basename(path) + if projection.excluded_chapter(name, name): + continue + kept.append(defigure(debris.clean(cut_back_matter(body)))) + texts = kept + if not texts: + continue + profile = admission.profile_for( + book, "law" if book in LAW_BOOKS else "prose") + book_text = admission.BookText("\n".join(texts)) + + # the terms the corpus already has, so the new ones are the new ones + known = set() + terms_path = os.path.join(corpus, "index", "terms", book + ".jsonl") + if os.path.exists(terms_path): + with open(terms_path, encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except ValueError: + continue + known.add(admission.fold(row.get("label", ""))) + + found = {} + for doc in nlp.pipe(texts, batch_size=32, n_process=args.jobs): + for name in candidates_from_doc(doc): + key = admission.fold(name) + if key: + found[key] = name + + rows = [] + added = 0 + for key in sorted(found): + name = found[key] + if key in known: + continue + decision = admission.admit(name, profile=profile, + book_text=book_text) + if decision["verdict"] == admission.ADMIT: + added += 1 + rows.append({"book": book, "term": name, + "source": "spacy_noun_chunk"}) + path = os.path.join(out_dir, book + ".jsonl") + with open(path, "w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + summary[book] = {"candidates": len(found), "new_terms": added, + "chapters": len(files)} + print("%-26s candidates=%-7d new terms=%-6d (%.0fs)" + % (book, len(found), added, time.time() - started), flush=True) + + with open(os.path.join(out_dir, "summary.json"), "w", + encoding="utf-8") as handle: + json.dump({"summary": summary, + "seconds": round(time.time() - started, 1), + "model": "en_core_web_sm", + "pattern": "(ADJ|NOUN|PROPN|NUM)+"}, + handle, indent=1, ensure_ascii=False) + print("done in %.0fs" % (time.time() - started)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/make_corpus_index.py b/pipeline/scripts/make_corpus_index.py new file mode 100644 index 00000000..fb12efe5 --- /dev/null +++ b/pipeline/scripts/make_corpus_index.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""scripts/make_corpus_index.py - the corpus-wide view of the index. + +Written 26 Nov 2026 by MCode, after the ruling of Claude Opus 5.5 on the +corpus-wide term index. + +A reader cannot ask the corpus a question at read time, so the build +answers the question in advance and writes the answer into each reader. +This page is the other half: the whole corpus at once, the concepts that +cross the books, and a way into every one of them. + + python3 scripts/make_corpus_index.py --corpus-root + +What it writes: + + corpus-index.html the corpus-wide view, standing on its own +""" +import argparse +import html +import json +import os +import sys +import time + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus import index_block # noqa: E402 + +TEMPLATE = """ + + + + +The corpus index + + + +
    +

    The corpus index

    +

    Every term in the corpus, the books that use it, and the books that use +it in the same sense. A term named in one book and confirmed in another is a +shared concept: the same idea, in two books, in one sense.

    +

    {{COUNT}}

    + +

    {{N}} concepts shown; a shared sense the judge split is counted as two and two senses it merged are counted as one, and the blind read found more merges made than missed, so this count is neither an established upper nor an established lower bound

    +

    The shared concepts

    +
    +{{BODY}} +
    +
    + + + +""" + + +def read_jsonl(path): + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + rows.append(json.loads(line)) + return rows + + +def book_title(corpus, book): + """The book's own title.""" + manifest = os.path.join(corpus, book, "manifest.json") + if os.path.exists(manifest): + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + found = (data.get("book") or {}).get("title") + if found: + return found + return book + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="make_corpus_index.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args(argv) + + corpus = args.corpus_root + index_root = os.path.join(corpus, "index") + started = time.time() + concepts = read_jsonl(os.path.join(index_root, "concepts.jsonl")) + review = read_jsonl(os.path.join(index_root, "review.jsonl")) + + # where every term of every book is, so a concept can point at it + places = {} + terms_by_book = {} + occurrences_dir = os.path.join(index_root, "occurrences") + for name in sorted(os.listdir(occurrences_dir)) if os.path.isdir(occurrences_dir) else []: + if not name.endswith(".jsonl"): + continue + path = os.path.join(occurrences_dir, name) + book = name[:-len(".jsonl")] + terms_by_book[book] = read_jsonl(path) + for row in terms_by_book[book]: + places["%s|%s" % (name, row["canonical"])] = row + titles = {name: book_title(corpus, name) for name in terms_by_book} + + rows = [] + for concept in concepts: + members = concept.get("members") or [] + if len(members) < 2: + continue + label = None + places_out = [] + for member in members: + found = places.get(member) + book = member.split("|", 1)[0] + if label is None and found: + label = found["label"] + anchors = (found or {}).get("anchors") or [] + places_out.append((book, titles.get(book, book), + anchors[0] if anchors else "")) + rows.append({"label": label or members[0].split("|", 1)[1], + "id": concept["concept_id"], + "size": len(members), "places": places_out}) + rows.sort(key=lambda row: (-row["size"], row["label"])) + + body = [] + for row in rows: + links = [] + for book, title, anchor in row["places"]: + href = "%s/index.html" % book + if anchor: + href += "#%s" % anchor + links.append('%s' + % (html.escape(href), html.escape(title))) + body.append("
    %s
    " % html.escape(row["label"])) + body.append('
    %s
    ' % ", ".join(links)) + total_terms = sum(len(rows) for rows in terms_by_book.values()) + count = ("%d books · %d terms · %d shared concepts · " + "%d terms waiting for a person" + % (len(terms_by_book), total_terms, len(rows), len(review))) + page = TEMPLATE.replace("{{COUNT}}", count) + page = page.replace("{{N}}", str(len(rows))) + page = page.replace("{{BODY}}", "\n".join(body)) + if not args.dry_run: + path = os.path.join(corpus, "corpus-index.html") + with open(path, "w", encoding="utf-8") as fh: + fh.write(page) + print("corpus index: %d books, %d terms, %d concepts, %d review | %.1f s" + % (len(terms_by_book), total_terms, len(rows), len(review), + time.time() - started)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/make_gold.py b/pipeline/scripts/make_gold.py new file mode 100644 index 00000000..0849631c --- /dev/null +++ b/pipeline/scripts/make_gold.py @@ -0,0 +1,495 @@ +#!/usr/bin/env python3 +"""scripts/make_gold.py - the gold set: the terms the books themselves claim. + +Written 27 Nov 2026 by MCode, after the ruling of Claude Fable 5.2 on the +systematic admission of terms (the question of the glossary split). + +WHAT THIS IS +The books in this corpus keep their own back matter: a subject index, a +glossary, a name index. The terms in those pages are the books' own +words about what a term is, and they are the ground truth a rule filter +can be measured against. A rule that refuses a gold term is a rule that +is wrong, and the only honest way to find that out is to have the gold +set and to replay the rules over it. + +So this script builds three files: + + index/gold/terms.jsonl the gold terms + index/gold/people.jsonl the name and author indexes, which + are people and not terms + index/gold/glossary-unmatched.jsonl the glossary lines whose term + boundary could not be found with + confidence; they are held, not + counted as gold + +A glossary line is "TERM definition ( Ch. 5 )" and the boundary is not +marked. The term is found by taking the longest leading run of words +that matches a term in the same book's subject index, with the forms +normalised on both sides: the case, the plural, the singular, the +parenthetical removed, and the inverted index form ("memory, short-term" +is the entry for "short-term memory"). When no such run exists the +first word is taken as a guess, and the guess is NOT gold: it goes to +the unmatched file for a person to look at. A guess that truncates a +term looks like a valid name and passes every rule, so the error would +be silent. + + python3 scripts/make_gold.py --corpus-root +""" +import argparse +import collections +import json +import os +import re + +LETTERS = re.compile(r"[A-Za-z]{3,}") +NUMS = re.compile(r"[0-9]") +NUM = r"(?:\d{1,4}|[ivxlcdmIVXLCDM]{1,7})" +RANGE = NUM + r"(?:\s*[-–—]\s*" + NUM + r")?" +PAGES_RE = re.compile( + r"^" + RANGE + r"(?:\s*,\s*" + RANGE + r")*\s*(?:,\s*)?" + r"(?:ff\.|f\.|t\.|n\.d\.|passim)?\.?$") +PAGE_MARK = re.compile(r"^={3,}\s*PAGE") +# a chapter whose name carries "index" is a subject index unless it is +# the name index or the author index: "25 Index.md" is a subject index +# too, and it is the common case. +PEOPLE = re.compile(r"name[s]? index|author[s]? index|authors index", re.I) +LAW_BOOKS = ("Law-of-Torts-2013", "McDermott-2001", "Stockard-2020", + "Kelly-2018") + + +def read_jsonl(path): + if not os.path.exists(path): + return [] + out = [] + with open(path, encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def write_jsonl(path, rows): + tmp = path + ".tmp" + with open(tmp, "w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + os.replace(tmp, path) + + +def fold(text): + return re.sub(r"\s+", " ", (text or "").strip().casefold()) + + +def singular(word): + if len(word) > 4 and word.endswith("ies"): + return word[:-3] + "y" + if len(word) > 4 and word.endswith("ses"): + return word[:-2] + if len(word) > 3 and word.endswith("s") and not word.endswith("ss"): + return word[:-1] + return word + + +def forms(word): + """The forms a word may be written in.""" + word = word.strip(",;:.").casefold() + if not word: + return [] + out = [word, singular(word)] + if word.endswith("s") and len(word) > 3: + out.append(word[:-1]) + return [f for f in out if f] + + +def clean(line): + return re.sub(r"^\s*[•·]\s*", "", (line or "").strip()) + + +def parse_index_line(line): + """One index line: (term, payload) or None. + + The term is what stands before the first comma, or before the page + list when the book writes without commas. A line where several + entries have run together is refused, and the count is kept. + """ + line = clean(line) + if not line or line.startswith("#") or line.startswith("Source:"): + return None + if PAGE_MARK.match(line): + return None + if re.match(r"^(page numbers|note:|subject index|name index|author " + r"index|glossary|contents)\b", line, re.I): + return None + if "," in line: + left, _, right = line.partition(",") + left, right = left.strip(), right.strip() + if not left: + return None + if PAGES_RE.match(right) and NUMS.search(right): + return (left, right) + m = re.match(r"^see\s+(.+)$", right, re.I) + if m: + return (left, m.group(1).strip()) + return None + m = re.search(r"\s(" + RANGE + r")\s*$", line) + if m: + term = line[:m.start()].strip() + if term and not PAGE_MARK.match(term): + return (term, m.group(1)) + return None + + +def index_entries(path): + """The terms of one index chapter, with the page or cross-reference.""" + entries, skipped = [], 0 + for raw in open(path, encoding="utf-8", errors="replace"): + parsed = parse_index_line(raw) + if parsed is None: + skipped += 1 + continue + entries.append(parsed) + return entries, skipped + + +def glossary_lines(path): + """The lines of one glossary chapter, with the citation taken off.""" + out = [] + for raw in open(path, encoding="utf-8", errors="replace"): + line = clean(raw) + if not line or line.startswith("#") or line.startswith("Source:"): + continue + if PAGE_MARK.match(line): + continue + line = re.sub(r"\s*\(\s*(Ch|Chs|p|pp)\b[^)]*\)\s*$", "", line).strip() + if len(line) >= 8: + out.append(line) + return out + + +def spine_forms(entries): + """The forms an index term may be written in, for the lookup.""" + lookup = {} + for term, _ in entries: + for word in term.split(): + for form in forms(word): + lookup.setdefault(form, term) + return lookup + + +def match_prefix(line, lookup, max_words=6): + """The longest leading run of the line that the index knows.""" + words = line.split() + for size in range(min(max_words, len(words)), 0, -1): + for words_slice in (words[:size],): + # the line as written, the line without a parenthetical, the + # inverted form, and the singular of each + variants = [" ".join(words_slice)] + joined = " ".join(words_slice) + no_paren = re.sub(r"\s*\([^)]*\)", "", joined).strip() + if no_paren and no_paren != joined: + variants.append(no_paren) + for variant in variants: + if not variant: + continue + key = fold(variant) + if key in lookup: + return variant, "index_prefix" + # every word singular or plural of an index term + parts = variant.split() + for i in range(len(parts)): + for form in forms(parts[i]): + if form != parts[i].casefold(): + trial = list(parts) + trial[i] = form + if fold(" ".join(trial)) in lookup: + return variant, "index_prefix" + # the inverted form: "memory, short-term" is "short-term memory" + if size >= 2 and "," in words_slice[0]: + pass + return None, None + + +def inverted_variants(line): + """The inverted index form of a line: the tail moved to the front.""" + words = line.split() + if len(words) < 3: + return [] + head = words[0].rstrip(",") + tail = " ".join(words[1:]) + if "," not in head: + return [] + return [tail + " " + head] + + +# The words a sub-entry can hang on. An index entry that ends with one +# of them is the head of a sub-entry - "synthesis of memory" is written +# "synthesis of memory, 123" or, when the columns are broken, "synthesis +# of" on a line of its own - and the head alone is not a term. This is a +# rule about how an index is laid out, not about what a term is, so it is +# applied while the index is read, and the entries it drops are counted. +SUB_ENTRY_WORDS = frozenset(""" +of and or in for as to at by from with the a an is are was were be been +into on per vs versus such +""".split()) + +PAGE_RUN = re.compile(r"\d{3,}") +PAGE_RANGE = re.compile(r"\d\s*[-\u2013\u2014]\s*\d") + + +FUNCTION_WORDS = frozenset(""" +the a an and or but of in on at to for with without from by as is are was +were be been being it its this that these those there here his her their +our your my me him them us they he she we you i not no nor so if then than +because while when where which who whom whose what how why all any both +each few more most other some only own same too very can could may might +must shall should will would do does did done have has had having about per +versus vs eg ie etc see also +""".split()) + + +# A sub-entry of an index hangs on a preposition: "emotional behavior +# after", "over visual cortex", "vs. environment". The head of such an +# entry is not a term. "above" and "inside" are left out on purpose: +# "above average effect" and "inside out" are terms the books name. +SUB_ENTRY_LEAD = frozenset(""" +under over during after before between among across within without through +throughout against around beside beyond toward towards into onto from about +upon versus vs with at by for in on to of and or outside as per +""".split()) + +# The words that hang a sub-entry at the end of an entry. +SUB_ENTRY_TAIL = frozenset(""" +after before between among across within without through throughout against +around beside beyond toward towards into onto from about upon versus vs +with at by for in on to of and or over under during outside inside the a i +""".split()) + +# The single words that are never a term on their own: a function word or +# a position word. +SINGLE_WORD_NOISE = frozenset(""" +back middle front top bottom left right side end edge over under during +after before out outside inside near past +""".split()) + + +def usable_term(term): + """Is this index entry a term, or the debris of a broken column?""" + words = term.split() + if not words: + return False, "empty" + if "[" in term or "]" in term: + return False, "web_artefact" + if term.rstrip().endswith("?"): + return False, "chapter_question" + if term.lstrip().startswith("-"): + return False, "bullet" + if len(words) == 1: + low = words[0].strip(",;:.").casefold() + if low in FUNCTION_WORDS or low in SINGLE_WORD_NOISE: + return False, "single_function_word" + if words[0].strip(",;:.").casefold() == "the": + # the books name their chapters "The Woman Who Cannot Forget" + # and the index lists them; a heading is not a term + return False, "chapter_title" + if words[0].strip(",;:.").casefold() in SUB_ENTRY_LEAD: + return False, "sub_entry_open" + if words[-1].strip(",;:.").casefold() in SUB_ENTRY_TAIL: + return False, "sub_entry_close" + last = words[-1].strip(",;:.") + if last.isdigit() and len(last) >= 2: + return False, "glued_pages" + if PAGE_RUN.search(term) or PAGE_RANGE.search(term): + return False, "glued_pages" + return True, "" + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--corpus-root", required=True) + args = parser.parse_args(argv) + + corpus = args.corpus_root + gold = [] + people = [] + unmatched = [] + summary = collections.OrderedDict() + reasons = collections.Counter() + + books = sorted(name for name in os.listdir(corpus) + if os.path.isdir(os.path.join(corpus, name, "chapters"))) + for book in books: + folder = os.path.join(corpus, book, "chapters") + stats = {"subject_index": 0, "glossary": 0, "glossary_prefix": 0, + "glossary_guess": 0, "defined": 0, "table": 0, + "people": 0, "lines_skipped": 0} + entries = [] + for name in sorted(os.listdir(folder)): + if not name.lower().endswith(".md"): + continue + path = os.path.join(folder, name) + base = name + if re.search(r"index", base, re.I) and not re.search(r"glossary", + base, re.I): + if PEOPLE.search(base): + found, skipped = index_entries(path) + stats["lines_skipped"] += skipped + for term, payload in found: + people.append({"book": book, "term": term, + "source": "name_index", "chapter": base}) + stats["people"] += 1 + continue + if re.search(r"index", base, re.I): + found, skipped = index_entries(path) + stats["lines_skipped"] += skipped + for term, payload in found: + ok, why = usable_term(term) + if not ok: + key = "index_dropped_" + why + stats[key] = stats.get(key, 0) + 1 + continue + entries.append((term, payload, base)) + elif re.search(r"glossary", base, re.I): + lines = glossary_lines(path) + stats["glossary"] += len(lines) + + # the subject index: the term, and the target of a cross-reference + lookup = spine_forms([(t, p) for t, p, _ in entries]) + for term, payload, chapter in entries: + gold.append({"book": book, "term": term, + "source": "subject_index", "confidence": "high", + "chapter": chapter}) + stats["subject_index"] += 1 + if payload.lower().startswith("see "): + target = payload[4:].strip() + ok, why = usable_term(target) + if not ok: + key = "index_dropped_" + why + stats[key] = stats.get(key, 0) + 1 + continue + gold.append({"book": book, "term": target, + "source": "subject_index_crossref", + "confidence": "high", "chapter": chapter}) + stats["subject_index"] += 1 + + # the glossary: the term is found by the index, or the line is held + for name in sorted(os.listdir(folder)): + if not name.lower().endswith(".md"): + continue + if not re.search(r"glossary", name, re.I): + continue + for line in glossary_lines(os.path.join(folder, name)): + term, how = match_prefix(line, lookup) + if term is None: + for variant in inverted_variants(line): + term, how = match_prefix(variant, lookup) + if term is not None: + break + if term is not None: + ok, why = usable_term(term) + if not ok: + key = "glossary_dropped_" + why + stats[key] = stats.get(key, 0) + 1 + unmatched.append({"book": book, "line": line, + "guess": term, + "source": "glossary", + "chapter": name}) + stats["glossary_guess"] += 1 + continue + gold.append({"book": book, "term": term, + "source": "glossary", "confidence": "high", + "chapter": name}) + stats["glossary_prefix"] += 1 + else: + first = line.split()[0] if line.split() else "" + unmatched.append({"book": book, "line": line, + "guess": first, "source": "glossary", + "chapter": name}) + stats["glossary_guess"] += 1 + reasons["no index match"] += 1 + + # the law books: the terms their codes define, and the names in + # their tables of cases and statutes + for row in read_jsonl(os.path.join(corpus, "index", "terms", + book + ".jsonl")): + if row.get("kind") == "defined" and row.get("label"): + gold.append({"book": book, "term": row["label"], + "source": "defined", "confidence": "high", + "chapter": ""}) + stats["defined"] += 1 + tables = os.path.join(corpus, book, "tables.jsonl") + for row in read_jsonl(tables): + for key in ("title", "name", "term", "case", "statute"): + if row.get(key): + gold.append({"book": book, "term": str(row[key]), + "source": "table", "confidence": "high", + "chapter": ""}) + stats["table"] += 1 + break + + summary[book] = stats + + # one row per term per book, sorted + seen = set() + unique = [] + for row in sorted(gold, key=lambda r: (r["book"], r["source"], + r["term"].casefold())): + key = (row["book"], fold(row["term"])) + if key in seen: + continue + seen.add(key) + unique.append(row) + + out = os.path.join(corpus, "index", "gold") + os.makedirs(out, exist_ok=True) + write_jsonl(os.path.join(out, "terms.jsonl"), unique) + write_jsonl(os.path.join(out, "people.jsonl"), + sorted(people, key=lambda r: (r["book"], r["term"]))) + write_jsonl(os.path.join(out, "glossary-unmatched.jsonl"), + sorted(unmatched, key=lambda r: (r["book"], r["line"]))) + # the exceptions file belongs to a person: it is what a human wrote + # down after looking at the terms the rules refuse, so a rebuild + # never overwrites it + exceptions_path = os.path.join(out, "exceptions.jsonl") + if not os.path.exists(exceptions_path): + write_jsonl(exceptions_path, []) + by_source = collections.Counter(r["source"] for r in unique) + totals = { + "books": len(summary), + "books_with_a_subject_index": sum( + 1 for s in summary.values() if s["subject_index"]), + "gold_terms": len(unique), + "gold_by_source": dict(by_source), + "people_entries": len(people), + "glossary_lines": sum(s["glossary"] for s in summary.values()), + "glossary_matched_by_the_index": sum( + s["glossary_prefix"] for s in summary.values()), + "glossary_held_for_a_person": sum( + s["glossary_guess"] for s in summary.values()), + "lines_skipped": sum(s["lines_skipped"] for s in summary.values()), + "per_book": summary, + } + with open(os.path.join(out, "summary.json"), "w", encoding="utf-8") as handle: + json.dump(totals, handle, indent=1, ensure_ascii=False) + + print("books %d" % totals["books"]) + print("books with a subject index %d" + % totals["books_with_a_subject_index"]) + print("gold terms %d" % totals["gold_terms"]) + for source, count in sorted(by_source.items()): + print(" %-26s %d" % (source, count)) + print("people entries held apart %d" % totals["people_entries"]) + print("glossary lines %d" % totals["glossary_lines"]) + print(" matched by the index %d" + % totals["glossary_matched_by_the_index"]) + print(" held for a person %d" + % totals["glossary_held_for_a_person"]) + print("index lines skipped %d" % totals["lines_skipped"]) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pipeline/scripts/make_heldout.py b/pipeline/scripts/make_heldout.py new file mode 100644 index 00000000..985a1313 --- /dev/null +++ b/pipeline/scripts/make_heldout.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""The held-out pairs: what the judge is measured against. + +The judge that made the corpus verdicts is one model. A model checked +against itself proves nothing, so a set of pairs with a known truth is +held back and planted in every batch, indistinguishable from the real +ones. The judge's catch rate is then a measurement. + +The truth here is not another model's opinion. It is the book's own +numbering: the catalogue says which printed figure each picture is, and +the notes say which printed figure each figure block is. A pair whose +two numbers agree is a pair of the same figure; a pair whose numbers +disagree is a pair of two different figures. The hard ones are the +disagreeing pairs whose descriptions read alike: a judge that reads the +description instead of the picture will accept them, and must not. + + python3 scripts/make_heldout.py --corpus-root --out +""" +import argparse +import json +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +NUMBER_RE = re.compile(r"^\s*(?:fig(?:ure)?|table)?\.?\s*([0-9]+(?:[.\-][0-9]+)*)\s*$", re.I) +NUMBER_IN_TEXT_RE = re.compile(r"\b(?:fig(?:ure)?|table)\s*\.?\s*([0-9]+(?:[.\-][0-9]+)*)", re.I) + + +def number_of(text): + """The printed figure number in a caption or a label.""" + if not text: + return "" + found = NUMBER_RE.match(text.strip()) + if found: + return found.group(1).replace("-", ".") + found = NUMBER_IN_TEXT_RE.search(text, re.I) + if found: + return found.group(1).replace("-", ".") + return "" + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="make_heldout.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--library", default=os.path.expanduser( + "~/Library/Mobile Documents/com~apple~CloudDocs/Textbooks")) + ap.add_argument("--wrong", type=int, default=60) + ap.add_argument("--right", type=int, default=60) + args = ap.parse_args(argv) + + catalogue = {} + index = os.path.join(args.library, "agent-index.jsonl") + with open(index, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except Exception: + continue + if row.get("id"): + catalogue[row["id"]] = row + + right = [] + wrong = [] + for book in sorted(os.listdir(args.corpus_root)): + folder = os.path.join(args.corpus_root, book) + manifest_path = os.path.join(folder, "figures.json") + if not os.path.exists(manifest_path): + continue + with open(manifest_path, encoding="utf-8") as fh: + manifest = json.load(fh) + for figure in manifest.get("figure_map") or []: + # the picture the figure was given, and the pictures it could + # have been given: both are pairs the judge can be asked about + candidates = [figure.get("image")] + list(figure.get("candidates") or []) + for picture_id in candidates: + if not picture_id: + continue + record = catalogue.get(picture_id) + if not record: + continue + label = (figure.get("label") or "").strip() + if not label or label.lower() in ("unnumbered", "none"): + continue + mine = number_of(label) + theirs = (number_of(record.get("figure") or "") + or number_of(record.get("caption") or "")) + if not mine or not theirs: + continue + row = {"picture": record.get("file"), + "picture_id": picture_id, + "book": book, + "figure_id": figure.get("id"), + "caption": (figure.get("caption") or ""), + "description": (figure.get("description") or ""), + "number": mine, + "picture_number": theirs, + "verified": True, + "source": "the books own numbering: the catalogue says which printed figure each picture is, and the notes say which figure each block is"} + if mine == theirs: + if len(right) < args.right: + right.append(dict(row, truth="right")) + elif len(wrong) < args.wrong: + wrong.append(dict(row, truth="wrong")) + rows = right + wrong + with open(args.out, "w", encoding="utf-8") as fh: + for row in rows: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + print("%d held-out pairs: %d right, %d wrong" % (len(rows), len(right), len(wrong))) + print("the truth is the books own numbering, not a model") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/make_index.py b/pipeline/scripts/make_index.py new file mode 100644 index 00000000..82af1b95 --- /dev/null +++ b/pipeline/scripts/make_index.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +"""scripts/make_index.py - the pairs a judge has to decide, and the evidence. + +Written 26 Nov 2026 by MCode, after the ruling of Claude Opus 5.5 on the +corpus-wide term index (briefs 12, 13 and 14). + +The forms are the terms that two or more books share, each with the books +that have it and the sentence the code found it in. The candidates were +the same canonical form. Every candidate carries the evidence: the +sentence in each book where the term is used, found here in the actual text +by code. The judge is asked about two words; the evidence tells it what +those words mean in these two books, and it is the code that found them. + + python3 scripts/make_index.py --corpus-root + +What it writes: + + index/links/forms.jsonl the forms: one term and every book with it + index/links/held-back.jsonl the names held back, and the rule that held them + +It is a build step: it reads the corpus and the admitted terms, and it +writes the candidates and nothing else. It asks nothing of any model. +""" +import argparse +import bisect +import collections +import json +import os +import re +import sys +import time + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus import admission # noqa: E402 +from book2corpus import terms # noqa: E402 +from book2corpus.pipeline import Settings # noqa: E402 + +# a sentence, with its offset in the text +SENTENCE = re.compile(r"[^.!?]*[.!?]+|[^.!?]+") + + +# the two windows of a term's evidence: the narrow one the judge reads +# first, and the wide one it asks for when the narrow one shows no sense. +# Both are measured: the wide window is the one the pilot used. +EVIDENCE_NARROW = 300 +EVIDENCE_WIDE = 1200 + + +def sentences_with_spans(text): + """The sentences of the text, with where they begin.""" + out = [] + for match in SENTENCE.finditer(text or ""): + body = match.group(0).strip() + if body: + out.append((match.start(), body)) + return out + + +def pattern_for(label): + """The pattern that finds a term in the text, however it is spaced.""" + words = [word for word in re.findall(r"[A-Za-z0-9]+", label or "") if word] + if not words: + return None + body = r"[\s\-]+".join(re.escape(word) for word in words) + return r"(?= 0: + start = max(start, before + 2) + after = text.find("\n\n", offset) + if after >= 0: + end = min(end, after) + return text[start:end].strip() + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="make_index.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--books", default="") + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args(argv) + + corpus = args.corpus_root + index_root = os.path.join(corpus, "index") + # the links folder is the corpus own: a library that has never been + # judged has no index/links yet, and the build must make it + if not os.path.isdir(os.path.join(index_root, "links")): + os.makedirs(os.path.join(index_root, "links")) + wanted = [b.strip() for b in args.books.split(",") if b.strip()] + books = sorted(d for d in os.listdir(corpus) + if not d.startswith(".") + and os.path.isdir(os.path.join(corpus, d)) + and (os.path.isdir(os.path.join(corpus, d, "chapters")) + or os.path.exists(os.path.join(corpus, d, + "paragraphs.jsonl"))) + and (not wanted or d in wanted)) + started = time.time() + settings = Settings() + index_settings = settings.get("index") or {} + law_books = frozenset(index_settings.get("law_books") or ()) + by_canonical = {} + # what each scope of each book holds, so the name indexes can be found + scope_labels = collections.defaultdict(list) + for name in books: + rows = terms.read_terms(os.path.join(index_root, "terms", "%s.jsonl" % name)) + if not rows: + continue + text, _marks = book_text(corpus, name) + snippets, wide, routes = evidence(text, rows) + for row in rows: + scope = row.get("scope") or "" + scope_labels[(name, scope)].append(row.get("label") or "") + by_canonical.setdefault(row["canonical"], []).append({ + "book": name, + "term_id": row["term_id"], + "label": row["label"], + "kind": row.get("kind") or "", + "scope": scope, + "use": snippets.get(row["term_id"], ""), + "wide": wide.get(row["term_id"], ""), + "route": routes.get(row["term_id"], ""), + }) + + # the scopes that are the book's own name index: the entries in them + # are names, and a name there is a name everywhere else too + people_scopes = set(key for key, labels in scope_labels.items() + if admission.is_people_scope(labels)) + + # the forms: one row per canonical form, with every book that has it + forms = [] + held = [] + rules = collections.Counter() + for canonical, found in sorted(by_canonical.items()): + # a form is a term two books share, so the books have to be two + # books: a book that files the same term twice (a singular and a + # plural, a hyphen and a space) is still one book, and it is + # one member of the form + members = [] + seen_books = set() + for item in sorted(found, key=lambda item: item["book"]): + if item["book"] in seen_books: + continue + seen_books.add(item["book"]) + members.append(item) + if len(members) < 2: + continue + # a name is not a sense two books can share: it stays in the book + # index and is held back from the link stage + rule_id = "" + for item in members: + people = (item["book"], item.get("scope") or "") in people_scopes + is_held, rule = admission.citation_tier( + item["label"], books=[item["book"]], + law_books=law_books, people_scope=people) + if is_held: + rule_id = rule + break + if rule_id: + rules[rule_id] += 1 + held.append({"canonical": canonical, "rule_id": rule_id, + "label": members[0]["label"], + "books": [item["book"] for item in members], + "scopes": sorted(set(item.get("scope") or "" + for item in members)), + "reason": "a name, not a sense two books can share"}) + continue + forms.append({"canonical": canonical, "books": members, + "pairs": len(members) * (len(members) - 1) // 2}) + if not args.dry_run: + path = os.path.join(index_root, "links", "forms.jsonl") + with open(path, "w", encoding="utf-8") as fh: + for row in forms: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + path = os.path.join(index_root, "links", "held-back.jsonl") + with open(path, "w", encoding="utf-8") as fh: + for row in held: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + print("books: %d | canonical forms: %d | shared forms: %d | held back: %d | %.1f s" + % (len(books), len(by_canonical), len(forms), len(held), + time.time() - started)) + for rule in sorted(rules): + print(" held by %-20s %d" % (rule, rules[rule])) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/make_policy.py b/pipeline/scripts/make_policy.py new file mode 100644 index 00000000..07270846 --- /dev/null +++ b/pipeline/scripts/make_policy.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""The picture policy: which tiers may show a picture, and why. + +The policy is data, not code: it lives in the corpus beside the evidence it +is computed from, so that a re-audit changes the decisions by itself. This +computes it. + +The rules: + + * a tier shows pictures only if the Wilson 95% lower bound of its + audited rate clears the bar, pooled over the books that pass the + per-book integrity gate. + * a book whose audited error rate over the text-only tiers is above the + integrity limit shows no text-only picture; a book with fewer than the + minimum of audited pairs is not measured and inherits the tier + decisions. + * the rate is corrected for the judge that measured it. A judge that + accepts a wrong picture eight times in a hundred makes a tier look + eight points better than it is, so the observed rate is corrected by + the Rogan-Gladen estimator and the uncertainty is carried. + * a tier whose bound straddles the bar is measured again, once, under a + stricter bar; if it still straddles, it stays closed. + * a tier whose sample is more than a tenth missing stays closed: a + failed call is missing data, not a verdict. + + python3 scripts/make_policy.py --corpus-root [--settings ] +""" +import argparse +import json +import os +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus.pipeline import rogan_gladen, wilson # noqa: E402 + +TIER_ORDER = ("numbered", "verified", "description-match", "probable", + "inferred", "ordinal", "candidate", "none") +TEXT_ONLY = ("verified", "probable", "description-match") + + +def wilson_interval(k, n, z=1.959964): + """The lower and the upper bound of a rate.""" + if n <= 0: + return (0.0, 1.0) + p = k / float(n) + d = 1 + z * z / n + centre = p + z * z / (2 * n) + spread = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) + return (max(0.0, (centre - spread) / d), min(1.0, (centre + spread) / d)) + + +def load_audits(corpus): + """What every book was judged to be, and how many calls never came back.""" + books = {} + for name in sorted(os.listdir(corpus)): + path = os.path.join(corpus, name, "figure-audit.json") + if not os.path.exists(path): + continue + with open(path, encoding="utf-8") as fh: + audit = json.load(fh) + tiers = {} + for tier, block in (audit.get("tiers") or {}).items(): + verdicts = block.get("verdicts") or [] + answered = [v for v in verdicts if v.get("verdict") != "error"] + right = sum(1 for v in answered + if v.get("verdict") in ("match", "partial")) + wrong = sum(1 for v in answered + if v.get("verdict") == "mismatch") + tiers[tier] = {"asked": len(verdicts), "answered": len(answered), + "right": right, "wrong": wrong, + "missing": len(verdicts) - len(answered)} + books[name] = {"tiers": tiers, + "judge": audit.get("judge"), + "model": audit.get("model")} + return books + + +def integrity(books, settings): + """The per-book gate: is this book's catalogue sound enough to trust?""" + limit = settings.get("integrity_limit", 0.15) + minimum = settings.get("min_audit_pairs", 10) + out = {} + for book, data in books.items(): + asked = sum(t["asked"] for t in data["tiers"].values()) + answered = sum(t["answered"] for t in data["tiers"].values()) + right = sum(t["right"] for t in data["tiers"].values()) + wrong = sum(t["wrong"] for t in data["tiers"].values()) + text = {tier: data["tiers"][tier] for tier in TEXT_ONLY + if tier in data["tiers"]} + text_asked = sum(t["asked"] for t in text.values()) + text_right = sum(t["right"] for t in text.values()) + text_wrong = sum(t["wrong"] for t in text.values()) + rate = (text_wrong / float(text_asked)) if text_asked else 0.0 + measured = text_asked >= minimum + if not measured: + verdict = "not measured" + elif rate > limit: + verdict = "fails" + else: + verdict = "pass" + out[book] = {"audited": text_asked, "error_rate": round(rate, 4), + "measured": measured, "right": text_right, + "wrong": text_wrong, "verdict": verdict, + "all_audited": answered, "all_asked": asked} + return out + + +def tier_decisions(books, gate_pass, settings, judge_error=None): + """Which tiers may show a picture.""" + bar = settings.get("bar", 0.90) + second = settings.get("second_look_bar", 0.975) + missing_limit = settings.get("missing_sample_limit", 0.10) + judge_error = judge_error or {} + sensitivity = judge_error.get("sensitivity") + specificity = judge_error.get("specificity") + decisions = {} + for tier in TIER_ORDER: + asked = right = wrong = missing = 0 + for book, data in books.items(): + if book not in gate_pass: + continue + cell = data["tiers"].get(tier) + if not cell: + continue + asked += cell["asked"] + right += cell["right"] + wrong += cell["wrong"] + missing += cell["missing"] + if not asked: + decisions[tier] = {"audited": 0, "right": 0, "rate": 0.0, + "wilson_lower": 0.0, "shows_picture": False, + "reason": "no audited pairs"} + continue + answered = right + wrong + missing_share = missing / float(asked) + observed = right / float(answered) if answered else 0.0 + corrected = rogan_gladen(observed, sensitivity, specificity) \ + if sensitivity and specificity else observed + lower, upper = wilson_interval(answered, answered) # placeholder + lower, upper = wilson_interval(right, answered) + corrected_lower, corrected_upper = wilson_interval( + int(round(corrected * answered)), answered) + shows = corrected_lower >= bar and missing_share <= missing_limit + reason = "the bound clears the bar" + if missing_share > missing_limit: + reason = "too much of the sample never came back" + elif corrected_lower < bar and corrected_upper >= bar: + reason = "the bound straddles the bar; it stays closed" + elif not shows: + reason = "the bound does not clear the bar" + decisions[tier] = {"audited": asked, "answered": answered, + "right": right, "wrong": wrong, + "missing": missing, + "missing_share": round(missing_share, 4), + "observed_rate": round(observed, 4), + "rate": round(corrected, 4), + "wilson_lower": round(corrected_lower, 4), + "wilson_upper": round(corrected_upper, 4), + "shows_picture": shows, "reason": reason} + return decisions + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="make_policy.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--settings", default=os.path.join(HERE, "settings", "pipeline.json")) + ap.add_argument("--judge-error", default="", + help="a JSON file with the measured sensitivity and specificity of the judge") + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args(argv) + + from book2corpus.pipeline import Settings + settings = Settings(args.settings).values + books = load_audits(args.corpus_root) + gate = integrity(books, settings) + passing = [book for book, cell in gate.items() if cell["verdict"] == "pass"] + judge_error = {} + if args.judge_error and os.path.exists(args.judge_error): + with open(args.judge_error, encoding="utf-8") as fh: + judge_error = json.load(fh) + decisions = tier_decisions(books, passing, settings, judge_error) + policy = {"schema": 2, "bar": settings.get("bar", 0.90), + "z": 1.959964, + "integrity_limit": settings.get("integrity_limit", 0.15), + "min_audit": settings.get("min_audit_pairs", 10), + "missing_sample_limit": settings.get("missing_sample_limit", 0.10), + "text_only_tiers": list(TEXT_ONLY), + "judge_error": judge_error, + "gate_a": {"pass": passing, + "fail": [b for b, c in gate.items() if c["verdict"] == "fails"], + "unmeasured": [b for b, c in gate.items() if c["verdict"] == "not measured"], + "rule": settings.get("integrity_rule", "a book whose audited error rate over the text-only tiers is above the limit shows no text-only picture; a book with fewer than the minimum of audited pairs is not measured and inherits the tier decisions")}, + "gate_b": {"rule": "a tier shows pictures only if the Wilson lower bound of its corrected audited rate, pooled over the books that passed Gate A, clears the bar", + "tiers": decisions}, + "integrity": gate} + verdicts = [] + for book in sorted(books): + for tier, cell in sorted(books[book]["tiers"].items()): + verdicts.append({"book": book, "tier": tier, + "audited": cell["asked"], "answered": cell["answered"], + "right": cell["right"], "wrong": cell["wrong"], + "missing": cell["missing"], + "source": "figure-audit.json"}) + out_policy = os.path.join(args.corpus_root, "picture-policy.json") + out_verdicts = os.path.join(args.corpus_root, "picture-verdicts.jsonl") + if not args.dry_run: + with open(out_policy, "w", encoding="utf-8") as fh: + json.dump(policy, fh, indent=1, sort_keys=True, ensure_ascii=False) + with open(out_verdicts, "w", encoding="utf-8") as fh: + for row in verdicts: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + print("Gate A: %d pass, %d fail, %d not measured" + % (len(policy["gate_a"]["pass"]), len(policy["gate_a"]["fail"]), + len(policy["gate_a"]["unmeasured"]))) + print("Gate B:") + for tier in TIER_ORDER: + cell = decisions.get(tier) or {} + print(" %-18s audited %-5s lower %-7s %s" + % (tier, cell.get("audited"), cell.get("wilson_lower"), + "shows" if cell.get("shows_picture") else "closed")) + if args.dry_run: + print("would write: %s (dry run)" % out_policy) + else: + print("written: %s" % out_policy) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/pipeline/scripts/make_search_index.py b/pipeline/scripts/make_search_index.py new file mode 100644 index 00000000..4643fb25 --- /dev/null +++ b/pipeline/scripts/make_search_index.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""scripts/make_search_index.py - the search index, derived from the index. + +Written 26 Nov 2026 by MCode, after the ruling of Claude Opus 5.5 on the +corpus-wide term index. + +The index's source of truth is the sorted JSONL in the corpus: it is +diffable, merge-friendly and byte-reproducible. Searching sixteen +thousand rows of it with a scan is fine for a person and slow for +anything else, so this builds the derived thing that is fast: an SQLite +database with FTS5 over the terms and over the concepts. + +It is DERIVED. It is rebuilt from the JSONL every time, it is not +committed, and nothing depends on it except the search. + + python3 scripts/make_search_index.py --corpus-root + python3 scripts/make_search_index.py --corpus-root --query amygdala +""" +import argparse +import json +import os +import sqlite3 +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +SEARCH_INDEX = "index/search.sqlite3" + +SCHEMA = """ +DROP TABLE IF EXISTS terms; +DROP TABLE IF EXISTS concepts; +CREATE VIRTUAL TABLE terms USING fts5( + book UNINDEXED, canonical UNINDEXED, label, scope, chapter, + tokenize='unicode61 remove_diacritics 2'); +CREATE VIRTUAL TABLE concepts USING fts5( + concept_id UNINDEXED, label, books, + tokenize='unicode61 remove_diacritics 2'); +CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT); +""" + + +def read_jsonl(path): + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + rows.append(json.loads(line)) + return rows + + +def build(corpus, path): + """The database, built from the JSONL.""" + directory = os.path.dirname(path) + if directory: + os.makedirs(directory, exist_ok=True) + if os.path.exists(path): + os.remove(path) + con = sqlite3.connect(path) + con.executescript(SCHEMA) + terms = 0 + for name in sorted(os.listdir(os.path.join(corpus, "index", "occurrences"))): + if not name.endswith(".jsonl"): + continue + book = name[:-len(".jsonl")] + for row in read_jsonl(os.path.join(corpus, "index", "occurrences", name)): + con.execute("INSERT INTO terms VALUES (?,?,?,?,?)", + (book, row.get("canonical") or "", row.get("label") or "", + row.get("scope") or "", row.get("chapter") or "")) + terms += 1 + concepts = 0 + for row in read_jsonl(os.path.join(corpus, "index", "concepts.jsonl")): + members = row.get("members") or [] + books = [] + for member in members: + book, _sep, canonical = member.partition("|") + books.append("%s: %s" % (book, canonical)) + label = "" + for member in members: + book, _sep, canonical = member.partition("|") + path2 = os.path.join(corpus, "index", "occurrences", + "%s.jsonl" % book) + for found in read_jsonl(path2): + if found.get("canonical") == canonical: + label = found.get("label") or canonical + break + if label: + break + con.execute("INSERT INTO concepts VALUES (?,?,?)", + (row.get("concept_id") or "", label, "; ".join(books))) + concepts += 1 + con.execute("INSERT INTO meta VALUES ('terms', ?)", (str(terms),)) + con.execute("INSERT INTO meta VALUES ('concepts', ?)", (str(concepts),)) + con.commit() + con.close() + return terms, concepts + + +def search(path, query, limit=25): + """What the index holds for a word.""" + if not os.path.exists(path): + return None + con = sqlite3.connect(path) + hits = [] + try: + for row in con.execute( + "SELECT book, label, chapter FROM terms WHERE terms MATCH ? " + "ORDER BY rank LIMIT ?", (query, limit)): + hits.append(("term",) + row) + for row in con.execute( + "SELECT concept_id, label, books FROM concepts " + "WHERE concepts MATCH ? ORDER BY rank LIMIT ?", (query, limit)): + hits.append(("concept",) + row) + except sqlite3.OperationalError as exc: + print("the query is not one FTS5 understands: %s" % exc) + con.close() + return hits + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="make_search_index.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--query", default="") + ap.add_argument("--path", default="") + args = ap.parse_args(argv) + path = args.path or os.path.join(args.corpus_root, SEARCH_INDEX) + if args.query: + hits = search(path, args.query) + if hits is None: + print("no search index yet: run without --query first") + return 1 + if not hits: + print("nothing for %r" % args.query) + return 0 + for kind, first, second, third in hits: + if kind == "term": + print("term %-24s %-40s %s" % (first, second[:40], third)) + else: + print("concept %-24s %-40s %s" % (first[:24], second[:40], + third[:60])) + return 0 + terms, concepts = build(args.corpus_root, path) + print("search index: %d terms, %d concepts | %s" + % (terms, concepts, path)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/make_terms.py b/pipeline/scripts/make_terms.py new file mode 100644 index 00000000..41246b09 --- /dev/null +++ b/pipeline/scripts/make_terms.py @@ -0,0 +1,1005 @@ +#!/usr/bin/env python3 +"""scripts/make_terms.py - the terms stage: the model names, the code proves. + +Written 26 Nov 2026 by MCode, after the ruling of Claude Opus 5.5 on the +corpus-wide term index (briefs 12, 13 and 14). + +THE RULE: THE MODEL PROPOSES, CODE PROVES. A model names the terms of a +chapter; the code then checks that each name occurs verbatim in that +chapter and runs the rule filter over it. A name that fails either test is +written down as a rejection, with its reason, and never enters the index. + +The model does not read the book. It reads a PROJECTION of the chapter: its +headings, its figure captions, the openings of a spread of its paragraphs, +the spans the chapter emphasises, the sentences that define something and +its glossary lines. The whole corpus is 26 million tokens and one pass over +it is not on the table, so the projection is what the model sees. What the +projection cannot show, the index does not claim: a term that occurs only +inside body prose is not in the index, and the corpus README says so in +those words. + +The money is bounded three times over: the stage has its own allocation, +the pre-flight refuses to start on an estimate that is too big, and the +pilot decides whether the cheap model is good enough before the real run. + + python3 scripts/make_terms.py --corpus-root the stage + python3 scripts/make_terms.py --corpus-root --pilot the pilot + +What it writes: + + index/terms/.jsonl the terms of one book, named and verified + index/seeds/.jsonl the hints this book's own text offers + index/cache/terms.jsonl the answer of every call, keyed by its hash + index/terms_rejected.jsonl every name that did not survive, and why + index/manifest/terms.jsonl one row per chapter: key, hashes, status +""" +import argparse +import hashlib +import json +import os +import re +import sys +import time +from concurrent.futures import ThreadPoolExecutor + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus import debris, projection, terms # noqa: E402 +from book2corpus.judge import Judge, ParseFailure # noqa: E402 +from book2corpus.pipeline import (CircuitBreaker, Ledger, # noqa: E402 + Settings, hash_of) + +TERMS_PROMPT = """You are naming the terms of one chapter of a textbook. + +You are given the parts of the chapter where its terms live. Every line is +tagged with what it is: a heading, a caption, the opening of a paragraph, a +definition, an emphasised span, or a glossary line. These are the places +where a term can be shown to be; they are not the whole chapter. + +%s + +HINTS: phrases this book uses often. They may be terms and they may not be: +%s + +Name the terms of this chapter: the concepts, mechanisms, theories, kinds of +thing, named parts, named laws and named people that the chapter is about. +Leave out layout words, credit lines, citation words and ordinary words. + +Reply with ONE JSON array of strings and nothing else, for example: +["working memory", "central executive"] + +At most %d terms. Each term must be written exactly as the chapter writes +it. +""" + +# the pilot: how many chapters, from how many books +PILOT_BOOKS = 12 +PILOT_CHAPTERS_PER_BOOK = 2 + +# a chapter goes to the strong model when this much of what the cheap +# model named did not survive the code +STRONG_RETRY_SHARE = 0.4 + + +def parse_terms(text): + """The answer is a bare JSON array of term strings. + + Anything else is a parse failure, and a parse failure is worth trying + again: the same question, asked again, is often answered properly. + """ + match = re.search(r"\[.*\]", text or "", re.S) + if not match: + raise ParseFailure("the model wrote no array") + try: + parsed = json.loads(match.group(0)) + except ValueError as exc: + raise ParseFailure("the array is not JSON: %s" % exc) + if not isinstance(parsed, list): + raise ParseFailure("the answer is not a list") + out = [] + for item in parsed: + if isinstance(item, str): + out.append(item) + elif isinstance(item, dict) and isinstance(item.get("term"), str): + out.append(item["term"]) + return out + + +def key_for(prompt, model): + """The hash of the question: the same question is asked once.""" + return hashlib.sha256((prompt + model).encode("utf-8")).hexdigest() + + +def book_title(corpus, book): + """The book's own title, for the header of the call.""" + manifest = os.path.join(corpus, book, "manifest.json") + if os.path.exists(manifest): + with open(manifest, encoding="utf-8") as fh: + data = json.load(fh) + found = (data.get("book") or {}).get("title") + if found: + return found + return book + + +def chapters_of(book_dir): + """The chapters of a notes book, in order, with their text.""" + out = [] + folder = os.path.join(book_dir, "chapters") + for name in sorted(os.listdir(folder)): + if not name.endswith(".md"): + continue + with open(os.path.join(folder, name), encoding="utf-8") as fh: + out.append((name, fh.read())) + return out + + +def figures_of(book_dir): + """The figures a notes book shows, with their captions.""" + path = os.path.join(book_dir, "figures.json") + if not os.path.exists(path): + return [] + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + return data.get("figures") or [] + + +def seeds_of(book_dir, chapters, figures): + """The hints this book's own text offers. + + The seeds are per book and are computed from that book's text alone: a + corpus-wide seed count would move when a book is added and would + silently change every chapter's key. + """ + seeds = {} + for _name, body in chapters: + for head in debris.headings(body): + key = terms.canonical_form(head["text"]) + if key and len(key) > 2: + seeds.setdefault(key, {"term_id": "seed:%s" % key, + "canonical": key, "label": head["text"], + "count": 0, "kind": "heading"}) + for figure in figures: + phrase = terms.clean_caption(figure.get("caption")) + key = terms.canonical_form(phrase) + if key and len(key) > 2: + seeds.setdefault(key, {"term_id": "seed:%s" % key, + "canonical": key, "label": phrase, + "count": 0, "kind": "caption"}) + text = "\n\n".join(body for _name, body in chapters) + for phrase, count in terms.frequent_phrases(text): + key = terms.canonical_form(phrase) + if key and len(key) > 2 and key not in seeds: + seeds[key] = {"term_id": "seed:%s" % key, "canonical": key, + "label": phrase, "count": count, "kind": "frequent"} + rows = list(seeds.values()) + rows.sort(key=lambda row: row["canonical"]) + return rows + + +def seed_slice(seeds, body, limit=30): + """The hints for one chapter: the seeds that occur in it. + + The chapter is read once: its phrases are put in a table and the seeds + are looked up in it. Looking a seed up by scanning the chapter again + would read every chapter once per seed, and there are a hundred seeds. + """ + words = debris.tokenise(body) + table = set() + for start in range(len(words)): + for length in range(1, 5): + table.add(tuple(words[start:start + length])) + rows = [] + for row in seeds: + key = tuple(row["canonical"].split()) + if key and key in table: + rows.append(row) + rows.sort(key=lambda row: (-row["count"], row["canonical"])) + return rows[:limit] + + +def prompt_for(title, chapter, path, items, hints, max_terms): + """The question asked of the model.""" + lines = [] + for item in items: + lines.append("[%s] %s" % (item["kind"], item["text"])) + head = ("BOOK: %s\nCHAPTER: %s\nSECTION: %s\n" + % (title, chapter, path or "-")) + hint_text = "; ".join(row["label"] for row in hints) or "none" + return TERMS_PROMPT % (head + "\n".join(lines), hint_text, max_terms) + + +def chapter_path(chapter_name, body): + """The title of a chapter, for the header of the call and the scope. + + The first heading of the chapter, and only that: a chapter with a + hundred sub-headings would otherwise give every term in it a scope + of a thousand words. + """ + for head in debris.headings(body): + if head["level"] == 1 and head["text"]: + return head["text"][:120] + for head in debris.headings(body): + if head["text"]: + return head["text"][:120] + stem = re.sub(r"\.md$", "", chapter_name) + stem = re.sub(r"^\d+\s*", "", stem) + return stem.strip()[:120] + + +def verify(term, body): + """Is this name really in the chapter? The rules have the last word. + + Returns "" when the term is admitted, or the reason it is not. + """ + if not debris.occurs(body, term): + return "not_verbatim" + return terms.rule_filter(term) + + +def call_cost(prices, model, tokens_in, tokens_out): + """What one call cost.""" + price = prices.get(model) or {} + return (tokens_in * price.get("in", 0.0)) + (tokens_out * price.get("out", 0.0)) + + +def estimate_cost(prices, model, calls, tokens_in_each, tokens_out_each): + """What a stage will cost, before it starts: the pre-flight.""" + total_in = calls * tokens_in_each + total_out = calls * tokens_out_each + return call_cost(prices, model, total_in, total_out) + + +def append_cache(path, row): + """One chapter's answer, on the disk, now. + + The flush and the fsync are the point: a run that is killed after this + line has lost nothing, and the next run reads the answer back. + """ + directory = os.path.dirname(path) + if directory: + os.makedirs(directory, exist_ok=True) + with open(path, "a", encoding="utf-8") as fh: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + fh.flush() + os.fsync(fh.fileno()) + + + +PROSE_PROMPT = """You are reading part of a chapter of a textbook and naming +its terms. + +%s + +Name the terms: the concepts, mechanisms, theories, kinds of thing, named +parts, named laws and named people that this text is about. Leave out +layout words, credit lines, citation words and ordinary words. + +Reply with ONE JSON array of strings and nothing else, for example: +["working memory", "central executive"] + +At most %d terms. Each term must be written exactly as the text writes +it. +""" + +# the most tokens of text one call may carry +PROSE_TOKENS = 8000 + +# the most characters that is, at four characters a token +PROSE_CHARS = PROSE_TOKENS * 4 + +# how many pieces one unit of a machine corpus holds, so that a finished +# unit is kept and a stopped run loses only the unit in flight +PROSE_UNIT_PIECES = 24 + + +def prose_chunks(body, limit=PROSE_CHARS): + """The text of a chapter, in pieces, cut at the paragraph boundary. + + A piece is never cut inside a paragraph: a term that is broken over + two pieces is a term the model cannot see. + """ + pieces = [] + current = "" + for paragraph in re.split(r"\n\s*\n", body): + block = paragraph + "\n\n" + if len(block) > limit: + if current: + pieces.append(current) + current = "" + for start in range(0, len(block), limit): + pieces.append(block[start:start + limit]) + continue + if len(current) + len(block) > limit: + pieces.append(current) + current = "" + current += block + if current: + pieces.append(current) + return pieces + + +def paragraphs_of(book_dir): + """The text of a machine corpus: its paragraphs, in order.""" + pieces = [] + path = os.path.join(book_dir, "paragraphs.jsonl") + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + record = json.loads(line) + if record.get("kind") not in (None, "body"): + continue + pieces.append(record.get("text") or "") + return "\n\n".join(pieces) + + +def prose_units(corpus, books): + """The units of the second pass: the text the projection did not show. + + The first pass reads a projection of each chapter: its headings, its + captions, a spread of its paragraph openings, its definitions and its + glossary. That is six per cent of the words. This pass reads the + rest, so that the index is not blind to a term that the prose names + and the structure does not. + """ + out = [] + for name in books: + book_dir = os.path.join(corpus, name) + if os.path.exists(os.path.join(book_dir, "paragraphs.jsonl")): + # a machine corpus has no chapters, but it has text, and the + # text is where its terms are. It is cut into units that can + # be finished and kept: one unit of a thousand pieces is + # one unit of an hour, and a run that is stopped loses it. + body = paragraphs_of(book_dir) + pieces = prose_chunks(body) + for start in range(0, len(pieces), PROSE_UNIT_PIECES): + group = pieces[start:start + PROSE_UNIT_PIECES] + out.append({"kind": "prose", "book": name, + "title": book_title(corpus, name), + "name": "the code %d" % (start // PROSE_UNIT_PIECES + 1), + "body": "\n\n".join(group), "pieces": group, + "hints": [], "path": ""}) + continue + chapters = chapters_of(book_dir) + seeds = seeds_of(book_dir, chapters, figures_of(book_dir)) + for chapter_name, body in chapters: + if projection.excluded_chapter(chapter_name, chapter_name): + continue + pieces = prose_chunks(body) + if not pieces: + continue + out.append({"kind": "prose", "book": name, + "title": book_title(corpus, name), + "name": chapter_name, "body": body, + "pieces": pieces, + "hints": seed_slice(seeds, body), + "path": chapter_path(chapter_name, body)}) + return out + + +def run_prose_unit(judge, unit, model, max_terms): + """The terms of one chapter, read from the prose.""" + admitted = [] + rejected = [] + named = [] + calls = 0 + tokens_in = 0 + tokens_out = 0 + for piece in unit["pieces"]: + prompt = PROSE_PROMPT % (piece, max_terms) + result = judge.text(prompt, key_for(prompt, model), model, + parse=parse_terms) + calls += 1 + tokens_in += result.get("tokens_in", 0) + tokens_out += result.get("tokens_out", 0) + answer = result.get("answer") + if not isinstance(answer, list): + return {"failed": True, "calls": calls, "tokens_in": tokens_in, + "tokens_out": tokens_out, "admitted": [], "rejected": [], + "named": []} + for term in answer[:max_terms]: + term = (term or "").strip() + if not term or term in named: + continue + named.append(term) + reason = verify(term, unit["body"]) + if reason: + rejected.append({"term": term, "reason": reason}) + else: + admitted.append(term) + return {"failed": False, "calls": calls, "tokens_in": tokens_in, + "tokens_out": tokens_out, "admitted": admitted, + "rejected": rejected, "named": named} + +def unit_key(unit, model, prompt_hash): + """The key of a unit of work. + + It is the hash of what was asked: the text, the hints, the prompt, the + model and the rules. A chapter whose key is already in the manifest is + not asked again, and a new book does not move any other book's keys. + """ + if unit["kind"] == "prose": + material = {"book": unit["book"], "kind": "prose", + "chapter": unit.get("name") or "", + "text": debris.normalise(unit["body"]), + "prompt": hashlib.sha256(PROSE_PROMPT.encode("utf-8")).hexdigest()[:16], + "model": model, "rules": terms.RULES_VERSION} + elif unit["kind"] == "law": + material = {"book": unit["book"], "kind": "law", + "text": hashlib.sha256( + "\n".join(p.get("text") or "" for p in unit["paragraphs"]) + .encode("utf-8")).hexdigest(), + "prompt": prompt_hash, "model": model, + "rules": terms.RULES_VERSION, + "projection": projection.PROJECTION_VERSION} + else: + material = {"book": unit["book"], "chapter": unit["name"], + "kind": "chapter", + "text": debris.normalise(unit["body"]), + "seeds": [row["canonical"] for row in unit["hints"]], + "prompt": prompt_hash, "model": model, + "rules": terms.RULES_VERSION, + "projection": projection.PROJECTION_VERSION} + return hash_of(material) + + +def units_of(corpus, books): + """The units of the stage: one chapter of a notes book, or one law code. + + A chapter that is a bibliography is not a unit: naming terms from a + list of references is waste, and the rule says so. + """ + out = [] + for name in books: + book_dir = os.path.join(corpus, name) + title = book_title(corpus, name) + paragraphs_path = os.path.join(book_dir, "paragraphs.jsonl") + if os.path.exists(paragraphs_path): + records = [] + with open(paragraphs_path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + records.append(json.loads(line)) + out.append({"kind": "law", "book": name, "title": title, + "paragraphs": records}) + continue + chapters = chapters_of(book_dir) + seeds = seeds_of(book_dir, chapters, figures_of(book_dir)) + for chapter_name, body in chapters: + if projection.excluded_chapter(chapter_name, chapter_name): + continue + items = projection.build(body, chapter_name) + if not items: + continue + hints = seed_slice(seeds, body) + out.append({"kind": "chapter", "book": name, "title": title, + "name": chapter_name, "body": body, "items": items, + "path": chapter_path(chapter_name, body), + "hints": hints, "seeds": seeds, + "headings": len([i for i in items if i["kind"] == "heading"])}) + return out + + +def run_unit(judge, unit, model, max_terms): + """Name the terms of one unit, and let the code decide. + + Every name the model gives is checked: first that it really occurs in + the text, then that it passes the rules. A name that fails is a + rejection, with its reason, and it is never admitted. + """ + admitted = [] + rejected = [] + named = [] + calls = 0 + tokens_in = 0 + tokens_out = 0 + groups = (projection.pack(unit["items"]) if unit["kind"] == "chapter" + else [unit["items"]]) + for group in groups: + prompt = prompt_for(unit["title"], unit.get("name") or "the code", + unit.get("path") or "", group, + unit.get("hints") or [], max_terms) + result = judge.text(prompt, key_for(prompt, model), model, + parse=parse_terms) + calls += 1 + tokens_in += result.get("tokens_in", 0) + tokens_out += result.get("tokens_out", 0) + if result.get("verdict") == "error" or result.get("answer") is None: + return {"failed": True, "calls": calls, "tokens_in": tokens_in, + "tokens_out": tokens_out, "admitted": [], "rejected": [], + "named": []} + for term in (result.get("answer") or [])[:max_terms]: + term = (term or "").strip() + if not term or term in named: + continue + named.append(term) + reason = verify(term, unit["body"] if unit["kind"] == "chapter" + else " ".join(p.get("text") or "" + for p in unit["paragraphs"])) + if reason: + rejected.append({"term": term, "reason": reason}) + else: + admitted.append(term) + return {"failed": False, "calls": calls, "tokens_in": tokens_in, + "tokens_out": tokens_out, "admitted": admitted, + "rejected": rejected, "named": named} + + +def law_run(unit): + """The terms of a law code: the ones the code itself defines.""" + found = terms.law_terms(unit["paragraphs"]) + records = [] + for row in found: + records.append({"term_id": "%s:%s" % (unit["book"], row["canonical"]), + "label": row["label"], "canonical": row["canonical"], + "kind": "defined", "scope": row.get("scope") or "", + "definition": row.get("definition")}) + return {"failed": False, "calls": 0, "tokens_in": 0, "tokens_out": 0, + "admitted": [row["label"] for row in found], + "rejected": [], "named": [row["label"] for row in found], + "records": records} + + +def pilot_chapters(units): + """The pilot's chapters: two from each of twelve books. + + The books are spread through the corpus, so the pilot is not taken from + one kind of book only. + """ + by_book = {} + for unit in units: + if unit["kind"] != "chapter": + continue + by_book.setdefault(unit["book"], []).append(unit) + names = sorted(by_book) + if not names: + return [] + step = max(1, len(names) // PILOT_BOOKS) + chosen = [] + for index in range(0, len(names), step): + # the chapters are taken from inside the book, not from its front + # matter: a cover page has nothing in it, and a pilot of cover + # pages says nothing about the books + chapters = by_book[names[index]] + picks = [] + for part in range(PILOT_CHAPTERS_PER_BOOK): + at = int(len(chapters) * (part + 1) / (PILOT_CHAPTERS_PER_BOOK + 1)) + at = min(at, len(chapters) - 1) + if chapters[at] not in picks: + picks.append(chapters[at]) + chosen.extend(picks) + if len({unit["book"] for unit in chosen}) >= PILOT_BOOKS: + break + return chosen[:PILOT_BOOKS * PILOT_CHAPTERS_PER_BOOK] + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="make_terms.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--books", default="") + ap.add_argument("--model", default="") + ap.add_argument("--strong-model", default="") + ap.add_argument("--jobs", type=int, default=8) + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--pilot", action="store_true") + ap.add_argument("--pass2", action="store_true", + help="read the text the projection did not show") + ap.add_argument("--prose-model", default="", + help="the model that reads the prose") + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args(argv) + + settings = Settings() + index_settings = settings.get("index") or {} + prices = settings["money"]["prices"] + model = args.model or index_settings.get("terms_model", "gemini-3.1-flash-lite") + strong_model = args.strong_model or index_settings.get("strong_model", + "gemini-3.8-flash") + allocation = index_settings.get("terms_cap_usd", 2.0) + preflight = index_settings.get("terms_preflight_usd", 1.5) + if args.pass2: + allocation = index_settings.get("prose_cap_usd", 3.0) + preflight = index_settings.get("prose_preflight_usd", 2.25) + if allocation is None or preflight is None: + # a stage with no cap is stopped before the first call + print("REFUSED: the terms stage has no money cap. A stage that has not") + print(" been given a cap is stopped before the first call.") + return 2 + allocation = float(allocation) + preflight = float(preflight) + strong_cap = float(index_settings.get("strong_retry_cap_usd", 0.6)) + max_terms = int(index_settings.get("terms_per_call", 40)) + corpus = args.corpus_root + index_root = os.path.join(corpus, "index") + + books = sorted(d for d in os.listdir(corpus) + if not d.startswith(".") + and os.path.isdir(os.path.join(corpus, d)) + and (os.path.isdir(os.path.join(corpus, d, "chapters")) + or os.path.exists(os.path.join(corpus, d, + "paragraphs.jsonl")))) + wanted = [b.strip() for b in args.books.split(",") if b.strip()] + if wanted: + books = [b for b in books if b in wanted] + units = (prose_units(corpus, books) if args.pass2 + else units_of(corpus, books)) + if args.limit: + units = units[:args.limit] + prompt_hash = hashlib.sha256(TERMS_PROMPT.encode("utf-8")).hexdigest()[:16] + started = time.time() + + if args.dry_run: + calls = 0 + tokens = 0 + for unit in units: + if unit["kind"] == "chapter": + calls += len(projection.pack(unit["items"])) + tokens += projection.tokens(unit["items"]) + elif unit["kind"] == "prose": + pieces = unit.get("pieces") or [] + calls += len(pieces) + tokens += sum(len(piece) // 4 + 120 for piece in pieces) + else: + calls += 1 + print("units: %d | calls: %d | projection tokens: %d" + % (len(units), calls, tokens)) + print("estimated cost on %s: $%.4f (allocation $%.2f, pre-flight $%.2f)" + % (model, estimate_cost(prices, model, calls, tokens // max(calls, 1), 400), + allocation, preflight)) + return 0 + + judge_settings = dict(settings["judge"]) + judge_settings["attempts"] = 3 + judge_settings["model"] = model + if args.pass2: + model = args.prose_model or index_settings.get( + "prose_model", "gemini-2.5-flash-lite") + judge_settings["model"] = model + ledger = Ledger(prices) + breaker = CircuitBreaker(judge_settings) + judge = Judge(judge_settings, ledger, breaker) + strong_settings = dict(judge_settings) + strong_settings["model"] = strong_model + strong_breaker = CircuitBreaker(strong_settings) + strong_judge = Judge(strong_settings, Ledger(prices), strong_breaker) + + if args.pilot: + return run_pilot(units, judge, strong_judge, model, strong_model, + max_terms, prices, index_root) + + # the manifest: what has been asked, and what came of it + manifest_path = os.path.join(index_root, "manifest", "terms.jsonl") + cache_path = os.path.join(index_root, "cache", "terms.jsonl") + manifest = {} + if os.path.exists(manifest_path): + with open(manifest_path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + row = json.loads(line) + manifest[row["key"]] = row + cache = {} + if os.path.exists(cache_path): + with open(cache_path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + row = json.loads(line) + cache[row["key"]] = row + + todo = [] + for unit in units: + key = unit_key(unit, model, prompt_hash) + if key in cache and key in manifest: + unit["key"] = key + unit["cached"] = cache[key] + continue + unit["key"] = key + todo.append(unit) + + # the pre-flight: the estimate is measured, not guessed + calls = 0 + tokens = 0 + for unit in todo: + if unit["kind"] == "chapter": + groups = projection.pack(unit["items"]) + calls += len(groups) + tokens += projection.tokens(unit["items"]) + elif unit["kind"] == "prose": + pieces = unit.get("pieces") or [] + calls += len(pieces) + tokens += sum(len(piece) // 4 + 120 for piece in pieces) + else: + calls += 1 + estimate = estimate_cost(prices, model, calls, tokens // max(calls, 1), + 400 if not args.pass2 else 200) + if estimate > preflight: + print("REFUSED: the terms pass is estimated at $%.4f, and the " + "pre-flight line is $%.2f" % (estimate, preflight)) + print("the allocation for this stage is $%.2f" % allocation) + return 2 + print("terms pass: %d units (%d to ask, %d reused), %d calls, " + "estimated $%.4f" + % (len(units), len(todo), len(units) - len(todo), calls, estimate)) + + results = {} + failures = [] + max_call_cost = [0.0] + strong_spend = [0.0] + lock = __import__("threading").Lock() + + def ask(unit): + if unit["kind"] == "law": + out = law_run(unit) + elif unit["kind"] == "prose": + out = run_prose_unit(judge, unit, model, max_terms) + else: + out = run_unit(judge, unit, model, max_terms) + cost = call_cost(prices, model, out["tokens_in"], out["tokens_out"]) + with lock: + if cost > max_call_cost[0]: + max_call_cost[0] = cost + return unit, out + + workers = max(1, args.jobs) + pending = [] + queue = list(todo) + stopped = False + with ThreadPoolExecutor(max_workers=workers) as pool: + while queue or pending: + while queue and len(pending) < workers and not stopped: + if ledger.usd() + 1.5 * max_call_cost[0] >= allocation: + stopped = True + break + unit = queue.pop(0) + pending.append(pool.submit(ask, unit)) + if not pending: + break + unit, out = pending.pop(0).result() + results[unit["key"]] = (unit, out) + if out["failed"]: + failures.append(unit) + continue + # the strong model, for the chapters the cheap model got wrong + named = max(1, len(out["named"])) + share = len(out["rejected"]) / float(named) + needs_strong = (share > STRONG_RETRY_SHARE + or (not out["admitted"] and unit.get("headings", 0) >= 5)) + if needs_strong and strong_spend[0] < strong_cap: + if unit["kind"] == "prose": + strong_out = run_prose_unit(strong_judge, unit, + strong_model, max_terms) + else: + strong_out = run_unit(strong_judge, unit, strong_model, + max_terms) + strong_spend[0] += call_cost(prices, strong_model, + strong_out["tokens_in"], + strong_out["tokens_out"]) + if not strong_out["failed"]: + out = strong_out + out["retried"] = True + else: + failures.append(unit) + continue + else: + out["retried"] = False + unit["out"] = out + with lock: + records = out.get("records") + if records is None: + records = [] + for label in out["admitted"]: + key = terms.canonical_form(label) + if not key: + continue + records.append({"term_id": "%s:%s" % (unit["book"], key), + "label": label, "canonical": key, + "kind": "named", + "scope": unit.get("path") or "", + "definition": None}) + cache[unit["key"]] = { + "key": unit["key"], "book": unit["book"], + "chapter": unit.get("name") or "code", + "model": strong_model if out.get("retried") else model, + "admitted": out["admitted"], "rejected": out["rejected"], + "terms": records, + "calls": out["calls"], "tokens_in": out["tokens_in"], + "tokens_out": out["tokens_out"]} + append_cache(cache_path, cache[unit["key"]]) + + return write_results(units, units, results, cache, manifest, manifest_path, + cache_path, index_root, ledger, failures, + time.time() - started, model, strong_model) + + +def read_rows(path): + """The rows of a file, one a line.""" + rows = [] + if not os.path.exists(path): + return rows + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if line: + rows.append(json.loads(line)) + return rows + + +def write_results(units, all_units, results, cache, manifest, manifest_path, + cache_path, index_root, ledger, failures, seconds, model, + strong_model): + """The terms of every book, the seeds, the rejections and the manifest.""" + rejected_rows = [] + per_book = {} + for unit in units: + if unit["key"] not in cache: + continue + row = cache[unit["key"]] + for item in row["rejected"]: + rejected_rows.append({"book": unit["book"], + "chapter": unit.get("name") or "code", + "term": item["term"], "reason": item["reason"]}) + per_book.setdefault(unit["book"], []).append(unit) + rejected_rows.sort(key=lambda row: (row["book"], row["chapter"], row["term"])) + + written = 0 + for book, book_units in sorted(per_book.items()): + found = {} + # what is already in the index stays: the second pass adds to it + for row in terms.read_terms(os.path.join(index_root, "terms", + "%s.jsonl" % book)): + found[row["canonical"]] = row + for unit in book_units: + row = cache.get(unit["key"]) + if not row: + continue + for record in row.get("terms") or []: + key = record["canonical"] + if not key or key in found: + continue + record = dict(record) + record["scope"] = unit.get("path") or record.get("scope") or "" + found[key] = record + terms.write_terms(os.path.join(index_root, "terms", "%s.jsonl" % book), + list(found.values())) + seeds = [] + for unit in book_units: + if unit.get("seeds"): + seeds = unit["seeds"] + break + if seeds: + terms.write_terms(os.path.join(index_root, "seeds", "%s.jsonl" % book), + seeds) + written += len(found) + + rejected_path = os.path.join(index_root, "terms_rejected.jsonl") + seen = set() + merged = [] + for row in rejected_rows: + mark = (row["book"], row["chapter"], row["term"], row["reason"]) + if mark in seen: + continue + seen.add(mark) + merged.append(row) + for row in read_rows(rejected_path): + mark = (row.get("book"), row.get("chapter"), row.get("term"), + row.get("reason")) + if mark in seen: + continue + seen.add(mark) + merged.append(row) + merged.sort(key=lambda row: (row["book"], row["chapter"], row["term"])) + with open(rejected_path, "w", encoding="utf-8") as fh: + for row in merged: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + + rows = [] + # the manifest describes every unit the corpus has, not only the ones + # this run touched: the cache holds them all + for key in sorted(cache): + cache_row = cache[key] + row = manifest.get(key) + if not cache_row: + continue + status = "reused" if row else "computed" + rows.append({ + "unit": "%s/%s" % (cache_row["book"], cache_row.get("chapter") or "code"), + "key": key, + "status": status, + "terms": len(cache_row["admitted"]), + "rejected": len(cache_row["rejected"]), + "calls": cache_row["calls"], + "model": cache_row["model"], + "output": hash_of(cache_row["admitted"]), + }) + rows.sort(key=lambda row: row["unit"]) + os.makedirs(os.path.dirname(manifest_path), exist_ok=True) + with open(manifest_path, "w", encoding="utf-8") as fh: + for row in rows: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + + os.makedirs(os.path.dirname(cache_path), exist_ok=True) + cache_rows = sorted(cache.values(), key=lambda row: row["key"]) + with open(cache_path, "w", encoding="utf-8") as fh: + for row in cache_rows: + fh.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n") + + print("terms: %d | rejected: %d | units: %d | failures: %d | " + "cost $%.4f | %.0f s" + % (written, len(rejected_rows), len(rows), len(failures), + ledger.usd(), seconds)) + if failures: + print("FAILED: %d chapter(s) could not be named; the stage fails" + % len(failures)) + return 1 + return 0 + + +def run_pilot(units, judge, strong_judge, model, strong_model, max_terms, + prices, index_root): + """The pilot: is the cheap model good enough? + + Twenty-four chapters, two from each of twelve books, each named by both + models. The cheap model is lost if it admits less than seventy per + cent of what the strong model admits on the same chapters, or if more + than thirty-five per cent of what it names does not survive the code. + """ + chosen = pilot_chapters(units) + if not chosen: + print("no chapters to pilot on") + return 1 + lite_admitted = 0 + strong_admitted = 0 + lite_rejected = 0 + lite_named = 0 + strong_named = 0 + details = [] + def both(unit): + lite = run_unit(judge, unit, model, max_terms) + strong = run_unit(strong_judge, unit, strong_model, max_terms) + return unit, lite, strong + + with ThreadPoolExecutor(max_workers=8) as pool: + for unit, lite, strong in pool.map(both, chosen): + lite_admitted += len(lite["admitted"]) + strong_admitted += len(strong["admitted"]) + lite_rejected += len(lite["rejected"]) + lite_named += len(lite["named"]) + strong_named += len(strong["named"]) + details.append({"book": unit["book"], "chapter": unit["name"], + "lite_admitted": len(lite["admitted"]), + "strong_admitted": len(strong["admitted"]), + "lite_rejected": len(lite["rejected"]), + "lite_named": len(lite["named"])}) + print(" %-26s %-34s lite %2d/%-2d strong %2d/%-2d" + % (unit["book"], unit["name"][:34], len(lite["admitted"]), + len(lite["named"]), len(strong["admitted"]), + len(strong["named"])), flush=True) + lite_share = (lite_admitted / float(strong_admitted)) if strong_admitted else 0.0 + rejection = (lite_rejected / float(lite_named)) if lite_named else 1.0 + lost = (lite_share < 0.7) or (rejection > 0.35) + verdict = {"chapters": len(chosen), "lite": model, "strong": strong_model, + "lite_admitted": lite_admitted, "strong_admitted": strong_admitted, + "lite_share": round(lite_share, 4), + "lite_rejection": round(rejection, 4), + "lite_lost": bool(lost), "details": details} + os.makedirs(os.path.join(index_root, "manifest"), exist_ok=True) + with open(os.path.join(index_root, "manifest", "pilot.json"), "w", + encoding="utf-8") as fh: + json.dump(verdict, fh, indent=1, sort_keys=True, ensure_ascii=False) + fh.write("\n") + print() + print("pilot: %d chapters | lite admitted %d, strong admitted %d (%.0f%%) | " + "lite rejection %.1f%%" + % (len(chosen), lite_admitted, strong_admitted, lite_share * 100, + rejection * 100)) + print("VERDICT: the cheap model is %s" % ("LOST" if lost else "good enough")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/md_corpus2html.py b/pipeline/scripts/md_corpus2html.py new file mode 100755 index 00000000..88ffe1f0 --- /dev/null +++ b/pipeline/scripts/md_corpus2html.py @@ -0,0 +1,690 @@ +#!/usr/bin/env python3 +r"""Turn the notes corpora into books: an HTML reader for each. + + python3 scripts/md_corpus2html.py --corpus-root \ + --library ~/Library/Mac\ Documents/com~apple~CloudDocs/Textbooks + +Every book gets index.html (the reader), figures/ (the pictures it uses), +figures.json (what was used, with the hash of every file) and a report. Each +book is checked against its own notes by a second, independent reading of the +source, and a book that fails the check is reported as failing rather than +quietly shipped. + +Before anything is built the gate is itself checked: a reader with a +paragraph removed, a figure field changed, a link broken, an id duplicated +and an outside reference added must each be caught. + +The build is a build system, so it behaves like one: + + * it measures itself (--profile says where the time went); + * it does only what changed (a book whose inputs are unchanged is left + alone, and --force says to redo it anyway); + * it can be run in parallel (--jobs); + * it writes the same bytes every time (the same inputs give the same + reader, whatever order the folders are listed in); + * it keeps a log of what it did (build-log.jsonl); + * and every switch it has can be turned off (see SWITCHES below). +""" +import argparse +import hashlib +import json +import multiprocessing +import os +import re +import shutil +import sys +import tempfile +from concurrent.futures import ThreadPoolExecutor +import time + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from book2corpus import figures, index_block, notes, notes_gate +from book2corpus import stamp +from book2corpus.figures import ALGORITHM_VERSION + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TEMPLATES = os.path.join(HERE, "book2corpus", "templates") +CACHE = os.path.expanduser("~/.cache/book2corpus") + +# The switches. Each has a default that does the right thing and an +# escape hatch that brings the older behaviour back, so a build can always +# be reproduced exactly as it was before a change. +SWITCHES = { + "B2C_MATCH": ("on", "on|off", + "match pictures to figures; off builds the text only"), + "B2C_ORDER": ("canonical", "canonical|legacy", + "the order the manifest and the candidates are written in"), + "B2C_MD": ("on", "on|off", + "render the notes' own markdown in the reader"), + "B2C_JOBS": ("4", "a number", + "how many books to build at once"), +} + + +def switch(name): + """A switch, with its default, and a warning if it is set to nonsense.""" + default, values, _ = SWITCHES[name] + value = os.environ.get(name, default).strip().lower() + allowed = values.split("|") + if value not in allowed and not value.isdigit(): + print("warning: %s=%s is not one of %s; using %s" + % (name, value, values, default)) + return default + return value + + +def switch_report(): + out = {} + for name, (default, values, meaning) in SWITCHES.items(): + out[name] = {"value": os.environ.get(name, default), + "default": default, "allowed": values, "meaning": meaning} + return out + + +SAMPLE = """# A Chapter + +Source: A Test Book (2026) + +=== PAGE 7 (PDF page 9) === + +The first paragraph of the test book, long enough to be a sentence of its own. + +[FIGURE 1] +TYPE: diagram +CAPTION: Figure 1.1 A test diagram +CONTENT: A box with an arrow pointing at another box, which is what a test diagram is. +TEXT IN FIGURE: none +-- +""" + + +def self_test(): + """A gate that has never been seen to fail proves little.""" + failures = [] + work = tempfile.mkdtemp(prefix="book2corpus-gate-") + try: + corpus = os.path.join(work, "book") + os.makedirs(os.path.join(corpus, "chapters")) + with open(os.path.join(corpus, "chapters", "01 A Chapter.md"), "w", + encoding="utf-8") as fh: + fh.write(SAMPLE) + library = os.path.join(work, "library") + os.makedirs(library) + built = notes.build_book(corpus, library) + meta = {"title": "A Test Book", "citation": "A Test Book (2026)"} + html = notes.render_html(built, meta, TEMPLATES) + problems = notes_gate.check(corpus, built, html) + if problems: + failures.append("the gate fails on a good reader: %s" % problems[:2]) + return failures + mutations = { + "a paragraph is removed": lambda text: re.sub(r'

    ]*>.*?

    ', + "", text, count=1, flags=re.S), + "a figure field is changed": lambda text: text.replace("A box with an arrow", + "A circle without an arrow"), + "a link is broken": lambda text: text.replace('href="#ch-01"', 'href="#nowhere"'), + "the contents loses a chapter": lambda text: text.replace( + 'class="chapter" data-chapter="1"', 'class="lost" data-chapter="1"'), + "an id is used twice": lambda text: text.replace('id="ch-01"', 'id="t-01-0001"'), + "the reader reaches outside": lambda text: text.replace("", + ''), + } + for name, mutate in mutations.items(): + broken = mutate(html) + if broken == html: + failures.append("the mutation did nothing: %s" % name) + continue + if not notes_gate.check(corpus, built, broken): + failures.append("the gate did not catch: %s" % name) + return failures + finally: + shutil.rmtree(work, ignore_errors=True) + + +def book_meta(book_dir): + """The book's own name and citation. + + The title is the book's own citation, as the notes give it, and not + the name of the file the notes were made from: a reader whose title + is a file name names the wrong thing. + """ + title = os.path.basename(book_dir.rstrip("/")) + citation = "" + source = "" + sources = [] + chapters = os.path.join(book_dir, "chapters") + if os.path.isdir(chapters): + for name in sorted(os.listdir(chapters)): + if not name.endswith(".md"): + continue + with open(os.path.join(chapters, name), encoding="utf-8") as fh: + for line in fh: + if line.startswith("Source:"): + sources.append(line.split(":", 1)[1].strip()) + break + if sources: + source = sources[0] + # the book own extent, not the first chapter: the pages run from + # the first chapter first page to the last chapter last page + pages = [] + for text in sources: + found = re.search(r"PDF pages\s+([0-9]+)\s+to\s+([0-9]+)", text) + if found: + pages.append((int(found.group(1)), int(found.group(2)))) + if pages: + first = min(p[0] for p in pages) + last = max(p[1] for p in pages) + source = re.sub(r",\s*PDF pages\s+[0-9]+\s+to\s+[0-9]+", + ", PDF pages %d to %d" % (first, last), source) + citation = source + title = re.split(r",\s*PDF pages\b", source)[0].strip() + title = re.sub(r"\s*\(printed page.*$", "", title).strip() + else: + path = os.path.join(book_dir, "index.md") + if os.path.exists(path): + with open(path, encoding="utf-8") as fh: + for line in fh: + if line.startswith("# "): + title = line[2:].strip() + break + return {"title": title, "citation": citation} + + +def _sha256_file(path): + digest = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def tool_state(): + """The tool that builds the readers: its hash and the files it covers. + + The closure is walked from the builders, so a change to code no + reader depends on - the term tokeniser, say - does not invalidate + every reader in the corpus. A walk that cannot be trusted falls + back to the whole package, which is the safe direction. + """ + return stamp.tool_state(HERE) + + +def tool_hash(): + """The hash of the tool that builds the readers.""" + return tool_state()["hash"] + + +def environment_hash(): + """The hash of what the build depends on besides the notes. + + The Python that runs it, the Pillow that makes the pictures and the + libwebp that encodes them: a different encoder writes different + bytes, so the reader has to be built again. + """ + parts = ["python=%d.%d" % (sys.version_info[0], sys.version_info[1])] + try: + import PIL + parts.append("pillow=" + PIL.__version__) + try: + from PIL import features + parts.append("webp=" + str(features.version("webp"))) + except Exception: + parts.append("webp=unknown") + except Exception: + parts.append("pillow=missing") + return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest() + + +def switches_hash(args, embed, level, picture_base): + """The hash of the switches that change what the reader says. + + The switches that only change how fast the build runs are not here: + the number of jobs and the verbosity do not touch the bytes. + """ + parts = ["embed=%s" % embed, + "level=%s" % (level or ""), + "picture_base=%s" % (picture_base or ""), + "match=%s" % os.environ.get("B2C_MATCH", "on"), + "order=%s" % os.environ.get("B2C_ORDER", "canonical"), + "md=%s" % os.environ.get("B2C_MD", "on")] + return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest() + + +def corpus_file_hash(path): + """The hash of a file of the corpus, or nothing when it is not there.""" + if not os.path.exists(path): + return "absent" + return _sha256_file(path) + + +def catalogue_slice_hash(records): + """The hash of the catalogue's lines that belong to one book. + + The catalogue holds every book, so hashing it whole would rebuild + every book when any one of them changes. Each book takes its own + slice, in a canonical order. + """ + parts = [] + for record in records: + item = json.dumps(record, sort_keys=True, ensure_ascii=False) + parts.append((record.get("file") or "", item)) + parts.sort() + return hashlib.sha256("\n".join(item for _file, item in parts) + .encode("utf-8")).hexdigest() + + +def picture_digests(library, records, cache): + """The digest of every picture the book uses. + + The digest is of the content, not of the size and the date: a file + that changed must change the reader. The library lives in the cloud, + and a picture that has not been read for a while costs a third of a + second to open however small it is, so the digests are cached by the + file's size and its date, and only a picture that moved is read + again. The cache is filled by scripts/warm_picture_cache.py. + """ + parts = [] + todo = [] + for record in records: + name = record.get("file") + if not name: + continue + path = os.path.join(library, name) + try: + info = os.stat(path) + except OSError: + parts.append("%s:absent" % name) + continue + key = os.path.abspath(path) + entry = cache.get(key) + if not entry or entry[0] != info.st_size or entry[1] != info.st_mtime_ns: + todo.append((name, key, info.st_size, info.st_mtime_ns, path)) + parts.append("%s:pending" % name) + else: + parts.append("%s:%s" % (name, entry[2])) + if todo: + workers = max(1, min(16, (os.cpu_count() or 4) * 2)) + with ThreadPoolExecutor(max_workers=workers) as pool: + digests = list(pool.map(_sha256_file, [item[4] for item in todo])) + for item, digest in zip(todo, digests): + name, key, size, mtime, _path = item + cache[key] = [size, mtime, digest] + parts.append("%s:%s" % (name, digest)) + parts.sort() + return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest() + + +def verdicts_slice_hash(path, book): + """The hash of the verdicts that belong to one book. + + The verdicts are the evidence the picture policy rests on. A new + verdict for one book must not rebuild the others. + """ + if not os.path.exists(path): + return "absent" + parts = [] + with open(path, encoding="utf-8") as fh: + for line in fh: + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except Exception: + continue + if row.get("book") == book: + parts.append(json.dumps(row, sort_keys=True, ensure_ascii=False)) + parts.sort() + return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest() + + +def stat_cache_path(): + """Where the digests of the library's pictures are kept.""" + os.makedirs(CACHE, exist_ok=True) + return os.path.join(CACHE, "picture-stat.json") + + +def index_payload_for(corpus_root, book): + """The compact block of cross-references this book's reader carries. + + The reader stands alone, so the build answers the corpus-wide question + in advance and writes the answer into the page. The full slice stays + in the corpus index; the page carries only what it shows. + """ + path = os.path.join(corpus_root, "index", "slices", "%s.json" % book) + if not os.path.exists(path): + return None + with open(path, encoding="utf-8") as fh: + payload = json.load(fh) + def link_to(other, anchor): + return "../%s/index.html#%s" % (other, anchor) + return index_block.build(payload.get("terms") or [], link_to=link_to) + + +def book_key(book_dir, book, tool, environment, switches, policy, verdicts, + catalogue, pictures): + """Everything a book's reader depends on, as one hash. + + This is Make's rule: a product is redone when an input is newer than + the result. The inputs are the notes, the builder, the environment + it runs in, the switches it runs with, the catalogue's own lines for + this book, the pictures it uses, the policy the pictures must obey + and the demotions the audit wrote. + """ + parts = [tool, environment, switches, policy, verdicts, catalogue, + pictures, "algorithm=%d" % figures.ALGORITHM_VERSION] + chapters = os.path.join(book_dir, "chapters") + for name in sorted(os.listdir(chapters)): + if name.endswith(".md"): + parts.append(name + ":" + _sha256_file(os.path.join(chapters, name))) + slice_path = os.path.join(os.path.dirname(os.path.abspath(book_dir)), + "index", "slices", "%s.json" % book) + if os.path.exists(slice_path): + parts.append("index:" + _sha256_file(slice_path)) + for name in ("demotions.json", "figure-audit.json", "audit-adjudication.json", + "golden.json"): + path = os.path.join(book_dir, name) + if os.path.exists(path): + parts.append(name + ":" + _sha256_file(path)) + return hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest() + + +def index_slice_hash(corpus_root, book): + """The hash of the index slice this book's reader shows.""" + return stamp.index_hash(corpus_root, book) + + +def stamp_html(html, corpus_root, book, tool, files=()): + """The reader carries the stamp of what it was built from. + + A reader that cannot say what it was built from cannot be checked: + the gate has to be able to tell a reader made from this index from + one made from the index before it. The files the tool hash covers + are in the stamp too, so a mismatch can be explained and not + guessed at. + """ + return stamp.stamp_html(html, index_slice_hash(corpus_root, book), tool, + files) + + +def cache_path(corpus_root): + os.makedirs(CACHE, exist_ok=True) + name = hashlib.sha256(os.path.abspath(corpus_root).encode("utf-8")).hexdigest()[:16] + return os.path.join(CACHE, "build-cache-%s.json" % name) + + +def log_path(): + os.makedirs(CACHE, exist_ok=True) + return os.path.join(CACHE, "build-log.jsonl") + + +def write_log(record): + """The audit trail: one line per build, with the switches in force.""" + with open(log_path(), "a", encoding="utf-8") as fh: + fh.write(json.dumps(record, sort_keys=True, ensure_ascii=False) + "\n") + + +def _build_one(job): + """Build one book and write it. Runs in its own process.""" + (corpus_root, library, folder, embed, picture_base, level) = job + book_dir = os.path.join(corpus_root, folder) + started = time.time() + built = notes.build_book(book_dir, library, embed=embed, level=level, + picture_base=picture_base) + if built is None: + return None + meta = book_meta(book_dir) + index_payload = index_payload_for(corpus_root, folder) + html = notes.render_html(built, meta, TEMPLATES, index_payload) + # the stamp says what this reader was built from, so the gate can + # tell it from one built from an older index + html = stamp_html(html, corpus_root, folder, tool_hash(), + tool_state()["files"]) + size = len(html.encode("utf-8")) + # a book that is too heavy to open gets smaller pictures, and a book + # that is still too heavy keeps its pictures beside it instead of + # inside it. A book that borrows its pictures carries none, so there + # is nothing to make smaller. + if size > notes.SOFT_BUDGET and embed and not picture_base: + for level_try in notes.LEVELS[1:]: + built = notes.build_book(book_dir, library, embed=True, level=level_try, + picture_base=picture_base) + html = notes.render_html(built, meta, TEMPLATES, index_payload) + size = len(html.encode("utf-8")) + if size <= notes.SOFT_BUDGET: + break + else: + built = notes.build_book(book_dir, library, embed=False, + level=notes.LEVELS[-1], picture_base=picture_base) + html = notes.render_html(built, meta, TEMPLATES, index_payload) + size = len(html.encode("utf-8")) + problems = notes_gate.check(book_dir, built, html, picture_base=picture_base) + # the findings that are not failures: a picture that another figure's + # description fits better is the audit's business, not the book's + suspects = [] + if not picture_base: + scan = notes_gate.Scan() + scan.feed(html) + suspects = notes_gate.swap_suspects(scan, built["manifest"], + built.get("figure_map") or []) + figures = sum(1 for c in built["chapters"] for b in c["blocks"] + if b["kind"] == "figure") + attached = sum(1 for c in built["chapters"] for b in c["blocks"] + if b.get("image")) + tiers = {} + for chapter in built["chapters"]: + for block in chapter["blocks"]: + if block["kind"] == "figure": + tier = block.get("tier") or "none" + tiers[tier] = tiers.get(tier, 0) + 1 + if size > notes.HARD_BUDGET: + problems.append("the reader is %.1f MB, over the %.0f MB ceiling" + % (size / 1e6, notes.HARD_BUDGET / 1e6)) + report = {"book": folder, "title": meta["title"], + "algorithm": ALGORITHM_VERSION, + "chapters": len(built["chapters"]), + "paragraphs": sum(1 for c in built["chapters"] for b in c["blocks"] + if b["kind"] == "paragraph"), + "figures": figures, "figures_with_pictures": attached, + "tiers": tiers, "pictures_bytes": built["embedded_bytes"], + "embedded": built["embed"], "html_bytes": size, + "problems": problems, "suspects": suspects} + if not problems: + # the pictures the reader does not use are removed only now: a + # build that failed its gate must leave the corpus as it was + for name in built.get("stale_derivatives") or []: + path = os.path.join(book_dir, "figures", name) + if os.path.exists(path): + os.remove(path) + with open(os.path.join(book_dir, "index.html"), "w", encoding="utf-8") as fh: + fh.write(html) + slice_path = os.path.join(corpus_root, "index", "slices", "%s.json" % folder) + if os.path.exists(slice_path): + with open(slice_path, encoding="utf-8") as source: + payload = json.load(source) + with open(os.path.join(book_dir, "%s.index.json" % folder), "w", + encoding="utf-8") as fh: + json.dump(payload, fh, indent=1, sort_keys=True, + ensure_ascii=False) + fh.write("\n") + with open(os.path.join(book_dir, "figures.json"), "w", encoding="utf-8") as fh: + json.dump({"book": folder, + "algorithm": ALGORITHM_VERSION, + "figures": built["manifest"], + "figure_map": built.get("figure_map", [])}, + fh, indent=1, ensure_ascii=False, sort_keys=True) + with open(os.path.join(book_dir, "notes-report.json"), "w", encoding="utf-8") as fh: + json.dump(report, fh, indent=1, ensure_ascii=False, sort_keys=True) + return {"folder": folder, "report": report, "seconds": time.time() - started} + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="md_corpus2html.py") + ap.add_argument("--corpus-root", required=True) + ap.add_argument("--library", required=True) + ap.add_argument("--books", default="", help="comma separated; default: every book") + ap.add_argument("--no-embed", action="store_true", + help="reference the picture files instead of embedding them") + ap.add_argument("--dry-run", action="store_true") + ap.add_argument("--picture-base", default="", + help="borrow the pictures from this host instead of carrying them") + ap.add_argument("--force", action="store_true", + help="rebuild every book, even the ones whose inputs have not changed") + ap.add_argument("--jobs", type=int, default=0, + help="how many books to build at once (default: from B2C_JOBS)") + ap.add_argument("--profile", action="store_true", + help="say where the time went") + args = ap.parse_args(argv) + + try: + import PIL # noqa: F401 + except ImportError: + print("Pillow is needed to build the readers: pip install pillow") + return 2 + failures = self_test() + if failures: + print("the gate's own checks failed, so nothing was built:") + for failure in failures: + print(" - %s" % failure) + return 2 + + wanted = [b.strip() for b in args.books.split(",") if b.strip()] + folders = sorted(d for d in os.listdir(args.corpus_root) + if os.path.isdir(os.path.join(args.corpus_root, d, "chapters"))) + # a machine corpus keeps its own reader, in its own typography, with the + # book's own paragraph numbers. Its chapters are not notes, and feeding + # them to the notes reader would throw that reader away. + machine = [d for d in folders + if os.path.exists(os.path.join(args.corpus_root, d, "paragraphs.jsonl"))] + folders = [d for d in folders if d not in machine or d in wanted] + if machine and not wanted: + print("not touched (a machine corpus, with its own reader): %s" + % ", ".join(machine)) + if wanted: + folders = [f for f in folders if f in wanted] + + jobs = args.jobs or int(switch("B2C_JOBS") or 4) + jobs = max(1, min(jobs, len(folders) or 1)) + embed = not args.no_embed + picture_base = args.picture_base or None + started = time.time() + + # the catalogue is read once, in this process; the children inherit it + catalogue = notes._catalogue(args.library) + + tool = tool_hash() + environment = environment_hash() + switches = switches_hash(args, embed, None, picture_base) + policy = corpus_file_hash(os.path.join(args.corpus_root, "picture-policy.json")) + verdicts_path = os.path.join(args.corpus_root, "picture-verdicts.jsonl") + # the digests of the library's pictures, kept between the builds so + # that only a picture that changed is read again + stat_file = stat_cache_path() + stat_cache = {} + if os.path.exists(stat_file): + try: + with open(stat_file, encoding="utf-8") as fh: + stat_cache = json.load(fh) + except Exception: + stat_cache = {} + + cache_file = cache_path(args.corpus_root) + cache = {} + if os.path.exists(cache_file) and not args.force: + try: + with open(cache_file, encoding="utf-8") as fh: + cache = json.load(fh).get("books", {}) + except Exception: + cache = {} + + todo = [] + reused = [] + keys = {} + for folder in folders: + book_dir = os.path.join(args.corpus_root, folder) + records = catalogue.get(folder) or [] + key = book_key(book_dir, folder, tool, environment, switches, policy, + verdicts_slice_hash(verdicts_path, folder), + catalogue_slice_hash(records), + picture_digests(args.library, records, stat_cache)) + keys[folder] = key + reader = os.path.join(book_dir, "index.html") + if (not args.force and not args.dry_run and cache.get(folder, {}).get("key") == key + and os.path.exists(reader)): + reused.append(folder) + continue + todo.append((args.corpus_root, args.library, folder, embed, picture_base, None)) + + if reused: + print("unchanged, so left alone (use --force to redo): %s" + % ", ".join(reused)) + if not todo: + print("nothing to do: every book is up to date") + return 0 + + results = [] + if jobs > 1 and len(todo) > 1: + context = multiprocessing.get_context("fork") + with context.Pool(processes=jobs) as pool: + results = pool.map(_build_one, todo) + else: + results = [_build_one(job) for job in todo] + + summary = [] + failed = [] + for result in results: + if result is None: + continue + folder = result["folder"] + report = result["report"] + summary.append(report) + if report["problems"]: + failed.append(folder) + else: + cache[folder] = {"key": keys.get(folder, ""), + "built": time.strftime("%Y-%m-%dT%H:%M:%S")} + print("%-26s chapters=%-4d figures=%-5d pictures=%-5d %-6s html=%5.1f MB %5.1fs %s" + % (folder, report["chapters"], report["figures"], + report["figures_with_pictures"], + "OK" if not report["problems"] else "FAILED", + report["html_bytes"] / 1e6, result["seconds"], + "" if not report["problems"] else report["problems"][:1])) + + if not args.dry_run: + os.makedirs(os.path.dirname(cache_file), exist_ok=True) + # the key of the whole corpus: the books' own keys, in order, and + # the policy that governs them + corpus_key = hashlib.sha256("\n".join("%s:%s" % (name, keys[name]) + for name in sorted(keys) + ).encode("utf-8")).hexdigest() + with open(cache_file, "w", encoding="utf-8") as fh: + json.dump({"schema": 2, "tool": tool, "environment": environment, + "policy": policy, "corpus": corpus_key, + "books": cache}, fh, indent=1, sort_keys=True) + with open(stat_file, "w", encoding="utf-8") as fh: + json.dump(stat_cache, fh, indent=1, sort_keys=True) + write_log({"time": time.strftime("%Y-%m-%dT%H:%M:%S"), + "corpus": os.path.abspath(args.corpus_root), + "switches": switch_report(), + "jobs": jobs, + "built": [r["folder"] for r in results if r], + "reused": reused, + "failed": failed, + "seconds": round(time.time() - started, 2)}) + + total_figures = sum(r["figures"] for r in summary) + total_pictures = sum(r["figures_with_pictures"] for r in summary) + print() + print("books: %d built, %d unchanged | figures: %d | with a picture: %d | failed: %d" + % (len(summary), len(reused), total_figures, total_pictures, len(failed))) + if failed: + print("failed:", ", ".join(failed)) + if args.profile: + print("time: %.1fs for %d books, %d at a time" + % (time.time() - started, len(summary), jobs)) + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/measure_candidates.py b/pipeline/scripts/measure_candidates.py new file mode 100644 index 00000000..220a8065 --- /dev/null +++ b/pipeline/scripts/measure_candidates.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""scripts/measure_candidates.py - does the part-of-speech generator earn its place? + +Written 27 Nov 2026 by MCode, after the ruling of Claude Fable 5.2 on the +first candidate generator to add to this pipeline. + +THE QUESTION +The pipeline generated its candidates from capitalisation. A new +generator, a part-of-speech pass over the books' own text, produces +noun-phrase candidates instead. It produces far more of them. The +question is not how many but how good: does it find terms the old +generator could not see, and what debris does it bring with it? + +THE MEASUREMENTS (the ones the ruling names) + candidate recall the share of the gold terms each generator produces + incremental recall the gold terms the new generator finds and the old one + does not + admitted recall the share of the gold terms that reach the index + precision the share of the new admissions that are gold terms + debris the new admissions that are in the negative set, per + a thousand admissions + boundary errors gold terms that appear only inside a longer candidate + hold-out the recall of a book's gold terms from the OTHER + books' candidates, so no book is measured with itself + +The verdict follows the rule the ruling gives: keep it if it adds about +five points of absolute gold recall and the debris does not rise; drop it +if the gain is under one or two points, or if the gain comes with debris. + + python3 scripts/measure_candidates.py --corpus-root + +What it writes: + + index/admission/candidates-report.json the numbers + index/admission/candidates-review.jsonl a sample for a person +""" +import argparse +import collections +import json +import os +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus import admission + +LAW_BOOKS = ("Law-of-Torts-2013", "McDermott-2001", "Stockard-2020", + "Kelly-2018") +SAMPLE = 100 +# the rule the ruling gives for keeping the generator +KEEP_POINTS = 5.0 +DROP_POINTS = 2.0 + + +def read_jsonl(path): + if not os.path.exists(path): + return [] + out = [] + with open(path, encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def write_jsonl(path, rows): + with open(path, "w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--sample", type=int, default=SAMPLE) + args = parser.parse_args(argv) + corpus = args.corpus_root + + gold = collections.defaultdict(set) + for row in read_jsonl(os.path.join(corpus, "index", "gold", "terms.jsonl")): + gold[row.get("book", "")].add(admission.fold(row.get("term", ""))) + + # what the old generator proposed, and what it admitted + proposed = collections.defaultdict(set) + admitted_old = collections.defaultdict(set) + for record in read_jsonl(os.path.join(corpus, "index", "cache", + "terms.jsonl")): + book = record.get("book", "") + for name in record.get("admitted") or []: + key = admission.fold(name) + proposed[book].add(key) + admitted_old[book].add(key) + for item in record.get("rejected") or []: + name = item.get("term") if isinstance(item, dict) else str(item) + if name: + proposed[book].add(admission.fold(name)) + + # the new generator's admissions + new_terms = collections.defaultdict(set) + folder = os.path.join(corpus, "index", "candidates_spacy") + for name in sorted(os.listdir(folder)) if os.path.isdir(folder) else []: + if not name.endswith(".jsonl"): + continue + book = name[:-6] + for row in read_jsonl(os.path.join(folder, name)): + key = admission.fold(row.get("term", "")) + if key: + new_terms[book].add(key) + + # the negative set: the names the old rules refused, minus the ones the + # books themselves vouch for, plus the furniture of the books + negative = collections.defaultdict(set) + for row in read_jsonl(os.path.join(corpus, "index", "terms_rejected.jsonl")): + book = row.get("book", "") + key = admission.fold(row.get("term", "")) + if key and key not in gold.get(book, set()): + negative[book].add(key) + + per_book = {} + gains = [] + sample_rows = [] + total_gold = old_hit = new_hit = union_hit = 0 + total_adm_old = total_adm_new = 0 + gold_in_new = debris_in_new = 0 + + # the old admissions, as a precision baseline + old_admitted_total = 0 + old_admitted_gold = 0 + for book in sorted(gold): + terms = gold[book] + if not terms: + continue + adm = admitted_old.get(book, set()) + old_admitted_total += len(adm) + old_admitted_gold += len(adm & terms) + + covered = [b for b in sorted(gold) + if os.path.exists(os.path.join(folder, b + ".jsonl"))] + for book in covered: + terms = gold[book] + if not terms: + continue + old = proposed.get(book, set()) + new = new_terms.get(book, set()) + o = len(terms & old) + n = len(terms & new) + u = len(terms & (old | new)) + only_new = terms & new - old + only_old = terms & old - new + total_gold += len(terms) + old_hit += o + new_hit += n + union_hit += u + total_adm_old += len(admitted_old.get(book, set())) + total_adm_new += len(new) + gold_in_new += n + debris_in_new += len(new & negative.get(book, set())) + per_book[book] = { + "gold": len(terms), + "old_candidate_recall": round(o / len(terms), 4), + "new_candidate_recall": round(n / len(terms), 4), + "union_recall": round(u / len(terms), 4), + "new_only": len(only_new), + "old_only": len(only_old), + "new_terms": len(new), + "law": book in LAW_BOOKS, + } + for term in sorted(only_new)[:20]: + gains.append({"book": book, "term": term}) + # a sample for a person to read + for key in sorted(new - gold.get(book, set()))[:40]: + if key in negative.get(book, set()): + sample_rows.append({"book": book, "term": key, + "kind": "negative_set", + "judgement": ""}) + else: + sample_rows.append({"book": book, "term": key, + "kind": "not_in_gold", + "judgement": ""}) + + # the hold-out: a book's gold terms found in the OTHER books' candidates + holdout = {} + for book in covered: + terms = gold[book] + others = set() + for other, new in new_terms.items(): + if other != book: + others |= new + holdout[book] = round(len(terms & others) / len(terms), 4) if terms else 0.0 + + recall_old = old_hit / total_gold if total_gold else 0.0 + recall_new = new_hit / total_gold if total_gold else 0.0 + recall_union = union_hit / total_gold if total_gold else 0.0 + precision_new = gold_in_new / total_adm_new if total_adm_new else 0.0 + debris_rate = (debris_in_new / total_adm_new * 1000) if total_adm_new else 0.0 + + points = (recall_union - recall_old) * 100 + if points >= KEEP_POINTS: + verdict = "keep" + elif points < DROP_POINTS: + verdict = "drop" + else: + verdict = "undecided" + + report = { + "books_covered": len(covered), + "books_with_gold": len(gold), + "gold_terms": total_gold, + "old_candidate_recall": round(recall_old, 4), + "new_candidate_recall": round(recall_new, 4), + "union_candidate_recall": round(recall_union, 4), + "gain_in_points": round(points, 2), + "new_terms_admitted": total_adm_new, + "precision_against_gold": round(precision_new, 4), + "old_admitted_total": old_admitted_total, + "old_admitted_gold": old_admitted_gold, + "old_admitted_precision": round( + old_admitted_gold / old_admitted_total, 4) if old_admitted_total else 0.0, + "old_admitted_recall": round( + sum(len(admitted_old.get(b, set()) & gold[b]) for b in covered) / total_gold, 4) + if total_gold else 0.0, + "debris_per_thousand": round(debris_rate, 1), + "rule": {"keep_at_points": KEEP_POINTS, "drop_below_points": DROP_POINTS}, + "verdict": verdict, + "holdout_recall": holdout, + "per_book": per_book, + "new_only_examples": gains[:80], + "review_sample_size": len(sample_rows), + } + out = os.path.join(corpus, "index", "admission") + os.makedirs(out, exist_ok=True) + with open(os.path.join(out, "candidates-report.json"), "w", + encoding="utf-8") as handle: + json.dump(report, handle, indent=1, ensure_ascii=False) + write_jsonl(os.path.join(out, "candidates-review.jsonl"), + sample_rows[:args.sample]) + + print("books covered %d of %d with a gold set" + % (len(covered), len(gold))) + print("gold terms in those books %d" % total_gold) + print("old generator, candidate recall %.1f%%" % (recall_old * 100)) + print("new generator, candidate recall %.1f%%" % (recall_new * 100)) + print("both together %.1f%%" % (recall_union * 100)) + print("the gain %+.1f points" % points) + print("new terms admitted %d" % total_adm_new) + print("precision against the gold set %.1f%%" % (precision_new * 100)) + print("the old admissions, for comparison:") + print(" admitted terms %d, of which gold %d (%.1f%%)" + % (old_admitted_total, old_admitted_gold, + (old_admitted_gold / old_admitted_total * 100) + if old_admitted_total else 0)) + print(" gold recall of the old admissions %.1f%%" + % (report["old_admitted_recall"] * 100)) + print("debris per thousand admissions %.1f" % debris_rate) + print("VERDICT: %s" % verdict) + print() + print("gold terms only the new generator finds:") + for row in gains[:25]: + print(" %-24s %s" % (row["book"][:24], row["term"][:60])) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/measure_termhood.py b/pipeline/scripts/measure_termhood.py new file mode 100644 index 00000000..46b9b015 --- /dev/null +++ b/pipeline/scripts/measure_termhood.py @@ -0,0 +1,411 @@ +#!/usr/bin/env python3 +"""scripts/measure_termhood.py - do the classical measures earn their place? + +Written 27 Nov 2026 by MCode, after the second ruling of Claude Fable 5.2: +the measures are features and not a replacement, the books are held out one +at a time, and the precision that is printed says what it is a bound of. + +THE EXPERIMENT + 1. Each measure alone: rank the terms it found and ask how many of the + gold terms are in the top fifty, the top hundred and the top five + hundred, and how many of the top hundred are gold. A measure that + cannot find the gold terms by itself is no use as a feature. + 2. The scorer, with and without the measure columns, one book held out + at a time: the average precision and the recall at a hundred, and a + paired bootstrap over the books to say whether the difference is + more than noise. + + ~/Documents/book2corpus/.venv-term/bin/python scripts/measure_termhood.py \ + --corpus-root + +What it writes: + + index/admission/termhood-report.json the numbers + index/admission/termhood-review.jsonl the top of the list, for a person +""" +import argparse +import collections +import json +import math +import os +import random +import sys + +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, HERE) + +from book2corpus import admission +from book2corpus import debris +from book2corpus import projection + +MAX_WORDS = 8 +ALGORITHMS = ["cvalue", "ncvalue", "ridf", "tfidf", "weirdness", "chisquare", + "rake", "basic"] + + +def read_jsonl(path): + if not os.path.exists(path): + return [] + out = [] + with open(path, encoding="utf-8") as handle: + for line in handle: + line = line.strip() + if line: + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def clean_chapters(corpus, book): + folder = os.path.join(corpus, book, "chapters") + out = [] + if not os.path.isdir(folder): + return out + for name in sorted(os.listdir(folder)): + if not name.lower().endswith(".md"): + continue + if projection.excluded_chapter(name, name): + continue + with open(os.path.join(folder, name), encoding="utf-8", + errors="replace") as handle: + body = handle.read() + lines = [] + for line in body.split("\n"): + if projection.excluded_chapter(line, line): + break + lines.append(line) + text = debris.clean("\n".join(lines)) + if len(text.split()) > 40: + out.append(text) + return out + + +def tuples_of(text): + words = admission.fold_tokens(text) + out = [] + for size in range(1, min(MAX_WORDS, len(words)) + 1): + for i in range(len(words) - size + 1): + out.append(tuple(words[i:i + size])) + return out + + +def count_candidates(texts, candidates): + freq = collections.Counter() + chapters = collections.Counter() + for text in texts: + seen = set() + for tup in tuples_of(text): + key = " ".join(tup) + if key in candidates: + freq[key] += 1 + seen.add(key) + for key in seen: + chapters[key] += 1 + return freq, chapters + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--corpus-root", required=True) + parser.add_argument("--top", type=int, default=100) + parser.add_argument("--bootstrap", type=int, default=2000) + args = parser.parse_args(argv) + corpus = args.corpus_root + + import numpy as np + from sklearn.linear_model import LogisticRegression + from sklearn.metrics import average_precision_score + import spacy + nlp = spacy.load("en_core_web_sm") + + gold = collections.defaultdict(set) + for row in read_jsonl(os.path.join(corpus, "index", "gold", "terms.jsonl")): + gold[row.get("book", "")].add(admission.fold(row.get("term", ""))) + + negative = collections.defaultdict(set) + for row in read_jsonl(os.path.join(corpus, "index", "terms_rejected.jsonl")): + book = row.get("book", "") + key = admission.fold(row.get("term", "")) + if key and key not in gold.get(book, set()): + negative[book].add(key) + + mine = collections.defaultdict(set) + folder = os.path.join(corpus, "index", "candidates_spacy") + for name in sorted(os.listdir(folder)) if os.path.isdir(folder) else []: + if not name.endswith(".jsonl"): + continue + book = name[:-6] + for row in read_jsonl(os.path.join(folder, name)): + key = admission.fold(row.get("term", "")) + if key: + mine[book].add(key) + + jate = collections.defaultdict(dict) + folder = os.path.join(corpus, "index", "admission", "jate") + for name in sorted(os.listdir(folder)) if os.path.isdir(folder) else []: + if not name.endswith(".json"): + continue + book = name[:-5] + with open(os.path.join(folder, name), encoding="utf-8") as handle: + payload = json.load(handle) + scores = {} + for algorithm, terms in payload.items(): + for row in terms: + key = admission.fold(row.get("term", "")) + if not key: + continue + scores.setdefault(key, {})[algorithm] = float( + row.get("score", 0.0)) + jate[book] = scores + + books = sorted(set(mine) | set(jate)) + books = [b for b in books if gold.get(b)] + print("books with a gold set and candidates: %d" % len(books), flush=True) + + universe = {} + for book in books: + terms = set(jate.get(book, {})) | set(mine.get(book, set())) + terms |= gold.get(book, set()) + universe[book] = terms + + counts = {} + word_freq = collections.Counter() + for book in books: + texts = clean_chapters(corpus, book) + freq, chapters = count_candidates(texts, universe[book]) + counts[book] = (freq, chapters, len(texts)) + for text in texts: + word_freq.update(admission.fold_tokens(text)) + print(" counted %-24s %d terms" % (book, len(universe[book])), + flush=True) + + book_freq = collections.Counter() + for book in books: + for key in counts[book][0]: + book_freq[key] += 1 + + flags = {} + for book in books: + names = sorted(universe[book]) + for doc in nlp.pipe(names, batch_size=256): + key = admission.fold(doc.text) + head = doc[-1] if doc else None + flags[(book, key)] = { + "words": len(doc), + "quantity": int(head is not None and head.ent_type_ in + ("QUANTITY", "PERCENT", "TIME", "DATE", + "MONEY", "CARDINAL")) + or int(any(t.like_num for t in doc)), + "not_a_phrase": int(any(t.pos_ in ("DET", "ADP", "CCONJ", + "PRON", "VERB", "AUX") + for t in doc)), + "abstract": int(len(doc) == 1 and doc[0].text.casefold() + .endswith(("ence", "ance", "ity", "ism"))), + "head_freq": word_freq.get(head.text.casefold(), 0) + if head is not None else 0, + } + + # the candidates indexed by their first word, so that the nesting + # count does not walk the whole book for every candidate: a book with + # fifty thousand candidates would be a billion comparisons + by_head = {} + for book in books: + index = {} + for term in universe[book]: + parts = term.split() + if parts: + index.setdefault(parts[0], []).append(parts) + by_head[book] = index + + def c_value(book, key): + freq = counts[book][0] + words = key.split() + longer = 0 + for parts in by_head[book].get(words[0], ()): + if len(parts) <= len(words): + continue + if parts[:len(words)] == words or parts[-len(words):] == words: + longer += 1 + value = freq.get(key, 0) + if value == 0: + return 0.0 + return value * (math.log2(len(universe[book]) + 1) + - math.log2(longer + 1) + 1) + + rows = [] + for book in books: + freq = counts[book][0] + chapters = counts[book][1] + n_chapters = max(1, counts[book][2]) + for key in sorted(universe[book]): + f = freq.get(key, 0) + words = key.split() + flag = flags.get((book, key), {}) + row = { + "book": book, "term": key, + "log_freq": math.log(f + 1), + "chapter_share": chapters.get(key, 0) / n_chapters, + "book_share": book_freq.get(key, 0) / max(1, len(books)), + "c_value": math.log1p(c_value(book, key)), + "residual": math.log(f + 1) - sum( + math.log(word_freq.get(w, 0) + 1) for w in words), + "words": flag.get("words", len(words)), + "quantity": flag.get("quantity", 0), + "not_a_phrase": flag.get("not_a_phrase", 0), + "abstract": flag.get("abstract", 0), + "head_freq": math.log1p(flag.get("head_freq", 0)), + "gold": int(key in gold.get(book, set())), + "negative": int(key in negative.get(book, set())), + } + for algorithm in ALGORITHMS: + value = jate.get(book, {}).get(key, {}).get(algorithm) + row["jate_" + algorithm] = (math.log1p(value) + if value and value > 0 else 0.0) + rows.append(row) + + CHEAP = ["log_freq", "chapter_share", "book_share", "c_value", + "residual", "words", "quantity", "not_a_phrase", "abstract", + "head_freq"] + JATE = ["jate_" + a for a in ALGORITHMS + if any(row.get("jate_" + a, 0) > 0 for row in rows)] + + print() + print("=== each measure alone, against the gold set ===") + print("%-12s %8s %8s %8s %8s" % ("measure", "R@50", "R@100", "R@500", + "P@100")) + solo = {} + for algorithm in ALGORITHMS: + column = "jate_" + algorithm + if column not in JATE: + continue + hits50 = hits100 = hits500 = top100 = total_gold = 0 + for book in books: + terms = gold.get(book, set()) + total_gold += len(terms) + ranked = sorted( + [r for r in rows if r["book"] == book and r[column] > 0], + key=lambda r: -r[column]) + hits50 += len(terms & {r["term"] for r in ranked[:50]}) + hits100 += len(terms & {r["term"] for r in ranked[:100]}) + hits500 += len(terms & {r["term"] for r in ranked[:500]}) + top100 += len(terms & {r["term"] for r in ranked[:100]}) + solo[algorithm] = { + "recall_at_50": hits50 / max(1, total_gold), + "recall_at_100": hits100 / max(1, total_gold), + "recall_at_500": hits500 / max(1, total_gold), + "precision_at_100": top100 / max(1, 100 * len(books)), + } + print("%-12s %7.1f%% %7.1f%% %7.1f%% %7.1f%%" + % (algorithm, solo[algorithm]["recall_at_50"] * 100, + solo[algorithm]["recall_at_100"] * 100, + solo[algorithm]["recall_at_500"] * 100, + solo[algorithm]["precision_at_100"] * 100)) + + train = [r for r in rows if r["gold"] or r["negative"]] + X_cheap = np.array([[r[f] for f in CHEAP] for r in train], dtype=float) + X_all = np.array([[r[f] for f in CHEAP + JATE] for r in train], dtype=float) + y = np.array([r["gold"] for r in train], dtype=int) + books_of = [r["book"] for r in train] + unique_books = sorted(set(books_of)) + + def evaluate(matrix): + probabilities = np.zeros(len(train)) + for held in unique_books: + test = np.array([i for i, b in enumerate(books_of) if b == held]) + keep = np.array([i for i, b in enumerate(books_of) if b != held]) + if len(set(y[keep])) < 2 or len(test) == 0: + continue + model = LogisticRegression(max_iter=3000, class_weight="balanced") + model.fit(matrix[keep], y[keep]) + probabilities[test] = model.predict_proba(matrix[test])[:, 1] + per_book = {} + for book in unique_books: + rows_here = [(r, p) for r, p in zip(train, probabilities) + if r["book"] == book] + if not rows_here: + continue + labels = [r["gold"] for r, _ in rows_here] + if len(set(labels)) < 2: + continue + scores = [p for _, p in rows_here] + order = sorted(range(len(scores)), key=lambda i: -scores[i]) + hits = sum(labels[i] for i in order[:args.top]) + per_book[book] = { + "average_precision": float( + average_precision_score(labels, scores)), + "recall_at_top": hits / max(1, sum(labels)), + } + return probabilities, per_book + + prob_cheap, per_cheap = evaluate(X_cheap) + prob_all, per_all = evaluate(X_all) + + def mean_of(per_book, key): + values = [v[key] for v in per_book.values()] + return sum(values) / len(values) if values else 0.0 + + shared = sorted(set(per_cheap) & set(per_all)) + deltas = [per_all[b]["average_precision"] - per_cheap[b]["average_precision"] + for b in shared] + random.seed(20261127) + wins = 0 + for _ in range(args.bootstrap): + sample = [random.choice(deltas) for _ in deltas] + if sum(sample) / len(sample) > 0: + wins += 1 + bootstrap_share = wins / max(1, args.bootstrap) + + ranked = sorted(zip(train, prob_all), key=lambda rp: -rp[1]) + review = [{"book": r["book"], "term": r["term"], + "score": round(float(p), 4), "judgement": ""} + for r, p in ranked if not r["gold"]] + + gold_total = sum(len(gold.get(b, set())) for b in books) + union_gold = sum(len(gold.get(b, set()) & universe[b]) for b in books) + report = { + "books": len(books), + "gold_terms": gold_total, + "gold_in_the_union": union_gold, + "recall_at_all": round(union_gold / max(1, gold_total), 4), + "measures_alone": solo, + "without_the_measures": { + "average_precision": round(mean_of(per_cheap, "average_precision"), 4), + "recall_at_top": round(mean_of(per_cheap, "recall_at_top"), 4), + }, + "with_the_measures": { + "average_precision": round(mean_of(per_all, "average_precision"), 4), + "recall_at_top": round(mean_of(per_all, "recall_at_top"), 4), + }, + "paired_bootstrap_share_of_books_better": round(bootstrap_share, 4), + "note": "the precision against the gold set is a lower bound: the gold " + "set holds what the books chose to index, and a real term " + "they did not index counts against it", + } + out = os.path.join(corpus, "index", "admission") + with open(os.path.join(out, "termhood-report.json"), "w", + encoding="utf-8") as handle: + json.dump(report, handle, indent=1, ensure_ascii=False) + with open(os.path.join(out, "termhood-review.jsonl"), "w", + encoding="utf-8") as handle: + for row in review[:400]: + handle.write(json.dumps(row, ensure_ascii=False) + "\n") + + print() + print("=== the scorer, one book held out at a time ===") + print("R@all vs gold set: %.3f (gold = %d terms, %d books)" + % (union_gold / max(1, gold_total), gold_total, len(books))) + print("without the measures: average precision %.3f, recall@%d %.3f" + % (report["without_the_measures"]["average_precision"], args.top, + report["without_the_measures"]["recall_at_top"])) + print("with the measures: average precision %.3f, recall@%d %.3f" + % (report["with_the_measures"]["average_precision"], args.top, + report["with_the_measures"]["recall_at_top"])) + print("the measures win on %.1f%% of the books (paired bootstrap, %d draws)" + % (bootstrap_share * 100, args.bootstrap)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/scripts/pipeline.py b/pipeline/scripts/pipeline.py new file mode 100644 index 00000000..afc1d8fc --- /dev/null +++ b/pipeline/scripts/pipeline.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +"""The pipeline: one command for the next book, and every book after it. + + python3 scripts/pipeline.py run --book # one book + python3 scripts/pipeline.py run --all # every book + python3 scripts/pipeline.py status # what the last run did + python3 scripts/pipeline.py resolve H-0007 --accept + python3 scripts/pipeline.py selftest # the tester, tested + +Each run writes under its date: runs/_