@kinloom/cli 0.1.1 → 0.3.0
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.
- package/dist/assets/cached-ocr.py +786 -0
- package/dist/assets/ocr.md +76 -0
- package/dist/assets/prep-scan.md +97 -0
- package/dist/assets/prep-scan.py +1313 -0
- package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
- package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
- package/dist/bundled-skills/archive-org/SKILL.md +162 -0
- package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
- package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
- package/dist/bundled-skills/california-archives/SKILL.md +130 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
- package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
- package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
- package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
- package/dist/bundled-skills/findagrave/SKILL.md +129 -0
- package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
- package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
- package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
- package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
- package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
- package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
- package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
- package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
- package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
- package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
- package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
- package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
- package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
- package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
- package/dist/bundled-skills/wikitree/SKILL.md +154 -0
- package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +488 -26
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +30 -5
- package/dist/client.js.map +1 -1
- package/dist/commands/ops/audit.d.ts +138 -0
- package/dist/commands/ops/audit.d.ts.map +1 -0
- package/dist/commands/ops/audit.js +872 -0
- package/dist/commands/ops/audit.js.map +1 -0
- package/dist/commands/ops/context.d.ts +100 -0
- package/dist/commands/ops/context.d.ts.map +1 -0
- package/dist/commands/ops/context.js +917 -0
- package/dist/commands/ops/context.js.map +1 -0
- package/dist/commands/ops/dates.d.ts +87 -0
- package/dist/commands/ops/dates.d.ts.map +1 -0
- package/dist/commands/ops/dates.js +228 -0
- package/dist/commands/ops/dates.js.map +1 -0
- package/dist/commands/ops/help.d.ts +8 -0
- package/dist/commands/ops/help.d.ts.map +1 -0
- package/dist/commands/ops/help.js +107 -0
- package/dist/commands/ops/help.js.map +1 -0
- package/dist/commands/ops/index.d.ts +8 -0
- package/dist/commands/ops/index.d.ts.map +1 -0
- package/dist/commands/ops/index.js +8 -0
- package/dist/commands/ops/index.js.map +1 -0
- package/dist/commands/ops/integrate.d.ts +61 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -0
- package/dist/commands/ops/integrate.js +1063 -0
- package/dist/commands/ops/integrate.js.map +1 -0
- package/dist/commands/ops/sync.d.ts +194 -0
- package/dist/commands/ops/sync.d.ts.map +1 -0
- package/dist/commands/ops/sync.js +1251 -0
- package/dist/commands/ops/sync.js.map +1 -0
- package/dist/commands/ops/telemetry.d.ts +79 -0
- package/dist/commands/ops/telemetry.d.ts.map +1 -0
- package/dist/commands/ops/telemetry.js +249 -0
- package/dist/commands/ops/telemetry.js.map +1 -0
- package/dist/commands/ops/verify.d.ts +76 -0
- package/dist/commands/ops/verify.d.ts.map +1 -0
- package/dist/commands/ops/verify.js +325 -0
- package/dist/commands/ops/verify.js.map +1 -0
- package/dist/commands/records/help.d.ts +18 -0
- package/dist/commands/records/help.d.ts.map +1 -0
- package/dist/commands/records/help.js +174 -0
- package/dist/commands/records/help.js.map +1 -0
- package/dist/commands/records/index.d.ts +5 -0
- package/dist/commands/records/index.d.ts.map +1 -0
- package/dist/commands/records/index.js +5 -0
- package/dist/commands/records/index.js.map +1 -0
- package/dist/commands/records/registry.d.ts +32 -0
- package/dist/commands/records/registry.d.ts.map +1 -0
- package/dist/commands/records/registry.js +227 -0
- package/dist/commands/records/registry.js.map +1 -0
- package/dist/commands/records/resolve.d.ts +14 -0
- package/dist/commands/records/resolve.d.ts.map +1 -0
- package/dist/commands/records/resolve.js +61 -0
- package/dist/commands/records/resolve.js.map +1 -0
- package/dist/commands/records/runner.d.ts +27 -0
- package/dist/commands/records/runner.d.ts.map +1 -0
- package/dist/commands/records/runner.js +255 -0
- package/dist/commands/records/runner.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
#!/usr/bin/env -S uv run --script
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.11"
|
|
4
|
+
# dependencies = [
|
|
5
|
+
# "click>=8.1",
|
|
6
|
+
# "httpx>=0.27",
|
|
7
|
+
# ]
|
|
8
|
+
# ///
|
|
9
|
+
"""CLI for UK/England genealogy: TNA Discovery API and FreeREG parish registers.
|
|
10
|
+
|
|
11
|
+
Verified live 2026-11-24 with plain HTTP (no API key):
|
|
12
|
+
|
|
13
|
+
- Discovery search: GET discovery.nationalarchives.gov.uk/API/search/v1/records
|
|
14
|
+
with sps.searchQuery, optional sps.dateFrom / sps.dateTo (YYYY-MM-DD), rows.
|
|
15
|
+
- Discovery detail: GET .../API/records/v1/details/<id> (not .../search/v1/...).
|
|
16
|
+
- FreeREG: GET home page for CSRF token, POST /search_queries with
|
|
17
|
+
search_query[...] fields; results HTML at /search_queries/<id>.
|
|
18
|
+
|
|
19
|
+
Nottinghamshire Archives CalmView (nawcat.nottinghamshire.gov.uk) timed out
|
|
20
|
+
from this host (45s+); no machine search is wired. Use `url --notts`.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import html as html_mod
|
|
27
|
+
import json
|
|
28
|
+
import math
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import time
|
|
32
|
+
from contextlib import contextmanager
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any, Callable, Iterator
|
|
35
|
+
from urllib.parse import quote, urlencode, urljoin
|
|
36
|
+
|
|
37
|
+
import click
|
|
38
|
+
import httpx
|
|
39
|
+
|
|
40
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
41
|
+
CACHE_SCHEMA = 1
|
|
42
|
+
|
|
43
|
+
DISCOVERY_SEARCH = "https://discovery.nationalarchives.gov.uk/API/search/v1/records"
|
|
44
|
+
DISCOVERY_DETAIL = "https://discovery.nationalarchives.gov.uk/API/records/v1/details"
|
|
45
|
+
DISCOVERY_WEB = "https://discovery.nationalarchives.gov.uk/details/r/"
|
|
46
|
+
FREEREG_BASE = "https://www.freereg.org.uk"
|
|
47
|
+
FREEREG_SEARCH = FREEREG_BASE + "/search_queries"
|
|
48
|
+
USER_AGENT = (
|
|
49
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
|
50
|
+
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# Chapman county codes (FreeREG). Extend as needed.
|
|
54
|
+
CHAPMAN: dict[str, str] = {
|
|
55
|
+
"nottinghamshire": "NTT",
|
|
56
|
+
"ntt": "NTT",
|
|
57
|
+
"london": "LND",
|
|
58
|
+
"lnd": "LND",
|
|
59
|
+
"kent": "KEN",
|
|
60
|
+
"ken": "KEN",
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
GENUKI_PARISHES: dict[str, str] = {
|
|
64
|
+
"england": "https://www.genuki.org.uk/big/eng",
|
|
65
|
+
"kent": "https://www.genuki.org.uk/big/eng/KEN",
|
|
66
|
+
"london": "https://www.genuki.org.uk/big/eng/LND",
|
|
67
|
+
"nottingham": "https://www.genuki.org.uk/big/eng/NTT/Nottingham",
|
|
68
|
+
"nottinghamshire": "https://www.genuki.org.uk/big/eng/NTT",
|
|
69
|
+
"yorkshire": "https://www.genuki.org.uk/big/eng/YKS",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def cache_dir() -> Path:
|
|
74
|
+
override = os.environ.get("KINLOOM_UK_ARCHIVES_CACHE_DIR")
|
|
75
|
+
if override:
|
|
76
|
+
return Path(override).expanduser()
|
|
77
|
+
return Path.home() / ".cache" / "kinloom-uk-archives"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
81
|
+
if cli_ttl is not None:
|
|
82
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
83
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
84
|
+
return float(cli_ttl)
|
|
85
|
+
raw = os.environ.get("KINLOOM_UK_ARCHIVES_CACHE_TTL_HOURS")
|
|
86
|
+
if raw is not None and raw.strip():
|
|
87
|
+
try:
|
|
88
|
+
parsed = float(raw.strip())
|
|
89
|
+
except ValueError as exc:
|
|
90
|
+
raise click.BadParameter(
|
|
91
|
+
f"Invalid KINLOOM_UK_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}."
|
|
92
|
+
) from exc
|
|
93
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
94
|
+
raise click.BadParameter(
|
|
95
|
+
f"Invalid KINLOOM_UK_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
|
|
96
|
+
)
|
|
97
|
+
return parsed
|
|
98
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@contextmanager
|
|
102
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
103
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
104
|
+
try:
|
|
105
|
+
import fcntl
|
|
106
|
+
except ImportError:
|
|
107
|
+
yield
|
|
108
|
+
return
|
|
109
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
with open(lock_path, "a+b") as lock_file:
|
|
111
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
112
|
+
try:
|
|
113
|
+
yield
|
|
114
|
+
finally:
|
|
115
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
119
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
120
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
121
|
+
try:
|
|
122
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
123
|
+
os.replace(tmp, dest)
|
|
124
|
+
except Exception:
|
|
125
|
+
tmp.unlink(missing_ok=True)
|
|
126
|
+
raise
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
130
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
131
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
135
|
+
if not path.is_file():
|
|
136
|
+
return None
|
|
137
|
+
try:
|
|
138
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
139
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
140
|
+
return None
|
|
141
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
142
|
+
return None
|
|
143
|
+
fetched = entry.get("fetched_at")
|
|
144
|
+
if not isinstance(fetched, (int, float)):
|
|
145
|
+
return None
|
|
146
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
147
|
+
return None
|
|
148
|
+
result = entry.get("result")
|
|
149
|
+
return result if isinstance(result, dict) else None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def cached_call(
|
|
153
|
+
kind: str,
|
|
154
|
+
payload: dict,
|
|
155
|
+
fetch: Callable[[], dict],
|
|
156
|
+
*,
|
|
157
|
+
refresh: bool,
|
|
158
|
+
ttl_hours: float,
|
|
159
|
+
cacheable: Callable[[dict], bool] = lambda _r: True,
|
|
160
|
+
) -> tuple[dict, bool]:
|
|
161
|
+
"""Return (result, cache_hit) with per-key flock and atomic JSON writes."""
|
|
162
|
+
key = cache_key(kind, payload)
|
|
163
|
+
root = cache_dir()
|
|
164
|
+
path = root / f"{key}.json"
|
|
165
|
+
if not refresh:
|
|
166
|
+
hit = read_cache(path, ttl_hours)
|
|
167
|
+
if hit is not None:
|
|
168
|
+
return hit, True
|
|
169
|
+
with file_lock(root / f"{key}.lock"):
|
|
170
|
+
if not refresh:
|
|
171
|
+
hit = read_cache(path, ttl_hours)
|
|
172
|
+
if hit is not None:
|
|
173
|
+
return hit, True
|
|
174
|
+
result = fetch()
|
|
175
|
+
if cacheable(result):
|
|
176
|
+
atomic_write_json(
|
|
177
|
+
path,
|
|
178
|
+
{
|
|
179
|
+
"schema": CACHE_SCHEMA,
|
|
180
|
+
"fetched_at": time.time(),
|
|
181
|
+
"kind": kind,
|
|
182
|
+
"query": payload,
|
|
183
|
+
"result": result,
|
|
184
|
+
},
|
|
185
|
+
)
|
|
186
|
+
return result, False
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def cache_options(func: Callable) -> Callable:
|
|
190
|
+
func = click.option(
|
|
191
|
+
"--cache-ttl-hours",
|
|
192
|
+
type=float,
|
|
193
|
+
default=None,
|
|
194
|
+
help="Cache TTL in hours (default 168, env KINLOOM_UK_ARCHIVES_CACHE_TTL_HOURS; 0 disables reads).",
|
|
195
|
+
)(func)
|
|
196
|
+
func = click.option(
|
|
197
|
+
"--refresh",
|
|
198
|
+
is_flag=True,
|
|
199
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).",
|
|
200
|
+
)(func)
|
|
201
|
+
return func
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _client() -> httpx.Client:
|
|
205
|
+
return httpx.Client(headers={"User-Agent": USER_AGENT}, timeout=90.0, follow_redirects=True)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _date_from(value: str | None) -> str | None:
|
|
209
|
+
if not value:
|
|
210
|
+
return None
|
|
211
|
+
value = value.strip()
|
|
212
|
+
if re.fullmatch(r"\d{4}", value):
|
|
213
|
+
return f"{value}-01-01"
|
|
214
|
+
return value
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _date_to(value: str | None) -> str | None:
|
|
218
|
+
if not value:
|
|
219
|
+
return None
|
|
220
|
+
value = value.strip()
|
|
221
|
+
if re.fullmatch(r"\d{4}", value):
|
|
222
|
+
return f"{value}-12-31"
|
|
223
|
+
return value
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _discovery_query(query: str, held_by: str | None, collection: str | None) -> str:
|
|
227
|
+
parts = [query.strip()]
|
|
228
|
+
if held_by:
|
|
229
|
+
parts.append(held_by.strip())
|
|
230
|
+
if collection:
|
|
231
|
+
parts.append(f'"{collection.strip()}"')
|
|
232
|
+
return " ".join(p for p in parts if p)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _discovery_hit(rec: dict) -> dict:
|
|
236
|
+
rec_id = rec.get("id") or ""
|
|
237
|
+
ref = rec.get("reference") or ""
|
|
238
|
+
return {
|
|
239
|
+
"id": rec_id,
|
|
240
|
+
"reference": ref,
|
|
241
|
+
"title": rec.get("title") or "",
|
|
242
|
+
"description": rec.get("description") or "",
|
|
243
|
+
"covering_dates": rec.get("coveringDates") or "",
|
|
244
|
+
"department": rec.get("department") or "",
|
|
245
|
+
"places": rec.get("places") or [],
|
|
246
|
+
"held_by": rec.get("heldBy") or [],
|
|
247
|
+
"record_url": DISCOVERY_WEB + rec_id if rec_id else "",
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _collection_match(rec: dict, collection: str) -> bool:
|
|
252
|
+
coll = collection.strip()
|
|
253
|
+
ref = rec.get("reference") or ""
|
|
254
|
+
if coll.upper().startswith("PROB"):
|
|
255
|
+
return ref.upper().startswith(coll.upper())
|
|
256
|
+
return coll.upper() in ref.upper() or coll.upper() in (rec.get("title") or "").upper()
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _discovery_detail_payload(raw: dict) -> dict:
|
|
260
|
+
scope = raw.get("scopeContent") or {}
|
|
261
|
+
desc = scope.get("description") if isinstance(scope, dict) else None
|
|
262
|
+
if desc and isinstance(desc, str):
|
|
263
|
+
desc = re.sub(r"<[^>]+>", " ", html_mod.unescape(desc))
|
|
264
|
+
desc = re.sub(r"\s+", " ", desc).strip()
|
|
265
|
+
held = raw.get("heldBy") or []
|
|
266
|
+
held_names = []
|
|
267
|
+
for item in held:
|
|
268
|
+
if isinstance(item, dict):
|
|
269
|
+
held_names.append(item.get("xReferenceName") or item.get("name") or "")
|
|
270
|
+
elif isinstance(item, str):
|
|
271
|
+
held_names.append(item)
|
|
272
|
+
return {
|
|
273
|
+
"id": raw.get("id"),
|
|
274
|
+
"citable_reference": raw.get("citableReference") or raw.get("referencePart"),
|
|
275
|
+
"covering_dates": raw.get("coveringDates"),
|
|
276
|
+
"description": desc,
|
|
277
|
+
"held_by": [h for h in held_names if h],
|
|
278
|
+
"digitised": raw.get("digitised"),
|
|
279
|
+
"legal_status": raw.get("legalStatus"),
|
|
280
|
+
"catalogue_level": raw.get("catalogueLevel"),
|
|
281
|
+
"record_url": DISCOVERY_WEB + (raw.get("id") or ""),
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _freereg_token(html: str) -> str:
|
|
286
|
+
m = re.search(r'name="authenticity_token" value="([^"]+)"', html)
|
|
287
|
+
if not m:
|
|
288
|
+
raise click.ClickException("FreeREG authenticity_token not found (page layout may have changed).")
|
|
289
|
+
return m.group(1)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def parse_freereg_results(page: str) -> list[dict]:
|
|
293
|
+
"""Parse FreeREG search results table rows."""
|
|
294
|
+
tbody = re.search(r"<tbody>(.*?)</tbody>", page, re.S | re.I)
|
|
295
|
+
if not tbody:
|
|
296
|
+
return []
|
|
297
|
+
out: list[dict] = []
|
|
298
|
+
for tr in re.finditer(r'<tr id="([^"]+)"[^>]*>(.*?)</tr>', tbody.group(1), re.S | re.I):
|
|
299
|
+
row_id = tr.group(1)
|
|
300
|
+
inner = tr.group(2)
|
|
301
|
+
link_m = re.search(r'href="([^"]+)"[^>]*>\s*View\s*\d+', inner, re.I)
|
|
302
|
+
path = link_m.group(1) if link_m else ""
|
|
303
|
+
cells = re.findall(r"<td[^>]*>(.*?)</td>", inner, re.S | re.I)
|
|
304
|
+
if len(cells) < 5:
|
|
305
|
+
continue
|
|
306
|
+
clean = []
|
|
307
|
+
for c in cells[1:]:
|
|
308
|
+
text = html_mod.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", c))).strip()
|
|
309
|
+
clean.append(text)
|
|
310
|
+
persons, record_type, event_date, county, register = (clean + [""] * 5)[:5]
|
|
311
|
+
out.append({
|
|
312
|
+
"transcript_id": row_id,
|
|
313
|
+
"persons": persons,
|
|
314
|
+
"record_type": record_type,
|
|
315
|
+
"event_date": event_date,
|
|
316
|
+
"county": county,
|
|
317
|
+
"register": register,
|
|
318
|
+
"transcript_url": urljoin(FREEREG_BASE, path) if path else "",
|
|
319
|
+
})
|
|
320
|
+
return out
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _get_json(url: str, *, params: dict[str, Any] | None = None, label: str) -> dict:
|
|
324
|
+
try:
|
|
325
|
+
with _client() as c:
|
|
326
|
+
resp = c.get(url, params=params)
|
|
327
|
+
resp.raise_for_status()
|
|
328
|
+
except httpx.HTTPStatusError as exc:
|
|
329
|
+
raise click.ClickException(f"{label} returned HTTP {exc.response.status_code}") from exc
|
|
330
|
+
except httpx.HTTPError as exc:
|
|
331
|
+
raise click.ClickException(f"{label} request failed: {exc}") from exc
|
|
332
|
+
try:
|
|
333
|
+
data = resp.json()
|
|
334
|
+
except ValueError as exc:
|
|
335
|
+
raise click.ClickException(f"{label} returned non-JSON: {exc}") from exc
|
|
336
|
+
if not isinstance(data, dict):
|
|
337
|
+
raise click.ClickException(f"{label} returned unexpected JSON shape")
|
|
338
|
+
return data
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
342
|
+
def cli() -> None:
|
|
343
|
+
"""Search UK archives: TNA Discovery and FreeREG parish registers."""
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
@cli.group("discovery")
|
|
347
|
+
def discovery() -> None:
|
|
348
|
+
"""The National Archives Discovery catalogue (free JSON API)."""
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
@discovery.command("search")
|
|
352
|
+
@click.argument("query", required=False, default=None)
|
|
353
|
+
@click.option("--query", "-q", "query_opt", default=None, help="Alias for positional QUERY.")
|
|
354
|
+
@click.option("--held-by", default=None, help="Extra text added to the query (e.g. Nottinghamshire).")
|
|
355
|
+
@click.option("--date-from", "--from-year", "date_from", default=None, help="Covering date from (YYYY or YYYY-MM-DD).")
|
|
356
|
+
@click.option("--date-to", "--to-year", "date_to", default=None, help="Covering date to (YYYY or YYYY-MM-DD).")
|
|
357
|
+
@click.option(
|
|
358
|
+
"--collection",
|
|
359
|
+
default=None,
|
|
360
|
+
help='Filter hits whose reference/title match this string (e.g. PROB 11). Also appended to the query.',
|
|
361
|
+
)
|
|
362
|
+
@click.option("--limit", default=10, show_default=True, type=int, help="Maximum records to return (API rows).")
|
|
363
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
364
|
+
@cache_options
|
|
365
|
+
def cmd_discovery_search(
|
|
366
|
+
query: str | None,
|
|
367
|
+
query_opt: str | None,
|
|
368
|
+
held_by: str | None,
|
|
369
|
+
date_from: str | None,
|
|
370
|
+
date_to: str | None,
|
|
371
|
+
collection: str | None,
|
|
372
|
+
limit: int,
|
|
373
|
+
as_json: bool,
|
|
374
|
+
refresh: bool,
|
|
375
|
+
cache_ttl_hours: float | None,
|
|
376
|
+
) -> None:
|
|
377
|
+
"""Search Discovery for catalogue records."""
|
|
378
|
+
resolved_query = query if query is not None else query_opt
|
|
379
|
+
if not resolved_query:
|
|
380
|
+
raise click.UsageError("Provide QUERY as a positional argument or via --query.")
|
|
381
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
382
|
+
q = _discovery_query(resolved_query, held_by, collection)
|
|
383
|
+
params: dict[str, str | int] = {"sps.searchQuery": q, "rows": min(max(limit, 1), 100)}
|
|
384
|
+
df = _date_from(date_from)
|
|
385
|
+
dt = _date_to(date_to)
|
|
386
|
+
if df:
|
|
387
|
+
params["sps.dateFrom"] = df
|
|
388
|
+
if dt:
|
|
389
|
+
params["sps.dateTo"] = dt
|
|
390
|
+
|
|
391
|
+
def _fetch() -> dict:
|
|
392
|
+
return _get_json(DISCOVERY_SEARCH, params=params, label="Discovery search")
|
|
393
|
+
|
|
394
|
+
data, hit = cached_call(
|
|
395
|
+
"discovery_search",
|
|
396
|
+
params,
|
|
397
|
+
_fetch,
|
|
398
|
+
refresh=refresh,
|
|
399
|
+
ttl_hours=ttl,
|
|
400
|
+
cacheable=lambda r: isinstance(r.get("records"), list) and (bool(r["records"]) or int(r.get("count") or 0) > 0),
|
|
401
|
+
)
|
|
402
|
+
records = [_discovery_hit(r) for r in data.get("records") or []]
|
|
403
|
+
if collection:
|
|
404
|
+
records = [r for r in records if _collection_match(
|
|
405
|
+
{"reference": r["reference"], "department": r["department"], "title": r["title"]},
|
|
406
|
+
collection,
|
|
407
|
+
)]
|
|
408
|
+
records = records[:limit]
|
|
409
|
+
total = data.get("count", len(records))
|
|
410
|
+
if as_json:
|
|
411
|
+
click.echo(
|
|
412
|
+
json.dumps(
|
|
413
|
+
{"query": q, "total": total, "returned": len(records), "records": records, "cache_hit": hit},
|
|
414
|
+
indent=1,
|
|
415
|
+
)
|
|
416
|
+
)
|
|
417
|
+
return
|
|
418
|
+
marker = " [cache]" if hit else ""
|
|
419
|
+
click.echo(f'{total} hit(s) for "{q}"; showing {len(records)}:{marker}')
|
|
420
|
+
for rec in records:
|
|
421
|
+
places = ", ".join(rec["places"]) if rec["places"] else ""
|
|
422
|
+
click.echo(f'{rec["id"]} {rec["reference"]} {rec["covering_dates"]}')
|
|
423
|
+
click.echo(f' {rec["title"]}')
|
|
424
|
+
if places:
|
|
425
|
+
click.echo(f" Places: {places}")
|
|
426
|
+
click.echo(f" {rec['record_url']}")
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
@discovery.command("detail")
|
|
430
|
+
@click.argument("record_id")
|
|
431
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
432
|
+
@cache_options
|
|
433
|
+
def cmd_discovery_detail(
|
|
434
|
+
record_id: str,
|
|
435
|
+
as_json: bool,
|
|
436
|
+
refresh: bool,
|
|
437
|
+
cache_ttl_hours: float | None,
|
|
438
|
+
) -> None:
|
|
439
|
+
"""Fetch one Discovery record by id (e.g. <record-id>)."""
|
|
440
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
441
|
+
url = f"{DISCOVERY_DETAIL}/{record_id}"
|
|
442
|
+
|
|
443
|
+
def _fetch() -> dict:
|
|
444
|
+
return _get_json(url, label="Discovery detail")
|
|
445
|
+
|
|
446
|
+
raw, hit = cached_call(
|
|
447
|
+
"discovery_detail",
|
|
448
|
+
{"id": record_id},
|
|
449
|
+
_fetch,
|
|
450
|
+
refresh=refresh,
|
|
451
|
+
ttl_hours=ttl,
|
|
452
|
+
cacheable=lambda r: bool(r.get("id") or r.get("citableReference") or r.get("referencePart")),
|
|
453
|
+
)
|
|
454
|
+
detail = _discovery_detail_payload(raw)
|
|
455
|
+
if as_json:
|
|
456
|
+
click.echo(json.dumps({**detail, "cache_hit": hit}, indent=1))
|
|
457
|
+
return
|
|
458
|
+
marker = " [cache]" if hit else ""
|
|
459
|
+
click.echo(f'{detail["id"]} {detail["citable_reference"]} {detail["covering_dates"]}{marker}')
|
|
460
|
+
if detail["description"]:
|
|
461
|
+
click.echo(f' {detail["description"]}')
|
|
462
|
+
if detail["held_by"]:
|
|
463
|
+
click.echo(" Held by: " + "; ".join(detail["held_by"]))
|
|
464
|
+
click.echo(f' Digitised: {detail["digitised"]} Legal status: {detail["legal_status"] or "n/a"}')
|
|
465
|
+
click.echo(f' {detail["record_url"]}')
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
discovery.add_command(cmd_discovery_detail, name="inspect")
|
|
469
|
+
discovery.add_command(cmd_discovery_detail, name="get")
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
@cli.group("freereg")
|
|
473
|
+
def freereg() -> None:
|
|
474
|
+
"""FreeREG parish register transcriptions (Rails form POST, no API key)."""
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
@freereg.command("search")
|
|
478
|
+
@click.option("--surname", required=True, help="Last name (required).")
|
|
479
|
+
@click.option("--given", default=None, help="First name.")
|
|
480
|
+
@click.option(
|
|
481
|
+
"--county",
|
|
482
|
+
default="NTT",
|
|
483
|
+
show_default=True,
|
|
484
|
+
help="Chapman county code or name (e.g. NTT / nottinghamshire).",
|
|
485
|
+
)
|
|
486
|
+
@click.option("--from-year", "--date-from", "from_year", default=None, help="Start year (YYYY).")
|
|
487
|
+
@click.option("--to-year", "--date-to", "to_year", default=None, help="End year (YYYY).")
|
|
488
|
+
@click.option(
|
|
489
|
+
"--record-type",
|
|
490
|
+
"record_type",
|
|
491
|
+
type=click.Choice(["all", "baptism", "marriage", "burial"], case_sensitive=False),
|
|
492
|
+
default="all",
|
|
493
|
+
show_default=True,
|
|
494
|
+
)
|
|
495
|
+
@click.option("--place-contains", default=None, help="Keep only hits whose register column contains this text.")
|
|
496
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
497
|
+
@cache_options
|
|
498
|
+
def cmd_freereg_search(
|
|
499
|
+
surname: str,
|
|
500
|
+
given: str | None,
|
|
501
|
+
county: str,
|
|
502
|
+
from_year: str | None,
|
|
503
|
+
to_year: str | None,
|
|
504
|
+
record_type: str,
|
|
505
|
+
place_contains: str | None,
|
|
506
|
+
as_json: bool,
|
|
507
|
+
refresh: bool,
|
|
508
|
+
cache_ttl_hours: float | None,
|
|
509
|
+
) -> None:
|
|
510
|
+
"""Search FreeREG parish register transcriptions."""
|
|
511
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
512
|
+
chapman = CHAPMAN.get(county.strip().lower(), county.strip().upper())
|
|
513
|
+
rt_key = record_type.lower()
|
|
514
|
+
rt_map = {"all": "", "baptism": "ba", "marriage": "ma", "burial": "bu"}
|
|
515
|
+
form_data: dict[str, str] = {
|
|
516
|
+
"utf8": "✓",
|
|
517
|
+
"search_query[last_name]": surname,
|
|
518
|
+
"search_query[chapman_codes][]": chapman,
|
|
519
|
+
"commit": "Search",
|
|
520
|
+
}
|
|
521
|
+
if given:
|
|
522
|
+
form_data["search_query[first_name]"] = given
|
|
523
|
+
if from_year:
|
|
524
|
+
form_data["search_query[start_year]"] = from_year
|
|
525
|
+
if to_year:
|
|
526
|
+
form_data["search_query[end_year]"] = to_year
|
|
527
|
+
rt = rt_map[rt_key]
|
|
528
|
+
if rt:
|
|
529
|
+
form_data["search_query[record_type]"] = rt
|
|
530
|
+
|
|
531
|
+
query_payload = {
|
|
532
|
+
"surname": surname.strip().lower(),
|
|
533
|
+
"given": (given or "").strip().lower(),
|
|
534
|
+
"county": chapman,
|
|
535
|
+
"from_year": (from_year or "").strip(),
|
|
536
|
+
"to_year": (to_year or "").strip(),
|
|
537
|
+
"record_type": rt_key,
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
def _fetch() -> dict:
|
|
541
|
+
post_data = dict(form_data)
|
|
542
|
+
try:
|
|
543
|
+
with _client() as c:
|
|
544
|
+
home = c.get(FREEREG_BASE + "/")
|
|
545
|
+
home.raise_for_status()
|
|
546
|
+
post_data["authenticity_token"] = _freereg_token(home.text)
|
|
547
|
+
resp = c.post(FREEREG_SEARCH, data=post_data)
|
|
548
|
+
resp.raise_for_status()
|
|
549
|
+
except httpx.HTTPStatusError as exc:
|
|
550
|
+
raise click.ClickException(f"FreeREG returned HTTP {exc.response.status_code}") from exc
|
|
551
|
+
except httpx.HTTPError as exc:
|
|
552
|
+
raise click.ClickException(f"FreeREG request failed: {exc}") from exc
|
|
553
|
+
return {"records": parse_freereg_results(resp.text)}
|
|
554
|
+
|
|
555
|
+
cached_data, hit = cached_call(
|
|
556
|
+
"freereg_search",
|
|
557
|
+
query_payload,
|
|
558
|
+
_fetch,
|
|
559
|
+
refresh=refresh,
|
|
560
|
+
ttl_hours=ttl,
|
|
561
|
+
cacheable=lambda r: bool(r.get("records")),
|
|
562
|
+
)
|
|
563
|
+
records = list(cached_data.get("records") or [])
|
|
564
|
+
if place_contains:
|
|
565
|
+
needle = place_contains.lower()
|
|
566
|
+
records = [r for r in records if needle in r["register"].lower()]
|
|
567
|
+
if as_json:
|
|
568
|
+
click.echo(
|
|
569
|
+
json.dumps(
|
|
570
|
+
{"surname": surname, "county": chapman, "returned": len(records), "records": records, "cache_hit": hit},
|
|
571
|
+
indent=1,
|
|
572
|
+
)
|
|
573
|
+
)
|
|
574
|
+
return
|
|
575
|
+
marker = " [cache]" if hit else ""
|
|
576
|
+
click.echo(f"{len(records)} FreeREG hit(s) for {surname} ({chapman}):{marker}")
|
|
577
|
+
for rec in records:
|
|
578
|
+
click.echo(f'{rec["event_date"]} {rec["record_type"]} {rec["persons"]}')
|
|
579
|
+
click.echo(f' {rec["register"]} ({rec["county"]})')
|
|
580
|
+
if rec["transcript_url"]:
|
|
581
|
+
click.echo(f' {rec["transcript_url"]}')
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
@cli.command("url")
|
|
585
|
+
@click.option("--discovery", "discovery_query", default=None, help="Discovery web search URL for a query.")
|
|
586
|
+
@click.option("--freereg", is_flag=True, help="FreeREG search form home.")
|
|
587
|
+
@click.option("--notts", "notts_query", default=None, help="Nottinghamshire Archives CalmView search hint (browser).")
|
|
588
|
+
@click.option("--bho", "bho_query", default=None, help="British History Online search query.")
|
|
589
|
+
@click.option(
|
|
590
|
+
"--genuki",
|
|
591
|
+
type=click.Choice(list(GENUKI_PARISHES.keys())),
|
|
592
|
+
default=None,
|
|
593
|
+
help="GENUKI county/parish page for England research.",
|
|
594
|
+
)
|
|
595
|
+
def cmd_url(
|
|
596
|
+
discovery_query: str | None,
|
|
597
|
+
freereg: bool,
|
|
598
|
+
notts_query: str | None,
|
|
599
|
+
bho_query: str | None,
|
|
600
|
+
genuki: str | None,
|
|
601
|
+
) -> None:
|
|
602
|
+
"""Print verified portal URLs (no search is run)."""
|
|
603
|
+
if discovery_query:
|
|
604
|
+
click.echo(
|
|
605
|
+
"https://discovery.nationalarchives.gov.uk/results/r?"
|
|
606
|
+
+ urlencode({"_q": discovery_query, "_p": 100}, quote_via=quote)
|
|
607
|
+
)
|
|
608
|
+
if freereg:
|
|
609
|
+
click.echo(FREEREG_BASE + "/")
|
|
610
|
+
if notts_query is not None:
|
|
611
|
+
click.echo("https://nawcat.nottinghamshire.gov.uk/CalmView/")
|
|
612
|
+
click.echo(
|
|
613
|
+
" (browser-only: HTTPS to nawcat timed out after 45s in automated checks; "
|
|
614
|
+
f"search in CalmView for: {notts_query or 'Lincoln'})"
|
|
615
|
+
)
|
|
616
|
+
if bho_query:
|
|
617
|
+
click.echo(
|
|
618
|
+
"https://www.british-history.ac.uk/search?"
|
|
619
|
+
+ urlencode({"query": bho_query})
|
|
620
|
+
)
|
|
621
|
+
if genuki:
|
|
622
|
+
click.echo(GENUKI_PARISHES[genuki])
|
|
623
|
+
if not any([discovery_query, freereg, notts_query is not None, bho_query, genuki]):
|
|
624
|
+
click.echo(DISCOVERY_WEB.rstrip("/"))
|
|
625
|
+
click.echo(FREEREG_BASE + "/")
|
|
626
|
+
click.echo("https://www.british-history.ac.uk/")
|
|
627
|
+
click.echo(GENUKI_PARISHES["nottinghamshire"])
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
if __name__ == "__main__":
|
|
631
|
+
cli()
|