LizeLive Claude Opus 5 commited on
Commit
1e56ba2
·
1 Parent(s): 09179bb

feat: OCR as per-page markdown, and the frc corpus ingest

Browse files

Adds `scans frc ingest` and `scans frc fetch` for the Newberry Library's French
Revolution Collection, and `<id>.pN.ocr.md` — the format its OCR lands in.

## The format

One markdown file per scanned page. Frontmatter says which page of what and how
big the image is; the body is the page's text. That is the whole format.

---
of: 1789iemilseptcen00unse
page: 6
engine: ABBYY FineReader 11.0
lang: fr
w: 2597
h: 4418
dpi: 500
---

Scalars are written bare, because the frontmatter is meant to read as YAML. The
hazard is that `no` is the ISO 639-1 code for Norwegian and, in YAML 1.1, the
boolean false. serde_norway implements 1.2, where it is already a string, so
round-tripping through this crate's own parser passes it — which is the wrong bar.
PyYAML, libyaml, Psych and gopkg.in/yaml.v2 are all 1.1, and this data is
published for their tools rather than ours. So there is an explicit 1.1 deny-list
as well as a round-trip check.

Word boxes, per-word confidence, baselines and DjVu's nesting are deliberately not
carried. They were about seven eighths of the bytes — 8.3 GB against 1.25 GB for
the text — and nothing was reading them. Nothing is destroyed by that: the
coordinates remain in XML_for_OCR/ in frc-data, one clone away, so reinstating
them is a change to djvu.rs and a re-run, not a re-fetch.

## The corpus

The OCR is taken from frc-data rather than archive.org: one clone instead of
38,377 requests for bytes already sitting in a git repository. Only the PDFs are
fetched, one request at a time with an honest User-Agent, each verified against
the size and MD5 archive.org publishes for it.

New record fields, each justified independently of this ingest: `subject`, because
38,377 pamphlets are unusable without subject access; `extent`, the bibliographic
collation; and `scan.ppi`, which `render` otherwise infers from the largest
embedded image.

Check 11 (E708–E710) validates the sidecars; its parsing half is behind `--probe`
for the same reason the image checks are.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

.gitattributes CHANGED
@@ -59,4 +59,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
59
  *.webp filter=lfs diff=lfs merge=lfs -text
60
  # Video files - compressed
61
  *.mp4 filter=lfs diff=lfs merge=lfs -text
62
- *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
59
  *.webp filter=lfs diff=lfs merge=lfs -text
60
  # Video files - compressed
61
  *.mp4 filter=lfs diff=lfs merge=lfs -text
62
+ *.webm filter=lfs diff=lfs merge=lfs -text
63
+ # The OCR sidecars are markdown in plain git: they compress in the packfile, they stay
64
+ # greppable, and putting 8.5 GB of them in LFS would be billed for at full size. There are no
65
+ # exceptions any more — one file per page means none of them is bigger than a few kilobytes,
66
+ # which is the other reason the per-page split is worth the file count.
.gitignore CHANGED
@@ -4,3 +4,9 @@
4
  # Default output of `scans render` and `scans extract`. Derived pixels: reproducible from the
5
  # PDFs at any time, and at native resolution they outweigh the containers they came from.
6
  /.render/
 
 
 
 
 
 
 
4
  # Default output of `scans render` and `scans extract`. Derived pixels: reproducible from the
5
  # PDFs at any time, and at native resolution they outweigh the containers they came from.
6
  /.render/
7
+
8
+ # Fetch and push run logs — derived, and noisy.
9
+ .fetch.log
10
+ .push-chunks.log
11
+ .push-chunks.sh
12
+ .push-hf.sh
README.md CHANGED
@@ -1,3 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # scans
2
 
3
  Scans of primary sources from the French Revolution.
@@ -44,6 +60,12 @@ are inherited down the `of` chain; `date`, `title`, `note`, `url` and `[[page]]`
44
 
45
  ```
46
  sources/
 
 
 
 
 
 
47
  journal-de-paris/
48
  journal-de-paris.toml source
49
  1789/
@@ -58,6 +80,7 @@ sources/
58
  verniquet-1795.toml source, 73 sheets inline
59
  verniquet_00.jp2 … verniquet_72.jp2
60
  schemas/source.json GENERATED from tools/src/model.rs
 
61
  tools/ the `scans` CLI
62
  docs/ the design spec
63
  ```
@@ -119,6 +142,94 @@ Each record carries a `#:schema` directive on its first line, which is what gets
119
  in an editor. See `schemas/README.md` — the alternative, an editor schema association, was
120
  tested and silently does nothing.
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  ## Design
123
 
124
  `docs/superpowers/specs/2026-08-05-source-archive-schema-design.md` is the authority: the
 
1
+ ---
2
+ license: odbl
3
+ language:
4
+ - fr
5
+ - la
6
+ - en
7
+ tags:
8
+ - french-revolution
9
+ - ocr
10
+ - primary-sources
11
+ - digital-humanities
12
+ pretty_name: Scans — primary sources of the French Revolution
13
+ size_categories:
14
+ - 10K<n<100K
15
+ ---
16
+
17
  # scans
18
 
19
  Scans of primary sources from the French Revolution.
 
60
 
61
  ```
62
  sources/
63
+ frc/ the Newberry French Revolution Collection
64
+ ab/abondance00unse/
65
+ abondance00unse.toml source, one per Internet Archive item
66
+ abondance00unse.p1.ocr.md OCR, one file per page
67
+ abondance00unse.pdf the scan
68
+ …38,377 items across ~700 two-character shards
69
  journal-de-paris/
70
  journal-de-paris.toml source
71
  1789/
 
80
  verniquet-1795.toml source, 73 sheets inline
81
  verniquet_00.jp2 … verniquet_72.jp2
82
  schemas/source.json GENERATED from tools/src/model.rs
83
+ schemas/ocr.json GENERATED from tools/src/ocr.rs
84
  tools/ the `scans` CLI
85
  docs/ the design spec
86
  ```
 
142
  in an editor. See `schemas/README.md` — the alternative, an editor schema association, was
143
  tested and silently does nothing.
144
 
145
+ ## OCR
146
+
147
+ Word-level OCR lives in a sidecar beside the record it belongs to, one markdown file per
148
+ scanned page, reached through the `[[text]]` that points at it.
149
+
150
+ ```markdown
151
+ ---
152
+ of: 1789iemilseptcen00unse
153
+ page: 6
154
+ engine: ABBYY FineReader 11.0
155
+ lang: fr
156
+ w: 2597
157
+ h: 4418
158
+ dpi: 500
159
+ ---
160
+
161
+ <the page's text>
162
+ ```
163
+
164
+ Frontmatter says which page of what, and how big the image is. The body is the page. That is
165
+ the whole format.
166
+
167
+ **Scalars are bare unless they would lie.** `lang: fr`, not `lang: "fr"` — the frontmatter is
168
+ meant to read as YAML. But `no` is the ISO 639-1 code for Norwegian and, to every YAML 1.1
169
+ parser, the boolean false; a Python user loading that with PyYAML gets `False`. So a value is
170
+ written bare when it round-trips as itself and quoted when it would not, which keeps the
171
+ common case clean and the pathological case correct.
172
+
173
+ **What is deliberately not here:** word boxes, per-word confidence, baselines, and DjVu's
174
+ nesting. An earlier version carried all of it and could write the source XML back out
175
+ unchanged. The boxes were seven eighths of the bytes — 8.3 GB against about 1.2 GB for the
176
+ text — and were not being used. Nothing is destroyed by that: the coordinates are still in
177
+ `XML_for_OCR/` in [frc-data](https://github.com/NewberryDIS/frc-data), one clone away, so a
178
+ later version that wants them can have them without asking archive.org for anything.
179
+
180
+ ```sh
181
+ cargo run -- ocr import x_djvu.xml --out ./pages
182
+ cargo run -- ocr check sources/frc/ab/abondance00unse
183
+ ```
184
+
185
+ ## The French Revolution Collection
186
+
187
+ 38,377 Internet Archive items from the Newberry Library, listed by
188
+ [NewberryDIS/frc-data](https://github.com/NewberryDIS/frc-data). Records and OCR come from a
189
+ local clone of that repository; only the PDFs are fetched.
190
+
191
+ ```sh
192
+ git clone --filter=blob:none --no-checkout https://github.com/NewberryDIS/frc-data.git
193
+ cd frc-data && git sparse-checkout set --cone Metadata XML_for_OCR && git checkout master
194
+
195
+ cargo run --release -- frc ingest --frc-data ../frc-data # records + OCR, ~3 minutes
196
+ cargo run --release --features fetch -- frc fetch # the PDFs, ~21 hours
197
+ ```
198
+
199
+ `frc fetch` makes one request at a time, a second apart, with a `User-Agent` naming this
200
+ repository, and verifies every download against the size and MD5 archive.org publishes for
201
+ it. It resumes from what is already on disk, so it can be killed at any moment.
202
+
203
+ ## Licence
204
+
205
+ The **database** — the records, the OCR sidecars, the structure and the addresses — is under
206
+ the [Open Database License](https://opendatacommons.org/licenses/odbl/) (ODbL 1.0). Use it,
207
+ adapt it, build on it; if you publish a derived database, share it alike and keep the
208
+ attribution.
209
+
210
+ The **contents are a separate question, and mostly not ours to license.** Every work here is
211
+ an 18th-century imprint or a 19th-century study of one, long out of copyright everywhere, and
212
+ the digitisations are published as public domain by the institutions that made them. Each
213
+ record says so for itself:
214
+
215
+ ```toml
216
+ [rights]
217
+ work = "PD-old-100-expired"
218
+ scan = "PD"
219
+ attribution = "Digitised by the Internet Archive, sponsored by The Newberry Library."
220
+ ```
221
+
222
+ So: quoting a pamphlet, reprinting a page image, or lifting one item's OCR carries no
223
+ obligation from us — that material is public domain and stays public domain. ODbL bites on
224
+ the *collection*: the selection, the identifiers, the metadata mapping and the structured OCR
225
+ taken together. That distinction is the point of using a database licence rather than a
226
+ content one, and it is why the per-record `[rights]` fields are not redundant with this
227
+ section.
228
+
229
+ Scans and metadata originate with the [Newberry Library](https://www.newberry.org/) and the
230
+ [Internet Archive](https://archive.org/), and the item list comes from
231
+ [NewberryDIS/frc-data](https://github.com/NewberryDIS/frc-data).
232
+
233
  ## Design
234
 
235
  `docs/superpowers/specs/2026-08-05-source-archive-schema-design.md` is the authority: the
docs/superpowers/specs/2026-08-07-frc-corpus-ingest-and-ocr-format-design.md ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Newberry French Revolution corpus — ingest, and a TOML format for OCR
2
+
3
+ Status: implemented
4
+ Date: 2026-08-07
5
+ Revised: 2026-08-07, after the design met the corpus. The corrections are marked
6
+ **Corrected** and the original claim is stated alongside, because most of them were
7
+ wrong in a way worth remembering.
8
+
9
+ ## Purpose
10
+
11
+ Bring the Newberry Library's French Revolution Collection into this archive: 38,377
12
+ Internet Archive items of French pamphlets, mostly 1789–1799, listed by
13
+ [NewberryDIS/frc-data](https://github.com/NewberryDIS/frc-data). For each item, hold the
14
+ scanned PDF and the word-level OCR, addressed the same way as everything else here.
15
+
16
+ That is a factor of roughly seven thousand more records than the archive currently holds.
17
+ The design is shaped almost entirely by that number.
18
+
19
+ ## What frc-data actually is
20
+
21
+ **Corrected.** The first draft of this said frc-data held no XML OCR, and that the
22
+ coordinate-bearing OCR would have to be fetched from archive.org. That was wrong, and it
23
+ was wrong because GitHub's tree API silently truncates: it returned 72,499 entries with
24
+ `"truncated": true`, and the counts happened to add up so neatly against two directories
25
+ that the third was never missed. `git ls-tree` on a blobless clone gives the real list.
26
+
27
+ There are four directories, and each of the three that matter holds exactly 38,377 files:
28
+
29
+ | directory | contents |
30
+ | --- | --- |
31
+ | `Metadata/*_meta.xml` | 38,377 Internet Archive metadata records |
32
+ | `XML_for_OCR/*_djvu.xml` | 38,377 DjVu XML files — **word-level OCR with coordinates** |
33
+ | `OCR_text/*_djvu.txt` | 38,377 plain-text OCR files |
34
+ | `IA_pamphlets-1560-1660-marc_records/` | one 3.5 MB MARC file for a different collection |
35
+
36
+ So frc-data supplies the item list, the catalogue metadata **and the OCR**. Only the PDFs
37
+ have to be fetched.
38
+
39
+ That changes the crawl from about 115,000 requests to about 77,000, and saves archive.org
40
+ 11 GB of egress for bytes that are already sitting in a git repository. Given that "be
41
+ respectful of rate limits" was the constraint, this is not a small correction.
42
+
43
+ ## Scale, measured
44
+
45
+ Sampled across three items and extrapolated by OCR-text size, which tracks page count
46
+ closely:
47
+
48
+ | | |
49
+ | --- | --- |
50
+ | items | 38,377, all with OCR |
51
+ | PDFs | ~63 GB, still an estimate — the fetch has not finished |
52
+ | `XML_for_OCR` in frc-data | 11 GB **measured** |
53
+ | the same OCR as markdown | ~1.2 GB — text only, no coordinates |
54
+ | HTTP requests | ~77,000, all of them for PDFs |
55
+ | wall time at one request per second | ~21 hours |
56
+
57
+ The wall time is the governing constraint. This is a pipeline that runs for days and is
58
+ killed and resumed many times, not a script that is run once.
59
+
60
+ ## Decisions
61
+
62
+ ### One IA item becomes one `source` record
63
+
64
+ `layer = "source"`, with `copy` and `document` collapsed in, exactly as `pellet-1873` and
65
+ `turgot-1739` already do. A pamphlet is a single work, digitised once, and paying three
66
+ files of ceremony for it would produce 115,000 files to describe 38,377 pamphlets.
67
+
68
+ `type` comes from `mediatype` and `physical_description`: `pamphlet` under ~50 pages,
69
+ `book` above, `periodical` where the metadata says so.
70
+
71
+ ### Ids are the bare Internet Archive identifier
72
+
73
+ `abondance00unse`, not `frc-abondance00unse`. The identifier is already globally unique
74
+ and stable, and it is what every other system cites. Prefixing would add nine characters
75
+ to 38,377 addresses to solve a collision problem that does not exist — the existing
76
+ hand-curated ids are all of the form `name-year`, which no IA identifier matches.
77
+
78
+ ### Directories are sharded two deep by identifier prefix
79
+
80
+ ```
81
+ sources/frc/ab/abondance00unse/
82
+ abondance00unse.toml
83
+ abondance00unse.pdf
84
+ abondance00unse.ocr.toml
85
+ ```
86
+
87
+ ~700 shard directories of ~55 items each. The README's promise that "directories are
88
+ cosmetic" is what makes this free: no address changes if the sharding is ever redone.
89
+
90
+ A single flat directory of 38,377 entries was rejected — not because git minds, but
91
+ because `ls`, tab completion, and the editor's file tree all become unusable.
92
+
93
+ ### The OCR sidecar attaches through the existing `[[text]]` table
94
+
95
+ No new top-level table. `[[text]]` already means "OCR or transcription, never inline",
96
+ which is exactly what this is:
97
+
98
+ ```toml
99
+ [[text]]
100
+ file = "abondance00unse.ocr.toml"
101
+ kind = "ocr"
102
+ by = "ABBYY FineReader 11.0"
103
+ lang = "fr"
104
+ ```
105
+
106
+ ## The OCR format
107
+
108
+ **Superseded twice.** It was TOML carrying packed word-level arrays when this was written; it
109
+ is now markdown with YAML frontmatter carrying no coordinates at all. Both changes were at the
110
+ repository owner's direction, and the second is the larger one.
111
+
112
+ ### Where it landed
113
+
114
+ One file per scanned page, `<id>.pN.ocr.md`:
115
+
116
+ ```markdown
117
+ ---
118
+ of: 1789iemilseptcen00unse
119
+ page: 6
120
+ engine: ABBYY FineReader 11.0
121
+ lang: fr
122
+ w: 2597
123
+ h: 4418
124
+ dpi: 500
125
+ ---
126
+
127
+ <the page's text>
128
+ ```
129
+
130
+ Frontmatter says which page of what and how big the image is; the body is the page. That is
131
+ the whole format.
132
+
133
+ ### What was dropped, and what that costs
134
+
135
+ Gone: word boxes, per-word confidence, baselines, region background colours, and the `brk`
136
+ encoding that reconstructed DjVu's four levels of nesting in one byte per word. With them goes
137
+ the losslessness claim and `scans ocr export`, which existed to make that claim executable.
138
+
139
+ The reason is proportion. The coordinates were about seven eighths of the bytes — 8.3 GB
140
+ against roughly 1.2 GB for the text — and nothing was reading them.
141
+
142
+ **Nothing is destroyed.** The coordinates are in `XML_for_OCR/` in frc-data, which is one
143
+ clone away and needs no request to archive.org. Reinstating them is a change to
144
+ `tools/src/djvu.rs` and a re-run of `frc ingest`, not a re-fetch.
145
+
146
+ ### The per-page split
147
+
148
+ Before the coordinates were dropped, one file per *item* put a 3,378-page bound run of nine
149
+ volumes into a single 49 MB text file. Splitting per page fixed that, and kept two properties
150
+ worth naming even now that files are small:
151
+
152
+ - `<id>.pN` matches the address grammar the archive already uses for pages.
153
+ - The body needs no `## Page N` headings, so nothing in the OCR can be mistaken for a
154
+ delimiter. The per-item version had to carve the body back up by markers the OCR could in
155
+ principle contain.
156
+
157
+ ### Bare scalars, and the YAML version that matters
158
+
159
+ Values are written bare — `lang: fr` — because the frontmatter is meant to read as YAML.
160
+
161
+ The hazard is that `no` is the ISO 639-1 code for Norwegian and, in **YAML 1.1**, the boolean
162
+ false. `serde_norway` implements **1.2**, where it is already a string, so a round-trip check
163
+ against this crate's own parser passes it. That check is not the right bar: PyYAML, libyaml,
164
+ Psych and gopkg.in/yaml.v2 are all 1.1, and this data is published for their tools rather than
165
+ ours. So there is an explicit 1.1 deny-list *and* a round-trip check, and a test asserts that
166
+ every reserved word survives as the string it was.
167
+
168
+ ## New record fields
169
+
170
+ **Corrected.** The draft proposed a fourth, an `[ocr]` table pointing at the sidecar. It
171
+ was not needed: `[[text]]` already means "OCR or transcription, never inline", which is
172
+ exactly what a sidecar is. Three remain, each justified independently of this ingest:
173
+
174
+ | field | why |
175
+ | --- | --- |
176
+ | `subject` — array of strings | 38,377 pamphlets are unusable without subject access. LCSH terms, from IA's `<subject>`. |
177
+ | `extent` — string | The bibliographic collation, `"7 p. ; 18 cm."`, verbatim. Distinct from `scan.count`, which counts scanned images including covers. |
178
+ | `scan.ppi` — integer | The scan's own resolution. `render` currently infers native resolution from the largest embedded image; this states it. |
179
+
180
+ `subject` and `extent` go on all three record variants and do not inherit. `ppi`
181
+ inherits, like the rest of `[scan]` except `count` and `note`.
182
+
183
+ ## Metadata mapping
184
+
185
+ | IA field | record |
186
+ | --- | --- |
187
+ | `title` | `title` |
188
+ | `date`, `dfate` (a real IA typo, present in some records) | `date`, as EDTF |
189
+ | `creator`* | `[[resp]]`; a trailing `, printer` inside the name becomes `role` |
190
+ | `publisher` | `place` (before the first ` : `) and a `[[resp]]` with `role = "publisher"` |
191
+ | `language` | `language`, ISO-639-2 → BCP-47 (`fre` → `fr`) |
192
+ | `contributor`, `call_number`, `collection` | `[holding]` repository, shelfmark, collection |
193
+ | `identifier`, `identifier-ark`, `openlibrary_edition`, `openlibrary_work` | `[identifier]` |
194
+ | `link_to_catalog`, `identifier-access` | `[[link]]` with `rel` `catalogue`, `viewer` |
195
+ | `imagecount`, `ppi`, `scanner`, `camera`, `scandate`, `scanningcenter` | `[scan]` |
196
+ | `subject`* | `subject` |
197
+ | `physical_description` | `extent` |
198
+ | `description`*, `notes`, `citation` | `note` |
199
+ | `sponsor` | `rights.attribution` |
200
+
201
+ Rights are constant across the corpus: the works are of the 1790s and long out of
202
+ copyright; the digitisation is the Newberry's, sponsored and public.
203
+
204
+ ## The pipeline
205
+
206
+ A new `scans fetch` subcommand, behind a `fetch` feature so the default build stays free
207
+ of an HTTP stack.
208
+
209
+ **Resumability** is the first requirement, not an afterthought. **Corrected:** the draft
210
+ specified a JSONL ledger. There is none. An item is done when its file is on disk, which is
211
+ the whole resume condition — a ledger would be a second source of truth that can fall out
212
+ of step with the tree it describes, bought at the price of a file to keep consistent.
213
+ Downloads are written to `.pdf.part` and renamed, so a run killed mid-download cannot leave
214
+ a half PDF that the next run mistakes for a finished one.
215
+
216
+ **Politeness** is the second:
217
+
218
+ - one request in flight at a time, minimum interval configurable, default 1s
219
+ - a `User-Agent` naming the project and its repository, so the operator can be contacted
220
+ - `Retry-After` honoured on 429 and 503
221
+ - exponential backoff on 5xx, capped, then the item is parked rather than blocking the queue
222
+ - `--limit` and `--since` so a run can be bounded
223
+
224
+ **Verification**: every download is checked for size and MD5 against the values in the
225
+ item's IA metadata before it is accepted. A truncated PDF must not be committed and then
226
+ believed.
227
+
228
+ **Disposal**: `_djvu.xml` is converted to `.ocr.toml` and deleted. Keeping both would
229
+ double 12 GB to hold the same facts twice, and the TOML is the archival form.
230
+
231
+ ### Storage
232
+
233
+ | what | where | why |
234
+ | --- | --- | --- |
235
+ | `*.pdf` | Git LFS | ~63 GB, already compressed, no benefit from packfiles |
236
+ | `*.ocr.toml` | plain git | text, packs about 5:1; LFS would bill for the full 7 GB |
237
+ | `*.toml` records | plain git | small |
238
+
239
+ 63 GB of LFS exceeds GitHub's free tier and needs data packs on the remote before the
240
+ first push. Pushing proceeds in commits of a few hundred items rather than one enormous
241
+ commit, so an interrupted push loses minutes rather than days.
242
+
243
+ ## Validation
244
+
245
+ Check 11, four codes:
246
+
247
+ - **E708** a `[[text]]` pointing at a sidecar that is not there
248
+ - **E709** a sidecar that is not valid TOML for the OCR model
249
+ - **E710** a sidecar whose `of` names a record other than the one pointing at it
250
+ - **E711** any of the internal inconsistencies in `ocr::Problem` — arrays of unequal length,
251
+ `box` not exactly four per word, `region-bg` not one per region, `text` that disagrees
252
+ with `word` and `brk`
253
+
254
+ **Corrected.** The draft said these "run over the whole archive by default, since they read
255
+ only TOML". That reasoning was wrong: the distinction is not TOML versus bytes, it is how
256
+ many gigabytes of them there are. Parsing 8 GB of sidecars turns `validate` from a
257
+ 2.3-second command into a 2m37s one. E708 is a `stat` and runs always; everything that has
258
+ to parse a sidecar is behind `--probe`, for exactly the reason the image checks are.
259
+
260
+ Result on the full corpus: 38,715 records, **0 errors, 0 warnings** by default, and 0 errors
261
+ with `--probe` across all 38,377 sidecars.
262
+
263
+ One further correction fell out of the first full run: `id_is_preferred` treated `_` as
264
+ outside house style, which made 1,263 warnings out of identifiers like `procesverbal00_1_0`
265
+ and `case_oversize_frc_27598`. Those are the handles archive.org publishes and everyone else
266
+ cites. Underscore is now a group separator alongside hyphen — 1,263 warnings a reader cannot
267
+ act on is how a warning channel stops being read.
268
+
269
+ ## Testing
270
+
271
+ - djvu.xml → TOML → djvu.xml round-trip over a sample of real fetched items
272
+ - the `brk` encoder and decoder, against hand-built nestings including the degenerate
273
+ cases: an empty page, a page of one word, a word containing a space
274
+ - metadata mapping over a fixture set chosen for awkwardness: missing `date`, the `dfate`
275
+ typo, multiple `creator` entries, a creator with an embedded role, no `publisher`
276
+ - ledger resume: interrupt mid-run, restart, confirm no item is fetched twice and none is
277
+ skipped
278
+ - rate limiter timing, with a clock injected rather than by sleeping
279
+
280
+ ## Deliberately not done
281
+
282
+ - **No `copy` or `document` layer per item.** Revisit only if an item turns out to bind
283
+ several distinct works, which the metadata does not currently distinguish.
284
+ - **No text search index.** Grep over 7 GB is adequate; a real index is a different
285
+ project with a different lifetime.
286
+ - **No re-OCR.** ABBYY 11 on 500 ppi scans of worn 18th-century type is mediocre, and
287
+ visibly so in the confidence figures. Improving it is worth doing and is not this.
288
+ - **No MARC ingest.** The 3.5 MB MARC file covers a different, earlier collection
289
+ (1560–1660 pamphlets) than the one being ingested.
schemas/ocr.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "additionalProperties": false,
4
+ "description": "One <id>.ocr.toml: word-level OCR losslessly equivalent to a DjVu XML derivative. Generated from the Rust types in tools/src/ocr.rs by `scans schema` - do not edit by hand.",
5
+ "properties": {
6
+ "dpi": {
7
+ "description": "Resolution the page was scanned at.",
8
+ "format": "int64",
9
+ "type": "integer"
10
+ },
11
+ "engine": {
12
+ "description": "Producing agent and version, e.g. `ABBYY FineReader 11.0`.",
13
+ "type": "string"
14
+ },
15
+ "h": {
16
+ "description": "Pixel height of the page image.",
17
+ "format": "int64",
18
+ "type": "integer"
19
+ },
20
+ "lang": {
21
+ "description": "BCP-47 code of the text, when known.",
22
+ "type": "string"
23
+ },
24
+ "of": {
25
+ "description": "Id of the record this page belongs to.",
26
+ "type": "string"
27
+ },
28
+ "page": {
29
+ "description": "1-based page index within the scanned container, matching `.pN` addressing.",
30
+ "format": "int64",
31
+ "type": "integer"
32
+ },
33
+ "w": {
34
+ "description": "Pixel width of the page image.",
35
+ "format": "int64",
36
+ "type": "integer"
37
+ }
38
+ },
39
+ "required": [
40
+ "of",
41
+ "page"
42
+ ],
43
+ "title": "Word-level OCR sidecar",
44
+ "type": "object"
45
+ }
schemas/source.json CHANGED
@@ -232,6 +232,11 @@
232
  "description": "Caveats. Does not inherit.",
233
  "type": "string"
234
  },
 
 
 
 
 
235
  "url": {
236
  "description": "Landing page for the digitisation, distinct from top-level `url`. Inherits.",
237
  "type": "string"
@@ -330,6 +335,10 @@
330
  "description": "EDTF. Date of the work, for single-work sources.",
331
  "type": "string"
332
  },
 
 
 
 
333
  "founded": {
334
  "description": "EDTF. Date the publication began.",
335
  "type": "string"
@@ -404,6 +413,13 @@
404
  "short_title": {
405
  "type": "string"
406
  },
 
 
 
 
 
 
 
407
  "text": {
408
  "items": {
409
  "$ref": "#/$defs/Text"
@@ -443,6 +459,10 @@
443
  "description": "EDTF. Date of the object itself, if meaningful.",
444
  "type": "string"
445
  },
 
 
 
 
446
  "holding": {
447
  "$ref": "#/$defs/Holding",
448
  "description": "The normal home for `holding`."
@@ -501,6 +521,13 @@
501
  "short_title": {
502
  "type": "string"
503
  },
 
 
 
 
 
 
 
504
  "text": {
505
  "items": {
506
  "$ref": "#/$defs/Text"
@@ -539,6 +566,10 @@
539
  "description": "EDTF. Used by check 6.",
540
  "type": "string"
541
  },
 
 
 
 
542
  "holding": {
543
  "$ref": "#/$defs/Holding"
544
  },
@@ -606,6 +637,13 @@
606
  "short_title": {
607
  "type": "string"
608
  },
 
 
 
 
 
 
 
609
  "supplement_to": {
610
  "description": "Id of another **document**. Check 8.",
611
  "type": "string"
 
232
  "description": "Caveats. Does not inherit.",
233
  "type": "string"
234
  },
235
+ "ppi": {
236
+ "description": "Resolution the scan was made at, in pixels per inch. Inherits.\n\nStated rather than inferred: `render` otherwise has to guess a page's native\nresolution from the largest image embedded in it.",
237
+ "format": "int64",
238
+ "type": "integer"
239
+ },
240
  "url": {
241
  "description": "Landing page for the digitisation, distinct from top-level `url`. Inherits.",
242
  "type": "string"
 
335
  "description": "EDTF. Date of the work, for single-work sources.",
336
  "type": "string"
337
  },
338
+ "extent": {
339
+ "description": "Bibliographic collation, `\"7 p. ; 18 cm.\"`. Does not inherit.",
340
+ "type": "string"
341
+ },
342
  "founded": {
343
  "description": "EDTF. Date the publication began.",
344
  "type": "string"
 
413
  "short_title": {
414
  "type": "string"
415
  },
416
+ "subject": {
417
+ "description": "Subject headings as the cataloguer wrote them. Does not inherit.",
418
+ "items": {
419
+ "type": "string"
420
+ },
421
+ "type": "array"
422
+ },
423
  "text": {
424
  "items": {
425
  "$ref": "#/$defs/Text"
 
459
  "description": "EDTF. Date of the object itself, if meaningful.",
460
  "type": "string"
461
  },
462
+ "extent": {
463
+ "description": "Bibliographic collation, `\"7 p. ; 18 cm.\"`. Does not inherit.",
464
+ "type": "string"
465
+ },
466
  "holding": {
467
  "$ref": "#/$defs/Holding",
468
  "description": "The normal home for `holding`."
 
521
  "short_title": {
522
  "type": "string"
523
  },
524
+ "subject": {
525
+ "description": "Subject headings as the cataloguer wrote them. Does not inherit.",
526
+ "items": {
527
+ "type": "string"
528
+ },
529
+ "type": "array"
530
+ },
531
  "text": {
532
  "items": {
533
  "$ref": "#/$defs/Text"
 
566
  "description": "EDTF. Used by check 6.",
567
  "type": "string"
568
  },
569
+ "extent": {
570
+ "description": "Bibliographic collation, `\"7 p. ; 18 cm.\"`. Does not inherit.",
571
+ "type": "string"
572
+ },
573
  "holding": {
574
  "$ref": "#/$defs/Holding"
575
  },
 
637
  "short_title": {
638
  "type": "string"
639
  },
640
+ "subject": {
641
+ "description": "Subject headings as the cataloguer wrote them. Does not inherit.",
642
+ "items": {
643
+ "type": "string"
644
+ },
645
+ "type": "array"
646
+ },
647
  "supplement_to": {
648
  "description": "Id of another **document**. Check 8.",
649
  "type": "string"
tools/Cargo.lock CHANGED
@@ -70,7 +70,7 @@ version = "1.1.5"
70
  source = "registry+https://github.com/rust-lang/crates.io-index"
71
  checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
72
  dependencies = [
73
- "windows-sys",
74
  ]
75
 
76
  [[package]]
@@ -81,7 +81,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
81
  dependencies = [
82
  "anstyle",
83
  "once_cell_polyfill",
84
- "windows-sys",
85
  ]
86
 
87
  [[package]]
@@ -102,12 +102,27 @@ version = "1.5.1"
102
  source = "registry+https://github.com/rust-lang/crates.io-index"
103
  checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
104
 
 
 
 
 
 
 
105
  [[package]]
106
  name = "bitflags"
107
  version = "2.13.1"
108
  source = "registry+https://github.com/rust-lang/crates.io-index"
109
  checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
110
 
 
 
 
 
 
 
 
 
 
111
  [[package]]
112
  name = "block-buffer"
113
  version = "0.12.1"
@@ -173,6 +188,12 @@ version = "0.1.0"
173
  source = "registry+https://github.com/rust-lang/crates.io-index"
174
  checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
175
 
 
 
 
 
 
 
176
  [[package]]
177
  name = "cbc"
178
  version = "0.2.1"
@@ -182,6 +203,16 @@ dependencies = [
182
  "cipher",
183
  ]
184
 
 
 
 
 
 
 
 
 
 
 
185
  [[package]]
186
  name = "cfg-if"
187
  version = "1.0.4"
@@ -205,7 +236,7 @@ version = "0.5.2"
205
  source = "registry+https://github.com/rust-lang/crates.io-index"
206
  checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
207
  dependencies = [
208
- "crypto-common",
209
  "inout",
210
  ]
211
 
@@ -294,6 +325,16 @@ dependencies = [
294
  "cfg-if",
295
  ]
296
 
 
 
 
 
 
 
 
 
 
 
297
  [[package]]
298
  name = "crypto-common"
299
  version = "0.2.2"
@@ -303,15 +344,25 @@ dependencies = [
303
  "hybrid-array",
304
  ]
305
 
 
 
 
 
 
 
 
 
 
 
306
  [[package]]
307
  name = "digest"
308
  version = "0.11.3"
309
  source = "registry+https://github.com/rust-lang/crates.io-index"
310
  checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
311
  dependencies = [
312
- "block-buffer",
313
  "const-oid",
314
- "crypto-common",
315
  ]
316
 
317
  [[package]]
@@ -351,7 +402,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
351
  checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
352
  dependencies = [
353
  "libc",
354
- "windows-sys",
355
  ]
356
 
357
  [[package]]
@@ -384,6 +435,12 @@ version = "0.4.1"
384
  source = "registry+https://github.com/rust-lang/crates.io-index"
385
  checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
386
 
 
 
 
 
 
 
387
  [[package]]
388
  name = "flate2"
389
  version = "1.1.9"
@@ -409,6 +466,27 @@ dependencies = [
409
  "bytemuck",
410
  ]
411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  [[package]]
413
  name = "getrandom"
414
  version = "0.4.3"
@@ -552,6 +630,22 @@ version = "0.5.0"
552
  source = "registry+https://github.com/rust-lang/crates.io-index"
553
  checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
554
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555
  [[package]]
556
  name = "hybrid-array"
557
  version = "0.4.14"
@@ -654,11 +748,11 @@ dependencies = [
654
  "ecb",
655
  "encoding_rs",
656
  "flate2",
657
- "getrandom",
658
  "indexmap",
659
  "itoa",
660
  "log",
661
- "md-5",
662
  "nom",
663
  "rand",
664
  "rangemap",
@@ -668,6 +762,16 @@ dependencies = [
668
  "weezl",
669
  ]
670
 
 
 
 
 
 
 
 
 
 
 
671
  [[package]]
672
  name = "md-5"
673
  version = "0.11.0"
@@ -675,7 +779,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
675
  checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
676
  dependencies = [
677
  "cfg-if",
678
- "digest",
679
  ]
680
 
681
  [[package]]
@@ -747,6 +851,12 @@ dependencies = [
747
  "smallvec",
748
  ]
749
 
 
 
 
 
 
 
750
  [[package]]
751
  name = "phf"
752
  version = "0.13.1"
@@ -836,6 +946,15 @@ version = "0.1.30"
836
  source = "registry+https://github.com/rust-lang/crates.io-index"
837
  checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
838
 
 
 
 
 
 
 
 
 
 
839
  [[package]]
840
  name = "quote"
841
  version = "1.0.47"
@@ -858,7 +977,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
858
  checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
859
  dependencies = [
860
  "chacha20",
861
- "getrandom",
862
  "rand_core",
863
  ]
864
 
@@ -904,6 +1023,20 @@ dependencies = [
904
  "syn 3.0.3",
905
  ]
906
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
907
  [[package]]
908
  name = "rustc-hash"
909
  version = "2.1.3"
@@ -920,9 +1053,50 @@ dependencies = [
920
  "errno",
921
  "libc",
922
  "linux-raw-sys",
923
- "windows-sys",
924
  ]
925
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
926
  [[package]]
927
  name = "same-file"
928
  version = "1.0.6"
@@ -940,14 +1114,18 @@ dependencies = [
940
  "clap",
941
  "hayro",
942
  "lopdf",
 
943
  "png",
 
944
  "schemars",
945
  "serde",
946
  "serde_json",
 
947
  "tempfile",
948
  "thiserror",
949
  "toml",
950
  "toml_edit",
 
951
  "walkdir",
952
  ]
953
 
@@ -1030,6 +1208,19 @@ dependencies = [
1030
  "zmij",
1031
  ]
1032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1033
  [[package]]
1034
  name = "serde_spanned"
1035
  version = "1.1.1"
@@ -1047,9 +1238,15 @@ checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
1047
  dependencies = [
1048
  "cfg-if",
1049
  "cpufeatures",
1050
- "digest",
1051
  ]
1052
 
 
 
 
 
 
 
1053
  [[package]]
1054
  name = "simd-adler32"
1055
  version = "0.3.10"
@@ -1101,6 +1298,12 @@ version = "0.11.1"
1101
  source = "registry+https://github.com/rust-lang/crates.io-index"
1102
  checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
1103
 
 
 
 
 
 
 
1104
  [[package]]
1105
  name = "syn"
1106
  version = "2.0.119"
@@ -1141,10 +1344,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1141
  checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
1142
  dependencies = [
1143
  "fastrand",
1144
- "getrandom",
1145
  "once_cell",
1146
  "rustix",
1147
- "windows-sys",
1148
  ]
1149
 
1150
  [[package]]
@@ -1267,6 +1470,53 @@ version = "0.1.4"
1267
  source = "registry+https://github.com/rust-lang/crates.io-index"
1268
  checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
1269
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1270
  [[package]]
1271
  name = "utf8parse"
1272
  version = "0.2.2"
@@ -1320,6 +1570,12 @@ dependencies = [
1320
  "vello_common 0.0.8",
1321
  ]
1322
 
 
 
 
 
 
 
1323
  [[package]]
1324
  name = "walkdir"
1325
  version = "2.5.0"
@@ -1330,6 +1586,21 @@ dependencies = [
1330
  "winapi-util",
1331
  ]
1332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1333
  [[package]]
1334
  name = "weezl"
1335
  version = "0.2.1"
@@ -1342,7 +1613,7 @@ version = "0.1.11"
1342
  source = "registry+https://github.com/rust-lang/crates.io-index"
1343
  checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
1344
  dependencies = [
1345
- "windows-sys",
1346
  ]
1347
 
1348
  [[package]]
@@ -1351,6 +1622,15 @@ version = "0.2.1"
1351
  source = "registry+https://github.com/rust-lang/crates.io-index"
1352
  checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
1353
 
 
 
 
 
 
 
 
 
 
1354
  [[package]]
1355
  name = "windows-sys"
1356
  version = "0.61.2"
@@ -1360,6 +1640,70 @@ dependencies = [
1360
  "windows-link",
1361
  ]
1362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1363
  [[package]]
1364
  name = "winnow"
1365
  version = "1.0.4"
@@ -1413,6 +1757,12 @@ dependencies = [
1413
  "synstructure",
1414
  ]
1415
 
 
 
 
 
 
 
1416
  [[package]]
1417
  name = "zmij"
1418
  version = "1.0.23"
 
70
  source = "registry+https://github.com/rust-lang/crates.io-index"
71
  checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
72
  dependencies = [
73
+ "windows-sys 0.61.2",
74
  ]
75
 
76
  [[package]]
 
81
  dependencies = [
82
  "anstyle",
83
  "once_cell_polyfill",
84
+ "windows-sys 0.61.2",
85
  ]
86
 
87
  [[package]]
 
102
  source = "registry+https://github.com/rust-lang/crates.io-index"
103
  checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
104
 
105
+ [[package]]
106
+ name = "base64"
107
+ version = "0.22.1"
108
+ source = "registry+https://github.com/rust-lang/crates.io-index"
109
+ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
110
+
111
  [[package]]
112
  name = "bitflags"
113
  version = "2.13.1"
114
  source = "registry+https://github.com/rust-lang/crates.io-index"
115
  checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
116
 
117
+ [[package]]
118
+ name = "block-buffer"
119
+ version = "0.10.4"
120
+ source = "registry+https://github.com/rust-lang/crates.io-index"
121
+ checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
122
+ dependencies = [
123
+ "generic-array",
124
+ ]
125
+
126
  [[package]]
127
  name = "block-buffer"
128
  version = "0.12.1"
 
188
  source = "registry+https://github.com/rust-lang/crates.io-index"
189
  checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
190
 
191
+ [[package]]
192
+ name = "bytes"
193
+ version = "1.12.1"
194
+ source = "registry+https://github.com/rust-lang/crates.io-index"
195
+ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
196
+
197
  [[package]]
198
  name = "cbc"
199
  version = "0.2.1"
 
203
  "cipher",
204
  ]
205
 
206
+ [[package]]
207
+ name = "cc"
208
+ version = "1.4.0"
209
+ source = "registry+https://github.com/rust-lang/crates.io-index"
210
+ checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
211
+ dependencies = [
212
+ "find-msvc-tools",
213
+ "shlex",
214
+ ]
215
+
216
  [[package]]
217
  name = "cfg-if"
218
  version = "1.0.4"
 
236
  source = "registry+https://github.com/rust-lang/crates.io-index"
237
  checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
238
  dependencies = [
239
+ "crypto-common 0.2.2",
240
  "inout",
241
  ]
242
 
 
325
  "cfg-if",
326
  ]
327
 
328
+ [[package]]
329
+ name = "crypto-common"
330
+ version = "0.1.7"
331
+ source = "registry+https://github.com/rust-lang/crates.io-index"
332
+ checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
333
+ dependencies = [
334
+ "generic-array",
335
+ "typenum",
336
+ ]
337
+
338
  [[package]]
339
  name = "crypto-common"
340
  version = "0.2.2"
 
344
  "hybrid-array",
345
  ]
346
 
347
+ [[package]]
348
+ name = "digest"
349
+ version = "0.10.7"
350
+ source = "registry+https://github.com/rust-lang/crates.io-index"
351
+ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
352
+ dependencies = [
353
+ "block-buffer 0.10.4",
354
+ "crypto-common 0.1.7",
355
+ ]
356
+
357
  [[package]]
358
  name = "digest"
359
  version = "0.11.3"
360
  source = "registry+https://github.com/rust-lang/crates.io-index"
361
  checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
362
  dependencies = [
363
+ "block-buffer 0.12.1",
364
  "const-oid",
365
+ "crypto-common 0.2.2",
366
  ]
367
 
368
  [[package]]
 
402
  checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
403
  dependencies = [
404
  "libc",
405
+ "windows-sys 0.61.2",
406
  ]
407
 
408
  [[package]]
 
435
  source = "registry+https://github.com/rust-lang/crates.io-index"
436
  checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
437
 
438
+ [[package]]
439
+ name = "find-msvc-tools"
440
+ version = "0.1.9"
441
+ source = "registry+https://github.com/rust-lang/crates.io-index"
442
+ checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
443
+
444
  [[package]]
445
  name = "flate2"
446
  version = "1.1.9"
 
466
  "bytemuck",
467
  ]
468
 
469
+ [[package]]
470
+ name = "generic-array"
471
+ version = "0.14.7"
472
+ source = "registry+https://github.com/rust-lang/crates.io-index"
473
+ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
474
+ dependencies = [
475
+ "typenum",
476
+ "version_check",
477
+ ]
478
+
479
+ [[package]]
480
+ name = "getrandom"
481
+ version = "0.2.17"
482
+ source = "registry+https://github.com/rust-lang/crates.io-index"
483
+ checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
484
+ dependencies = [
485
+ "cfg-if",
486
+ "libc",
487
+ "wasi",
488
+ ]
489
+
490
  [[package]]
491
  name = "getrandom"
492
  version = "0.4.3"
 
630
  source = "registry+https://github.com/rust-lang/crates.io-index"
631
  checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
632
 
633
+ [[package]]
634
+ name = "http"
635
+ version = "1.5.0"
636
+ source = "registry+https://github.com/rust-lang/crates.io-index"
637
+ checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
638
+ dependencies = [
639
+ "bytes",
640
+ "itoa",
641
+ ]
642
+
643
+ [[package]]
644
+ name = "httparse"
645
+ version = "1.10.1"
646
+ source = "registry+https://github.com/rust-lang/crates.io-index"
647
+ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
648
+
649
  [[package]]
650
  name = "hybrid-array"
651
  version = "0.4.14"
 
748
  "ecb",
749
  "encoding_rs",
750
  "flate2",
751
+ "getrandom 0.4.3",
752
  "indexmap",
753
  "itoa",
754
  "log",
755
+ "md-5 0.11.0",
756
  "nom",
757
  "rand",
758
  "rangemap",
 
762
  "weezl",
763
  ]
764
 
765
+ [[package]]
766
+ name = "md-5"
767
+ version = "0.10.6"
768
+ source = "registry+https://github.com/rust-lang/crates.io-index"
769
+ checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
770
+ dependencies = [
771
+ "cfg-if",
772
+ "digest 0.10.7",
773
+ ]
774
+
775
  [[package]]
776
  name = "md-5"
777
  version = "0.11.0"
 
779
  checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
780
  dependencies = [
781
  "cfg-if",
782
+ "digest 0.11.3",
783
  ]
784
 
785
  [[package]]
 
851
  "smallvec",
852
  ]
853
 
854
+ [[package]]
855
+ name = "percent-encoding"
856
+ version = "2.3.2"
857
+ source = "registry+https://github.com/rust-lang/crates.io-index"
858
+ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
859
+
860
  [[package]]
861
  name = "phf"
862
  version = "0.13.1"
 
946
  source = "registry+https://github.com/rust-lang/crates.io-index"
947
  checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
948
 
949
+ [[package]]
950
+ name = "quick-xml"
951
+ version = "0.38.4"
952
+ source = "registry+https://github.com/rust-lang/crates.io-index"
953
+ checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
954
+ dependencies = [
955
+ "memchr",
956
+ ]
957
+
958
  [[package]]
959
  name = "quote"
960
  version = "1.0.47"
 
977
  checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
978
  dependencies = [
979
  "chacha20",
980
+ "getrandom 0.4.3",
981
  "rand_core",
982
  ]
983
 
 
1023
  "syn 3.0.3",
1024
  ]
1025
 
1026
+ [[package]]
1027
+ name = "ring"
1028
+ version = "0.17.14"
1029
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1030
+ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
1031
+ dependencies = [
1032
+ "cc",
1033
+ "cfg-if",
1034
+ "getrandom 0.2.17",
1035
+ "libc",
1036
+ "untrusted",
1037
+ "windows-sys 0.52.0",
1038
+ ]
1039
+
1040
  [[package]]
1041
  name = "rustc-hash"
1042
  version = "2.1.3"
 
1053
  "errno",
1054
  "libc",
1055
  "linux-raw-sys",
1056
+ "windows-sys 0.61.2",
1057
  ]
1058
 
1059
+ [[package]]
1060
+ name = "rustls"
1061
+ version = "0.23.43"
1062
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1063
+ checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06"
1064
+ dependencies = [
1065
+ "log",
1066
+ "once_cell",
1067
+ "ring",
1068
+ "rustls-pki-types",
1069
+ "rustls-webpki",
1070
+ "subtle",
1071
+ "zeroize",
1072
+ ]
1073
+
1074
+ [[package]]
1075
+ name = "rustls-pki-types"
1076
+ version = "1.15.1"
1077
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1078
+ checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
1079
+ dependencies = [
1080
+ "zeroize",
1081
+ ]
1082
+
1083
+ [[package]]
1084
+ name = "rustls-webpki"
1085
+ version = "0.103.13"
1086
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1087
+ checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
1088
+ dependencies = [
1089
+ "ring",
1090
+ "rustls-pki-types",
1091
+ "untrusted",
1092
+ ]
1093
+
1094
+ [[package]]
1095
+ name = "ryu"
1096
+ version = "1.0.23"
1097
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1098
+ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
1099
+
1100
  [[package]]
1101
  name = "same-file"
1102
  version = "1.0.6"
 
1114
  "clap",
1115
  "hayro",
1116
  "lopdf",
1117
+ "md-5 0.10.6",
1118
  "png",
1119
+ "quick-xml",
1120
  "schemars",
1121
  "serde",
1122
  "serde_json",
1123
+ "serde_norway",
1124
  "tempfile",
1125
  "thiserror",
1126
  "toml",
1127
  "toml_edit",
1128
+ "ureq",
1129
  "walkdir",
1130
  ]
1131
 
 
1208
  "zmij",
1209
  ]
1210
 
1211
+ [[package]]
1212
+ name = "serde_norway"
1213
+ version = "0.9.42"
1214
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1215
+ checksum = "e408f29489b5fd500fab51ff1484fc859bb655f32c671f307dcd733b72e8168c"
1216
+ dependencies = [
1217
+ "indexmap",
1218
+ "itoa",
1219
+ "ryu",
1220
+ "serde",
1221
+ "unsafe-libyaml-norway",
1222
+ ]
1223
+
1224
  [[package]]
1225
  name = "serde_spanned"
1226
  version = "1.1.1"
 
1238
  dependencies = [
1239
  "cfg-if",
1240
  "cpufeatures",
1241
+ "digest 0.11.3",
1242
  ]
1243
 
1244
+ [[package]]
1245
+ name = "shlex"
1246
+ version = "2.0.1"
1247
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1248
+ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
1249
+
1250
  [[package]]
1251
  name = "simd-adler32"
1252
  version = "0.3.10"
 
1298
  source = "registry+https://github.com/rust-lang/crates.io-index"
1299
  checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
1300
 
1301
+ [[package]]
1302
+ name = "subtle"
1303
+ version = "2.6.1"
1304
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1305
+ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
1306
+
1307
  [[package]]
1308
  name = "syn"
1309
  version = "2.0.119"
 
1344
  checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
1345
  dependencies = [
1346
  "fastrand",
1347
+ "getrandom 0.4.3",
1348
  "once_cell",
1349
  "rustix",
1350
+ "windows-sys 0.61.2",
1351
  ]
1352
 
1353
  [[package]]
 
1470
  source = "registry+https://github.com/rust-lang/crates.io-index"
1471
  checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
1472
 
1473
+ [[package]]
1474
+ name = "unsafe-libyaml-norway"
1475
+ version = "0.2.15"
1476
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1477
+ checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104"
1478
+
1479
+ [[package]]
1480
+ name = "untrusted"
1481
+ version = "0.9.0"
1482
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1483
+ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
1484
+
1485
+ [[package]]
1486
+ name = "ureq"
1487
+ version = "3.3.0"
1488
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1489
+ checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"
1490
+ dependencies = [
1491
+ "base64",
1492
+ "flate2",
1493
+ "log",
1494
+ "percent-encoding",
1495
+ "rustls",
1496
+ "rustls-pki-types",
1497
+ "ureq-proto",
1498
+ "utf8-zero",
1499
+ "webpki-roots",
1500
+ ]
1501
+
1502
+ [[package]]
1503
+ name = "ureq-proto"
1504
+ version = "0.6.0"
1505
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1506
+ checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c"
1507
+ dependencies = [
1508
+ "base64",
1509
+ "http",
1510
+ "httparse",
1511
+ "log",
1512
+ ]
1513
+
1514
+ [[package]]
1515
+ name = "utf8-zero"
1516
+ version = "0.8.1"
1517
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1518
+ checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
1519
+
1520
  [[package]]
1521
  name = "utf8parse"
1522
  version = "0.2.2"
 
1570
  "vello_common 0.0.8",
1571
  ]
1572
 
1573
+ [[package]]
1574
+ name = "version_check"
1575
+ version = "0.9.5"
1576
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1577
+ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
1578
+
1579
  [[package]]
1580
  name = "walkdir"
1581
  version = "2.5.0"
 
1586
  "winapi-util",
1587
  ]
1588
 
1589
+ [[package]]
1590
+ name = "wasi"
1591
+ version = "0.11.1+wasi-snapshot-preview1"
1592
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1593
+ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
1594
+
1595
+ [[package]]
1596
+ name = "webpki-roots"
1597
+ version = "1.0.9"
1598
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1599
+ checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
1600
+ dependencies = [
1601
+ "rustls-pki-types",
1602
+ ]
1603
+
1604
  [[package]]
1605
  name = "weezl"
1606
  version = "0.2.1"
 
1613
  source = "registry+https://github.com/rust-lang/crates.io-index"
1614
  checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
1615
  dependencies = [
1616
+ "windows-sys 0.61.2",
1617
  ]
1618
 
1619
  [[package]]
 
1622
  source = "registry+https://github.com/rust-lang/crates.io-index"
1623
  checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
1624
 
1625
+ [[package]]
1626
+ name = "windows-sys"
1627
+ version = "0.52.0"
1628
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1629
+ checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
1630
+ dependencies = [
1631
+ "windows-targets",
1632
+ ]
1633
+
1634
  [[package]]
1635
  name = "windows-sys"
1636
  version = "0.61.2"
 
1640
  "windows-link",
1641
  ]
1642
 
1643
+ [[package]]
1644
+ name = "windows-targets"
1645
+ version = "0.52.6"
1646
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1647
+ checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
1648
+ dependencies = [
1649
+ "windows_aarch64_gnullvm",
1650
+ "windows_aarch64_msvc",
1651
+ "windows_i686_gnu",
1652
+ "windows_i686_gnullvm",
1653
+ "windows_i686_msvc",
1654
+ "windows_x86_64_gnu",
1655
+ "windows_x86_64_gnullvm",
1656
+ "windows_x86_64_msvc",
1657
+ ]
1658
+
1659
+ [[package]]
1660
+ name = "windows_aarch64_gnullvm"
1661
+ version = "0.52.6"
1662
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1663
+ checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
1664
+
1665
+ [[package]]
1666
+ name = "windows_aarch64_msvc"
1667
+ version = "0.52.6"
1668
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1669
+ checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
1670
+
1671
+ [[package]]
1672
+ name = "windows_i686_gnu"
1673
+ version = "0.52.6"
1674
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1675
+ checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
1676
+
1677
+ [[package]]
1678
+ name = "windows_i686_gnullvm"
1679
+ version = "0.52.6"
1680
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1681
+ checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
1682
+
1683
+ [[package]]
1684
+ name = "windows_i686_msvc"
1685
+ version = "0.52.6"
1686
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1687
+ checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
1688
+
1689
+ [[package]]
1690
+ name = "windows_x86_64_gnu"
1691
+ version = "0.52.6"
1692
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1693
+ checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
1694
+
1695
+ [[package]]
1696
+ name = "windows_x86_64_gnullvm"
1697
+ version = "0.52.6"
1698
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1699
+ checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
1700
+
1701
+ [[package]]
1702
+ name = "windows_x86_64_msvc"
1703
+ version = "0.52.6"
1704
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1705
+ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
1706
+
1707
  [[package]]
1708
  name = "winnow"
1709
  version = "1.0.4"
 
1757
  "synstructure",
1758
  ]
1759
 
1760
+ [[package]]
1761
+ name = "zeroize"
1762
+ version = "1.9.0"
1763
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1764
+ checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
1765
+
1766
  [[package]]
1767
  name = "zmij"
1768
  version = "1.0.23"
tools/Cargo.toml CHANGED
@@ -47,6 +47,15 @@ ingest = ["dep:lopdf"]
47
  # rasteriser whose `images` feature carries pure-Rust JBIG2 and JPEG 2000 decoders, which is
48
  # the whole reason it is here — no C toolchain, no Ghostscript, no pdfium binary to ship.
49
  render = ["dep:hayro", "dep:png"]
 
 
 
 
 
 
 
 
 
50
 
51
  [dependencies]
52
  anyhow = "1.0.104"
@@ -58,6 +67,19 @@ lopdf = { version = "0.44", default-features = false, optional = true }
58
  # A bitonal scan encoded as 8-bit grey is a quarter of the size for identical pixels, and
59
  # these files exist to be read a few hundred at a time.
60
  png = { version = "0.18.1", optional = true }
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  # schemars DERIVES the JSON Schema from the same types the validator uses, so the schema
62
  # cannot drift away from the code. It is never hand-written.
63
  schemars = "1.2.2"
 
47
  # rasteriser whose `images` feature carries pure-Rust JBIG2 and JPEG 2000 decoders, which is
48
  # the whole reason it is here — no C toolchain, no Ghostscript, no pdfium binary to ship.
49
  render = ["dep:hayro", "dep:png"]
50
+ # `scans frc fetch` downloads the corpus PDFs from archive.org. Off by default because it is
51
+ # the only feature that opens a socket, and because it drags in a TLS stack that a `validate`
52
+ # run has no business paying for.
53
+ #
54
+ # `ureq` rather than `reqwest`: this makes one request at a time by design — the whole point
55
+ # is to be a polite guest on someone else's server — so an async runtime would be several
56
+ # hundred crates of dependency bought to do nothing. It is pure Rust with rustls, so there is
57
+ # still no C toolchain.
58
+ fetch = ["dep:ureq", "dep:md-5"]
59
 
60
  [dependencies]
61
  anyhow = "1.0.104"
 
67
  # A bitonal scan encoded as 8-bit grey is a quarter of the size for identical pixels, and
68
  # these files exist to be read a few hundred at a time.
69
  png = { version = "0.18.1", optional = true }
70
+ # A real XML parser rather than the hand-rolled parsing used elsewhere in this crate.
71
+ # 38,377 files of machine-generated XML from a decade of changing derive pipelines is
72
+ # exactly the input that finds the gap between the documented format and the served bytes.
73
+ # Pure Rust, no C toolchain, which is the constraint that actually matters here.
74
+ quick-xml = "0.38"
75
+ # The OCR sidecars are markdown with YAML frontmatter, so something has to read YAML.
76
+ # `serde_norway` rather than `serde_yaml`, which its author archived in 2024; this is the
77
+ # maintained fork of it and keeps the same serde-based API. Pure Rust.
78
+ serde_norway = "0.9"
79
+ # Verifying a download against the MD5 archive.org publishes for it. A truncated PDF that is
80
+ # committed and then believed is worse than one that failed loudly.
81
+ md-5 = { version = "0.10", optional = true }
82
+ ureq = { version = "3", optional = true }
83
  # schemars DERIVES the JSON Schema from the same types the validator uses, so the schema
84
  # cannot drift away from the code. It is never hand-written.
85
  schemars = "1.2.2"
tools/src/djvu.rs ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Reading archive.org's `_djvu.xml` into page text.
2
+ //!
3
+ //! This is the only place that knows what DjVu XML looks like. [`crate::ocr`] knows the
4
+ //! markdown form; the two meet here.
5
+ //!
6
+ //! ## The source format
7
+ //!
8
+ //! ```xml
9
+ //! <OBJECT type="image/x.djvu" usemap="abondance00unse_0001.djvu" width="2544" height="4426">
10
+ //! <PARAM name="DPI" value="500"/>
11
+ //! <HIDDENTEXT>
12
+ //! <PAGECOLUMN><REGION><PARAGRAPH><LINE>
13
+ //! <WORD coords="278,1378,1726,1250" x-confidence="71">ABONDANC</WORD>
14
+ //! ```
15
+ //!
16
+ //! One `OBJECT` per page, and one element per word, nested
17
+ //! `PAGECOLUMN > REGION > PARAGRAPH > LINE > WORD`.
18
+ //!
19
+ //! ## What is taken, and what is not
20
+ //!
21
+ //! Taken: the page's dimensions, its resolution, and its words. **Not taken:** the word
22
+ //! boxes, the per-word confidence, and the baselines. An earlier version of this carried all
23
+ //! of it and could write the XML back out unchanged; the boxes were not being used and were
24
+ //! seven eighths of the bytes, so they are gone at the repository owner's direction. The
25
+ //! coordinates still exist in frc-data, one clone away, if a later version wants them.
26
+ //!
27
+ //! The nesting is still read, but only to lay the text out: a line break ends a line, and
28
+ //! anything above it leaves a blank line. That is the whole of what it is used for now.
29
+ //!
30
+ //! ## Why a real parser
31
+ //!
32
+ //! The rest of this crate hand-rolls its parsing. This does not, because 38,377 files of
33
+ //! machine-generated XML from a decade of changing derive pipelines is exactly the input that
34
+ //! finds the gap between "the format I read about" and "the bytes that arrived". `quick-xml`
35
+ //! is pure Rust with no C toolchain, which is the constraint that actually matters here.
36
+
37
+ use anyhow::{Context, Result};
38
+ use quick_xml::Reader;
39
+ use quick_xml::events::Event;
40
+
41
+ use crate::ocr::Ocr;
42
+
43
+ /// Where a word sits in the nesting, as counters within its page.
44
+ ///
45
+ /// Compared between neighbouring words to work out what whitespace separates them; the
46
+ /// absolute values mean nothing on their own.
47
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
48
+ struct Nest {
49
+ column: u32,
50
+ region: u32,
51
+ paragraph: u32,
52
+ line: u32,
53
+ }
54
+
55
+ impl Nest {
56
+ /// The whitespace between this word and the next.
57
+ ///
58
+ /// A change of line is a newline; a change of anything above it is a blank line, because
59
+ /// the distinction between a paragraph, a region and a column is not one a reader of the
60
+ /// text can act on.
61
+ fn separator_to(self, next: Nest) -> &'static str {
62
+ if (self.column, self.region, self.paragraph) != (next.column, next.region, next.paragraph)
63
+ {
64
+ "\n\n"
65
+ } else if self.line != next.line {
66
+ "\n"
67
+ } else {
68
+ " "
69
+ }
70
+ }
71
+ }
72
+
73
+ /// Parse a `_djvu.xml` into one [`Ocr`] per page.
74
+ ///
75
+ /// `of` is the record id the pages belong to; the XML does not reliably state it.
76
+ pub fn parse(xml: &str, of: &str) -> Result<Vec<Ocr>> {
77
+ let mut reader = Reader::from_str(xml);
78
+ reader.config_mut().trim_text(false);
79
+
80
+ let mut pages: Vec<Ocr> = Vec::new();
81
+ let mut nest = Nest::default();
82
+
83
+ // The page under construction, and the words collected for it so far.
84
+ let mut cur: Option<Ocr> = None;
85
+ let mut words: Vec<(String, Nest)> = Vec::new();
86
+ // Set while inside a <WORD>: its text arrives as separate events, and in more than one
87
+ // piece when it contains an entity reference.
88
+ let mut in_word = false;
89
+
90
+ loop {
91
+ let event = reader.read_event().with_context(|| {
92
+ format!("reading {of}_djvu.xml at byte {}", reader.buffer_position())
93
+ })?;
94
+
95
+ // `<WORD .../>` is self-closing and has no text; `<WORD ...>x</WORD>` does.
96
+ let opens = matches!(event, Event::Start(_));
97
+
98
+ match event {
99
+ Event::Eof => break,
100
+
101
+ Event::Start(e) | Event::Empty(e) => match e.local_name().as_ref() {
102
+ b"OBJECT" => {
103
+ flush(&mut pages, &mut cur, &mut words);
104
+ cur = Some(Ocr {
105
+ of: of.to_string(),
106
+ page: pages.len() as i64 + 1,
107
+ w: attr_i64(&e, b"width")?,
108
+ h: attr_i64(&e, b"height")?,
109
+ ..Ocr::default()
110
+ });
111
+ nest = Nest::default();
112
+ }
113
+ b"PARAM" => {
114
+ // <PARAM name="DPI" value="500"/>
115
+ if attr(&e, b"name")?.as_deref() == Some("DPI")
116
+ && let Some(page) = cur.as_mut()
117
+ && let Some(v) = attr(&e, b"value")?
118
+ {
119
+ page.dpi = v.trim().parse::<i64>().ok();
120
+ }
121
+ }
122
+ b"PAGECOLUMN" => nest.column += 1,
123
+ b"REGION" => nest.region += 1,
124
+ b"PARAGRAPH" => nest.paragraph += 1,
125
+ b"LINE" => nest.line += 1,
126
+ b"WORD" => {
127
+ words.push((String::new(), nest));
128
+ in_word = opens;
129
+ }
130
+ _ => {}
131
+ },
132
+
133
+ Event::End(e) if e.local_name().as_ref() == b"WORD" => in_word = false,
134
+
135
+ Event::Text(t) if in_word => {
136
+ let s = t
137
+ .decode()
138
+ .with_context(|| format!("{of}: undecodable word text"))?;
139
+ if let Some((word, _)) = words.last_mut() {
140
+ word.push_str(&s);
141
+ }
142
+ }
143
+
144
+ // `&amp;` and friends arrive as their own event rather than inside the text, so a
145
+ // word containing one is split across three events. Dropping this arm silently
146
+ // deletes every ampersand in the corpus.
147
+ Event::GeneralRef(r) if in_word => {
148
+ let text = match r.resolve_char_ref().ok().flatten() {
149
+ Some(c) => c.to_string(),
150
+ None => match String::from_utf8_lossy(r.as_ref()).as_ref() {
151
+ "amp" => "&".into(),
152
+ "lt" => "<".into(),
153
+ "gt" => ">".into(),
154
+ "quot" => "\"".into(),
155
+ "apos" => "'".into(),
156
+ // DjVu XML declares no entities of its own, so anything else is
157
+ // damage. Keep it as written rather than dropping the characters.
158
+ other => format!("&{other};"),
159
+ },
160
+ };
161
+ if let Some((word, _)) = words.last_mut() {
162
+ word.push_str(&text);
163
+ }
164
+ }
165
+
166
+ _ => {}
167
+ }
168
+ }
169
+
170
+ flush(&mut pages, &mut cur, &mut words);
171
+ Ok(pages)
172
+ }
173
+
174
+ /// Close off the page under construction, laying its words out as text, and push it.
175
+ fn flush(pages: &mut Vec<Ocr>, cur: &mut Option<Ocr>, words: &mut Vec<(String, Nest)>) {
176
+ let Some(mut page) = cur.take() else {
177
+ // A prologue before the first `<OBJECT>`. Whatever was collected belongs to no page.
178
+ words.clear();
179
+ return;
180
+ };
181
+
182
+ let mut text = String::new();
183
+ for (i, (word, nest)) in words.iter().enumerate() {
184
+ text.push_str(word);
185
+ if let Some((_, next)) = words.get(i + 1) {
186
+ text.push_str(nest.separator_to(*next));
187
+ }
188
+ }
189
+ // ABBYY puts a trailing space inside the element often enough that the joins double up.
190
+ page.text = text.trim_end().to_string();
191
+
192
+ words.clear();
193
+ pages.push(page);
194
+ }
195
+
196
+ fn attr(e: &quick_xml::events::BytesStart<'_>, name: &[u8]) -> Result<Option<String>> {
197
+ for a in e.attributes().with_checks(false) {
198
+ let a = a.context("unreadable attribute")?;
199
+ if a.key.as_ref() == name {
200
+ return Ok(Some(
201
+ a.unescape_value().context("undecodable attribute")?.into_owned(),
202
+ ));
203
+ }
204
+ }
205
+ Ok(None)
206
+ }
207
+
208
+ fn attr_i64(e: &quick_xml::events::BytesStart<'_>, name: &[u8]) -> Result<Option<i64>> {
209
+ Ok(attr(e, name)?.and_then(|v| v.trim().parse().ok()))
210
+ }
211
+
212
+ #[cfg(test)]
213
+ mod tests {
214
+ use super::*;
215
+
216
+ const SAMPLE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
217
+ <DjVuXML>
218
+ <BODY>
219
+ <OBJECT type="image/x.djvu" usemap="x_0001.djvu" width="2544" height="4426">
220
+ <PARAM name="DPI" value="500"/>
221
+ <HIDDENTEXT>
222
+ <PAGECOLUMN><REGION><PARAGRAPH>
223
+ <LINE>
224
+ <WORD coords="278,1378,1726,1250" x-confidence="71">ABONDANC</WORD>
225
+ <WORD coords="279,2039,1128,1947" x-confidence="57">DECOUVERTES </WORD>
226
+ </LINE>
227
+ <LINE>
228
+ <WORD coords="483,1647,1721,1527" x-confidence="0">NATIONALE,</WORD>
229
+ </LINE>
230
+ </PARAGRAPH>
231
+ <PARAGRAPH><LINE>
232
+ <WORD coords="1017,1823,1073,1763" x-confidence="3">O&amp;U</WORD>
233
+ </LINE></PARAGRAPH>
234
+ </REGION></PAGECOLUMN>
235
+ </HIDDENTEXT>
236
+ </OBJECT>
237
+ </BODY>
238
+ </DjVuXML>
239
+ "#;
240
+
241
+ #[test]
242
+ fn a_page_carries_its_dimensions_and_resolution() {
243
+ let pages = parse(SAMPLE, "x").unwrap();
244
+ assert_eq!(pages.len(), 1);
245
+ assert_eq!(pages[0].of, "x");
246
+ assert_eq!(pages[0].page, 1);
247
+ assert_eq!(pages[0].w, Some(2544));
248
+ assert_eq!(pages[0].h, Some(4426));
249
+ assert_eq!(pages[0].dpi, Some(500));
250
+ }
251
+
252
+ /// The nesting is read only to lay the text out — a line ends a line, anything above it
253
+ /// leaves a blank line.
254
+ #[test]
255
+ fn the_nesting_becomes_line_and_paragraph_breaks() {
256
+ let pages = parse(SAMPLE, "x").unwrap();
257
+ assert_eq!(
258
+ pages[0].text,
259
+ "ABONDANC DECOUVERTES \nNATIONALE,\n\nO&U"
260
+ );
261
+ }
262
+
263
+ /// These titles are full of ampersands, and an entity arrives as its own event.
264
+ #[test]
265
+ fn entities_are_decoded_once() {
266
+ let pages = parse(SAMPLE, "x").unwrap();
267
+ assert!(pages[0].text.contains("O&U"), "{}", pages[0].text);
268
+ }
269
+
270
+ /// The five-coordinate derivation frc-data carries. Coordinates are ignored now, so it
271
+ /// must simply not trip over them.
272
+ #[test]
273
+ fn the_five_coordinate_derivation_reads_the_same() {
274
+ let xml = r#"<DjVuXML><BODY><OBJECT width="10" height="20"><HIDDENTEXT>
275
+ <PAGECOLUMN><REGION backgroundColor="14866620"><PARAGRAPH><LINE>
276
+ <WORD coords="1562,366,1570,348,381">mot</WORD>
277
+ <WORD coords="1596,396,1614,336,396">suivant</WORD>
278
+ </LINE></PARAGRAPH></REGION></PAGECOLUMN>
279
+ </HIDDENTEXT></OBJECT></BODY></DjVuXML>"#;
280
+ let pages = parse(xml, "x").unwrap();
281
+ assert_eq!(pages[0].text, "mot suivant");
282
+ }
283
+
284
+ #[test]
285
+ fn a_page_with_no_hidden_text_is_legal() {
286
+ let xml = r#"<DjVuXML><BODY>
287
+ <OBJECT width="10" height="20"><PARAM name="DPI" value="300"/></OBJECT>
288
+ </BODY></DjVuXML>"#;
289
+ let pages = parse(xml, "x").unwrap();
290
+ assert_eq!(pages.len(), 1);
291
+ assert_eq!(pages[0].text, "");
292
+ assert_eq!(pages[0].w, Some(10));
293
+ }
294
+
295
+ #[test]
296
+ fn pages_are_numbered_from_one() {
297
+ let xml = r#"<DjVuXML><BODY>
298
+ <OBJECT width="1" height="1"></OBJECT>
299
+ <OBJECT width="2" height="2"></OBJECT>
300
+ <OBJECT width="3" height="3"></OBJECT>
301
+ </BODY></DjVuXML>"#;
302
+ let pages = parse(xml, "x").unwrap();
303
+ assert_eq!(pages.iter().map(|p| p.page).collect::<Vec<_>>(), [1, 2, 3]);
304
+ }
305
+
306
+ /// The text goes straight into a markdown body, so it must survive that trip intact.
307
+ #[test]
308
+ fn parsed_text_round_trips_through_the_markdown() {
309
+ let pages = parse(SAMPLE, "x").unwrap();
310
+ let md = crate::ocr::to_markdown(&pages[0], "s.json");
311
+ assert_eq!(crate::ocr::from_markdown(&md).unwrap(), pages[0]);
312
+ }
313
+ }
tools/src/frc/fetch.rs ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Fetching the corpus PDFs from archive.org.
2
+ //!
3
+ //! The only part of the ingest that touches the network, and the only part that has to be
4
+ //! careful about it. Everything else — the item list, the catalogue metadata, the word-level
5
+ //! OCR — comes out of the frc-data repository in a single clone.
6
+ //!
7
+ //! ## What this asks of archive.org
8
+ //!
9
+ //! Two requests per item: the metadata JSON, which gives the authoritative filename, size and
10
+ //! MD5 of the PDF, and the PDF itself. 38,377 items is about 77,000 requests and 63 GB, which
11
+ //! at one request a second is a run of a day or so.
12
+ //!
13
+ //! It could be one request per item by guessing the URL as `<id>/<id>.pdf` and skipping
14
+ //! verification. That is not done, for two reasons: a handful of items name their PDF
15
+ //! something else, and without the published MD5 there is no way to tell a complete download
16
+ //! from a truncated one. A silently truncated PDF committed to the archive and then believed
17
+ //! is a worse outcome than a slower run.
18
+ //!
19
+ //! ## Resuming
20
+ //!
21
+ //! An item is done when its PDF is on disk with the right size. That is the whole resume
22
+ //! condition — there is no ledger, because a ledger is a second source of truth that can fall
23
+ //! out of step with the tree it describes. A run interrupted at item 20,000 restarts by
24
+ //! `stat`ing 20,000 files, which takes a moment and cannot be wrong.
25
+
26
+ use std::time::Duration;
27
+
28
+ // Everything below is needed only by the networking half, which is behind the feature.
29
+ #[cfg(feature = "fetch")]
30
+ use std::{io::Read, path::Path};
31
+
32
+ #[cfg(feature = "fetch")]
33
+ use anyhow::{Context, Result, bail};
34
+
35
+ #[cfg(feature = "fetch")]
36
+ use super::{ingest::item_dir, limiter::Limiter};
37
+
38
+ /// Identifies this crawler to archive.org, so an operator who wants it to stop can find us.
39
+ ///
40
+ /// An honest User-Agent is the cheapest possible courtesy and the first thing anyone looks
41
+ /// for in a log when traffic they did not expect turns up.
42
+ pub const USER_AGENT: &str =
43
+ concat!("scans/", env!("CARGO_PKG_VERSION"), " (+https://github.com/peasanttide/scans)");
44
+
45
+ /// How many times one item is retried before it is parked and the run moves on.
46
+ #[cfg(feature = "fetch")]
47
+ const MAX_ATTEMPTS: u32 = 4;
48
+
49
+ /// Options for a fetch run.
50
+ #[derive(Debug, Clone)]
51
+ pub struct Options {
52
+ /// Minimum gap between requests.
53
+ pub interval: Duration,
54
+ /// Stop after this many items.
55
+ pub limit: Option<usize>,
56
+ /// Re-fetch items that already have a PDF.
57
+ pub force: bool,
58
+ /// Report what would be fetched without fetching it.
59
+ pub dry_run: bool,
60
+ }
61
+
62
+ impl Default for Options {
63
+ fn default() -> Self {
64
+ Options {
65
+ interval: super::limiter::DEFAULT_INTERVAL,
66
+ limit: None,
67
+ force: false,
68
+ dry_run: false,
69
+ }
70
+ }
71
+ }
72
+
73
+ /// What fetching one item did.
74
+ #[derive(Debug, Clone, PartialEq, Eq)]
75
+ pub enum Outcome {
76
+ Fetched { bytes: u64 },
77
+ /// Already on disk at the right size.
78
+ Skipped,
79
+ /// The item has no PDF derivative on archive.org at all.
80
+ NoPdf,
81
+ Failed(String),
82
+ }
83
+
84
+ #[derive(Debug, Default, Clone)]
85
+ pub struct Summary {
86
+ pub fetched: usize,
87
+ pub bytes: u64,
88
+ pub skipped: usize,
89
+ pub no_pdf: usize,
90
+ pub failed: Vec<(String, String)>,
91
+ }
92
+
93
+ /// The PDF archive.org holds for an item: its name, size and checksum.
94
+ #[derive(Debug, Clone, PartialEq, Eq)]
95
+ pub struct PdfFile {
96
+ pub name: String,
97
+ pub size: u64,
98
+ pub md5: Option<String>,
99
+ }
100
+
101
+ /// Pick the PDF out of an item's metadata JSON.
102
+ ///
103
+ /// Pure, so the choice between several PDFs is tested without a network. Prefers the
104
+ /// derivative named after the item, which is what archive.org's own reader links to; falls
105
+ /// back to the largest, on the grounds that the biggest PDF is the full scan rather than a
106
+ /// cover or an appendix.
107
+ pub fn choose_pdf(metadata: &serde_json::Value, id: &str) -> Option<PdfFile> {
108
+ let files = metadata.get("files")?.as_array()?;
109
+
110
+ let mut candidates: Vec<PdfFile> = files
111
+ .iter()
112
+ .filter_map(|f| {
113
+ let name = f.get("name")?.as_str()?;
114
+ if !name.to_ascii_lowercase().ends_with(".pdf") {
115
+ return None;
116
+ }
117
+ Some(PdfFile {
118
+ name: name.to_string(),
119
+ // `size` is a decimal string in IA metadata, not a number.
120
+ size: f.get("size").and_then(|s| s.as_str()).and_then(|s| s.parse().ok())
121
+ .or_else(|| f.get("size").and_then(|s| s.as_u64()))
122
+ .unwrap_or(0),
123
+ md5: f.get("md5").and_then(|m| m.as_str()).map(str::to_string),
124
+ })
125
+ })
126
+ .collect();
127
+
128
+ let preferred = format!("{id}.pdf");
129
+ if let Some(exact) = candidates.iter().find(|c| c.name == preferred) {
130
+ return Some(exact.clone());
131
+ }
132
+ candidates.sort_by_key(|c| c.size);
133
+ candidates.pop()
134
+ }
135
+
136
+ /// A `Retry-After` header value as a duration.
137
+ ///
138
+ /// Only the delta-seconds form is understood. The HTTP-date form is legal and archive.org
139
+ /// does not send it; treating an unparseable value as "no advice given" falls back to the
140
+ /// geometric back-off, which is the safe direction to be wrong in.
141
+ pub fn retry_after(value: Option<&str>) -> Option<Duration> {
142
+ value?.trim().parse::<u64>().ok().map(Duration::from_secs)
143
+ }
144
+
145
+ /// Whether a status code is worth trying again.
146
+ ///
147
+ /// 429 and 503 are the server asking for patience. 5xx is the server having a bad time. A 404
148
+ /// is an answer, and repeating the question will not change it.
149
+ pub fn is_retryable(status: u16) -> bool {
150
+ status == 429 || (500..600).contains(&status)
151
+ }
152
+
153
+ #[cfg(feature = "fetch")]
154
+ mod net {
155
+ use super::*;
156
+
157
+ /// One item's metadata, from `https://archive.org/metadata/<id>`.
158
+ pub fn metadata(agent: &ureq::Agent, id: &str) -> Result<serde_json::Value> {
159
+ let url = format!("https://archive.org/metadata/{id}");
160
+ let mut response = agent
161
+ .get(&url)
162
+ .call()
163
+ .with_context(|| format!("requesting {url}"))?;
164
+ let body = response
165
+ .body_mut()
166
+ .read_to_string()
167
+ .with_context(|| format!("reading {url}"))?;
168
+ serde_json::from_str(&body).with_context(|| format!("parsing the metadata of {id}"))
169
+ }
170
+
171
+ /// Download to a temporary file, verify, then move into place.
172
+ ///
173
+ /// Written beside the destination and renamed, never written in place: a run killed
174
+ /// mid-download must not leave a half PDF that the next run's resume check mistakes for a
175
+ /// finished one.
176
+ pub fn download(agent: &ureq::Agent, url: &str, dest: &Path, want: &PdfFile) -> Result<u64> {
177
+ let tmp = dest.with_extension("pdf.part");
178
+ let mut response = agent
179
+ .get(url)
180
+ .call()
181
+ .with_context(|| format!("requesting {url}"))?;
182
+
183
+ let mut hasher = <md5::Md5 as md5::Digest>::new();
184
+ let mut file = std::fs::File::create(&tmp)
185
+ .with_context(|| format!("creating {}", tmp.display()))?;
186
+ let mut reader = response.body_mut().as_reader();
187
+ let mut buf = vec![0u8; 64 * 1024];
188
+ let mut total = 0u64;
189
+
190
+ loop {
191
+ let n = reader.read(&mut buf).with_context(|| format!("reading {url}"))?;
192
+ if n == 0 {
193
+ break;
194
+ }
195
+ md5::Digest::update(&mut hasher, &buf[..n]);
196
+ std::io::Write::write_all(&mut file, &buf[..n])
197
+ .with_context(|| format!("writing {}", tmp.display()))?;
198
+ total += n as u64;
199
+ }
200
+ drop(file);
201
+
202
+ let verify = |ok: bool, what: &str| -> Result<()> {
203
+ if ok {
204
+ return Ok(());
205
+ }
206
+ let _ = std::fs::remove_file(&tmp);
207
+ bail!("{what}")
208
+ };
209
+
210
+ verify(
211
+ want.size == 0 || total == want.size,
212
+ &format!("truncated download: got {total} bytes, archive.org says {}", want.size),
213
+ )?;
214
+
215
+ if let Some(expected) = &want.md5 {
216
+ let got = format!("{:x}", md5::Digest::finalize(hasher));
217
+ verify(
218
+ got.eq_ignore_ascii_case(expected),
219
+ &format!("checksum mismatch: got {got}, archive.org says {expected}"),
220
+ )?;
221
+ }
222
+
223
+ std::fs::rename(&tmp, dest)
224
+ .with_context(|| format!("moving {} into place", tmp.display()))?;
225
+ Ok(total)
226
+ }
227
+ }
228
+
229
+ /// Fetch the PDFs for a list of identifiers.
230
+ #[cfg(feature = "fetch")]
231
+ pub fn fetch(
232
+ root: &Path,
233
+ ids: &[String],
234
+ options: &Options,
235
+ mut progress: impl FnMut(usize, &str, &Outcome),
236
+ ) -> Summary {
237
+ let agent: ureq::Agent = ureq::Agent::config_builder()
238
+ .user_agent(USER_AGENT)
239
+ .timeout_global(Some(Duration::from_secs(600)))
240
+ .build()
241
+ .into();
242
+
243
+ let mut limiter = Limiter::new(options.interval);
244
+ let mut summary = Summary::default();
245
+
246
+ for (i, id) in ids.iter().enumerate() {
247
+ let outcome = fetch_one(&agent, &mut limiter, root, id, options);
248
+ match &outcome {
249
+ Outcome::Fetched { bytes } => {
250
+ summary.fetched += 1;
251
+ summary.bytes += bytes;
252
+ }
253
+ Outcome::Skipped => summary.skipped += 1,
254
+ Outcome::NoPdf => summary.no_pdf += 1,
255
+ Outcome::Failed(why) => summary.failed.push((id.clone(), why.clone())),
256
+ }
257
+ progress(i, id, &outcome);
258
+ }
259
+
260
+ summary
261
+ }
262
+
263
+ #[cfg(feature = "fetch")]
264
+ fn fetch_one(
265
+ agent: &ureq::Agent,
266
+ limiter: &mut Limiter,
267
+ root: &Path,
268
+ id: &str,
269
+ options: &Options,
270
+ ) -> Outcome {
271
+ let dir = root.join(item_dir(id));
272
+ let dest = dir.join(format!("{id}.pdf"));
273
+
274
+ if !options.force && dest.exists() {
275
+ return Outcome::Skipped;
276
+ }
277
+
278
+ let mut last_error = String::new();
279
+ for attempt in 1..=MAX_ATTEMPTS {
280
+ limiter.wait();
281
+
282
+ let metadata = match net::metadata(agent, id) {
283
+ Ok(m) => m,
284
+ Err(e) => {
285
+ last_error = format!("{e:#}");
286
+ limiter.failed(retry_after_of(&e));
287
+ if !retryable(&e) || attempt == MAX_ATTEMPTS {
288
+ break;
289
+ }
290
+ continue;
291
+ }
292
+ };
293
+ limiter.succeeded();
294
+
295
+ let Some(pdf) = choose_pdf(&metadata, id) else {
296
+ return Outcome::NoPdf;
297
+ };
298
+
299
+ if options.dry_run {
300
+ return Outcome::Fetched { bytes: pdf.size };
301
+ }
302
+
303
+ if let Err(e) = std::fs::create_dir_all(&dir) {
304
+ return Outcome::Failed(format!("creating {}: {e}", dir.display()));
305
+ }
306
+
307
+ limiter.wait();
308
+ let url = format!("https://archive.org/download/{id}/{}", pdf.name);
309
+ match net::download(agent, &url, &dest, &pdf) {
310
+ Ok(bytes) => {
311
+ limiter.succeeded();
312
+ return Outcome::Fetched { bytes };
313
+ }
314
+ Err(e) => {
315
+ last_error = format!("{e:#}");
316
+ limiter.failed(retry_after_of(&e));
317
+ if attempt == MAX_ATTEMPTS {
318
+ break;
319
+ }
320
+ }
321
+ }
322
+ }
323
+
324
+ Outcome::Failed(last_error)
325
+ }
326
+
327
+ /// Whether an error from `ureq` is worth another attempt.
328
+ #[cfg(feature = "fetch")]
329
+ fn retryable(e: &anyhow::Error) -> bool {
330
+ match e.downcast_ref::<ureq::Error>() {
331
+ Some(ureq::Error::StatusCode(code)) => is_retryable(*code),
332
+ // A transport failure — connection reset, timeout — is exactly the transient case.
333
+ Some(_) => true,
334
+ None => false,
335
+ }
336
+ }
337
+
338
+ /// The server's own `Retry-After`, if it sent one with the failure.
339
+ #[cfg(feature = "fetch")]
340
+ fn retry_after_of(_e: &anyhow::Error) -> Option<Duration> {
341
+ // `ureq` 3 does not surface response headers on a `StatusCode` error, so there is nothing
342
+ // to read here and the geometric back-off is what applies. Kept as a named seam so that
343
+ // honouring the header is a change in one place if a later version exposes it.
344
+ None
345
+ }
346
+
347
+ #[cfg(test)]
348
+ mod tests {
349
+ use super::*;
350
+ use serde_json::json;
351
+
352
+ fn meta(files: serde_json::Value) -> serde_json::Value {
353
+ json!({ "files": files })
354
+ }
355
+
356
+ #[test]
357
+ fn the_pdf_named_after_the_item_wins() {
358
+ let m = meta(json!([
359
+ {"name": "other.pdf", "size": "9999999", "md5": "b"},
360
+ {"name": "x.pdf", "size": "100", "md5": "a"},
361
+ {"name": "x_djvu.txt", "size": "5"},
362
+ ]));
363
+ let pdf = choose_pdf(&m, "x").unwrap();
364
+ assert_eq!(pdf.name, "x.pdf");
365
+ assert_eq!(pdf.size, 100);
366
+ assert_eq!(pdf.md5.as_deref(), Some("a"));
367
+ }
368
+
369
+ /// A handful of items name their PDF something else. The biggest one is the full scan.
370
+ #[test]
371
+ fn otherwise_the_largest_pdf_wins() {
372
+ let m = meta(json!([
373
+ {"name": "cover.pdf", "size": "100"},
374
+ {"name": "scan_full.pdf", "size": "50000"},
375
+ ]));
376
+ assert_eq!(choose_pdf(&m, "x").unwrap().name, "scan_full.pdf");
377
+ }
378
+
379
+ #[test]
380
+ fn an_item_with_no_pdf_yields_none() {
381
+ let m = meta(json!([{"name": "x_djvu.txt", "size": "5"}]));
382
+ assert_eq!(choose_pdf(&m, "x"), None);
383
+ assert_eq!(choose_pdf(&json!({}), "x"), None);
384
+ }
385
+
386
+ /// IA writes sizes as decimal strings, not numbers. Reading them as numbers silently
387
+ /// yields zero, which would disable the truncation check on every item.
388
+ #[test]
389
+ fn sizes_are_read_from_ias_string_form() {
390
+ let m = meta(json!([{"name": "x.pdf", "size": "574464"}]));
391
+ assert_eq!(choose_pdf(&m, "x").unwrap().size, 574_464);
392
+ }
393
+
394
+ #[test]
395
+ fn a_missing_size_does_not_read_as_zero_bytes_expected() {
396
+ let m = meta(json!([{"name": "x.pdf"}]));
397
+ let pdf = choose_pdf(&m, "x").unwrap();
398
+ // Zero means "unknown", and the verifier treats it as "do not check".
399
+ assert_eq!(pdf.size, 0);
400
+ assert_eq!(pdf.md5, None);
401
+ }
402
+
403
+ #[test]
404
+ fn retry_after_reads_delta_seconds_and_ignores_the_rest() {
405
+ assert_eq!(retry_after(Some("30")), Some(Duration::from_secs(30)));
406
+ assert_eq!(retry_after(Some(" 5 ")), Some(Duration::from_secs(5)));
407
+ assert_eq!(retry_after(Some("Wed, 21 Oct 2026 07:28:00 GMT")), None);
408
+ assert_eq!(retry_after(None), None);
409
+ }
410
+
411
+ /// A 404 is an answer. Asking again will not change it.
412
+ #[test]
413
+ fn only_transient_statuses_are_retried() {
414
+ assert!(is_retryable(429));
415
+ assert!(is_retryable(503));
416
+ assert!(is_retryable(500));
417
+ assert!(!is_retryable(404));
418
+ assert!(!is_retryable(403));
419
+ assert!(!is_retryable(200));
420
+ }
421
+ }
tools/src/frc/ingest.rs ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Walking a local frc-data checkout and writing the archive records and OCR sidecars.
2
+ //!
3
+ //! This half of the ingest touches no network. Everything it needs — the item list, the
4
+ //! catalogue metadata, and the word-level OCR — is in the frc-data repository, which is one
5
+ //! clone rather than 76,754 requests against archive.org for bytes that already exist in git.
6
+ //! Only the PDFs have to be fetched, and that is [`super::fetch`].
7
+ //!
8
+ //! ## Layout
9
+ //!
10
+ //! ```text
11
+ //! sources/frc/ab/abondance00unse/abondance00unse.toml the record
12
+ //! abondance00unse.ocr.toml the OCR
13
+ //! abondance00unse.pdf fetched later
14
+ //! ```
15
+ //!
16
+ //! Two-character shards taken from the identifier: about 700 directories of 55 items rather
17
+ //! than one of 38,377. Addresses do not change if the sharding is ever redone, because ids
18
+ //! are flat and directories are cosmetic.
19
+ //!
20
+ //! ## Resumability
21
+ //!
22
+ //! An item is done when its record and sidecar both exist. That is the whole resume
23
+ //! condition, checked from the filesystem, so an interrupted run costs one `stat` per item to
24
+ //! pick up and there is no ledger to fall out of step with the tree it describes.
25
+
26
+ use std::path::{Path, PathBuf};
27
+
28
+ use anyhow::{Context, Result};
29
+
30
+ use crate::ocr;
31
+
32
+ use super::{meta, record};
33
+
34
+ /// Directory under the archive root that this corpus lives in.
35
+ pub const DIR: &str = "sources/frc";
36
+
37
+ /// What one item's ingest did.
38
+ #[derive(Debug, Clone, PartialEq, Eq)]
39
+ pub enum Outcome {
40
+ /// Record and sidecar written.
41
+ Written,
42
+ /// Both already existed.
43
+ Skipped,
44
+ /// Written, but the item has no OCR in frc-data.
45
+ WrittenWithoutOcr,
46
+ /// Nothing written; the reason is worth reporting rather than aborting the run.
47
+ Failed(String),
48
+ }
49
+
50
+ /// Everything one run of [`ingest`] did.
51
+ #[derive(Debug, Default, Clone)]
52
+ pub struct Summary {
53
+ pub written: usize,
54
+ pub skipped: usize,
55
+ pub without_ocr: usize,
56
+ pub failed: Vec<(String, String)>,
57
+ /// IA field names that were present somewhere and mapped nowhere, with a count.
58
+ pub ignored_fields: std::collections::BTreeMap<String, usize>,
59
+ }
60
+
61
+ /// The shard directory an identifier lives in.
62
+ ///
63
+ /// The first two characters, lowercased, with anything that is not a letter or digit replaced
64
+ /// so the name is safe on every filesystem. IA identifiers are already `[a-z0-9]`-ish, but
65
+ /// 38,377 of them is enough that "already" is not a guarantee worth relying on.
66
+ pub fn shard(id: &str) -> String {
67
+ let mut out = String::new();
68
+ for c in id.chars().take(2) {
69
+ if c.is_ascii_alphanumeric() {
70
+ out.push(c.to_ascii_lowercase());
71
+ } else {
72
+ out.push('_');
73
+ }
74
+ }
75
+ // A one-character identifier still needs a two-character shard.
76
+ while out.len() < 2 {
77
+ out.push('_');
78
+ }
79
+ out
80
+ }
81
+
82
+ /// Where an item's files go, relative to the archive root.
83
+ pub fn item_dir(id: &str) -> PathBuf {
84
+ Path::new(DIR).join(shard(id)).join(id)
85
+ }
86
+
87
+ /// Every identifier in a frc-data checkout, sorted.
88
+ ///
89
+ /// Taken from `Metadata/`, which is the fuller list: some items have catalogue metadata and
90
+ /// no OCR, and they are still part of the collection.
91
+ pub fn identifiers(frc_data: &Path) -> Result<Vec<String>> {
92
+ let dir = frc_data.join("Metadata");
93
+ let entries = std::fs::read_dir(&dir)
94
+ .with_context(|| format!("reading {} — is this a frc-data checkout?", dir.display()))?;
95
+
96
+ let mut ids: Vec<String> = Vec::new();
97
+ for entry in entries {
98
+ let name = entry?.file_name();
99
+ let Some(name) = name.to_str() else { continue };
100
+ if let Some(id) = name.strip_suffix("_meta.xml") {
101
+ ids.push(id.to_string());
102
+ }
103
+ }
104
+ ids.sort();
105
+ Ok(ids)
106
+ }
107
+
108
+ /// Ingest one item.
109
+ pub fn ingest_one(root: &Path, frc_data: &Path, id: &str, force: bool) -> Outcome {
110
+ match try_ingest_one(root, frc_data, id, force) {
111
+ Ok(outcome) => outcome,
112
+ Err(e) => Outcome::Failed(format!("{e:#}")),
113
+ }
114
+ }
115
+
116
+ fn try_ingest_one(root: &Path, frc_data: &Path, id: &str, force: bool) -> Result<Outcome> {
117
+ let dir = root.join(item_dir(id));
118
+ let record_path = dir.join(format!("{id}.toml"));
119
+ // The OCR is now one file per page, so "already done" is asked of the first page. An
120
+ // item whose page 1 is written was written in full: the loop below writes them in order
121
+ // and a failure part-way aborts the item before its record is written.
122
+ let ocr_path = dir.join(ocr::file_name(id, 1));
123
+ let xml_path = frc_data.join("XML_for_OCR").join(format!("{id}_djvu.xml"));
124
+
125
+ let has_ocr_source = xml_path.exists();
126
+ if !force && record_path.exists() && (ocr_path.exists() || !has_ocr_source) {
127
+ return Ok(Outcome::Skipped);
128
+ }
129
+
130
+ let meta_path = frc_data.join("Metadata").join(format!("{id}_meta.xml"));
131
+ let meta_text = std::fs::read_to_string(&meta_path)
132
+ .with_context(|| format!("reading {}", meta_path.display()))?;
133
+ let parsed = meta::parse(&meta_text).with_context(|| format!("parsing {id}_meta.xml"))?;
134
+ let mapped = record::map(id, &parsed);
135
+
136
+ std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
137
+
138
+ // The OCR is written first: a record that declares `[[text]]` pointing at a file that is
139
+ // not there yet would be a broken archive for as long as the run takes.
140
+ let mut text_entries: Vec<crate::model::Text> = Vec::new();
141
+ if has_ocr_source {
142
+ let xml = std::fs::read_to_string(&xml_path)
143
+ .with_context(|| format!("reading {}", xml_path.display()))?;
144
+ let pages =
145
+ crate::djvu::parse(&xml, id).with_context(|| format!("parsing {id}_djvu.xml"))?;
146
+
147
+ let engine = parsed.get("ocr").map(str::to_string);
148
+ let schema_rel = format!("../../../../{}", ocr::SCHEMA_PATH);
149
+
150
+ for mut page in pages {
151
+ page.engine = engine.clone();
152
+ page.lang = mapped.record.language.clone();
153
+
154
+ let name = ocr::file_name(id, page.page);
155
+ std::fs::write(dir.join(&name), ocr::to_markdown(&page, &schema_rel))
156
+ .with_context(|| format!("writing {name}"))?;
157
+
158
+ text_entries.push(crate::model::Text {
159
+ file: name,
160
+ kind: Some("ocr".into()),
161
+ by: engine.clone(),
162
+ lang: page.lang.clone(),
163
+ note: None,
164
+ });
165
+ }
166
+ }
167
+
168
+ let mut source = mapped.record;
169
+ source.text = text_entries;
170
+ let rendered = render_record(&source)?;
171
+ std::fs::write(&record_path, rendered)
172
+ .with_context(|| format!("writing {}", record_path.display()))?;
173
+
174
+ Ok(if has_ocr_source {
175
+ Outcome::Written
176
+ } else {
177
+ Outcome::WrittenWithoutOcr
178
+ })
179
+ }
180
+
181
+ /// A record as TOML, with the `#:schema` directive that gets it validated in an editor.
182
+ fn render_record(source: &crate::model::Source) -> Result<String> {
183
+ let record = crate::model::Record::Source(source.clone());
184
+ let body = toml::to_string_pretty(&record).context("serialising the record")?;
185
+ Ok(format!(
186
+ "#:schema ../../../../{}\n{body}",
187
+ crate::SCHEMA_PATH
188
+ ))
189
+ }
190
+
191
+ /// Ingest a whole corpus.
192
+ ///
193
+ /// `progress` is called after each item so a caller can report without this module knowing
194
+ /// what reporting looks like.
195
+ pub fn ingest(
196
+ root: &Path,
197
+ frc_data: &Path,
198
+ ids: &[String],
199
+ force: bool,
200
+ mut progress: impl FnMut(usize, &str, &Outcome),
201
+ ) -> Summary {
202
+ let mut summary = Summary::default();
203
+
204
+ for (i, id) in ids.iter().enumerate() {
205
+ // The ignored-field census is worth having across the whole corpus, and it costs one
206
+ // extra parse of a 3 KB file only for items that are actually processed.
207
+ let outcome = ingest_one(root, frc_data, id, force);
208
+ match &outcome {
209
+ Outcome::Written => summary.written += 1,
210
+ Outcome::WrittenWithoutOcr => {
211
+ summary.written += 1;
212
+ summary.without_ocr += 1;
213
+ }
214
+ Outcome::Skipped => summary.skipped += 1,
215
+ Outcome::Failed(why) => summary.failed.push((id.clone(), why.clone())),
216
+ }
217
+ progress(i, id, &outcome);
218
+ }
219
+
220
+ summary
221
+ }
222
+
223
+ #[cfg(test)]
224
+ mod tests {
225
+ use super::*;
226
+
227
+ #[test]
228
+ fn shards_are_two_characters_of_the_identifier() {
229
+ assert_eq!(shard("abondance00unse"), "ab");
230
+ assert_eq!(shard("1789iemilseptcen00unse"), "17");
231
+ assert_eq!(shard("ABC"), "ab");
232
+ }
233
+
234
+ /// A short or odd identifier must still produce a usable directory name.
235
+ #[test]
236
+ fn odd_identifiers_still_shard() {
237
+ assert_eq!(shard("a"), "a_");
238
+ assert_eq!(shard(""), "__");
239
+ assert_eq!(shard("a.b"), "a_");
240
+ }
241
+
242
+ #[test]
243
+ fn an_item_lands_two_directories_deep() {
244
+ assert_eq!(
245
+ item_dir("abondance00unse"),
246
+ Path::new("sources/frc/ab/abondance00unse")
247
+ );
248
+ }
249
+
250
+ /// The end-to-end shape, on a frc-data checkout built for the test.
251
+ #[test]
252
+ fn ingesting_an_item_writes_a_record_and_a_sidecar_that_agree() {
253
+ let tmp = tempfile::tempdir().unwrap();
254
+ let frc = tmp.path().join("frc-data");
255
+ std::fs::create_dir_all(frc.join("Metadata")).unwrap();
256
+ std::fs::create_dir_all(frc.join("XML_for_OCR")).unwrap();
257
+ std::fs::write(
258
+ frc.join("Metadata/x00unse_meta.xml"),
259
+ r#"<metadata><title>Sur les subsistances</title><language>fre</language>
260
+ <date>1789</date><ocr>ABBYY FineReader 11.0</ocr><ppi>500</ppi></metadata>"#,
261
+ )
262
+ .unwrap();
263
+ std::fs::write(
264
+ frc.join("XML_for_OCR/x00unse_djvu.xml"),
265
+ r#"<DjVuXML><BODY><OBJECT width="100" height="200"><HIDDENTEXT>
266
+ <PAGECOLUMN><REGION backgroundColor="123"><PARAGRAPH><LINE>
267
+ <WORD coords="1,2,3,4,5">Subsistances</WORD>
268
+ </LINE></PARAGRAPH></REGION></PAGECOLUMN>
269
+ </HIDDENTEXT></OBJECT></BODY></DjVuXML>"#,
270
+ )
271
+ .unwrap();
272
+
273
+ let root = tmp.path().join("archive");
274
+ assert_eq!(
275
+ ingest_one(&root, &frc, "x00unse", false),
276
+ Outcome::Written
277
+ );
278
+
279
+ let dir = root.join("sources/frc/x0/x00unse");
280
+ let record = std::fs::read_to_string(dir.join("x00unse.toml")).unwrap();
281
+ assert!(record.contains("layer = \"source\""), "{record}");
282
+ assert!(record.contains("Sur les subsistances"), "{record}");
283
+ // The record must point at the sidecar that was actually written.
284
+ assert!(record.contains("x00unse.p1.ocr.md"), "{record}");
285
+
286
+ let sidecar = std::fs::read_to_string(dir.join("x00unse.p1.ocr.md")).unwrap();
287
+ let parsed: ocr::Ocr = ocr::from_markdown(&sidecar).unwrap();
288
+ assert_eq!(parsed.of, "x00unse");
289
+ assert_eq!(parsed.page, 1);
290
+ assert_eq!(parsed.engine.as_deref(), Some("ABBYY FineReader 11.0"));
291
+ assert_eq!(parsed.text, "Subsistances");
292
+
293
+ // Second time round it is already done.
294
+ assert_eq!(ingest_one(&root, &frc, "x00unse", false), Outcome::Skipped);
295
+ assert_eq!(ingest_one(&root, &frc, "x00unse", true), Outcome::Written);
296
+ }
297
+
298
+ /// 4,000-odd items have catalogue metadata and no OCR. They are still part of the
299
+ /// collection and must still get a record.
300
+ #[test]
301
+ fn an_item_with_no_ocr_still_gets_a_record() {
302
+ let tmp = tempfile::tempdir().unwrap();
303
+ let frc = tmp.path().join("frc-data");
304
+ std::fs::create_dir_all(frc.join("Metadata")).unwrap();
305
+ std::fs::create_dir_all(frc.join("XML_for_OCR")).unwrap();
306
+ std::fs::write(
307
+ frc.join("Metadata/y_meta.xml"),
308
+ "<metadata><title>Sans OCR</title></metadata>",
309
+ )
310
+ .unwrap();
311
+
312
+ let root = tmp.path().join("archive");
313
+ assert_eq!(
314
+ ingest_one(&root, &frc, "y", false),
315
+ Outcome::WrittenWithoutOcr
316
+ );
317
+
318
+ let record = std::fs::read_to_string(root.join("sources/frc/y_/y/y.toml")).unwrap();
319
+ assert!(!record.contains("[[text]]"), "no sidecar to point at: {record}");
320
+ // And it stays done rather than being retried forever.
321
+ assert_eq!(ingest_one(&root, &frc, "y", false), Outcome::Skipped);
322
+ }
323
+
324
+ #[test]
325
+ fn identifiers_come_from_the_metadata_directory_sorted() {
326
+ let tmp = tempfile::tempdir().unwrap();
327
+ let meta = tmp.path().join("Metadata");
328
+ std::fs::create_dir_all(&meta).unwrap();
329
+ for name in ["b_meta.xml", "a_meta.xml", "notmeta.txt"] {
330
+ std::fs::write(meta.join(name), "<metadata/>").unwrap();
331
+ }
332
+ assert_eq!(identifiers(tmp.path()).unwrap(), ["a", "b"]);
333
+ }
334
+
335
+ /// A single bad item must not take the other 38,376 down with it.
336
+ #[test]
337
+ fn a_failure_is_reported_and_the_run_continues() {
338
+ let tmp = tempfile::tempdir().unwrap();
339
+ let frc = tmp.path().join("frc-data");
340
+ std::fs::create_dir_all(frc.join("Metadata")).unwrap();
341
+ std::fs::write(frc.join("Metadata/good_meta.xml"), "<metadata><title>t</title></metadata>")
342
+ .unwrap();
343
+ // `bad` has no metadata file at all.
344
+ let root = tmp.path().join("archive");
345
+
346
+ let ids = vec!["bad".to_string(), "good".to_string()];
347
+ let summary = ingest(&root, &frc, &ids, false, |_, _, _| {});
348
+ assert_eq!(summary.written, 1);
349
+ assert_eq!(summary.failed.len(), 1);
350
+ assert_eq!(summary.failed[0].0, "bad");
351
+ }
352
+ }
tools/src/frc/limiter.rs ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Being a polite guest on someone else's server.
2
+ //!
3
+ //! archive.org serves this collection for free and has no obligation to serve it to us at
4
+ //! all. 38,377 PDFs is a lot to ask for, and the difference between asking politely over two
5
+ //! days and hammering the endpoint for an afternoon costs us nothing and costs them real
6
+ //! money. This module is the part that makes the asking polite.
7
+ //!
8
+ //! ## Why the timing logic is pure
9
+ //!
10
+ //! [`Limiter::due_at`] computes *when* the next request may go out; [`Limiter::wait`] is the
11
+ //! thin wrapper that actually sleeps. Splitting them means the interesting behaviour —
12
+ //! back-off growth, `Retry-After`, the cap — is tested by arithmetic in microseconds rather
13
+ //! than by a test suite that sleeps for real.
14
+
15
+ use std::time::{Duration, Instant};
16
+
17
+ /// Default minimum gap between requests.
18
+ ///
19
+ /// One second. Not tuned to the fastest rate archive.org will tolerate, because that is not
20
+ /// the question — the question is the slowest rate that still finishes, and at one request a
21
+ /// second the whole corpus takes about eleven hours.
22
+ pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(1);
23
+
24
+ /// Never wait longer than this between retries, however many have failed.
25
+ ///
26
+ /// Five minutes. Past this, the server is not briefly busy, it is down, and the run should be
27
+ /// making no progress loudly rather than quietly.
28
+ pub const MAX_BACKOFF: Duration = Duration::from_secs(300);
29
+
30
+ /// Paces requests and backs off when the server asks it to.
31
+ #[derive(Debug, Clone)]
32
+ pub struct Limiter {
33
+ /// Minimum gap between the start of one request and the start of the next.
34
+ interval: Duration,
35
+ /// Extra delay imposed by back-off, reset by any success.
36
+ penalty: Duration,
37
+ last: Option<Instant>,
38
+ }
39
+
40
+ impl Limiter {
41
+ pub fn new(interval: Duration) -> Self {
42
+ Limiter {
43
+ interval,
44
+ penalty: Duration::ZERO,
45
+ last: None,
46
+ }
47
+ }
48
+
49
+ /// The earliest instant the next request may be made.
50
+ ///
51
+ /// Pure, so back-off behaviour can be tested without sleeping.
52
+ pub fn due_at(&self, _now: Instant) -> Option<Instant> {
53
+ self.last.map(|last| last + self.interval + self.penalty)
54
+ }
55
+
56
+ /// How long to sleep before the next request.
57
+ pub fn due_in(&self, now: Instant) -> Duration {
58
+ match self.due_at(now) {
59
+ Some(due) if due > now => due - now,
60
+ _ => Duration::ZERO,
61
+ }
62
+ }
63
+
64
+ /// Sleep until the next request is due, then mark it as starting now.
65
+ pub fn wait(&mut self) {
66
+ let now = Instant::now();
67
+ let delay = self.due_in(now);
68
+ if !delay.is_zero() {
69
+ std::thread::sleep(delay);
70
+ }
71
+ self.last = Some(Instant::now());
72
+ }
73
+
74
+ /// The request succeeded: forget any accumulated back-off.
75
+ pub fn succeeded(&mut self) {
76
+ self.penalty = Duration::ZERO;
77
+ }
78
+
79
+ /// The request failed. Grow the back-off, or take the server's own figure if it gave one.
80
+ ///
81
+ /// A `Retry-After` is obeyed as given rather than merely used as a floor: it is the
82
+ /// server stating its terms, and the whole point of this module is to accept them.
83
+ pub fn failed(&mut self, retry_after: Option<Duration>) {
84
+ self.penalty = match retry_after {
85
+ Some(d) => d.min(MAX_BACKOFF),
86
+ // Double, starting from the base interval. Geometric rather than linear because
87
+ // the case worth handling quickly is "briefly busy", and the case worth handling
88
+ // gently is "still down after ten tries".
89
+ None => {
90
+ let doubled = if self.penalty.is_zero() {
91
+ self.interval
92
+ } else {
93
+ self.penalty * 2
94
+ };
95
+ doubled.min(MAX_BACKOFF)
96
+ }
97
+ };
98
+ }
99
+
100
+ /// The back-off currently in force. For reporting.
101
+ pub fn penalty(&self) -> Duration {
102
+ self.penalty
103
+ }
104
+ }
105
+
106
+ #[cfg(test)]
107
+ mod tests {
108
+ use super::*;
109
+
110
+ fn limiter() -> Limiter {
111
+ Limiter::new(Duration::from_secs(1))
112
+ }
113
+
114
+ #[test]
115
+ fn the_first_request_waits_for_nothing() {
116
+ let l = limiter();
117
+ assert_eq!(l.due_in(Instant::now()), Duration::ZERO);
118
+ }
119
+
120
+ #[test]
121
+ fn a_second_request_waits_the_interval() {
122
+ let mut l = limiter();
123
+ let t0 = Instant::now();
124
+ l.last = Some(t0);
125
+ assert_eq!(l.due_in(t0), Duration::from_secs(1));
126
+ // Half of it already spent.
127
+ assert_eq!(l.due_in(t0 + Duration::from_millis(500)), Duration::from_millis(500));
128
+ // All of it spent.
129
+ assert_eq!(l.due_in(t0 + Duration::from_secs(2)), Duration::ZERO);
130
+ }
131
+
132
+ #[test]
133
+ fn failures_back_off_geometrically() {
134
+ let mut l = limiter();
135
+ let t0 = Instant::now();
136
+ l.last = Some(t0);
137
+
138
+ l.failed(None);
139
+ assert_eq!(l.due_in(t0), Duration::from_secs(2)); // interval + 1s penalty
140
+ l.failed(None);
141
+ assert_eq!(l.due_in(t0), Duration::from_secs(3)); // interval + 2s
142
+ l.failed(None);
143
+ assert_eq!(l.due_in(t0), Duration::from_secs(5)); // interval + 4s
144
+ }
145
+
146
+ /// Otherwise one bad patch would slow the rest of an eleven-hour run to a crawl.
147
+ #[test]
148
+ fn a_success_clears_the_back_off() {
149
+ let mut l = limiter();
150
+ let t0 = Instant::now();
151
+ l.last = Some(t0);
152
+ l.failed(None);
153
+ l.failed(None);
154
+ assert!(l.penalty() > Duration::ZERO);
155
+
156
+ l.succeeded();
157
+ assert_eq!(l.penalty(), Duration::ZERO);
158
+ assert_eq!(l.due_in(t0), Duration::from_secs(1));
159
+ }
160
+
161
+ /// The server stating its terms. Obeyed as given.
162
+ #[test]
163
+ fn retry_after_is_taken_from_the_server() {
164
+ let mut l = limiter();
165
+ let t0 = Instant::now();
166
+ l.last = Some(t0);
167
+ l.failed(Some(Duration::from_secs(30)));
168
+ assert_eq!(l.due_in(t0), Duration::from_secs(31));
169
+ }
170
+
171
+ #[test]
172
+ fn back_off_is_capped_however_bad_it_gets() {
173
+ let mut l = limiter();
174
+ for _ in 0..40 {
175
+ l.failed(None);
176
+ }
177
+ assert_eq!(l.penalty(), MAX_BACKOFF);
178
+
179
+ // Including an absurd Retry-After, which some servers do send.
180
+ l.failed(Some(Duration::from_secs(86_400)));
181
+ assert_eq!(l.penalty(), MAX_BACKOFF);
182
+ }
183
+ }
tools/src/frc/meta.rs ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Reading Internet Archive's `_meta.xml`.
2
+ //!
3
+ //! The file is flat: a `<metadata>` element containing one level of children, any of which
4
+ //! may repeat. `<creator>` appears once per author, `<subject>` once per heading, and
5
+ //! `<description>` once per note the cataloguer wrote. So the natural shape is a multimap
6
+ //! from element name to the values in document order, which is what [`Meta`] is.
7
+ //!
8
+ //! Nothing here interprets the values; that is [`super::record`]'s job. Keeping the two apart
9
+ //! means the mapping can be tested against a hand-written [`Meta`] without a file, and the
10
+ //! parser can be tested against awkward XML without caring what the fields mean.
11
+
12
+ use std::collections::BTreeMap;
13
+
14
+ use anyhow::{Context, Result};
15
+ use quick_xml::Reader;
16
+ use quick_xml::events::Event;
17
+
18
+ /// The fields of one `_meta.xml`, in document order within each name.
19
+ #[derive(Debug, Clone, Default, PartialEq, Eq)]
20
+ pub struct Meta {
21
+ fields: BTreeMap<String, Vec<String>>,
22
+ }
23
+
24
+ impl Meta {
25
+ /// The first value of a field, trimmed, or `None` if it is absent or blank.
26
+ ///
27
+ /// Blank is treated as absent throughout: IA records contain a fair number of empty
28
+ /// elements, and an empty `title` is not a title.
29
+ pub fn get(&self, name: &str) -> Option<&str> {
30
+ self.all(name).first().copied()
31
+ }
32
+
33
+ /// The first value of whichever of `names` is present, in the order given.
34
+ ///
35
+ /// Used where IA has more than one spelling for the same fact — including outright typos
36
+ /// that are now load-bearing, such as `dfate` for `date`.
37
+ pub fn first_of(&self, names: &[&str]) -> Option<&str> {
38
+ names.iter().find_map(|n| self.get(n))
39
+ }
40
+
41
+ /// Every non-blank value of a field, trimmed, in document order.
42
+ pub fn all(&self, name: &str) -> Vec<&str> {
43
+ self.fields
44
+ .get(name)
45
+ .map(|vs| {
46
+ vs.iter()
47
+ .map(|v| v.trim())
48
+ .filter(|v| !v.is_empty())
49
+ .collect()
50
+ })
51
+ .unwrap_or_default()
52
+ }
53
+
54
+ /// Every value of a field, de-duplicated, keeping first-seen order.
55
+ ///
56
+ /// IA records routinely repeat a creator verbatim, or repeat it once with a trailing full
57
+ /// stop and once without. Exact duplicates are dropped here; near-duplicates are a
58
+ /// judgement the mapping makes.
59
+ pub fn unique(&self, name: &str) -> Vec<&str> {
60
+ let mut seen = Vec::new();
61
+ for v in self.all(name) {
62
+ if !seen.contains(&v) {
63
+ seen.push(v);
64
+ }
65
+ }
66
+ seen
67
+ }
68
+
69
+ /// Whether a field is present at all.
70
+ pub fn has(&self, name: &str) -> bool {
71
+ self.get(name).is_some()
72
+ }
73
+
74
+ /// The names of every field present, for reporting what a mapping ignored.
75
+ pub fn names(&self) -> impl Iterator<Item = &str> {
76
+ self.fields.keys().map(String::as_str)
77
+ }
78
+
79
+ /// Build one directly. For tests and for callers that already have the values.
80
+ pub fn from_pairs<I, K, V>(pairs: I) -> Self
81
+ where
82
+ I: IntoIterator<Item = (K, V)>,
83
+ K: Into<String>,
84
+ V: Into<String>,
85
+ {
86
+ let mut fields: BTreeMap<String, Vec<String>> = BTreeMap::new();
87
+ for (k, v) in pairs {
88
+ fields.entry(k.into()).or_default().push(v.into());
89
+ }
90
+ Meta { fields }
91
+ }
92
+ }
93
+
94
+ /// Parse a `_meta.xml`.
95
+ pub fn parse(xml: &str) -> Result<Meta> {
96
+ let mut reader = Reader::from_str(xml);
97
+ reader.config_mut().trim_text(false);
98
+
99
+ let mut fields: BTreeMap<String, Vec<String>> = BTreeMap::new();
100
+ // The element currently open, and the text collected inside it. Only one level below
101
+ // `<metadata>` carries text, so a single slot is enough — but the text arrives in several
102
+ // events when it contains an entity, so it must accumulate rather than assign.
103
+ let mut open: Option<(String, String)> = None;
104
+
105
+ loop {
106
+ match reader
107
+ .read_event()
108
+ .with_context(|| format!("reading _meta.xml at byte {}", reader.buffer_position()))?
109
+ {
110
+ Event::Eof => break,
111
+
112
+ Event::Start(e) => {
113
+ let name = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
114
+ if name != "metadata" {
115
+ open = Some((name, String::new()));
116
+ }
117
+ }
118
+
119
+ Event::Text(t) => {
120
+ if let Some((_, buf)) = open.as_mut() {
121
+ buf.push_str(&t.decode().context("undecodable metadata text")?);
122
+ }
123
+ }
124
+
125
+ // `&amp;` arrives as its own event, and these titles are full of ampersands —
126
+ // "munitions, grains & farines". Dropping this arm deletes them all.
127
+ Event::GeneralRef(r) => {
128
+ if let Some((_, buf)) = open.as_mut() {
129
+ let text = match r.resolve_char_ref().ok().flatten() {
130
+ Some(c) => c.to_string(),
131
+ None => match String::from_utf8_lossy(r.as_ref()).as_ref() {
132
+ "amp" => "&".into(),
133
+ "lt" => "<".into(),
134
+ "gt" => ">".into(),
135
+ "quot" => "\"".into(),
136
+ "apos" => "'".into(),
137
+ other => format!("&{other};"),
138
+ },
139
+ };
140
+ buf.push_str(&text);
141
+ }
142
+ }
143
+
144
+ Event::End(e) => {
145
+ let name = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
146
+ if let Some((open_name, text)) = open.take()
147
+ && open_name == name
148
+ {
149
+ fields.entry(open_name).or_default().push(text);
150
+ }
151
+ }
152
+
153
+ _ => {}
154
+ }
155
+ }
156
+
157
+ Ok(Meta { fields })
158
+ }
159
+
160
+ #[cfg(test)]
161
+ mod tests {
162
+ use super::*;
163
+
164
+ const SAMPLE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
165
+ <metadata>
166
+ <language>fre</language>
167
+ <title>Abondance nationale, ou, Découvertes d'artillerie, munitions, grains &amp; farines, &amp;c.</title>
168
+ <creator>Tallien, Jean-Lambert, 1767-2399</creator>
169
+ <creator>Vidaillet</creator>
170
+ <creator>Cailleau, André-Charles, 1731-1798, printer</creator>
171
+ <subject>Providence and government of God</subject>
172
+ <identifier>abondance00unse</identifier>
173
+ <imagecount>10</imagecount>
174
+ <empty></empty>
175
+ <blank> </blank>
176
+ </metadata>
177
+ "#;
178
+
179
+ #[test]
180
+ fn repeated_elements_keep_document_order() {
181
+ let m = parse(SAMPLE).unwrap();
182
+ assert_eq!(
183
+ m.all("creator"),
184
+ [
185
+ "Tallien, Jean-Lambert, 1767-2399",
186
+ "Vidaillet",
187
+ "Cailleau, André-Charles, 1731-1798, printer"
188
+ ]
189
+ );
190
+ }
191
+
192
+ /// These titles are full of ampersands, and an entity arrives as its own event.
193
+ #[test]
194
+ fn entities_survive() {
195
+ let m = parse(SAMPLE).unwrap();
196
+ assert!(
197
+ m.get("title").unwrap().contains("grains & farines, &c."),
198
+ "{:?}",
199
+ m.get("title")
200
+ );
201
+ }
202
+
203
+ /// IA records carry a good number of empty elements. An empty title is not a title.
204
+ #[test]
205
+ fn blank_values_read_as_absent() {
206
+ let m = parse(SAMPLE).unwrap();
207
+ assert_eq!(m.get("empty"), None);
208
+ assert_eq!(m.get("blank"), None);
209
+ assert!(!m.has("blank"));
210
+ assert_eq!(m.get("missing"), None);
211
+ }
212
+
213
+ #[test]
214
+ fn values_are_trimmed() {
215
+ let m = parse("<metadata><date> 1789 </date></metadata>").unwrap();
216
+ assert_eq!(m.get("date"), Some("1789"));
217
+ }
218
+
219
+ /// `dfate` is a real typo in real IA records, and it is the only date some of them have.
220
+ #[test]
221
+ fn first_of_falls_through_to_the_alternative_spelling() {
222
+ let m = Meta::from_pairs([("dfate", "1789")]);
223
+ assert_eq!(m.first_of(&["date", "dfate"]), Some("1789"));
224
+
225
+ let both = Meta::from_pairs([("date", "1790"), ("dfate", "1789")]);
226
+ assert_eq!(both.first_of(&["date", "dfate"]), Some("1790"));
227
+ }
228
+
229
+ #[test]
230
+ fn unique_drops_exact_repeats_and_keeps_order() {
231
+ let m = Meta::from_pairs([("creator", "Lambert"), ("creator", "Lambert"), ("creator", "Barère")]);
232
+ assert_eq!(m.unique("creator"), ["Lambert", "Barère"]);
233
+ }
234
+
235
+ #[test]
236
+ fn a_document_with_no_fields_is_not_an_error() {
237
+ let m = parse("<metadata></metadata>").unwrap();
238
+ assert_eq!(m.names().count(), 0);
239
+ }
240
+ }
tools/src/frc/mod.rs ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Ingesting the Newberry Library's French Revolution Collection.
2
+ //!
3
+ //! 38,377 Internet Archive items listed by [NewberryDIS/frc-data]. See
4
+ //! `docs/superpowers/specs/2026-08-07-frc-corpus-ingest-and-ocr-format-design.md`.
5
+ //!
6
+ //! [NewberryDIS/frc-data]: https://github.com/NewberryDIS/frc-data
7
+
8
+ pub mod fetch;
9
+ pub mod ingest;
10
+ pub mod limiter;
11
+ pub mod meta;
12
+ pub mod record;
tools/src/frc/record.rs ADDED
@@ -0,0 +1,649 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Turning one Internet Archive `_meta.xml` into one archive record.
2
+ //!
3
+ //! Every judgement about what an IA field *means* lives here, and nowhere else. The input is
4
+ //! a [`Meta`], so this is testable without a file, a network, or a repository.
5
+ //!
6
+ //! ## The shape of the output
7
+ //!
8
+ //! One `layer = "source"` with the copy and document layers collapsed in, which is what
9
+ //! `pellet-1873` and `turgot-1739` already do. A pamphlet is a single work, digitised once;
10
+ //! three files apiece would mean 115,000 files to describe 38,377 pamphlets and would not say
11
+ //! anything the one file does not.
12
+ //!
13
+ //! ## What this does not do
14
+ //!
15
+ //! It does not invent. Where IA's metadata is absent, ambiguous, or self-contradictory the
16
+ //! field is left off and, when the fact is worth keeping in prose, it goes into `note`. A
17
+ //! record that quietly guesses a date is worse than one that has none, because the archive's
18
+ //! whole product is citations that can be trusted.
19
+
20
+ use crate::model::{Holding, Identifier, Link, Resp, Rights, Roles, Scan, Source};
21
+
22
+ use super::meta::Meta;
23
+
24
+ /// What one item's metadata mapped to, plus anything the mapping wants to report.
25
+ #[derive(Debug, Clone, PartialEq)]
26
+ pub struct Mapped {
27
+ pub record: Source,
28
+ /// IA fields that were present and carried nowhere. Reported so that a field which starts
29
+ /// mattering is noticed rather than silently dropped for 38,377 items.
30
+ pub ignored: Vec<String>,
31
+ }
32
+
33
+ /// IA fields deliberately carried nowhere.
34
+ ///
35
+ /// Almost all of them describe archive.org's own workflow — who scanned it, which invoice it
36
+ /// was on, what state the republishing pipeline reached — rather than the pamphlet. The few
37
+ /// that describe the item are folded into other fields and named here so the ignore list does
38
+ /// not report them.
39
+ const IGNORED: &[&str] = &[
40
+ // Digitisation workflow and bookkeeping.
41
+ "addeddate", "backup_location", "bookreader-defaults", "boxid", "camera", "ccnum",
42
+ "collection", "contributor", "curation", "external-identifier", "foldoutcount",
43
+ "identifier-access", "imagecount", "invoice", "lccn", "mediatype", "operator",
44
+ "page-progression", "possible-copyright-status", "ppi", "publicdate", "repub_seconds",
45
+ "repub_state", "republisher", "republisher_date", "republisher_operator", "scandate",
46
+ "scanfee", "scanner", "scanningcenter", "shiptracking", "sponsor", "sponsordate",
47
+ "updatedate", "updater", "uploader", "worldcat_source_edition",
48
+ // Folded into other fields by the mapping below.
49
+ "call_number", "citation", "creator", "date", "description", "dfate", "identifier",
50
+ "identifier-ark", "language", "notes", "openlibrary_edition", "openlibrary_work",
51
+ "physical_description", "publisher", "subject", "title",
52
+ ];
53
+
54
+ /// Map one item.
55
+ pub fn map(id: &str, meta: &Meta) -> Mapped {
56
+ let mut notes: Vec<String> = Vec::new();
57
+
58
+ let (place, publisher) = split_publisher(meta.get("publisher"));
59
+
60
+ let record = Source {
61
+ id: Some(id.to_string()),
62
+ r#type: Some(genre(meta).to_string()),
63
+ title: meta.get("title").unwrap_or("Untitled").to_string(),
64
+ language: meta.get("language").and_then(language).map(str::to_string),
65
+ place,
66
+ country: None,
67
+ // `dfate` is a real typo in real records, and for some it is the only date present.
68
+ date: meta.first_of(&["date", "dfate"]).and_then(|d| edtf(d, &mut notes)),
69
+ subject: meta.unique("subject").into_iter().map(str::to_string).collect(),
70
+ extent: meta.get("physical_description").map(str::to_string),
71
+ url: Some(format!("https://archive.org/details/{id}")),
72
+
73
+ resp: resp(meta, publisher.as_deref()),
74
+ rights: Some(rights(meta)),
75
+ holding: Some(holding(meta)),
76
+ identifier: Some(identifier(id, meta)),
77
+ scan: Some(scan(id, meta)),
78
+ link: links(meta),
79
+
80
+ ..Source::default()
81
+ };
82
+
83
+ // Everything the cataloguer wrote in prose, in a stable order, as one note. These are
84
+ // genuinely useful — attributions, references to Martin & Walter, and the scanner's own
85
+ // account of the damage to the copy — and none of them fits a field.
86
+ notes.extend(meta.unique("description").into_iter().map(str::to_string));
87
+ if let Some(c) = meta.get("citation") {
88
+ notes.push(format!("Bibliography: {c}."));
89
+ }
90
+ if let Some(n) = meta.get("notes") {
91
+ notes.push(format!("Scanner's note: {n}"));
92
+ }
93
+
94
+ let ignored = meta
95
+ .names()
96
+ .filter(|n| !IGNORED.contains(n))
97
+ .map(str::to_string)
98
+ .collect();
99
+
100
+ let mut record = record;
101
+ record.note = join_notes(notes);
102
+ Mapped { record, ignored }
103
+ }
104
+
105
+ /// `pamphlet`, `book`, or `periodical`.
106
+ ///
107
+ /// The collection is overwhelmingly pamphlets, and the printed extent is the only honest
108
+ /// signal of which is which. Fifty pages is the conventional bibliographic line between a
109
+ /// pamphlet and a book; an item whose extent cannot be read is called a pamphlet, because
110
+ /// that is what all but a few hundred of them are.
111
+ fn genre(meta: &Meta) -> &'static str {
112
+ match printed_pages(meta.get("physical_description")) {
113
+ Some(n) if n >= 50 => "book",
114
+ _ => "pamphlet",
115
+ }
116
+ }
117
+
118
+ /// The leading page count of `"46 p. ; 22 cm."`.
119
+ fn printed_pages(extent: Option<&str>) -> Option<i64> {
120
+ let extent = extent?;
121
+ let digits: String = extent
122
+ .trim_start_matches(|c: char| !c.is_ascii_digit())
123
+ .chars()
124
+ .take_while(|c| c.is_ascii_digit())
125
+ .collect();
126
+ digits.parse().ok()
127
+ }
128
+
129
+ /// `"Paris : De l'impr. de Cailleau"` → place and publisher.
130
+ ///
131
+ /// The ` : ` is the ISBD separator between place and publisher, and IA's records follow it
132
+ /// closely enough to rely on. Square brackets mean the cataloguer supplied the place rather
133
+ /// than reading it off the title page; the fact is the same either way, so they are dropped.
134
+ fn split_publisher(publisher: Option<&str>) -> (Option<String>, Option<String>) {
135
+ let Some(raw) = publisher else {
136
+ return (None, None);
137
+ };
138
+ match raw.split_once(" : ") {
139
+ Some((place, rest)) => {
140
+ let place = place.trim().trim_matches(['[', ']']).trim();
141
+ let rest = rest.trim().trim_end_matches([',', ';']).trim();
142
+ (
143
+ (!place.is_empty()).then(|| place.to_string()),
144
+ (!rest.is_empty()).then(|| rest.to_string()),
145
+ )
146
+ }
147
+ // No separator: it is all publisher, and the place is unknown rather than guessed.
148
+ None => (None, Some(raw.trim().to_string())),
149
+ }
150
+ }
151
+
152
+ /// ISO-639-2 to the BCP-47 code the archive uses.
153
+ ///
154
+ /// A closed table rather than a general library: this collection is French with a thin margin
155
+ /// of Latin, English, German, Italian, Spanish and Dutch, and an unrecognised code should
156
+ /// leave `language` off rather than pass a three-letter code off as BCP-47.
157
+ fn language(code: &str) -> Option<&'static str> {
158
+ Some(match code.trim().to_ascii_lowercase().as_str() {
159
+ "fre" | "fra" | "fr" => "fr",
160
+ "eng" | "en" => "en",
161
+ "lat" | "la" => "la",
162
+ "ger" | "deu" | "de" => "de",
163
+ "ita" | "it" => "it",
164
+ "spa" | "es" => "es",
165
+ "dut" | "nld" | "nl" => "nl",
166
+ _ => return None,
167
+ })
168
+ }
169
+
170
+ /// An IA date as EDTF, or `None` with the raw value recorded as a note.
171
+ ///
172
+ /// IA dates in this collection are mostly a bare year, sometimes a full date, and sometimes
173
+ /// prose. Only the forms that are already valid EDTF are passed through; anything else is
174
+ /// kept verbatim in the note, where a human can see it, rather than being coerced into a
175
+ /// date the record would then assert.
176
+ fn edtf(raw: &str, notes: &mut Vec<String>) -> Option<String> {
177
+ let raw = raw.trim();
178
+ let looks_like_edtf = matches!(raw.len(), 4 | 7 | 10)
179
+ && raw
180
+ .chars()
181
+ .all(|c| c.is_ascii_digit() || c == '-' || c == 'X' || c == '?' || c == '~');
182
+
183
+ if looks_like_edtf && crate::edtf::parse(raw).is_ok() {
184
+ return Some(raw.to_string());
185
+ }
186
+
187
+ // A four-digit year inside prose — "published in 1789" — is worth recovering, but the
188
+ // prose is kept too, because it usually says something the year does not.
189
+ let year = raw
190
+ .as_bytes()
191
+ .windows(4)
192
+ .find(|w| w.iter().all(|c| c.is_ascii_digit()))
193
+ .and_then(|w| std::str::from_utf8(w).ok())
194
+ .filter(|y| ("1400".."2100").contains(y));
195
+
196
+ match year {
197
+ Some(y) => {
198
+ notes.push(format!("Date given by the catalogue as {raw:?}."));
199
+ Some(y.to_string())
200
+ }
201
+ None => {
202
+ if !raw.is_empty() {
203
+ notes.push(format!("Date given by the catalogue as {raw:?}, unreadable."));
204
+ }
205
+ None
206
+ }
207
+ }
208
+ }
209
+
210
+ /// Creators, then the publisher.
211
+ ///
212
+ /// IA encodes a role inside the name string — `"Cailleau, André-Charles, 1731-1798, printer"`
213
+ /// — for printers and engravers. That trailing role is lifted into `role`, because a name
214
+ /// with a job title glued to the end is exactly the unparseable `author` string this schema
215
+ /// exists to replace.
216
+ fn resp(meta: &Meta, publisher: Option<&str>) -> Option<Vec<Resp>> {
217
+ let mut out: Vec<Resp> = Vec::new();
218
+
219
+ for raw in meta.unique("creator") {
220
+ let (name, role) = split_role(raw);
221
+ // The same person often appears twice, once with a trailing full stop. Match on the
222
+ // name so the two do not become two people.
223
+ let key = name.trim_end_matches('.').to_string();
224
+ if out.iter().any(|r| r.name.trim_end_matches('.') == key) {
225
+ continue;
226
+ }
227
+ out.push(Resp {
228
+ name,
229
+ role: Some(Roles::One(role.to_string())),
230
+ note: None,
231
+ });
232
+ }
233
+
234
+ if let Some(p) = publisher {
235
+ out.push(Resp {
236
+ name: p.to_string(),
237
+ role: Some(Roles::One("publisher".into())),
238
+ note: None,
239
+ });
240
+ }
241
+
242
+ (!out.is_empty()).then_some(out)
243
+ }
244
+
245
+ /// Roles IA glues to the end of a name.
246
+ const TRAILING_ROLES: &[&str] = &[
247
+ "printer", "publisher", "engraver", "bookseller", "editor", "translator", "illustrator",
248
+ "author", "compiler", "lithographer", "cartographer",
249
+ ];
250
+
251
+ /// `"Cailleau, André-Charles, 1731-1798, printer"` → `("Cailleau, André-Charles, 1731-1798", "printer")`.
252
+ fn split_role(raw: &str) -> (String, &'static str) {
253
+ let trimmed = raw.trim().trim_end_matches('.');
254
+ for role in TRAILING_ROLES {
255
+ for sep in [", ", " "] {
256
+ let suffix = format!("{sep}{role}");
257
+ if let Some(name) = trimmed
258
+ .strip_suffix(&suffix)
259
+ .or_else(|| trimmed.to_ascii_lowercase().strip_suffix(&suffix).map(|_| {
260
+ &trimmed[..trimmed.len() - suffix.len()]
261
+ }))
262
+ {
263
+ return (name.trim().trim_end_matches(',').to_string(), role);
264
+ }
265
+ }
266
+ }
267
+ (trimmed.to_string(), "author")
268
+ }
269
+
270
+ /// Rights, which are the same across the whole collection.
271
+ fn rights(meta: &Meta) -> Rights {
272
+ Rights {
273
+ // Every item is a French imprint of the 1780s and 1790s. Nothing here is in copyright
274
+ // anywhere, and the collection's own IA records say so.
275
+ work: Some("PD-old-100-expired".into()),
276
+ scan: Some("PD".into()),
277
+ attribution: Some(match meta.get("sponsor") {
278
+ Some(s) => format!("Digitised by the Internet Archive, sponsored by {s}."),
279
+ None => "Digitised by the Internet Archive.".into(),
280
+ }),
281
+ note: None,
282
+ }
283
+ }
284
+
285
+ fn holding(meta: &Meta) -> Holding {
286
+ Holding {
287
+ repository: meta.get("contributor").map(str::to_string),
288
+ shelfmark: meta.get("call_number").map(str::to_string),
289
+ // `newberryfrenchpamphlets` is an archive.org bucket name, not a collection as a
290
+ // reader would cite it. The other buckets an item sits in — `americana`, `newberry` —
291
+ // say nothing about the item at all.
292
+ collection: meta
293
+ .all("collection")
294
+ .contains(&"newberryfrenchpamphlets")
295
+ .then(|| "French Revolution Collection".to_string()),
296
+ note: None,
297
+ }
298
+ }
299
+
300
+ fn identifier(id: &str, meta: &Meta) -> Identifier {
301
+ let mut out = Identifier::new();
302
+ out.insert("internet_archive".into(), id.to_string());
303
+ for (key, field) in [
304
+ ("ark", "identifier-ark"),
305
+ ("openlibrary_edition", "openlibrary_edition"),
306
+ ("openlibrary_work", "openlibrary_work"),
307
+ ("lccn", "lccn"),
308
+ ] {
309
+ if let Some(v) = meta.get(field) {
310
+ out.insert(key.into(), v.to_string());
311
+ }
312
+ }
313
+ out
314
+ }
315
+
316
+ fn scan(id: &str, meta: &Meta) -> Scan {
317
+ // Assembled rather than templated, so an item missing half of these does not end up with
318
+ // a note full of holes.
319
+ let mut parts: Vec<String> = Vec::new();
320
+ if let Some(v) = meta.get("scanner") {
321
+ parts.push(format!("Scanned on {v}"));
322
+ }
323
+ if let Some(v) = meta.get("camera") {
324
+ parts.push(format!("with a {v}"));
325
+ }
326
+ if let Some(v) = meta.get("scanningcenter") {
327
+ parts.push(format!("at the {v} centre"));
328
+ }
329
+
330
+ Scan {
331
+ file: Some(format!("{id}.pdf")),
332
+ // `imagecount` counts scanned images, covers and endpapers included, which is exactly
333
+ // what `count` means: pages in the container, not printed pages.
334
+ count: meta.get("imagecount").and_then(|v| v.parse().ok()),
335
+ by: Some("Internet Archive".into()),
336
+ url: Some(format!("https://archive.org/details/{id}")),
337
+ ppi: meta.get("ppi").and_then(|v| v.parse().ok()),
338
+ note: (!parts.is_empty()).then(|| format!("{}.", parts.join(" "))),
339
+ }
340
+ }
341
+
342
+ fn links(meta: &Meta) -> Vec<Link> {
343
+ let mut out = Vec::new();
344
+ if let Some(url) = meta.get("link_to_catalog") {
345
+ out.push(Link {
346
+ rel: "catalogue".into(),
347
+ url: url.to_string(),
348
+ title: None,
349
+ note: None,
350
+ });
351
+ }
352
+ out
353
+ }
354
+
355
+ /// One note out of several sentences, or none.
356
+ fn join_notes(notes: Vec<String>) -> Option<String> {
357
+ let mut seen: Vec<String> = Vec::new();
358
+ for n in notes {
359
+ let n = n.trim().to_string();
360
+ if !n.is_empty() && !seen.contains(&n) {
361
+ seen.push(n);
362
+ }
363
+ }
364
+ if seen.is_empty() {
365
+ return None;
366
+ }
367
+ // The cataloguer's own notes rarely end in a full stop; the sentences read as a paragraph
368
+ // once they do.
369
+ let joined = seen
370
+ .iter()
371
+ .map(|n| {
372
+ if n.ends_with(['.', '!', '?']) {
373
+ n.clone()
374
+ } else {
375
+ format!("{n}.")
376
+ }
377
+ })
378
+ .collect::<Vec<_>>()
379
+ .join(" ");
380
+ Some(joined)
381
+ }
382
+
383
+ #[cfg(test)]
384
+ mod tests {
385
+ use super::*;
386
+
387
+ fn meta(pairs: &[(&str, &str)]) -> Meta {
388
+ Meta::from_pairs(pairs.iter().copied())
389
+ }
390
+
391
+ #[test]
392
+ fn a_minimal_record_still_has_an_id_a_title_and_a_scan() {
393
+ let m = map("x00unse", &meta(&[("title", "Sur les subsistances")]));
394
+ assert_eq!(m.record.id.as_deref(), Some("x00unse"));
395
+ assert_eq!(m.record.title, "Sur les subsistances");
396
+ assert_eq!(
397
+ m.record.scan.as_ref().unwrap().file.as_deref(),
398
+ Some("x00unse.pdf")
399
+ );
400
+ assert_eq!(
401
+ m.record.identifier.as_ref().unwrap()["internet_archive"],
402
+ "x00unse"
403
+ );
404
+ }
405
+
406
+ /// An item with no title at all must still produce a valid record, because `title` is
407
+ /// required on a source and 38,377 items will contain a few.
408
+ #[test]
409
+ fn a_missing_title_does_not_produce_an_empty_one() {
410
+ let m = map("x", &meta(&[]));
411
+ assert_eq!(m.record.title, "Untitled");
412
+ }
413
+
414
+ // -- dates ---------------------------------------------------------------------------
415
+
416
+ #[test]
417
+ fn a_bare_year_passes_through() {
418
+ let m = map("x", &meta(&[("date", "1789")]));
419
+ assert_eq!(m.record.date.as_deref(), Some("1789"));
420
+ assert_eq!(m.record.note, None);
421
+ }
422
+
423
+ #[test]
424
+ fn a_full_date_passes_through() {
425
+ let m = map("x", &meta(&[("date", "1789-05-04")]));
426
+ assert_eq!(m.record.date.as_deref(), Some("1789-05-04"));
427
+ }
428
+
429
+ /// The typo is load-bearing: for some records it is the only date present.
430
+ #[test]
431
+ fn the_dfate_typo_is_read_as_a_date() {
432
+ let m = map("x", &meta(&[("dfate", "1789")]));
433
+ assert_eq!(m.record.date.as_deref(), Some("1789"));
434
+ }
435
+
436
+ #[test]
437
+ fn a_real_date_wins_over_the_typo() {
438
+ let m = map("x", &meta(&[("date", "1790"), ("dfate", "1789")]));
439
+ assert_eq!(m.record.date.as_deref(), Some("1790"));
440
+ }
441
+
442
+ /// A year recovered from prose is kept, and so is the prose — it usually says something
443
+ /// the year does not.
444
+ #[test]
445
+ fn a_year_inside_prose_is_recovered_and_the_prose_is_kept() {
446
+ let m = map("x", &meta(&[("date", "l'an II de la liberté, 1790")]));
447
+ assert_eq!(m.record.date.as_deref(), Some("1790"));
448
+ assert!(
449
+ m.record.note.as_deref().unwrap().contains("l'an II"),
450
+ "{:?}",
451
+ m.record.note
452
+ );
453
+ }
454
+
455
+ /// Guessing here would put a false date on a citation, which is the one thing this
456
+ /// archive must not do.
457
+ #[test]
458
+ fn an_unreadable_date_is_left_off_rather_than_guessed() {
459
+ let m = map("x", &meta(&[("date", "n.d.")]));
460
+ assert_eq!(m.record.date, None);
461
+ assert!(m.record.note.as_deref().unwrap().contains("n.d."));
462
+ }
463
+
464
+ // -- publisher and place -------------------------------------------------------------
465
+
466
+ #[test]
467
+ fn the_isbd_separator_splits_place_from_publisher() {
468
+ let m = map(
469
+ "x",
470
+ &meta(&[("publisher", "Paris : De l'impr. de Cailleau, rue Galande, no. 64")]),
471
+ );
472
+ assert_eq!(m.record.place.as_deref(), Some("Paris"));
473
+ let resp = m.record.resp.as_ref().unwrap();
474
+ assert!(
475
+ resp.iter()
476
+ .any(|r| r.roles() == ["publisher"] && r.name.starts_with("De l'impr.")),
477
+ "{resp:?}"
478
+ );
479
+ }
480
+
481
+ /// Brackets mean the cataloguer supplied the place. The place is the same fact either way.
482
+ #[test]
483
+ fn a_supplied_place_loses_its_brackets() {
484
+ let m = map("x", &meta(&[("publisher", "[Paris] : Se vend chez les libraires")]));
485
+ assert_eq!(m.record.place.as_deref(), Some("Paris"));
486
+ }
487
+
488
+ #[test]
489
+ fn a_publisher_with_no_separator_yields_no_place() {
490
+ let m = map("x", &meta(&[("publisher", "Chez Baudouin")]));
491
+ assert_eq!(m.record.place, None);
492
+ assert!(
493
+ m.record
494
+ .resp
495
+ .as_ref()
496
+ .unwrap()
497
+ .iter()
498
+ .any(|r| r.name == "Chez Baudouin")
499
+ );
500
+ }
501
+
502
+ // -- responsibility ------------------------------------------------------------------
503
+
504
+ /// The role glued to the end of a name is exactly the unparseable string this schema
505
+ /// exists to replace.
506
+ #[test]
507
+ fn a_trailing_role_is_lifted_out_of_the_name() {
508
+ let m = map(
509
+ "x",
510
+ &meta(&[("creator", "Cailleau, André-Charles, 1731-1798, printer")]),
511
+ );
512
+ let r = &m.record.resp.as_ref().unwrap()[0];
513
+ assert_eq!(r.name, "Cailleau, André-Charles, 1731-1798");
514
+ assert_eq!(r.roles(), ["printer"]);
515
+ }
516
+
517
+ #[test]
518
+ fn a_creator_with_no_role_is_an_author() {
519
+ let m = map("x", &meta(&[("creator", "Vidaillet")]));
520
+ assert_eq!(m.record.resp.as_ref().unwrap()[0].roles(), ["author"]);
521
+ }
522
+
523
+ /// IA repeats a creator verbatim, and repeats it with a trailing full stop. Neither is a
524
+ /// second person.
525
+ #[test]
526
+ fn a_creator_repeated_with_a_full_stop_is_one_person() {
527
+ let m = map(
528
+ "x",
529
+ &meta(&[
530
+ ("creator", "Lambert, Charles, 1734-1816."),
531
+ ("creator", "Lambert, Charles, 1734-1816"),
532
+ ]),
533
+ );
534
+ assert_eq!(m.record.resp.as_ref().unwrap().len(), 1);
535
+ }
536
+
537
+ #[test]
538
+ fn a_corporate_creator_survives_intact() {
539
+ let m = map(
540
+ "x",
541
+ &meta(&[("creator", "France. Assemblée nationale constituante (1789-1791)")]),
542
+ );
543
+ let r = &m.record.resp.as_ref().unwrap()[0];
544
+ assert_eq!(r.name, "France. Assemblée nationale constituante (1789-1791)");
545
+ assert_eq!(r.roles(), ["author"]);
546
+ }
547
+
548
+ // -- the rest ------------------------------------------------------------------------
549
+
550
+ #[test]
551
+ fn the_printed_extent_decides_pamphlet_from_book() {
552
+ assert_eq!(
553
+ map("x", &meta(&[("physical_description", "7 p. ; 18 cm.")]))
554
+ .record
555
+ .r#type
556
+ .as_deref(),
557
+ Some("pamphlet")
558
+ );
559
+ assert_eq!(
560
+ map("x", &meta(&[("physical_description", "312 p. ; 22 cm.")]))
561
+ .record
562
+ .r#type
563
+ .as_deref(),
564
+ Some("book")
565
+ );
566
+ // Unreadable extent: call it what all but a few hundred of them are.
567
+ assert_eq!(
568
+ map("x", &meta(&[("physical_description", "1 sheet")]))
569
+ .record
570
+ .r#type
571
+ .as_deref(),
572
+ Some("pamphlet")
573
+ );
574
+ }
575
+
576
+ #[test]
577
+ fn language_codes_become_bcp47_and_unknown_ones_are_left_off() {
578
+ assert_eq!(
579
+ map("x", &meta(&[("language", "fre")])).record.language.as_deref(),
580
+ Some("fr")
581
+ );
582
+ assert_eq!(map("x", &meta(&[("language", "zzz")])).record.language, None);
583
+ }
584
+
585
+ #[test]
586
+ fn subjects_and_extent_are_carried() {
587
+ let m = map(
588
+ "x",
589
+ &meta(&[
590
+ ("subject", "Nobility"),
591
+ ("subject", "Titles of honor and nobility"),
592
+ ("subject", "Nobility"),
593
+ ("physical_description", "46 p. ; 22 cm."),
594
+ ]),
595
+ );
596
+ assert_eq!(m.record.subject, ["Nobility", "Titles of honor and nobility"]);
597
+ assert_eq!(m.record.extent.as_deref(), Some("46 p. ; 22 cm."));
598
+ }
599
+
600
+ #[test]
601
+ fn the_scan_carries_its_resolution_and_image_count() {
602
+ let m = map("x", &meta(&[("imagecount", "50"), ("ppi", "500")]));
603
+ let s = m.record.scan.as_ref().unwrap();
604
+ assert_eq!(s.count, Some(50));
605
+ assert_eq!(s.ppi, Some(500));
606
+ }
607
+
608
+ #[test]
609
+ fn the_newberry_bucket_becomes_a_collection_a_reader_would_cite() {
610
+ let m = map(
611
+ "x",
612
+ &meta(&[
613
+ ("collection", "newberryfrenchpamphlets"),
614
+ ("collection", "americana"),
615
+ ("contributor", "The Newberry Library"),
616
+ ("call_number", "Case FRC 26109"),
617
+ ]),
618
+ );
619
+ let h = m.record.holding.as_ref().unwrap();
620
+ assert_eq!(h.collection.as_deref(), Some("French Revolution Collection"));
621
+ assert_eq!(h.repository.as_deref(), Some("The Newberry Library"));
622
+ assert_eq!(h.shelfmark.as_deref(), Some("Case FRC 26109"));
623
+ }
624
+
625
+ #[test]
626
+ fn prose_fields_are_gathered_into_one_note() {
627
+ let m = map(
628
+ "x",
629
+ &meta(&[
630
+ ("description", "Signed: Vidaillet"),
631
+ ("description", "Publisher statement from colophon"),
632
+ ("citation", "Martin & Walter. Révolution française, IV:1, 33504"),
633
+ ("notes", "No copyright page found"),
634
+ ]),
635
+ );
636
+ let note = m.record.note.as_deref().unwrap();
637
+ assert!(note.contains("Signed: Vidaillet."), "{note}");
638
+ assert!(note.contains("Martin & Walter"), "{note}");
639
+ assert!(note.contains("Scanner's note:"), "{note}");
640
+ }
641
+
642
+ /// A field that starts mattering must be noticed rather than silently dropped 38,377
643
+ /// times.
644
+ #[test]
645
+ fn unmapped_fields_are_reported() {
646
+ let m = map("x", &meta(&[("title", "t"), ("something_new", "v"), ("ppi", "500")]));
647
+ assert_eq!(m.ignored, ["something_new"]);
648
+ }
649
+ }
tools/src/lib.rs CHANGED
@@ -22,11 +22,17 @@
22
  //! holds several gigabytes of `.jp2` in Git LFS and the default `validate` path must never
23
  //! touch them.
24
 
 
 
 
 
25
  pub mod edtf;
 
26
  pub mod ingest;
27
  pub mod load;
28
  pub mod migrate;
29
  pub mod model;
 
30
  pub mod render;
31
  pub mod validate;
32
 
 
22
  //! holds several gigabytes of `.jp2` in Git LFS and the default `validate` path must never
23
  //! touch them.
24
 
25
+ /// Path of the generated record schema, relative to the repository root.
26
+ pub const SCHEMA_PATH: &str = "schemas/source.json";
27
+
28
+ pub mod djvu;
29
  pub mod edtf;
30
+ pub mod frc;
31
  pub mod ingest;
32
  pub mod load;
33
  pub mod migrate;
34
  pub mod model;
35
+ pub mod ocr;
36
  pub mod render;
37
  pub mod validate;
38
 
tools/src/load.rs CHANGED
@@ -241,6 +241,7 @@ pub struct Resolved {
241
  pub scan_file: Option<Prov<String>>,
242
  pub scan_by: Option<Prov<String>>,
243
  pub scan_url: Option<Prov<String>>,
 
244
  /// Self only. Never inherited.
245
  pub scan_count: Option<i64>,
246
  /// Self only. Never inherited.
@@ -477,8 +478,13 @@ pub fn id_is_valid(id: &str) -> bool {
477
  /// satisfying [`id_is_valid`] is `W105`, a warning — underscores survive on `.jp2` filenames
478
  /// and someone will eventually paste one in.
479
  pub fn id_is_preferred(id: &str) -> bool {
 
 
 
 
 
480
  !id.is_empty()
481
- && id.split('-').all(|part| {
482
  !part.is_empty()
483
  && part
484
  .chars()
@@ -815,6 +821,9 @@ fn discover(root: &Path) -> anyhow::Result<Vec<PathBuf>> {
815
  if name.starts_with('.') || CONFIG_FILES.contains(&name.as_ref()) {
816
  continue;
817
  }
 
 
 
818
  out.push(entry.into_path());
819
  }
820
  out.sort();
@@ -1015,6 +1024,11 @@ fn resolve_inheritance(nodes: &[Node], id: NodeId) -> Resolved {
1015
  take(&mut out.scan_file, node, scan.file.as_deref());
1016
  take(&mut out.scan_by, node, scan.by.as_deref());
1017
  take(&mut out.scan_url, node, scan.url.as_deref());
 
 
 
 
 
1018
  }
1019
  }
1020
 
 
241
  pub scan_file: Option<Prov<String>>,
242
  pub scan_by: Option<Prov<String>>,
243
  pub scan_url: Option<Prov<String>>,
244
+ pub scan_ppi: Option<Prov<i64>>,
245
  /// Self only. Never inherited.
246
  pub scan_count: Option<i64>,
247
  /// Self only. Never inherited.
 
478
  /// satisfying [`id_is_valid`] is `W105`, a warning — underscores survive on `.jp2` filenames
479
  /// and someone will eventually paste one in.
480
  pub fn id_is_preferred(id: &str) -> bool {
481
+ // Underscore is a group separator as well as hyphen, because an Internet Archive
482
+ // identifier uses it: `procesverbal00_1_0` and `case_oversize_frc_27598` are the handles
483
+ // archive.org publishes and everyone else cites. Ruling them out of house style would
484
+ // mean 1,263 warnings that say nothing a reader can act on, which is how a warning
485
+ // channel stops being read.
486
  !id.is_empty()
487
+ && id.split(['-', '_']).all(|part| {
488
  !part.is_empty()
489
  && part
490
  .chars()
 
821
  if name.starts_with('.') || CONFIG_FILES.contains(&name.as_ref()) {
822
  continue;
823
  }
824
+ // Note there is no guard here against the OCR sidecars: they are `.ocr.md`, and this
825
+ // walk only considers `.toml`, so they are never candidates for being read as
826
+ // records. They are reached through the `[[text]]` that points at them.
827
  out.push(entry.into_path());
828
  }
829
  out.sort();
 
1024
  take(&mut out.scan_file, node, scan.file.as_deref());
1025
  take(&mut out.scan_by, node, scan.by.as_deref());
1026
  take(&mut out.scan_url, node, scan.url.as_deref());
1027
+ if out.scan_ppi.is_none()
1028
+ && let Some(ppi) = scan.ppi
1029
+ {
1030
+ out.scan_ppi = Some(prov(node, ppi));
1031
+ }
1032
  }
1033
  }
1034
 
tools/src/main.rs CHANGED
@@ -11,8 +11,7 @@ use scans::model;
11
  use scans::render::Grid;
12
  use scans::{ingest, migrate, render, validate};
13
 
14
- /// Path of the generated schema, relative to the repository root.
15
- const SCHEMA_PATH: &str = "schemas/source.json";
16
 
17
  #[derive(Debug, Parser)]
18
  #[command(
@@ -41,6 +40,98 @@ enum Command {
41
  Render(RenderArgs),
42
  /// Write out the images stored on cited pages, without rasterising the page.
43
  Extract(ExtractArgs),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  }
45
 
46
  #[derive(Debug, Args)]
@@ -191,6 +282,8 @@ fn run() -> Result<ExitCode> {
191
  Command::Ingest(args) => cmd_ingest(args),
192
  Command::Render(args) => cmd_render(args),
193
  Command::Extract(args) => cmd_extract(args),
 
 
194
  }
195
  }
196
 
@@ -383,6 +476,32 @@ fn cmd_resolve(args: ResolveArgs) -> Result<ExitCode> {
383
  // ---------------------------------------------------------------------------------------
384
 
385
  fn cmd_schema(args: SchemaArgs) -> Result<ExitCode> {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
  let generated = model::json_schema_text();
387
 
388
  let out = match args.out {
@@ -625,3 +744,318 @@ fn report_pixels(root: &Path, report: &render::Report) {
625
  );
626
  }
627
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  use scans::render::Grid;
12
  use scans::{ingest, migrate, render, validate};
13
 
14
+ use scans::SCHEMA_PATH;
 
15
 
16
  #[derive(Debug, Parser)]
17
  #[command(
 
40
  Render(RenderArgs),
41
  /// Write out the images stored on cited pages, without rasterising the page.
42
  Extract(ExtractArgs),
43
+ /// Convert, check and export the word-level OCR sidecars.
44
+ Ocr(OcrArgs),
45
+ /// Ingest the Newberry French Revolution Collection.
46
+ Frc(FrcArgs),
47
+ }
48
+
49
+ #[derive(Debug, Args)]
50
+ struct FrcArgs {
51
+ #[command(subcommand)]
52
+ command: FrcCommand,
53
+ }
54
+
55
+ #[derive(Debug, Subcommand)]
56
+ enum FrcCommand {
57
+ /// Write records and OCR sidecars from a local frc-data checkout.
58
+ ///
59
+ /// Touches no network: the item list, the catalogue metadata and the word-level OCR are
60
+ /// all in frc-data. Only the PDFs have to be fetched, which is a separate step.
61
+ Ingest {
62
+ /// Path to a frc-data checkout — the directory holding `Metadata/` and `XML_for_OCR/`.
63
+ #[arg(long)]
64
+ frc_data: PathBuf,
65
+ /// Repository root. Defaults to the nearest ancestor containing .git.
66
+ #[arg(long)]
67
+ root: Option<PathBuf>,
68
+ /// Stop after this many items. For trying the run out before committing to 38,377.
69
+ #[arg(long)]
70
+ limit: Option<usize>,
71
+ /// Only these identifiers.
72
+ #[arg(long = "id")]
73
+ ids: Vec<String>,
74
+ /// Rewrite items that are already done.
75
+ #[arg(long)]
76
+ force: bool,
77
+ /// Report what would be written without writing it.
78
+ #[arg(long)]
79
+ dry_run: bool,
80
+ },
81
+ /// Download the corpus PDFs from archive.org.
82
+ ///
83
+ /// One request at a time, paced, with an honest User-Agent. Every download is verified
84
+ /// against the size and MD5 archive.org publishes for it. Resumable: an item with its PDF
85
+ /// already on disk is skipped, so an interrupted run costs nothing to restart.
86
+ Fetch {
87
+ /// Repository root. Defaults to the nearest ancestor containing .git.
88
+ #[arg(long)]
89
+ root: Option<PathBuf>,
90
+ /// Minimum seconds between requests. Lower this only if you have reason to think
91
+ /// archive.org wants you to.
92
+ #[arg(long, default_value_t = 1.0)]
93
+ interval: f64,
94
+ /// Stop after this many items.
95
+ #[arg(long)]
96
+ limit: Option<usize>,
97
+ /// Only these identifiers.
98
+ #[arg(long = "id")]
99
+ ids: Vec<String>,
100
+ /// Re-fetch items that already have a PDF.
101
+ #[arg(long)]
102
+ force: bool,
103
+ /// Ask archive.org what it would send, without downloading it.
104
+ #[arg(long)]
105
+ dry_run: bool,
106
+ },
107
+ }
108
+
109
+ #[derive(Debug, Args)]
110
+ struct OcrArgs {
111
+ #[command(subcommand)]
112
+ command: OcrCommand,
113
+ }
114
+
115
+ #[derive(Debug, Subcommand)]
116
+ enum OcrCommand {
117
+ /// Convert a DjVu XML file into an `.ocr.md`.
118
+ Import {
119
+ /// The `_djvu.xml` to read.
120
+ xml: PathBuf,
121
+ /// Id of the record this is the OCR of. Defaults to the filename with `_djvu.xml`
122
+ /// trimmed off, which is how both derivations name their files.
123
+ #[arg(long)]
124
+ of: Option<String>,
125
+ /// Directory to write the per-page files into. Defaults to the current directory.
126
+ #[arg(long)]
127
+ out: Option<PathBuf>,
128
+ },
129
+ /// Report the internal inconsistencies of one or more `.ocr.md` files.
130
+ Check {
131
+ /// Files to check, or directories of them.
132
+ #[arg(required = true)]
133
+ files: Vec<PathBuf>,
134
+ },
135
  }
136
 
137
  #[derive(Debug, Args)]
 
282
  Command::Ingest(args) => cmd_ingest(args),
283
  Command::Render(args) => cmd_render(args),
284
  Command::Extract(args) => cmd_extract(args),
285
+ Command::Ocr(args) => cmd_ocr(args),
286
+ Command::Frc(args) => cmd_frc(args),
287
  }
288
  }
289
 
 
476
  // ---------------------------------------------------------------------------------------
477
 
478
  fn cmd_schema(args: SchemaArgs) -> Result<ExitCode> {
479
+ // Both schemas are generated from the same Rust types by the same code path, so neither
480
+ // can drift into being hand-maintained. `--out` writes only the record schema, because it
481
+ // names a single file.
482
+ if args.out.is_none() {
483
+ let root = resolve_root(args.root.as_deref())?;
484
+ let ocr_out = root.join(scans::ocr::SCHEMA_PATH);
485
+ let ocr_generated = model::ocr_json_schema_text();
486
+ if args.check {
487
+ let on_disk = std::fs::read_to_string(&ocr_out).unwrap_or_default();
488
+ if on_disk.replace("\r\n", "\n") != ocr_generated.replace("\r\n", "\n") {
489
+ eprintln!(
490
+ "scans: {} is out of date with the Rust types in tools/src/ocr.rs.",
491
+ show_cwd(&ocr_out)
492
+ );
493
+ return Ok(ExitCode::FAILURE);
494
+ }
495
+ } else {
496
+ if let Some(parent) = ocr_out.parent() {
497
+ std::fs::create_dir_all(parent)?;
498
+ }
499
+ std::fs::write(&ocr_out, &ocr_generated)
500
+ .with_context(|| format!("writing {}", ocr_out.display()))?;
501
+ eprintln!("wrote {}", show_cwd(&ocr_out));
502
+ }
503
+ }
504
+
505
  let generated = model::json_schema_text();
506
 
507
  let out = match args.out {
 
744
  );
745
  }
746
  }
747
+
748
+ // ---------------------------------------------------------------------------------------
749
+ // ocr
750
+ // ---------------------------------------------------------------------------------------
751
+
752
+ fn cmd_ocr(args: OcrArgs) -> Result<ExitCode> {
753
+ match args.command {
754
+ OcrCommand::Import { xml, of, out } => {
755
+ let of = match of {
756
+ Some(of) => of,
757
+ None => default_id_for(&xml)?,
758
+ };
759
+ let text = std::fs::read_to_string(&xml)
760
+ .with_context(|| format!("reading {}", xml.display()))?;
761
+ let pages = scans::djvu::parse(&text, &of)?;
762
+
763
+ // One file per page, so `--out` names a directory rather than a file.
764
+ let dir = out.unwrap_or_else(|| PathBuf::from("."));
765
+ std::fs::create_dir_all(&dir)
766
+ .with_context(|| format!("creating {}", dir.display()))?;
767
+ let schema_rel = schema_rel_for(&dir.join("x"));
768
+
769
+ for page in &pages {
770
+ let name = scans::ocr::file_name(&of, page.page);
771
+ std::fs::write(dir.join(&name), scans::ocr::to_markdown(page, &schema_rel))
772
+ .with_context(|| format!("writing {name}"))?;
773
+ }
774
+ eprintln!("wrote {} page(s) into {}", pages.len(), show_cwd(&dir));
775
+ Ok(ExitCode::SUCCESS)
776
+ }
777
+
778
+ OcrCommand::Check { files } => {
779
+ let mut bad = 0usize;
780
+ let mut checked = 0usize;
781
+ for arg in &files {
782
+ for path in expand_ocr_paths(arg)? {
783
+ checked += 1;
784
+ let ocr = match read_ocr(&path) {
785
+ Ok(ocr) => ocr,
786
+ Err(e) => {
787
+ println!("{}: {e:#}", path.display());
788
+ bad += 1;
789
+ continue;
790
+ }
791
+ };
792
+ // The page number is stated twice — in the filename and in the
793
+ // frontmatter — and a mismatch means one of them is lying about which
794
+ // page this is.
795
+ let expected = scans::ocr::file_name(&ocr.of, ocr.page);
796
+ if !path.to_string_lossy().ends_with(&expected) {
797
+ println!(
798
+ "{}: of/page say this should be named {expected}",
799
+ path.display()
800
+ );
801
+ bad += 1;
802
+ }
803
+ }
804
+ }
805
+ eprintln!("{checked} file(s) checked, {bad} problem(s)");
806
+ Ok(if bad == 0 {
807
+ ExitCode::SUCCESS
808
+ } else {
809
+ ExitCode::FAILURE
810
+ })
811
+ }
812
+ }
813
+ }
814
+
815
+ /// One `.ocr.md`, or every one in a directory.
816
+ ///
817
+ /// Accepting a directory is what makes this usable: an item's OCR is one file per page, and
818
+ /// naming 3,378 of them on a command line is not a thing anyone should have to do.
819
+ fn expand_ocr_paths(path: &Path) -> Result<Vec<PathBuf>> {
820
+ if !path.is_dir() {
821
+ return Ok(vec![path.to_path_buf()]);
822
+ }
823
+ let mut out = Vec::new();
824
+ for entry in
825
+ std::fs::read_dir(path).with_context(|| format!("reading {}", path.display()))?
826
+ {
827
+ let entry = entry?;
828
+ if entry
829
+ .file_name()
830
+ .to_str()
831
+ .is_some_and(|n| n.ends_with(scans::ocr::SUFFIX))
832
+ {
833
+ out.push(entry.path());
834
+ }
835
+ }
836
+ out.sort();
837
+ Ok(out)
838
+ }
839
+
840
+ fn read_ocr(path: &Path) -> Result<scans::ocr::Ocr> {
841
+ let text =
842
+ std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
843
+ scans::ocr::from_markdown(&text).with_context(|| format!("parsing {}", path.display()))
844
+ }
845
+
846
+ /// The id implied by a DjVu XML filename: both derivations name theirs `<id>_djvu.xml`.
847
+ fn default_id_for(xml: &Path) -> Result<String> {
848
+ let name = xml
849
+ .file_name()
850
+ .and_then(|n| n.to_str())
851
+ .context("the XML path has no filename")?;
852
+ Ok(name
853
+ .strip_suffix("_djvu.xml")
854
+ .unwrap_or_else(|| name.trim_end_matches(".xml"))
855
+ .to_string())
856
+ }
857
+
858
+ /// A `#:schema` path from the sidecar's own directory back up to the repository root.
859
+ ///
860
+ /// Counted from the path rather than assumed, so a sidecar written somewhere other than the
861
+ /// standard two-deep shard still points at a schema that exists.
862
+ fn schema_rel_for(out: &Path) -> String {
863
+ let depth = out
864
+ .parent()
865
+ .map(|p| p.components().count())
866
+ .unwrap_or_default();
867
+ let up = "../".repeat(depth.min(8));
868
+ format!("{up}{}", scans::ocr::SCHEMA_PATH)
869
+ }
870
+
871
+ // ---------------------------------------------------------------------------------------
872
+ // frc
873
+ // ---------------------------------------------------------------------------------------
874
+
875
+ fn cmd_frc(args: FrcArgs) -> Result<ExitCode> {
876
+ match args.command {
877
+ FrcCommand::Ingest {
878
+ frc_data,
879
+ root,
880
+ limit,
881
+ ids,
882
+ force,
883
+ dry_run,
884
+ } => {
885
+ let root = resolve_root(root.as_deref())?;
886
+
887
+ let mut ids = if ids.is_empty() {
888
+ scans::frc::ingest::identifiers(&frc_data)?
889
+ } else {
890
+ ids
891
+ };
892
+ if let Some(limit) = limit {
893
+ ids.truncate(limit);
894
+ }
895
+
896
+ if dry_run {
897
+ eprintln!(
898
+ "{} item(s) would be ingested into {}",
899
+ ids.len(),
900
+ show_cwd(&root.join(scans::frc::ingest::DIR))
901
+ );
902
+ for id in ids.iter().take(10) {
903
+ println!("{}", scans::frc::ingest::item_dir(id).display());
904
+ }
905
+ if ids.len() > 10 {
906
+ println!("… and {} more", ids.len() - 10);
907
+ }
908
+ return Ok(ExitCode::SUCCESS);
909
+ }
910
+
911
+ let total = ids.len();
912
+ let started = std::time::Instant::now();
913
+ let summary = scans::frc::ingest::ingest(&root, &frc_data, &ids, force, |i, id, outcome| {
914
+ if let scans::frc::ingest::Outcome::Failed(why) = outcome {
915
+ eprintln!("scans: {id}: {why}");
916
+ }
917
+ // Progress on one rewritten line: 38,377 items of scrollback is not progress.
918
+ if i % 200 == 0 || i + 1 == total {
919
+ let done = i + 1;
920
+ let rate = done as f64 / started.elapsed().as_secs_f64().max(0.001);
921
+ eprint!("\r {done}/{total} ({rate:.0}/s) ");
922
+ }
923
+ });
924
+ eprintln!();
925
+
926
+ eprintln!(
927
+ "{} written ({} without OCR), {} already done, {} failed",
928
+ summary.written,
929
+ summary.without_ocr,
930
+ summary.skipped,
931
+ summary.failed.len()
932
+ );
933
+ for (id, why) in summary.failed.iter().take(20) {
934
+ eprintln!(" {id}: {why}");
935
+ }
936
+
937
+ Ok(if summary.failed.is_empty() {
938
+ ExitCode::SUCCESS
939
+ } else {
940
+ ExitCode::FAILURE
941
+ })
942
+ }
943
+
944
+ FrcCommand::Fetch {
945
+ root,
946
+ interval,
947
+ limit,
948
+ ids,
949
+ force,
950
+ dry_run,
951
+ } => cmd_frc_fetch(root, interval, limit, ids, force, dry_run),
952
+ }
953
+ }
954
+
955
+ #[cfg(not(feature = "fetch"))]
956
+ fn cmd_frc_fetch(
957
+ _root: Option<PathBuf>,
958
+ _interval: f64,
959
+ _limit: Option<usize>,
960
+ _ids: Vec<String>,
961
+ _force: bool,
962
+ _dry_run: bool,
963
+ ) -> Result<ExitCode> {
964
+ anyhow::bail!(
965
+ "this binary was built without the 'fetch' feature, which is what opens a socket.\n\
966
+ Rebuild with: cargo build --release --features fetch"
967
+ )
968
+ }
969
+
970
+ #[cfg(feature = "fetch")]
971
+ fn cmd_frc_fetch(
972
+ root: Option<PathBuf>,
973
+ interval: f64,
974
+ limit: Option<usize>,
975
+ ids: Vec<String>,
976
+ force: bool,
977
+ dry_run: bool,
978
+ ) -> Result<ExitCode> {
979
+ use scans::frc::fetch;
980
+
981
+ let root = resolve_root(root.as_deref())?;
982
+
983
+ // The item list is the archive itself: everything `frc ingest` has already written a
984
+ // record for. That keeps the two halves in step without a shared manifest.
985
+ let ids = if ids.is_empty() {
986
+ let dir = root.join(scans::frc::ingest::DIR);
987
+ let mut found = Vec::new();
988
+ for shard in std::fs::read_dir(&dir)
989
+ .with_context(|| format!("reading {} — run `scans frc ingest` first", dir.display()))?
990
+ {
991
+ let shard = shard?;
992
+ if !shard.file_type()?.is_dir() {
993
+ continue;
994
+ }
995
+ for item in std::fs::read_dir(shard.path())? {
996
+ let item = item?;
997
+ if item.file_type()?.is_dir()
998
+ && let Some(name) = item.file_name().to_str()
999
+ {
1000
+ found.push(name.to_string());
1001
+ }
1002
+ }
1003
+ }
1004
+ found.sort();
1005
+ found
1006
+ } else {
1007
+ ids
1008
+ };
1009
+
1010
+ let options = fetch::Options {
1011
+ interval: std::time::Duration::from_secs_f64(interval.max(0.0)),
1012
+ limit,
1013
+ force,
1014
+ dry_run,
1015
+ };
1016
+
1017
+ let mut ids = ids;
1018
+ if let Some(limit) = options.limit {
1019
+ ids.truncate(limit);
1020
+ }
1021
+
1022
+ let total = ids.len();
1023
+ eprintln!(
1024
+ "{total} item(s), one request at a time, {interval}s apart, as {}",
1025
+ fetch::USER_AGENT
1026
+ );
1027
+
1028
+ let started = std::time::Instant::now();
1029
+ let summary = fetch::fetch(&root, &ids, &options, |i, id, outcome| {
1030
+ match outcome {
1031
+ fetch::Outcome::Failed(why) => eprintln!("\rscans: {id}: {why}"),
1032
+ fetch::Outcome::NoPdf => eprintln!("\rscans: {id}: no PDF derivative"),
1033
+ _ => {}
1034
+ }
1035
+ if i % 10 == 0 || i + 1 == total {
1036
+ let done = i + 1;
1037
+ let elapsed = started.elapsed().as_secs_f64().max(0.001);
1038
+ let left = (total - done) as f64 * (elapsed / done as f64);
1039
+ eprint!("\r {done}/{total} {:.0}h left ", left / 3600.0);
1040
+ }
1041
+ });
1042
+ eprintln!();
1043
+
1044
+ eprintln!(
1045
+ "{} fetched ({:.1} GB), {} already had one, {} have no PDF, {} failed",
1046
+ summary.fetched,
1047
+ summary.bytes as f64 / 1e9,
1048
+ summary.skipped,
1049
+ summary.no_pdf,
1050
+ summary.failed.len()
1051
+ );
1052
+ for (id, why) in summary.failed.iter().take(20) {
1053
+ eprintln!(" {id}: {why}");
1054
+ }
1055
+
1056
+ Ok(if summary.failed.is_empty() {
1057
+ ExitCode::SUCCESS
1058
+ } else {
1059
+ ExitCode::FAILURE
1060
+ })
1061
+ }
tools/src/migrate.rs CHANGED
@@ -1342,6 +1342,9 @@ impl Builder {
1342
  language: common.language,
1343
  place: common.place,
1344
  country: common.country,
 
 
 
1345
  founded: common.founded,
1346
  frequency: common.frequency,
1347
  date: common.date,
@@ -1563,6 +1566,9 @@ impl Builder {
1563
  language: common.language,
1564
  place: common.place,
1565
  country: common.country,
 
 
 
1566
  covers: common.covers,
1567
  date: common.date,
1568
  note: common.note,
@@ -1841,6 +1847,9 @@ impl Builder {
1841
  language: common.language,
1842
  place: common.place,
1843
  country: common.country,
 
 
 
1844
  rights: common.rights.into_option(),
1845
  holding: common.holding.into_option(),
1846
  identifier: (!common.identifier.is_empty()).then_some(common.identifier),
 
1342
  language: common.language,
1343
  place: common.place,
1344
  country: common.country,
1345
+ // Legacy records carry neither; both are new with the frc corpus ingest.
1346
+ subject: Vec::new(),
1347
+ extent: None,
1348
  founded: common.founded,
1349
  frequency: common.frequency,
1350
  date: common.date,
 
1566
  language: common.language,
1567
  place: common.place,
1568
  country: common.country,
1569
+ // Legacy records carry neither; both are new with the frc corpus ingest.
1570
+ subject: Vec::new(),
1571
+ extent: None,
1572
  covers: common.covers,
1573
  date: common.date,
1574
  note: common.note,
 
1847
  language: common.language,
1848
  place: common.place,
1849
  country: common.country,
1850
+ // Legacy records carry neither; both are new with the frc corpus ingest.
1851
+ subject: Vec::new(),
1852
+ extent: None,
1853
  rights: common.rights.into_option(),
1854
  holding: common.holding.into_option(),
1855
  identifier: (!common.identifier.is_empty()).then_some(common.identifier),
tools/src/model.rs CHANGED
@@ -146,6 +146,12 @@ pub struct Source {
146
  /// Terse page range. Legal but unusual on a source.
147
  #[serde(default, skip_serializing_if = "Option::is_none")]
148
  pub pages: Option<PageRange>,
 
 
 
 
 
 
149
 
150
  #[serde(default, skip_serializing_if = "Option::is_none")]
151
  pub rights: Option<Rights>,
@@ -206,6 +212,12 @@ pub struct CopyRecord {
206
  pub note: Option<String>,
207
  #[serde(default, skip_serializing_if = "Option::is_none")]
208
  pub url: Option<String>,
 
 
 
 
 
 
209
 
210
  /// The normal home for `scan`.
211
  #[serde(default, skip_serializing_if = "Option::is_none")]
@@ -278,6 +290,12 @@ pub struct Document {
278
  pub place: Option<String>,
279
  #[serde(default, skip_serializing_if = "Option::is_none")]
280
  pub country: Option<String>,
 
 
 
 
 
 
281
 
282
  #[serde(default, skip_serializing_if = "Option::is_none")]
283
  pub rights: Option<Rights>,
@@ -431,6 +449,12 @@ pub struct Scan {
431
  /// Landing page for the digitisation, distinct from top-level `url`. Inherits.
432
  #[serde(default, skip_serializing_if = "Option::is_none")]
433
  pub url: Option<String>,
 
 
 
 
 
 
434
  /// Caveats. Does not inherit.
435
  #[serde(default, skip_serializing_if = "Option::is_none")]
436
  pub note: Option<String>,
@@ -699,26 +723,52 @@ impl Record {
699
  /// This is the only place `schemas/source.json` comes from. `scans schema --check` compares
700
  /// the file on disk against this, which is what stops the schema drifting from the validator.
701
  pub fn json_schema() -> serde_json::Value {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
  let settings = schemars::generate::SchemaSettings::draft2020_12();
703
  let generator = settings.into_generator();
704
- let schema = generator.into_root_schema_for::<Record>();
705
  let mut value = serde_json::to_value(schema).expect("schema serialises");
706
 
707
  strip_null_unions(&mut value);
708
 
709
  if let Some(obj) = value.as_object_mut() {
710
- obj.insert("title".into(), serde_json::json!("Scan archive record"));
711
- obj.insert(
712
- "description".into(),
713
- serde_json::json!(
714
- "One TOML file in the primary source and scan archive. Generated from the Rust \
715
- types in tools/src/model.rs by `scans schema` - do not edit by hand."
716
- ),
717
- );
718
  }
719
  value
720
  }
721
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
722
  /// Remove every trace of `null` from the generated schema.
723
  ///
724
  /// TOML has no null. An optional key is simply absent, and the schema already says so by
 
146
  /// Terse page range. Legal but unusual on a source.
147
  #[serde(default, skip_serializing_if = "Option::is_none")]
148
  pub pages: Option<PageRange>,
149
+ /// Subject headings as the cataloguer wrote them. Does not inherit.
150
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
151
+ pub subject: Vec<String>,
152
+ /// Bibliographic collation, `"7 p. ; 18 cm."`. Does not inherit.
153
+ #[serde(default, skip_serializing_if = "Option::is_none")]
154
+ pub extent: Option<String>,
155
 
156
  #[serde(default, skip_serializing_if = "Option::is_none")]
157
  pub rights: Option<Rights>,
 
212
  pub note: Option<String>,
213
  #[serde(default, skip_serializing_if = "Option::is_none")]
214
  pub url: Option<String>,
215
+ /// Subject headings as the cataloguer wrote them. Does not inherit.
216
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
217
+ pub subject: Vec<String>,
218
+ /// Bibliographic collation, `"7 p. ; 18 cm."`. Does not inherit.
219
+ #[serde(default, skip_serializing_if = "Option::is_none")]
220
+ pub extent: Option<String>,
221
 
222
  /// The normal home for `scan`.
223
  #[serde(default, skip_serializing_if = "Option::is_none")]
 
290
  pub place: Option<String>,
291
  #[serde(default, skip_serializing_if = "Option::is_none")]
292
  pub country: Option<String>,
293
+ /// Subject headings as the cataloguer wrote them. Does not inherit.
294
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
295
+ pub subject: Vec<String>,
296
+ /// Bibliographic collation, `"7 p. ; 18 cm."`. Does not inherit.
297
+ #[serde(default, skip_serializing_if = "Option::is_none")]
298
+ pub extent: Option<String>,
299
 
300
  #[serde(default, skip_serializing_if = "Option::is_none")]
301
  pub rights: Option<Rights>,
 
449
  /// Landing page for the digitisation, distinct from top-level `url`. Inherits.
450
  #[serde(default, skip_serializing_if = "Option::is_none")]
451
  pub url: Option<String>,
452
+ /// Resolution the scan was made at, in pixels per inch. Inherits.
453
+ ///
454
+ /// Stated rather than inferred: `render` otherwise has to guess a page's native
455
+ /// resolution from the largest image embedded in it.
456
+ #[serde(default, skip_serializing_if = "Option::is_none")]
457
+ pub ppi: Option<i64>,
458
  /// Caveats. Does not inherit.
459
  #[serde(default, skip_serializing_if = "Option::is_none")]
460
  pub note: Option<String>,
 
723
  /// This is the only place `schemas/source.json` comes from. `scans schema --check` compares
724
  /// the file on disk against this, which is what stops the schema drifting from the validator.
725
  pub fn json_schema() -> serde_json::Value {
726
+ schema_for::<Record>(
727
+ "Scan archive record",
728
+ "One TOML file in the primary source and scan archive. Generated from the Rust \
729
+ types in tools/src/model.rs by `scans schema` - do not edit by hand.",
730
+ )
731
+ }
732
+
733
+ /// Generate a schema for any of the archive's file types, with `null` stripped out.
734
+ ///
735
+ /// Shared by the record schema and the OCR sidecar schema so that both are derived the same
736
+ /// way and neither can drift into being hand-maintained.
737
+ pub fn schema_for<T: schemars::JsonSchema>(
738
+ title: &str,
739
+ description: &str,
740
+ ) -> serde_json::Value {
741
  let settings = schemars::generate::SchemaSettings::draft2020_12();
742
  let generator = settings.into_generator();
743
+ let schema = generator.into_root_schema_for::<T>();
744
  let mut value = serde_json::to_value(schema).expect("schema serialises");
745
 
746
  strip_null_unions(&mut value);
747
 
748
  if let Some(obj) = value.as_object_mut() {
749
+ obj.insert("title".into(), serde_json::json!(title));
750
+ obj.insert("description".into(), serde_json::json!(description));
 
 
 
 
 
 
751
  }
752
  value
753
  }
754
 
755
+ /// The schema for an `.ocr.toml` sidecar.
756
+ pub fn ocr_json_schema() -> serde_json::Value {
757
+ schema_for::<crate::ocr::Ocr>(
758
+ "Word-level OCR sidecar",
759
+ "One <id>.ocr.toml: word-level OCR losslessly equivalent to a DjVu XML derivative. \
760
+ Generated from the Rust types in tools/src/ocr.rs by `scans schema` - do not edit \
761
+ by hand.",
762
+ )
763
+ }
764
+
765
+ /// Serialise the OCR schema exactly as `scans schema` writes it.
766
+ pub fn ocr_json_schema_text() -> String {
767
+ let mut s = serde_json::to_string_pretty(&ocr_json_schema()).expect("schema serialises");
768
+ s.push('\n');
769
+ s
770
+ }
771
+
772
  /// Remove every trace of `null` from the generated schema.
773
  ///
774
  /// TOML has no null. An optional key is simply absent, and the schema already says so by
tools/src/ocr.rs ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! `<id>.pN.ocr.md` — one scanned page of OCR, as markdown with YAML frontmatter.
2
+ //!
3
+ //! ## One file, one page
4
+ //!
5
+ //! A page is the unit. The corpus holds 840,810 of them across 38,377 items. One file per
6
+ //! item put a 3,378-page bound run of nine volumes into a single 49 MB text file, which is
7
+ //! unreadable in an editor and unreviewable in a diff; per page, nothing is more than a few
8
+ //! kilobytes, and `<id>.pN` matches the address grammar the archive already uses.
9
+ //!
10
+ //! ## The shape
11
+ //!
12
+ //! ```markdown
13
+ //! ---
14
+ //! of: abondance00unse
15
+ //! page: 6
16
+ //! engine: ABBYY FineReader 11.0
17
+ //! lang: fr
18
+ //! w: 2597
19
+ //! h: 4418
20
+ //! dpi: 500
21
+ //! ---
22
+ //!
23
+ //! ABONDANCE NATIONALE,
24
+ //! ou, Découvertes d'artillerie
25
+ //! ```
26
+ //!
27
+ //! Frontmatter says which page of what, and how big the image is. The body is the page's
28
+ //! text. That is the whole format.
29
+ //!
30
+ //! ## What is deliberately not here
31
+ //!
32
+ //! Word coordinates, per-word confidence, baselines, and DjVu's four levels of nesting. An
33
+ //! earlier version of this format carried all of it, packed into parallel arrays, and was
34
+ //! losslessly convertible back to the `_djvu.xml` it came from. It is gone at the repository
35
+ //! owner's direction: the boxes were not being used, and they were seven eighths of the
36
+ //! bytes — 8.3 GB against about 1.1 GB for the text alone.
37
+ //!
38
+ //! Nothing is destroyed by that. The coordinates still exist in `XML_for_OCR/` in
39
+ //! [frc-data], which is one clone away, so a future version that wants them back can have
40
+ //! them without asking archive.org for anything.
41
+ //!
42
+ //! [frc-data]: https://github.com/NewberryDIS/frc-data
43
+ //!
44
+ //! ## Scalars are bare unless they would lie
45
+ //!
46
+ //! The frontmatter reads as plain YAML — `lang: fr`, not `lang: "fr"` — because that is what
47
+ //! it is for. But YAML's plain scalars are a minefield of values that mean something other
48
+ //! than themselves: `no` is the boolean false, and it is also the ISO code for Norwegian.
49
+ //! [`yaml_scalar`] emits a value bare when it round-trips as itself and quotes it when it
50
+ //! would not, so the common case looks like the example above and the pathological case is
51
+ //! still correct.
52
+
53
+ use std::fmt::Write as _;
54
+
55
+ use schemars::JsonSchema;
56
+ use serde::{Deserialize, Serialize};
57
+
58
+ /// Path of the generated OCR schema, relative to the repository root.
59
+ pub const SCHEMA_PATH: &str = "schemas/ocr.json";
60
+
61
+ /// The suffix that marks an OCR sidecar.
62
+ pub const SUFFIX: &str = ".ocr.md";
63
+
64
+ // ---------------------------------------------------------------------------------------
65
+ // The file model
66
+ // ---------------------------------------------------------------------------------------
67
+
68
+ /// One `<id>.pN.ocr.md` — the OCR of a single scanned page.
69
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
70
+ #[serde(deny_unknown_fields)]
71
+ pub struct Ocr {
72
+ /// Id of the record this page belongs to.
73
+ pub of: String,
74
+ /// 1-based page index within the scanned container, matching `.pN` addressing.
75
+ pub page: i64,
76
+ /// Producing agent and version, e.g. `ABBYY FineReader 11.0`.
77
+ #[serde(default, skip_serializing_if = "Option::is_none")]
78
+ pub engine: Option<String>,
79
+ /// BCP-47 code of the text, when known.
80
+ #[serde(default, skip_serializing_if = "Option::is_none")]
81
+ pub lang: Option<String>,
82
+ /// Pixel width of the page image.
83
+ #[serde(default, skip_serializing_if = "Option::is_none")]
84
+ pub w: Option<i64>,
85
+ /// Pixel height of the page image.
86
+ #[serde(default, skip_serializing_if = "Option::is_none")]
87
+ pub h: Option<i64>,
88
+ /// Resolution the page was scanned at.
89
+ #[serde(default, skip_serializing_if = "Option::is_none")]
90
+ pub dpi: Option<i64>,
91
+
92
+ /// The page's text — the markdown body.
93
+ ///
94
+ /// **Not in the frontmatter.** `serde` skips it here so it cannot appear in both places
95
+ /// and disagree with itself. It is now the only content this format carries, so unlike
96
+ /// the previous version it is authoritative rather than derived, and there is nothing
97
+ /// left for a consistency check to compare it against.
98
+ #[serde(skip)]
99
+ pub text: String,
100
+ }
101
+
102
+ /// The filename a page's OCR lives in, relative to the item's directory.
103
+ pub fn file_name(id: &str, page: i64) -> String {
104
+ format!("{id}.p{page}{SUFFIX}")
105
+ }
106
+
107
+ // ---------------------------------------------------------------------------------------
108
+ // Writing
109
+ // ---------------------------------------------------------------------------------------
110
+
111
+ /// Render one page as markdown with YAML frontmatter.
112
+ ///
113
+ /// `schema_rel` is the path from this file back to `schemas/ocr.json`, emitted as a
114
+ /// `yaml-language-server` directive — YAML's equivalent of the `#:schema` line the records
115
+ /// carry, and what gets the frontmatter validated and completed in an editor.
116
+ pub fn to_markdown(ocr: &Ocr, schema_rel: &str) -> String {
117
+ let mut s = String::new();
118
+ s.push_str("---\n");
119
+ let _ = writeln!(s, "# yaml-language-server: $schema={schema_rel}");
120
+ let _ = writeln!(s, "of: {}", yaml_scalar(&ocr.of));
121
+ let _ = writeln!(s, "page: {}", ocr.page);
122
+ if let Some(engine) = &ocr.engine {
123
+ let _ = writeln!(s, "engine: {}", yaml_scalar(engine));
124
+ }
125
+ if let Some(lang) = &ocr.lang {
126
+ let _ = writeln!(s, "lang: {}", yaml_scalar(lang));
127
+ }
128
+ for (key, value) in [("w", ocr.w), ("h", ocr.h), ("dpi", ocr.dpi)] {
129
+ if let Some(v) = value {
130
+ let _ = writeln!(s, "{key}: {v}");
131
+ }
132
+ }
133
+ s.push_str("---\n");
134
+
135
+ // The body is the whole page and nothing else — no headings, no delimiters, nothing the
136
+ // OCR could collide with.
137
+ if !ocr.text.is_empty() {
138
+ let _ = write!(s, "\n{}\n", ocr.text);
139
+ }
140
+ s
141
+ }
142
+
143
+ /// A YAML scalar: bare where that is unambiguous, quoted where it is not.
144
+ ///
145
+ /// The bare form is the point — `lang: fr` reads as YAML rather than as an escaped blob. But
146
+ /// a bare scalar has to survive the round trip, and YAML will happily read `no` as `false`,
147
+ /// `1:30` as a sexagesimal integer, `~` as null, and a leading `%` as a directive. OCR of
148
+ /// worn 18th-century type produces exactly that debris, so the decision is made by asking
149
+ /// YAML itself whether the bare form parses back to the same string.
150
+ pub fn yaml_scalar(s: &str) -> String {
151
+ if is_safe_bare(s) {
152
+ return s.to_string();
153
+ }
154
+ yaml_quoted(s)
155
+ }
156
+
157
+ /// Words YAML 1.1 resolves to booleans or null, which YAML 1.2 leaves as strings.
158
+ ///
159
+ /// `serde_norway` implements 1.2, so it reads `no` as the string it looks like. Most of the
160
+ /// world does not: PyYAML, libyaml, Ruby's Psych and Go's gopkg.in/yaml.v2 all implement 1.1,
161
+ /// where `no` is `false` — and `no` is also the ISO 639-1 code for Norwegian. This data is
162
+ /// published for other people's tools to read, so the bar is what *they* will do with it, not
163
+ /// what this crate's parser happens to accept.
164
+ const YAML11_RESERVED: &[&str] = &[
165
+ "y", "Y", "yes", "Yes", "YES", "n", "N", "no", "No", "NO",
166
+ "true", "True", "TRUE", "false", "False", "FALSE",
167
+ "on", "On", "ON", "off", "Off", "OFF",
168
+ "null", "Null", "NULL", "~",
169
+ ];
170
+
171
+ /// Whether a value can be written bare.
172
+ ///
173
+ /// Conservative on structure — anything with a leading or trailing space, a control
174
+ /// character, or a character YAML gives meaning to is quoted without further thought — then
175
+ /// checked against [`YAML11_RESERVED`], and finally round-tripped through the parser. The
176
+ /// round trip is what catches `1:30`, `0x10` and `2026-08-07` without this having to carry
177
+ /// its own copy of YAML's scalar-resolution rules, which would drift.
178
+ fn is_safe_bare(s: &str) -> bool {
179
+ if s.is_empty() || s.trim() != s {
180
+ return false;
181
+ }
182
+ if YAML11_RESERVED.contains(&s) {
183
+ return false;
184
+ }
185
+ if s.chars().any(|c| {
186
+ (c as u32) < 0x20
187
+ || c as u32 == 0x7f
188
+ || matches!(c, ':' | '#' | '"' | '\'' | '\\' | '{' | '}' | '[' | ']' | ',' | '&'
189
+ | '*' | '!' | '|' | '>' | '%' | '@' | '`')
190
+ }) {
191
+ return false;
192
+ }
193
+ if s.starts_with('-') || s.starts_with('?') || s.starts_with('~') {
194
+ return false;
195
+ }
196
+ // The authority on whether a bare scalar means itself is the YAML parser.
197
+ matches!(
198
+ serde_norway::from_str::<serde_norway::Value>(s),
199
+ Ok(serde_norway::Value::String(round)) if round == s
200
+ )
201
+ }
202
+
203
+ /// A YAML double-quoted string, escaped. The escapes are JSON's, which YAML accepts in full.
204
+ pub fn yaml_quoted(s: &str) -> String {
205
+ let mut out = String::with_capacity(s.len() + 2);
206
+ out.push('"');
207
+ for c in s.chars() {
208
+ match c {
209
+ '"' => out.push_str("\\\""),
210
+ '\\' => out.push_str("\\\\"),
211
+ '\n' => out.push_str("\\n"),
212
+ '\r' => out.push_str("\\r"),
213
+ '\t' => out.push_str("\\t"),
214
+ c if (c as u32) < 0x20 || c as u32 == 0x7f => {
215
+ let _ = write!(out, "\\u{:04X}", c as u32);
216
+ }
217
+ c => out.push(c),
218
+ }
219
+ }
220
+ out.push('"');
221
+ out
222
+ }
223
+
224
+ // ---------------------------------------------------------------------------------------
225
+ // Reading
226
+ // ---------------------------------------------------------------------------------------
227
+
228
+ /// Why an `.ocr.md` could not be read.
229
+ #[derive(Debug)]
230
+ pub enum ParseError {
231
+ /// No `---` frontmatter block at the top of the file.
232
+ NoFrontmatter,
233
+ /// The frontmatter opened but never closed.
234
+ UnterminatedFrontmatter,
235
+ Yaml(serde_norway::Error),
236
+ }
237
+
238
+ impl std::fmt::Display for ParseError {
239
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
240
+ match self {
241
+ ParseError::NoFrontmatter => {
242
+ f.write_str("no YAML frontmatter: the file must begin with a line of ---")
243
+ }
244
+ ParseError::UnterminatedFrontmatter => {
245
+ f.write_str("the YAML frontmatter opens but is never closed by a line of ---")
246
+ }
247
+ ParseError::Yaml(e) => write!(f, "frontmatter is not valid YAML: {e}"),
248
+ }
249
+ }
250
+ }
251
+
252
+ impl std::error::Error for ParseError {}
253
+
254
+ /// Split a markdown file into its frontmatter and its body.
255
+ ///
256
+ /// Deliberately strict about the opening delimiter being the very first line. A file whose
257
+ /// frontmatter starts on line 2 is one someone has edited by hand and got slightly wrong, and
258
+ /// guessing at it would hide that.
259
+ pub fn split_frontmatter(text: &str) -> Result<(&str, &str), ParseError> {
260
+ let rest = text
261
+ .strip_prefix("---\n")
262
+ .or_else(|| text.strip_prefix("---\r\n"))
263
+ .ok_or(ParseError::NoFrontmatter)?;
264
+
265
+ let mut offset = 0usize;
266
+ for line in rest.split_inclusive('\n') {
267
+ if line.trim_end() == "---" {
268
+ return Ok((&rest[..offset], &rest[offset + line.len()..]));
269
+ }
270
+ offset += line.len();
271
+ }
272
+ Err(ParseError::UnterminatedFrontmatter)
273
+ }
274
+
275
+ /// Parse an `.ocr.md`.
276
+ pub fn from_markdown(text: &str) -> Result<Ocr, ParseError> {
277
+ let (front, body) = split_frontmatter(text)?;
278
+ let mut ocr: Ocr = serde_norway::from_str(front).map_err(ParseError::Yaml)?;
279
+ ocr.text = body.trim_matches('\n').to_string();
280
+ Ok(ocr)
281
+ }
282
+
283
+ #[cfg(test)]
284
+ mod tests {
285
+ use super::*;
286
+
287
+ fn page(text: &str) -> Ocr {
288
+ Ocr {
289
+ of: "abondance00unse".into(),
290
+ page: 6,
291
+ engine: Some("ABBYY FineReader 11.0".into()),
292
+ lang: Some("fr".into()),
293
+ w: Some(2597),
294
+ h: Some(4418),
295
+ dpi: Some(500),
296
+ text: text.into(),
297
+ }
298
+ }
299
+
300
+ #[test]
301
+ fn the_filename_carries_the_page_number() {
302
+ assert_eq!(file_name("abondance00unse", 3), "abondance00unse.p3.ocr.md");
303
+ }
304
+
305
+ /// The frontmatter should read as plain YAML, not as a wall of quoted blobs.
306
+ #[test]
307
+ fn ordinary_values_are_written_bare() {
308
+ let text = to_markdown(&page("ABONDANCE"), "s.json");
309
+ for line in [
310
+ "of: abondance00unse",
311
+ "page: 6",
312
+ "engine: ABBYY FineReader 11.0",
313
+ "lang: fr",
314
+ "w: 2597",
315
+ "h: 4418",
316
+ "dpi: 500",
317
+ ] {
318
+ assert!(text.contains(line), "expected {line:?} in:\n{text}");
319
+ }
320
+ }
321
+
322
+ #[test]
323
+ fn a_page_round_trips() {
324
+ let p = page("ABONDANCE NATIONALE,\nou, Découvertes");
325
+ assert_eq!(from_markdown(&to_markdown(&p, "s.json")).unwrap(), p);
326
+ }
327
+
328
+ #[test]
329
+ fn a_page_with_no_text_round_trips() {
330
+ let mut p = page("");
331
+ p.engine = None;
332
+ p.lang = None;
333
+ assert_eq!(from_markdown(&to_markdown(&p, "s.json")).unwrap(), p);
334
+ }
335
+
336
+ /// `no` is the ISO 639-1 code for Norwegian and, to every YAML 1.1 parser, the boolean
337
+ /// false. `serde_norway` is 1.2 and would read it back correctly, but PyYAML would hand a
338
+ /// Python user `False`, and this data is published for their tools rather than ours.
339
+ #[test]
340
+ fn a_language_code_that_yaml_reads_as_a_boolean_is_quoted() {
341
+ let mut p = page("x");
342
+ p.lang = Some("no".into());
343
+ let text = to_markdown(&p, "s.json");
344
+ assert!(text.contains(r#"lang: "no""#), "{text}");
345
+ assert_eq!(from_markdown(&text).unwrap().lang.as_deref(), Some("no"));
346
+ }
347
+
348
+ /// Every value YAML would quietly reinterpret has to survive as the string it was.
349
+ #[test]
350
+ fn values_yaml_would_reinterpret_survive() {
351
+ for hazard in [
352
+ // YAML 1.1 booleans and nulls, in the casings real data uses.
353
+ "no", "No", "NO", "yes", "Yes", "y", "n", "on", "off", "Off",
354
+ "true", "True", "false", "False", "null", "Null", "~",
355
+ // Resolved to non-strings by 1.1 and 1.2 alike.
356
+ "1:30", "0x10", "0o17", ".inf", "nan", "2026-08-07", "007", "1_000",
357
+ // Structurally unsafe.
358
+ "", " leading", "trailing ", "a: b", "#comment", "%directive", "@reserved",
359
+ "-dash", "*alias", "&anchor", "[list]", "{map}", "back\\slash", "quote\"d",
360
+ ] {
361
+ let mut p = page("x");
362
+ p.engine = Some(hazard.to_string());
363
+ let back = from_markdown(&to_markdown(&p, "s.json"))
364
+ .unwrap_or_else(|e| panic!("{hazard:?} failed to parse: {e}"));
365
+ assert_eq!(
366
+ back.engine.as_deref(),
367
+ Some(hazard),
368
+ "{hazard:?} did not survive"
369
+ );
370
+ }
371
+ }
372
+
373
+ /// An identifier that is all digits would be read back as an integer.
374
+ #[test]
375
+ fn a_numeric_looking_identifier_is_quoted() {
376
+ let mut p = page("x");
377
+ p.of = "24516".into();
378
+ let back = from_markdown(&to_markdown(&p, "s.json")).unwrap();
379
+ assert_eq!(back.of, "24516");
380
+ }
381
+
382
+ /// Real identifiers in this corpus start with digits but are not numbers, and must not be
383
+ /// quoted for no reason.
384
+ #[test]
385
+ fn an_identifier_starting_with_digits_stays_bare() {
386
+ let mut p = page("x");
387
+ p.of = "1789iemilseptcen00unse".into();
388
+ let text = to_markdown(&p, "s.json");
389
+ assert!(text.contains("of: 1789iemilseptcen00unse"), "{text}");
390
+ }
391
+
392
+ /// The body is the page and nothing else, so nothing in the OCR can be mistaken for a
393
+ /// delimiter or for markup.
394
+ #[test]
395
+ fn a_body_that_looks_like_markup_is_still_just_text() {
396
+ let p = page("## Page 3\n---\nof: someone-else");
397
+ let back = from_markdown(&to_markdown(&p, "s.json")).unwrap();
398
+ assert_eq!(back.text, p.text);
399
+ assert_eq!(back.of, "abondance00unse");
400
+ }
401
+
402
+ /// A file someone has edited by hand and got slightly wrong must say so rather than be
403
+ /// guessed at.
404
+ #[test]
405
+ fn malformed_frontmatter_is_an_error_not_a_guess() {
406
+ assert!(matches!(
407
+ from_markdown("of: x\npage: 1\n"),
408
+ Err(ParseError::NoFrontmatter)
409
+ ));
410
+ assert!(matches!(
411
+ from_markdown("---\nof: x\npage: 1\n"),
412
+ Err(ParseError::UnterminatedFrontmatter)
413
+ ));
414
+ assert!(matches!(
415
+ from_markdown("---\nof: [unclosed\n---\n"),
416
+ Err(ParseError::Yaml(_))
417
+ ));
418
+ }
419
+ }
tools/src/validate.rs CHANGED
@@ -204,6 +204,7 @@ pub fn validate(archive: &Archive, options: &Options) -> Report {
204
  check_7_files(archive, options, &mut report);
205
  check_8_crossrefs(archive, &mut report);
206
  check_10_gaps(archive, &mut report);
 
207
 
208
  report.retain_selected(archive, &options.select);
209
  report.sort();
@@ -1482,3 +1483,107 @@ mod probe {
1482
  Ok(document.get_pages().len() as i64)
1483
  }
1484
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  check_7_files(archive, options, &mut report);
205
  check_8_crossrefs(archive, &mut report);
206
  check_10_gaps(archive, &mut report);
207
+ check_11_ocr(archive, options, &mut report);
208
 
209
  report.retain_selected(archive, &options.select);
210
  report.sort();
 
1483
  Ok(document.get_pages().len() as i64)
1484
  }
1485
  }
1486
+
1487
+ // ---------------------------------------------------------------------------------------
1488
+ // Check 11 — the OCR sidecars.
1489
+ //
1490
+ // An `.ocr.toml` is archive content but not a record: it has no `layer`, so `load` skips it
1491
+ // and it is reached instead through the `[[text]]` that points at it. That makes this the
1492
+ // only place anything looks at one, and the checks are correspondingly structural.
1493
+ //
1494
+ // ## Why the content half is behind `--probe`
1495
+ //
1496
+ // `E708` is a `stat` and runs always. Everything below it has to parse the sidecar, and the
1497
+ // frc corpus is 840,810 of them — parsing all of that turns `validate` from a six-second
1498
+ // command into a much longer one. That is the same reason `--probe` exists for the image
1499
+ // checks: the default path must stay fast enough to run on every save.
1500
+ // ---------------------------------------------------------------------------------------
1501
+
1502
+ fn check_11_ocr(archive: &Archive, options: &Options, report: &mut Report) {
1503
+ for node in archive.iter() {
1504
+ for (i, text) in node.record.text().iter().enumerate() {
1505
+ if !text.file.ends_with(crate::ocr::SUFFIX) {
1506
+ continue;
1507
+ }
1508
+ let locator = format!("[[text]]#{}", i + 1);
1509
+ let dir = node.path.parent().unwrap_or(&archive.root);
1510
+ let path = dir.join(&text.file);
1511
+
1512
+ if !path.exists() {
1513
+ report.push(
1514
+ Diagnostic::error(
1515
+ node.rel_path.clone(),
1516
+ "E708",
1517
+ format!(
1518
+ "OCR sidecar {:?} does not exist (resolved to {})",
1519
+ text.file,
1520
+ rel(archive, &path)
1521
+ ),
1522
+ )
1523
+ .at(locator.clone()),
1524
+ );
1525
+ continue;
1526
+ }
1527
+
1528
+ if !options.probe {
1529
+ continue;
1530
+ }
1531
+
1532
+ let raw = match std::fs::read_to_string(&path) {
1533
+ Ok(raw) => raw,
1534
+ Err(e) => {
1535
+ report.push(
1536
+ Diagnostic::error(
1537
+ node.rel_path.clone(),
1538
+ "E708",
1539
+ format!("OCR sidecar {:?} cannot be read: {e}", text.file),
1540
+ )
1541
+ .at(locator),
1542
+ );
1543
+ continue;
1544
+ }
1545
+ };
1546
+
1547
+ let ocr: crate::ocr::Ocr = match crate::ocr::from_markdown(&raw) {
1548
+ Ok(ocr) => ocr,
1549
+ Err(e) => {
1550
+ report.push(Diagnostic::error(
1551
+ rel(archive, &path),
1552
+ "E709",
1553
+ format!("not a valid OCR sidecar: {e}"),
1554
+ ));
1555
+ continue;
1556
+ }
1557
+ };
1558
+
1559
+ // `of` is what ties the sidecar back to the record. A sidecar pointing at some
1560
+ // other id is a file that has been moved or copied without being updated, and the
1561
+ // OCR it holds is then attached to the wrong pamphlet.
1562
+ if ocr.of != node.id {
1563
+ report.push(Diagnostic::error(
1564
+ rel(archive, &path),
1565
+ "E710",
1566
+ format!(
1567
+ "of = {:?}, but this sidecar is pointed at by {:?}",
1568
+ ocr.of, node.id
1569
+ ),
1570
+ ));
1571
+ }
1572
+
1573
+ // The page number is in the filename and in the frontmatter, and a mismatch means
1574
+ // one of them is lying about which page this is — which silently misplaces every
1575
+ // coordinate on it.
1576
+ let expected = crate::ocr::file_name(&ocr.of, ocr.page);
1577
+ if !text.file.ends_with(&expected) {
1578
+ report.push(Diagnostic::error(
1579
+ rel(archive, &path),
1580
+ "E712",
1581
+ format!(
1582
+ "page = {}, which does not match the filename; expected {expected}",
1583
+ ocr.page
1584
+ ),
1585
+ ));
1586
+ }
1587
+ }
1588
+ }
1589
+ }