paratext-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
paratext/AGENTS.md ADDED
@@ -0,0 +1,254 @@
1
+ # paratext — agent guide
2
+
3
+ Modular metadata-extraction pipeline for digitised library/archive collections,
4
+ driven by a multimodal model. This orients AI coding agents; `README.md` is the
5
+ human guide.
6
+
7
+ paratext is **built to be adapted**. Most users need a project of their own, and
8
+ some need a new input format or a new export format. Those are extension points,
9
+ not forks — the recipes below are the supported way in.
10
+
11
+ ## Rules
12
+
13
+ - **Read a file in full before editing it.** These modules are short by design;
14
+ there is no excuse for patching blind.
15
+ - **Run `uv run pytest -q` and `uv run ruff check` after every change.** Both must
16
+ be clean. Line length 100, rules E/F/I/W.
17
+ - **Never edit `prompt.md` and `schema.py` casually.** A prompt edit rolls a new
18
+ review round and invalidates comparisons; a schema change needs a
19
+ `schema_version` bump. Both cost a model run to re-evaluate.
20
+ - **Keep a project's fields in step across all three places** (schema, prompt,
21
+ view) and call `audit_project()` from its tests.
22
+ - **Add a notice, not a silent fallback.** If you write a degraded path, append to
23
+ `Source.notices` so `extract` reports it. Preprocessing that silently does
24
+ nothing looks like a clean run and quietly costs accuracy — it is the worst
25
+ failure mode in this codebase.
26
+ - **Don't hardcode institution-specific values.** Detector weights, verso
27
+ thresholds and grid regions are all config.
28
+ - **Ask before removing functionality** that looks deliberate.
29
+ - Say "multimodal model" or "the model" — never "VLM".
30
+
31
+ ## Setup, build, run
32
+
33
+ ```bash
34
+ uv sync --extra dev # add --extra detector for the torch card detector
35
+ uv run paratext … # run the CLI against local source
36
+ uv run pytest -q
37
+ uv run ruff check
38
+ ```
39
+
40
+ Python 3.11–3.13 via `uv`. The model endpoint is any OpenAI-compatible server;
41
+ set `base-url` in `paratext.toml` or `PARATEXT_BASE_URL`.
42
+
43
+ **The installed-vs-source trap:** a non-editable install means source edits do
44
+ nothing until reinstall. `paratext inspect` reports the *installed* project — when
45
+ behaviour doesn't match the source you're reading, check there first.
46
+
47
+ ## Architecture
48
+
49
+ One CLI runs the loop: `extract` (model → JSONL) → `package` (JSONL → review
50
+ dataset) → `review` (web UI) → `export` (publish). `run` does extract+package.
51
+
52
+ | Module | Responsibility |
53
+ | --- | --- |
54
+ | `cli.py` | Argparse wiring, round resolution, command bodies |
55
+ | `config.py` | `paratext.toml` + `PARATEXT_*` resolution |
56
+ | `projects/` | The `Project` plug-in contract, `View`, `audit_project` |
57
+ | `sources.py` | Input adapters (`image_source`, `pdf_source`) |
58
+ | `extract.py` / `runner.py` | Sample loop; model call, retries, image encoding |
59
+ | `packaging.py` | JSONL → `samples.json` + `images/` + `view.json` |
60
+ | `store.py` | SQLite annotations + gold labels — **not** web code |
61
+ | `datasets.py` | Discovering packaged rounds, resolving `view.json` |
62
+ | `records.py` | Format-neutral gold selection, shared by all exports |
63
+ | `catalogue.py` / `hf_export.py` | MARC/DC and Hugging Face exports |
64
+ | `review/server.py` | HTTP layer only; `review/static/` is the vanilla-JS frontend |
65
+ | `cards.py` | Optional scanned-card tools (verso, crop, show-through) |
66
+ | `carbon.py` | Grid-intensity providers for `--green` |
67
+
68
+ `store.py` and `datasets.py` are deliberately outside `review/` so exporters can
69
+ read a reviewed round without starting a web server.
70
+
71
+ Output is JSONL with a `_provenance` header (git commit, prompt hash, model,
72
+ schema version, timestamp), and is resumable: re-running with the same `--output`
73
+ skips ids already present.
74
+
75
+ ---
76
+
77
+ # Extending paratext
78
+
79
+ ## Recipe: a new project
80
+
81
+ The common case — a user's own collection. `paratext new <name>` scaffolds it;
82
+ these are the files it makes and what to edit.
83
+
84
+ ```
85
+ my_cards/
86
+ prompt.md # behaviour lives here
87
+ schema.py # Pydantic model = the fields, also sent as response_format
88
+ __init__.py # wires them into PROJECT
89
+ ```
90
+
91
+ ```python
92
+ from paratext.projects import Project, load_prompt
93
+ from paratext.sources import image_source
94
+
95
+ from .schema import Record
96
+
97
+ PROJECT = Project(
98
+ name="my-cards",
99
+ schema_version="v1",
100
+ prompt=load_prompt(__file__),
101
+ schema=Record,
102
+ source=image_source(),
103
+ )
104
+ ```
105
+
106
+ Register it in the user's `pyproject.toml`:
107
+
108
+ ```toml
109
+ [project.entry-points."paratext.projects"]
110
+ my-cards = "my_cards:PROJECT"
111
+ ```
112
+
113
+ Then `uv sync` — entry points are re-scanned per request, so the review server
114
+ picks up a new project without a restart, but **framework code changes still need
115
+ one**.
116
+
117
+ Optional, in order of how often you'll need them:
118
+
119
+ - `view=View(...)` — curate the review display. Defaults to every schema field.
120
+ - `curate(rec) -> Curation` — `keep` / `drop` / `quarantine` per record.
121
+ - `build_record(rec, images)` — extra keys in `samples.json`.
122
+ - `ground_truth(rec)` — attach existing catalogue data for side-by-side review.
123
+ - `disable_thinking` — some models need `enable_thinking=False`.
124
+
125
+ **Field discipline:** the field names appear in schema, prompt and view with no
126
+ compile-time link. `audit_project(PROJECT)` checks the view's fields exist in the
127
+ schema and that every model-output field is named in the prompt. Call it from a
128
+ test — `paratext new` generates one.
129
+
130
+ Put behaviour in `prompt.md` (prose, examples, versioned by the prompt hash).
131
+ Keep `Field(description=...)` short and structural: it is *also* sent to the
132
+ model and shouldn't restate the prompt in a second voice.
133
+
134
+ ## Recipe: a new source adapter
135
+
136
+ For an input shape neither `image_source` nor `pdf_source` covers — a IIIF
137
+ manifest, a METS/ALTO tree, a CSV of URLs, a database query.
138
+
139
+ A `Source` is two functions that must agree on the metadata they pass between
140
+ them, plus optional notices and a descriptive config:
141
+
142
+ ```python
143
+ from paratext.sources import Source
144
+ from paratext.projects import Sample
145
+ from paratext.packaging import save_image
146
+
147
+ def iiif_source(*, max_items: int | None = None) -> Source:
148
+ notices: list[str] = []
149
+
150
+ def _iter(source: Path, limit: int | None) -> Iterator[Sample]:
151
+ # yield one Sample per unit of work
152
+ yield Sample(
153
+ id="unique-stable-id", # becomes the JSONL/review key
154
+ images=[pil_image], # what the model sees
155
+ metadata={"iiif_url": url}, # anything materialise() will need
156
+ )
157
+
158
+ def _materialise(rec: dict, out: Path, max_size: int) -> list[str]:
159
+ # write review images under `out`, return paths relative to it
160
+ rel = f"images/{rec['id']}/image.jpg"
161
+ save_image(local_path, out / rel, max_size)
162
+ return [rel]
163
+
164
+ return Source(
165
+ iter_samples=_iter,
166
+ materialise=_materialise,
167
+ notices=notices,
168
+ config={"kind": "iiif", "max_items": max_items}, # shown by `paratext inspect`
169
+ )
170
+ ```
171
+
172
+ Rules specific to sources:
173
+
174
+ - **`id` must be stable across runs** — resume and round-updating both key on it.
175
+ - **`metadata` is the contract between the two halves.** `_materialise` runs at
176
+ packaging time, long after iteration, and gets only the JSONL record.
177
+ - **Degrade loudly.** Falling back? `notices.append(...)`, and say what to do
178
+ about it.
179
+ - **`config` is descriptive only** — nothing reads it back to make decisions; it
180
+ exists so `paratext inspect` can show what preprocessing was applied.
181
+ - If your images need no special handling, reuse `packaging.default_materialise`
182
+ rather than writing the same six lines again.
183
+
184
+ A source can also pre-classify a sample to skip the model entirely: set
185
+ `metadata["preclassified"] = {...}` and `extract` writes it straight through
186
+ (this is how the verso filter avoids paying for blank card backs).
187
+
188
+ ## Recipe: a new export format
189
+
190
+ For a shape the built-in `hf` / `marc` / `dc` don't cover — EAD, MODS, a local ILS
191
+ format, a CSV for a spreadsheet workflow.
192
+
193
+ **Never re-derive which records are gold.** `records.select_records()` is the
194
+ single source of truth and every format shares it:
195
+
196
+ ```python
197
+ from paratext.records import select_records
198
+
199
+ sel = select_records(dataset_dir, project, db_path=db_path)
200
+ for rec in sel.records:
201
+ rec.label # {field: value} — the gold label
202
+ rec.status # verified | corrected | rejected
203
+ rec.verdict # the model's original verdict, kept for corrected rows
204
+ rec.document_id # stable id, falls back to rec.sid
205
+ rec.images # resolved paths (may be empty)
206
+ sel.schema_fields # field order from the Pydantic schema
207
+ sel.provenance # model, prompt_hash, schema_version
208
+ ```
209
+
210
+ Then follow `catalogue.py`'s shape — a pure `build_*(records, mapping)` that
211
+ returns bytes or a tree, and a `run()` that selects, builds and writes:
212
+
213
+ 1. Write `build_ead(records, mapping) -> ET.ElementTree` with no I/O, so it's
214
+ unit-testable without a dataset on disk.
215
+ 2. Add a `run(dataset_dir, project, fmt)` that calls `select_records`, builds,
216
+ and writes to `EXPORT_ROOT`.
217
+ 3. Plumb it into the CLI in `cli.py`: add the name to `--format`'s `choices`, to
218
+ `_FORMAT_MENU`, and to the `_cmd_export` dispatch.
219
+ 4. If fields need mapping to a target vocabulary, reuse `resolve_mapping()` —
220
+ config under `[project.<name>.export.<fmt>]` wins, then canonical inference by
221
+ field name, and anything left goes to the wizard. Unmapped fields are dropped
222
+ with a warning, **never** a hard error.
223
+
224
+ To expose it in the review UI's export modal as well, add a tab in
225
+ `review/static/app.js` (`openExportModal`) and an endpoint in `review/server.py`
226
+ alongside `_api_export_catalogue`.
227
+
228
+ ---
229
+
230
+ ## Conventions
231
+
232
+ - **Rounds.** `run` writes `review/<project>-r<N>`, keyed on the **prompt hash**:
233
+ editing `prompt.md` rolls a new round (the UI diffs the two latest); re-running
234
+ the same prompt updates the current round in place, keeping its annotations.
235
+ Rounds are linear — reverting a prompt starts a new round, it doesn't return to
236
+ the old one. `--round N` forces; `--fresh` rebuilds and discards annotations.
237
+ - **Reading feedback back into the prompt.** `annotations.db` holds verdicts and
238
+ notes (`annotations`) and human-corrected answers (`gold_labels`); read it via
239
+ `store.py`. With the server running, `GET /api/stats` gives accuracy and
240
+ eval-gold size. Tighten the fields reviewers corrected most.
241
+ The `annotations.corrections` column is unrelated — handwritten corrections on
242
+ the *card*, not reviewer edits.
243
+ - **Export gold** is `good_enough` rows (`_label_status: verified`) plus corrected
244
+ `gold_labels` rows (`corrected`). `_verdict` preserves the model's original
245
+ verdict, so accuracy still measures the model, not the human who fixed it.
246
+ - **`paratext.cards`** (verso filter, RetinaNet crop, show-through suppression) is
247
+ **off by default** and calibrated on one library's scans. Never assume it
248
+ transfers to another collection unchanged.
249
+ - **`paratext carbon` / `run --green`** is opt-in carbon-aware scheduling; the grid
250
+ region is declared in `[carbon]`, never auto-detected. Stdlib `urllib` only.
251
+ - **Config keys are kebab-case** (`base-url`), matching the CLI flag that sets
252
+ them. Snake_case still parses so old configs work, but generate kebab-case.
253
+ - **Bump `schema_version`** when a schema changes.
254
+ - **Commits:** short messages, no Co-Authored-By trailer.
paratext/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """paratext — metadata extraction from digitised collections with a multimodal model."""
2
+
3
+ __version__ = "0.1.0"