@kinloom/cli 0.2.0 → 0.3.1
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 +346 -116
- package/dist/assets/ocr.md +25 -1
- package/dist/assets/prep-scan.md +42 -4
- package/dist/assets/prep-scan.py +432 -10
- package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
- package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
- package/dist/bundled-skills/archive-org/SKILL.md +40 -7
- package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
- package/dist/bundled-skills/california-archives/SKILL.md +10 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
- package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
- package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
- package/dist/bundled-skills/findagrave/SKILL.md +18 -5
- package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
- package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
- package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
- package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
- package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
- package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
- package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
- package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
- package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
- package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
- package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
- package/dist/bundled-skills/wikitree/SKILL.md +7 -1
- package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +107 -2
- 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.map +1 -1
- package/dist/commands/ops/audit.js +5 -0
- package/dist/commands/ops/audit.js.map +1 -1
- 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 +3 -1
- package/dist/commands/ops/help.d.ts.map +1 -1
- package/dist/commands/ops/help.js +33 -0
- package/dist/commands/ops/help.js.map +1 -1
- package/dist/commands/ops/index.d.ts +3 -1
- package/dist/commands/ops/index.d.ts.map +1 -1
- package/dist/commands/ops/index.js +2 -0
- package/dist/commands/ops/index.js.map +1 -1
- package/dist/commands/ops/integrate.d.ts +5 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -1
- package/dist/commands/ops/integrate.js +272 -26
- package/dist/commands/ops/integrate.js.map +1 -1
- package/dist/commands/ops/sync.d.ts +17 -0
- package/dist/commands/ops/sync.d.ts.map +1 -1
- package/dist/commands/ops/sync.js +173 -0
- package/dist/commands/ops/sync.js.map +1 -1
- 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/index.d.ts +1 -1
- package/dist/commands/records/index.d.ts.map +1 -1
- package/dist/commands/records/index.js +1 -1
- package/dist/commands/records/index.js.map +1 -1
- package/dist/commands/records/runner.d.ts +2 -0
- package/dist/commands/records/runner.d.ts.map +1 -1
- package/dist/commands/records/runner.js +33 -2
- package/dist/commands/records/runner.js.map +1 -1
- package/package.json +2 -2
|
@@ -22,14 +22,24 @@ from this host (45s+); no machine search is wired. Use `url --notts`.
|
|
|
22
22
|
|
|
23
23
|
from __future__ import annotations
|
|
24
24
|
|
|
25
|
+
import hashlib
|
|
25
26
|
import html as html_mod
|
|
26
27
|
import json
|
|
28
|
+
import math
|
|
29
|
+
import os
|
|
27
30
|
import re
|
|
31
|
+
import time
|
|
32
|
+
from contextlib import contextmanager
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any, Callable, Iterator
|
|
28
35
|
from urllib.parse import quote, urlencode, urljoin
|
|
29
36
|
|
|
30
37
|
import click
|
|
31
38
|
import httpx
|
|
32
39
|
|
|
40
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
41
|
+
CACHE_SCHEMA = 1
|
|
42
|
+
|
|
33
43
|
DISCOVERY_SEARCH = "https://discovery.nationalarchives.gov.uk/API/search/v1/records"
|
|
34
44
|
DISCOVERY_DETAIL = "https://discovery.nationalarchives.gov.uk/API/records/v1/details"
|
|
35
45
|
DISCOVERY_WEB = "https://discovery.nationalarchives.gov.uk/details/r/"
|
|
@@ -60,6 +70,137 @@ GENUKI_PARISHES: dict[str, str] = {
|
|
|
60
70
|
}
|
|
61
71
|
|
|
62
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
|
+
|
|
63
204
|
def _client() -> httpx.Client:
|
|
64
205
|
return httpx.Client(headers={"User-Agent": USER_AGENT}, timeout=90.0, follow_redirects=True)
|
|
65
206
|
|
|
@@ -179,6 +320,24 @@ def parse_freereg_results(page: str) -> list[dict]:
|
|
|
179
320
|
return out
|
|
180
321
|
|
|
181
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
|
+
|
|
182
341
|
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
183
342
|
def cli() -> None:
|
|
184
343
|
"""Search UK archives: TNA Discovery and FreeREG parish registers."""
|
|
@@ -190,10 +349,11 @@ def discovery() -> None:
|
|
|
190
349
|
|
|
191
350
|
|
|
192
351
|
@discovery.command("search")
|
|
193
|
-
@click.argument("query")
|
|
352
|
+
@click.argument("query", required=False, default=None)
|
|
353
|
+
@click.option("--query", "-q", "query_opt", default=None, help="Alias for positional QUERY.")
|
|
194
354
|
@click.option("--held-by", default=None, help="Extra text added to the query (e.g. Nottinghamshire).")
|
|
195
|
-
@click.option("--date-from", "date_from", default=None, help="Covering date from (YYYY or YYYY-MM-DD).")
|
|
196
|
-
@click.option("--date-to", "date_to", default=None, help="Covering date to (YYYY or YYYY-MM-DD).")
|
|
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).")
|
|
197
357
|
@click.option(
|
|
198
358
|
"--collection",
|
|
199
359
|
default=None,
|
|
@@ -201,17 +361,25 @@ def discovery() -> None:
|
|
|
201
361
|
)
|
|
202
362
|
@click.option("--limit", default=10, show_default=True, type=int, help="Maximum records to return (API rows).")
|
|
203
363
|
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
364
|
+
@cache_options
|
|
204
365
|
def cmd_discovery_search(
|
|
205
|
-
query: str,
|
|
366
|
+
query: str | None,
|
|
367
|
+
query_opt: str | None,
|
|
206
368
|
held_by: str | None,
|
|
207
369
|
date_from: str | None,
|
|
208
370
|
date_to: str | None,
|
|
209
371
|
collection: str | None,
|
|
210
372
|
limit: int,
|
|
211
373
|
as_json: bool,
|
|
374
|
+
refresh: bool,
|
|
375
|
+
cache_ttl_hours: float | None,
|
|
212
376
|
) -> None:
|
|
213
377
|
"""Search Discovery for catalogue records."""
|
|
214
|
-
|
|
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)
|
|
215
383
|
params: dict[str, str | int] = {"sps.searchQuery": q, "rows": min(max(limit, 1), 100)}
|
|
216
384
|
df = _date_from(date_from)
|
|
217
385
|
dt = _date_to(date_to)
|
|
@@ -219,10 +387,18 @@ def cmd_discovery_search(
|
|
|
219
387
|
params["sps.dateFrom"] = df
|
|
220
388
|
if dt:
|
|
221
389
|
params["sps.dateTo"] = dt
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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
|
+
)
|
|
226
402
|
records = [_discovery_hit(r) for r in data.get("records") or []]
|
|
227
403
|
if collection:
|
|
228
404
|
records = [r for r in records if _collection_match(
|
|
@@ -232,9 +408,15 @@ def cmd_discovery_search(
|
|
|
232
408
|
records = records[:limit]
|
|
233
409
|
total = data.get("count", len(records))
|
|
234
410
|
if as_json:
|
|
235
|
-
click.echo(
|
|
411
|
+
click.echo(
|
|
412
|
+
json.dumps(
|
|
413
|
+
{"query": q, "total": total, "returned": len(records), "records": records, "cache_hit": hit},
|
|
414
|
+
indent=1,
|
|
415
|
+
)
|
|
416
|
+
)
|
|
236
417
|
return
|
|
237
|
-
|
|
418
|
+
marker = " [cache]" if hit else ""
|
|
419
|
+
click.echo(f'{total} hit(s) for "{q}"; showing {len(records)}:{marker}')
|
|
238
420
|
for rec in records:
|
|
239
421
|
places = ", ".join(rec["places"]) if rec["places"] else ""
|
|
240
422
|
click.echo(f'{rec["id"]} {rec["reference"]} {rec["covering_dates"]}')
|
|
@@ -247,18 +429,34 @@ def cmd_discovery_search(
|
|
|
247
429
|
@discovery.command("detail")
|
|
248
430
|
@click.argument("record_id")
|
|
249
431
|
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
250
|
-
|
|
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:
|
|
251
439
|
"""Fetch one Discovery record by id (e.g. <record-id>)."""
|
|
440
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
252
441
|
url = f"{DISCOVERY_DETAIL}/{record_id}"
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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
|
+
)
|
|
257
454
|
detail = _discovery_detail_payload(raw)
|
|
258
455
|
if as_json:
|
|
259
|
-
click.echo(json.dumps(detail, indent=1))
|
|
456
|
+
click.echo(json.dumps({**detail, "cache_hit": hit}, indent=1))
|
|
260
457
|
return
|
|
261
|
-
|
|
458
|
+
marker = " [cache]" if hit else ""
|
|
459
|
+
click.echo(f'{detail["id"]} {detail["citable_reference"]} {detail["covering_dates"]}{marker}')
|
|
262
460
|
if detail["description"]:
|
|
263
461
|
click.echo(f' {detail["description"]}')
|
|
264
462
|
if detail["held_by"]:
|
|
@@ -267,6 +465,10 @@ def cmd_discovery_detail(record_id: str, as_json: bool) -> None:
|
|
|
267
465
|
click.echo(f' {detail["record_url"]}')
|
|
268
466
|
|
|
269
467
|
|
|
468
|
+
discovery.add_command(cmd_discovery_detail, name="inspect")
|
|
469
|
+
discovery.add_command(cmd_discovery_detail, name="get")
|
|
470
|
+
|
|
471
|
+
|
|
270
472
|
@cli.group("freereg")
|
|
271
473
|
def freereg() -> None:
|
|
272
474
|
"""FreeREG parish register transcriptions (Rails form POST, no API key)."""
|
|
@@ -281,8 +483,8 @@ def freereg() -> None:
|
|
|
281
483
|
show_default=True,
|
|
282
484
|
help="Chapman county code or name (e.g. NTT / nottinghamshire).",
|
|
283
485
|
)
|
|
284
|
-
@click.option("--from-year", "from_year", default=None, help="Start year (YYYY).")
|
|
285
|
-
@click.option("--to-year", "to_year", default=None, help="End year (YYYY).")
|
|
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).")
|
|
286
488
|
@click.option(
|
|
287
489
|
"--record-type",
|
|
288
490
|
"record_type",
|
|
@@ -292,6 +494,7 @@ def freereg() -> None:
|
|
|
292
494
|
)
|
|
293
495
|
@click.option("--place-contains", default=None, help="Keep only hits whose register column contains this text.")
|
|
294
496
|
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
497
|
+
@cache_options
|
|
295
498
|
def cmd_freereg_search(
|
|
296
499
|
surname: str,
|
|
297
500
|
given: str | None,
|
|
@@ -301,39 +504,76 @@ def cmd_freereg_search(
|
|
|
301
504
|
record_type: str,
|
|
302
505
|
place_contains: str | None,
|
|
303
506
|
as_json: bool,
|
|
507
|
+
refresh: bool,
|
|
508
|
+
cache_ttl_hours: float | None,
|
|
304
509
|
) -> None:
|
|
305
510
|
"""Search FreeREG parish register transcriptions."""
|
|
511
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
306
512
|
chapman = CHAPMAN.get(county.strip().lower(), county.strip().upper())
|
|
513
|
+
rt_key = record_type.lower()
|
|
307
514
|
rt_map = {"all": "", "baptism": "ba", "marriage": "ma", "burial": "bu"}
|
|
308
|
-
|
|
515
|
+
form_data: dict[str, str] = {
|
|
309
516
|
"utf8": "✓",
|
|
310
517
|
"search_query[last_name]": surname,
|
|
311
518
|
"search_query[chapman_codes][]": chapman,
|
|
312
519
|
"commit": "Search",
|
|
313
520
|
}
|
|
314
521
|
if given:
|
|
315
|
-
|
|
522
|
+
form_data["search_query[first_name]"] = given
|
|
316
523
|
if from_year:
|
|
317
|
-
|
|
524
|
+
form_data["search_query[start_year]"] = from_year
|
|
318
525
|
if to_year:
|
|
319
|
-
|
|
320
|
-
rt = rt_map[
|
|
526
|
+
form_data["search_query[end_year]"] = to_year
|
|
527
|
+
rt = rt_map[rt_key]
|
|
321
528
|
if rt:
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
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 [])
|
|
330
564
|
if place_contains:
|
|
331
565
|
needle = place_contains.lower()
|
|
332
566
|
records = [r for r in records if needle in r["register"].lower()]
|
|
333
567
|
if as_json:
|
|
334
|
-
click.echo(
|
|
568
|
+
click.echo(
|
|
569
|
+
json.dumps(
|
|
570
|
+
{"surname": surname, "county": chapman, "returned": len(records), "records": records, "cache_hit": hit},
|
|
571
|
+
indent=1,
|
|
572
|
+
)
|
|
573
|
+
)
|
|
335
574
|
return
|
|
336
|
-
|
|
575
|
+
marker = " [cache]" if hit else ""
|
|
576
|
+
click.echo(f"{len(records)} FreeREG hit(s) for {surname} ({chapman}):{marker}")
|
|
337
577
|
for rec in records:
|
|
338
578
|
click.echo(f'{rec["event_date"]} {rec["record_type"]} {rec["persons"]}')
|
|
339
579
|
click.echo(f' {rec["register"]} ({rec["county"]})')
|
|
@@ -388,4 +628,4 @@ def cmd_url(
|
|
|
388
628
|
|
|
389
629
|
|
|
390
630
|
if __name__ == "__main__":
|
|
391
|
-
cli()
|
|
631
|
+
cli()
|
|
@@ -15,6 +15,15 @@ This skill includes a standalone executable Python CLI at `skills/usgs-gnis/scri
|
|
|
15
15
|
|
|
16
16
|
Path: `skills/usgs-gnis/scripts/gnis`
|
|
17
17
|
|
|
18
|
+
### Persistent local disk cache
|
|
19
|
+
|
|
20
|
+
Downloaded state/historical files and `search` query results are cached atomically under `~/.cache/kinloom-gnis/` (overrideable via `KINLOOM_GNIS_CACHE_DIR`, with legacy `GNIS_CACHE_DIR` fallback) using advisory file locks (`fcntl.flock` on POSIX, safe fallback elsewhere) so concurrent processes never race on downloads and repeated searches return immediately with zero HTTP requests or re-parsing.
|
|
21
|
+
|
|
22
|
+
Cache layout:
|
|
23
|
+
|
|
24
|
+
- `<STATE>.txt` and `HistoricalFeatures.txt`: extracted pipe-delimited USGS tables.
|
|
25
|
+
- `_queries/<sha256>.json`: cached `search` query JSON keyed by canonical parameters with a 720-hour (30-day) default TTL (`--cache-ttl-hours` or `KINLOOM_GNIS_QUERY_TTL_HOURS`). Pass `--refresh` on `search`, `get`, or `download` to bypass the cache and re-download fresh USGS data.
|
|
26
|
+
|
|
18
27
|
### Download a state file
|
|
19
28
|
|
|
20
29
|
```bash
|
|
@@ -25,7 +34,7 @@ skills/usgs-gnis/scripts/gnis download IL
|
|
|
25
34
|
skills/usgs-gnis/scripts/gnis download CA
|
|
26
35
|
```
|
|
27
36
|
|
|
28
|
-
Files land in `~/.cache/kinloom-gnis/<STATE>.txt` (override with `
|
|
37
|
+
Files land in `~/.cache/kinloom-gnis/<STATE>.txt` (override with `KINLOOM_GNIS_CACHE_DIR`).
|
|
29
38
|
|
|
30
39
|
### Search feature names
|
|
31
40
|
|
|
@@ -78,7 +87,8 @@ skills/usgs-gnis/scripts/gnis url "New Salem"
|
|
|
78
87
|
|
|
79
88
|
## Environment variables
|
|
80
89
|
|
|
81
|
-
- `
|
|
90
|
+
- `KINLOOM_GNIS_CACHE_DIR`: where state text files and query results are cached (default `~/.cache/kinloom-gnis`; `GNIS_CACHE_DIR` is still accepted as a fallback).
|
|
91
|
+
- `KINLOOM_GNIS_QUERY_TTL_HOURS`: optional override for the `search` query cache TTL in hours (default `720`, 30 days).
|
|
82
92
|
|
|
83
93
|
## Research workflow notes
|
|
84
94
|
|