@kinloom/cli 0.2.0 → 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 +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 +217 -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
|
@@ -38,7 +38,18 @@ skills/new-jersey-archives/scripts/nj-archives url land
|
|
|
38
38
|
skills/new-jersey-archives/scripts/nj-archives url births-1848-1925
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
-
`search` options: `--surname` (required), `--given
|
|
41
|
+
`search` options: `--surname` (alias `--last`; required except for `natguard-photos`, which uses `--keyword`, and for the two marriage databases, which also accept `--spouse-surname` alone), `--given` (alias `--first`), `--spouse-surname` (alias `--spouse`) / `--spouse-given` (marriage databases), `--county`, `--location`, `--from-year`, `--to-year`, `--role` (land: Grantor/Grantee/Named/Official; supreme-court: Plaintiff/Defendant/Official/Victim/Other), `--case-type` / `--case-number` (supreme-court), `--keyword` (natguard-photos), `--limit`, `--pages` (stops cleanly when no further pager link exists), `--refresh`, `--cache-ttl-hours`, `--json`. County and role values are matched case-insensitively (and with or without a trailing `" County"`) against the live dropdown options on the search page. `search` refuses order-form-only databases with the form URL; use `url` for those.
|
|
42
|
+
|
|
43
|
+
Database names are forgiving: case, spaces, and underscores are normalized, and common variants resolve (`marriages-colonial`, `marriage-colonial`, `colonial-marriage` → `colonial-marriages`; `marriages` → `marriages-1848-1900`; `deeds` → `land`). A typo exits 2 with a "Did you mean" hint and makes no network call.
|
|
44
|
+
|
|
45
|
+
### Disk cache
|
|
46
|
+
|
|
47
|
+
`search` and `monmouth` cache each result on disk, keyed by database, every criterion, and `--pages`. A repeat search reads the cache file and makes no network call. JSON output carries `"cache_hit": true|false`, and text output marks hits with `[cache]`.
|
|
48
|
+
|
|
49
|
+
- Location: `~/.cache/kinloom-nj-archives/` (override with `KINLOOM_NJ_ARCHIVES_CACHE_DIR`).
|
|
50
|
+
- TTL: 168 hours (override with `--cache-ttl-hours` or `KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS`; `0` disables reads).
|
|
51
|
+
- `--refresh` re-queries the portal and rewrites the entry.
|
|
52
|
+
- Writes are atomic (temp file + rename). A per-query `flock` makes concurrent agents that run the same search wait for the first one and then read its file.
|
|
42
53
|
|
|
43
54
|
## How the machine interface works (verified live 2026-11-24)
|
|
44
55
|
|
|
@@ -110,6 +121,12 @@ Inferred, not verified: the Monmouth results page shows pager links whose postba
|
|
|
110
121
|
- Every searchable database's search page and field list was read live by navigating its portal row (see the table above); births and probate request forms were confirmed to be order forms (`btnAddToCart`, no `Search` button).
|
|
111
122
|
- Portal counts update continuously as staff enter records; re-run `nj-archives databases` rather than quoting counts from memory.
|
|
112
123
|
|
|
124
|
+
### Re-verification 2026-11-25
|
|
125
|
+
|
|
126
|
+
- All 13 searchable databases returned exit 0 live with surname `Smith` (natguard-photos with a keyword) in 0.8-1.9 s each. Paged searches with `--role`, `--from-year`/`--to-year`, and `--county` (up to `--pages 12`, 132 rows) also returned exit 0.
|
|
127
|
+
- The earlier HTTP 500 failures came from posting `Page$N` past the last page (ASP.NET EventValidation rejects it). The CLI now pages only when the grid renders a link for the next page, and it retries a transient 5xx once with a fresh session.
|
|
128
|
+
- The other failures were exit-2 usage errors: a spouse-only marriage search (`--spouse-surname` without `--surname`) and guessed database names (`marriages-colonial`). Both now work.
|
|
129
|
+
|
|
113
130
|
## What this skill does not cover
|
|
114
131
|
|
|
115
132
|
- Department of Agriculture Photographs (7,111 photographs), Federal Writers' Project Photographs (3,911 images), and the Military Service Records request form appear on the portal but have no CLI support; open them in the browser from the portal index.
|
|
@@ -22,14 +22,123 @@ verification log and the per-database field maps.
|
|
|
22
22
|
|
|
23
23
|
from __future__ import annotations
|
|
24
24
|
|
|
25
|
+
import difflib
|
|
26
|
+
import hashlib
|
|
25
27
|
import html as html_mod
|
|
26
28
|
import json
|
|
29
|
+
import math
|
|
30
|
+
import os
|
|
27
31
|
import re
|
|
28
32
|
import sys
|
|
33
|
+
import time
|
|
34
|
+
from contextlib import contextmanager
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import Any, Callable, Iterator
|
|
29
37
|
|
|
30
38
|
import click
|
|
31
39
|
import httpx
|
|
32
40
|
|
|
41
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
42
|
+
CACHE_SCHEMA = 1
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def cache_dir() -> Path:
|
|
46
|
+
override = os.environ.get("KINLOOM_NJ_ARCHIVES_CACHE_DIR")
|
|
47
|
+
if override:
|
|
48
|
+
return Path(override).expanduser()
|
|
49
|
+
return Path.home() / ".cache" / "kinloom-nj-archives"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
53
|
+
if cli_ttl is not None:
|
|
54
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
55
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
56
|
+
return float(cli_ttl)
|
|
57
|
+
raw = os.environ.get("KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS")
|
|
58
|
+
if raw is not None and raw.strip():
|
|
59
|
+
try:
|
|
60
|
+
parsed = float(raw.strip())
|
|
61
|
+
except ValueError as exc:
|
|
62
|
+
raise click.BadParameter(f"Invalid KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
63
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
64
|
+
raise click.BadParameter(
|
|
65
|
+
f"Invalid KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0).")
|
|
66
|
+
return parsed
|
|
67
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@contextmanager
|
|
71
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
72
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
73
|
+
try:
|
|
74
|
+
import fcntl
|
|
75
|
+
except ImportError:
|
|
76
|
+
yield
|
|
77
|
+
return
|
|
78
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
with open(lock_path, "a+b") as lock_file:
|
|
80
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
81
|
+
try:
|
|
82
|
+
yield
|
|
83
|
+
finally:
|
|
84
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
88
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
90
|
+
try:
|
|
91
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
92
|
+
os.replace(tmp, dest)
|
|
93
|
+
except Exception:
|
|
94
|
+
tmp.unlink(missing_ok=True)
|
|
95
|
+
raise
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
99
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
100
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
104
|
+
if not path.is_file():
|
|
105
|
+
return None
|
|
106
|
+
try:
|
|
107
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
108
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
109
|
+
return None
|
|
110
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
111
|
+
return None
|
|
112
|
+
fetched = entry.get("fetched_at")
|
|
113
|
+
if not isinstance(fetched, (int, float)):
|
|
114
|
+
return None
|
|
115
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
116
|
+
return None
|
|
117
|
+
result = entry.get("result")
|
|
118
|
+
return result if isinstance(result, dict) else None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def cached_call(kind: str, payload: dict, fetch: Callable[[], dict], *,
|
|
122
|
+
refresh: bool, ttl_hours: float) -> tuple[dict, bool]:
|
|
123
|
+
"""Return (result, cache_hit). Concurrent callers of one query serialize
|
|
124
|
+
on a per-key flock, so the second caller reads the first caller's file."""
|
|
125
|
+
key = cache_key(kind, payload)
|
|
126
|
+
root = cache_dir()
|
|
127
|
+
path = root / f"{key}.json"
|
|
128
|
+
if not refresh:
|
|
129
|
+
hit = read_cache(path, ttl_hours)
|
|
130
|
+
if hit is not None:
|
|
131
|
+
return hit, True
|
|
132
|
+
with file_lock(root / f"{key}.lock"):
|
|
133
|
+
if not refresh:
|
|
134
|
+
hit = read_cache(path, ttl_hours)
|
|
135
|
+
if hit is not None:
|
|
136
|
+
return hit, True
|
|
137
|
+
result = fetch()
|
|
138
|
+
atomic_write_json(path, {"schema": CACHE_SCHEMA, "fetched_at": time.time(),
|
|
139
|
+
"kind": kind, "query": payload, "result": result})
|
|
140
|
+
return result, False
|
|
141
|
+
|
|
33
142
|
PORTAL_BASE = "https://wwwdnet-dos.nj.gov/DOS_ArchivesDBPortal/"
|
|
34
143
|
PORTAL_INDEX = PORTAL_BASE + "index.aspx"
|
|
35
144
|
MONMOUTH_BASE = "https://oprs.co.monmouth.nj.us/oprs/Archives/"
|
|
@@ -180,6 +289,52 @@ ORDER_ONLY = {
|
|
|
180
289
|
"WorldWarIRecordRequest.aspx", "GridView6", "ctl03"),
|
|
181
290
|
}
|
|
182
291
|
|
|
292
|
+
MARRIAGE_DATABASES = {"colonial-marriages", "marriages-1848-1900"}
|
|
293
|
+
|
|
294
|
+
# Names agents actually typed (telemetry 2026-11-25) plus obvious variants.
|
|
295
|
+
DATABASE_ALIASES = {
|
|
296
|
+
"colonial-marriage": "colonial-marriages",
|
|
297
|
+
"marriages-colonial": "colonial-marriages",
|
|
298
|
+
"marriage-colonial": "colonial-marriages",
|
|
299
|
+
"colonial-marriage-bonds": "colonial-marriages",
|
|
300
|
+
"marriage-bonds": "colonial-marriages",
|
|
301
|
+
"marriages": "marriages-1848-1900",
|
|
302
|
+
"marriage": "marriages-1848-1900",
|
|
303
|
+
"marriages-1848": "marriages-1848-1900",
|
|
304
|
+
"deaths": "deaths-1878-1900",
|
|
305
|
+
"deaths-1848": "deaths-1848-1878",
|
|
306
|
+
"deaths-1878": "deaths-1878-1900",
|
|
307
|
+
"land-records": "land",
|
|
308
|
+
"early-land-records": "land",
|
|
309
|
+
"deeds": "land",
|
|
310
|
+
"supreme": "supreme-court",
|
|
311
|
+
"court": "supreme-court",
|
|
312
|
+
"name-change": "name-changes",
|
|
313
|
+
"census": "census-1885",
|
|
314
|
+
"revwar": "revwar-damage",
|
|
315
|
+
"revwar-damages": "revwar-damage",
|
|
316
|
+
"civilwar": "civilwar-service",
|
|
317
|
+
"wwi": "wwi-deaths",
|
|
318
|
+
"natguard": "natguard-photos",
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def resolve_database(name: str) -> str:
|
|
323
|
+
"""Map a typed database name to a registry key, or raise a helpful error."""
|
|
324
|
+
key = re.sub(r"[\s_]+", "-", name.strip().lower())
|
|
325
|
+
if key in DATABASES or key in ORDER_ONLY or key == "monmouth":
|
|
326
|
+
return key
|
|
327
|
+
if key in DATABASE_ALIASES:
|
|
328
|
+
return DATABASE_ALIASES[key]
|
|
329
|
+
known = [*DATABASES, *ORDER_ONLY, *DATABASE_ALIASES]
|
|
330
|
+
close = difflib.get_close_matches(key, known, n=3, cutoff=0.6)
|
|
331
|
+
hint = f" Did you mean: {', '.join(DATABASE_ALIASES.get(c, c) for c in close)}?" if close else ""
|
|
332
|
+
raise click.UsageError(
|
|
333
|
+
f"unknown database {name!r}.{hint} Valid: {', '.join(DATABASES)}. "
|
|
334
|
+
"Run `nj-archives databases` for the live list."
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
|
|
183
338
|
MONMOUTH_TOWNS = ["Atlantic", "Freehold", "Holmdel", "Howell", "Marlboro",
|
|
184
339
|
"Middletown", "Ocean", "Shrewsbury", "Upper Freehold", "Wall"]
|
|
185
340
|
MONMOUTH_CATEGORIES = ["Agriculture", "Commerce", "Manufactures", "Mining",
|
|
@@ -251,8 +406,13 @@ def parse_grid(page_html: str, table_hint: str) -> tuple[list[str], list[dict]]:
|
|
|
251
406
|
continue
|
|
252
407
|
if len(texts) == 1 and texts[0] == "No Records Found":
|
|
253
408
|
return [], []
|
|
254
|
-
if len(texts) == 1 and re.fullmatch(r"[\d\s]+", texts[0]):
|
|
409
|
+
if len(texts) == 1 and re.fullmatch(r"[\d\s.]+", texts[0]):
|
|
255
410
|
continue # pager row ("1 2 3 4 5 6")
|
|
411
|
+
if (
|
|
412
|
+
"Page$" in row_html
|
|
413
|
+
and all(re.fullmatch(r"(?:\d+|\.{2,3})", t) for t in texts if t)
|
|
414
|
+
):
|
|
415
|
+
continue # multi-cell ASP.NET GridView pager row
|
|
256
416
|
links = [
|
|
257
417
|
{"text": clean(label), "href": html_mod.unescape(href)}
|
|
258
418
|
for href, label in re.findall(
|
|
@@ -280,21 +440,64 @@ def parse_grid(page_html: str, table_hint: str) -> tuple[list[str], list[dict]]:
|
|
|
280
440
|
def capped_notice(page_html: str) -> bool:
|
|
281
441
|
return "Results are limited to 500 records per search" in clean(page_html)
|
|
282
442
|
|
|
443
|
+
|
|
444
|
+
def has_page_link(page_html: str, page_num: int, grid_target: str = GRID_TARGET) -> bool:
|
|
445
|
+
"""Return True if the ASP.NET GridView rendered a postback link for page_num."""
|
|
446
|
+
pattern = (
|
|
447
|
+
r"__doPostBack\((?:'|')"
|
|
448
|
+
+ re.escape(grid_target)
|
|
449
|
+
+ r"(?:'|'),\s*(?:'|')Page\$"
|
|
450
|
+
+ str(page_num)
|
|
451
|
+
+ r"(?:'|')\)"
|
|
452
|
+
)
|
|
453
|
+
return bool(re.search(pattern, page_html))
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def match_option_value(value: str, options: list[str]) -> str | None:
|
|
457
|
+
"""Match a CLI option against ASP.NET <select> options (exact, case-insensitive, or County suffix)."""
|
|
458
|
+
if value in options:
|
|
459
|
+
return value
|
|
460
|
+
norm = value.strip().lower()
|
|
461
|
+
for opt in options:
|
|
462
|
+
if opt.strip().lower() == norm:
|
|
463
|
+
return opt
|
|
464
|
+
stripped = re.sub(r"\s+county$", "", norm)
|
|
465
|
+
for opt in options:
|
|
466
|
+
opt_norm = re.sub(r"\s+county$", "", opt.strip().lower())
|
|
467
|
+
if opt_norm and opt_norm == stripped:
|
|
468
|
+
return opt
|
|
469
|
+
return None
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
RETRYABLE_HTTP_STATUSES = {500, 502, 503, 504}
|
|
473
|
+
|
|
474
|
+
|
|
283
475
|
class Portal:
|
|
284
476
|
"""One cookie-carrying session against the NJ State Archives portal."""
|
|
285
477
|
|
|
286
|
-
def __init__(self) -> None:
|
|
287
|
-
self.
|
|
478
|
+
def __init__(self, *, timeout: float = 25.0, client: httpx.Client | None = None) -> None:
|
|
479
|
+
self._timeout = timeout
|
|
480
|
+
self._external_client = client is not None
|
|
481
|
+
self.client = client or self._make_client()
|
|
482
|
+
|
|
483
|
+
def _make_client(self) -> httpx.Client:
|
|
484
|
+
return httpx.Client(
|
|
288
485
|
headers={"User-Agent": USER_AGENT},
|
|
289
486
|
follow_redirects=True,
|
|
290
|
-
timeout=
|
|
487
|
+
timeout=self._timeout,
|
|
291
488
|
)
|
|
292
489
|
|
|
490
|
+
def _reset_session(self) -> None:
|
|
491
|
+
if not self._external_client:
|
|
492
|
+
self.client.close()
|
|
493
|
+
self.client = self._make_client()
|
|
494
|
+
|
|
293
495
|
def __enter__(self) -> "Portal":
|
|
294
496
|
return self
|
|
295
497
|
|
|
296
498
|
def __exit__(self, *exc: object) -> None:
|
|
297
|
-
self.
|
|
499
|
+
if not self._external_client:
|
|
500
|
+
self.client.close()
|
|
298
501
|
|
|
299
502
|
def _get(self, url: str) -> str:
|
|
300
503
|
response = self.client.get(url)
|
|
@@ -339,17 +542,16 @@ class Portal:
|
|
|
339
542
|
action = form_action(page_html) or spec["page"]
|
|
340
543
|
return PORTAL_BASE + action.lstrip("./"), page_html
|
|
341
544
|
|
|
342
|
-
def
|
|
343
|
-
"""Run a search and optionally page through GridView1 results."""
|
|
545
|
+
def _search_once(self, key: str, criteria: dict[str, str | None], pages: int) -> dict:
|
|
344
546
|
spec = DATABASES[key]
|
|
345
547
|
page_url, page_html = self.open_search_page(key)
|
|
346
|
-
self._validate(criteria, spec, page_html)
|
|
548
|
+
resolved = self._validate(criteria, spec, page_html)
|
|
347
549
|
data: dict[str, str] = {
|
|
348
550
|
**hidden_fields(page_html),
|
|
349
551
|
"__EVENTTARGET": "",
|
|
350
552
|
"__EVENTARGUMENT": "",
|
|
351
553
|
}
|
|
352
|
-
for option, value in
|
|
554
|
+
for option, value in resolved.items():
|
|
353
555
|
if value is not None and option in spec["fields"]:
|
|
354
556
|
data[PREFIX + spec["fields"][option]] = value
|
|
355
557
|
data[PREFIX + SUBMIT_BUTTON.get(key, "Search")] = "Search"
|
|
@@ -358,11 +560,14 @@ class Portal:
|
|
|
358
560
|
capped = capped_notice(result_html)
|
|
359
561
|
seen_pages = 1
|
|
360
562
|
while seen_pages < pages and rows:
|
|
563
|
+
next_page = seen_pages + 1
|
|
564
|
+
if not has_page_link(result_html, next_page):
|
|
565
|
+
break
|
|
361
566
|
page_html = result_html
|
|
362
567
|
data = {
|
|
363
568
|
**hidden_fields(page_html),
|
|
364
569
|
"__EVENTTARGET": GRID_TARGET,
|
|
365
|
-
"__EVENTARGUMENT": f"Page${
|
|
570
|
+
"__EVENTARGUMENT": f"Page${next_page}",
|
|
366
571
|
}
|
|
367
572
|
result_html = self._post(page_url, data)
|
|
368
573
|
_h, more = parse_grid(result_html, "GridView1")
|
|
@@ -373,24 +578,51 @@ class Portal:
|
|
|
373
578
|
return {"database": key, "title": spec["title"], "headers": headers,
|
|
374
579
|
"rows": rows, "capped_500": capped, "pages_read": seen_pages}
|
|
375
580
|
|
|
581
|
+
def search(self, key: str, criteria: dict[str, str | None], pages: int = 1) -> dict:
|
|
582
|
+
"""Run a search and optionally page through GridView1 results (1 retry on transient 5xx/network error)."""
|
|
583
|
+
for attempt in range(2):
|
|
584
|
+
try:
|
|
585
|
+
return self._search_once(key, criteria, pages=pages)
|
|
586
|
+
except httpx.HTTPStatusError as exc:
|
|
587
|
+
if exc.response.status_code in RETRYABLE_HTTP_STATUSES and attempt == 0:
|
|
588
|
+
time.sleep(0.5)
|
|
589
|
+
self._reset_session()
|
|
590
|
+
continue
|
|
591
|
+
raise
|
|
592
|
+
except (httpx.TimeoutException, httpx.RemoteProtocolError, httpx.ConnectError):
|
|
593
|
+
if attempt == 0:
|
|
594
|
+
time.sleep(0.5)
|
|
595
|
+
self._reset_session()
|
|
596
|
+
continue
|
|
597
|
+
raise
|
|
598
|
+
raise RuntimeError("unreachable")
|
|
599
|
+
|
|
376
600
|
@staticmethod
|
|
377
|
-
def _validate(criteria: dict[str, str | None], spec: dict, page_html: str) -> None:
|
|
601
|
+
def _validate(criteria: dict[str, str | None], spec: dict, page_html: str) -> dict[str, str | None]:
|
|
602
|
+
resolved = dict(criteria)
|
|
378
603
|
for option, value in criteria.items():
|
|
379
604
|
if value is None or option not in spec["fields"]:
|
|
380
605
|
continue
|
|
381
606
|
short = spec["fields"][option]
|
|
382
607
|
options = select_options(page_html, short)
|
|
383
|
-
if options
|
|
608
|
+
if options:
|
|
609
|
+
matched = match_option_value(value, options)
|
|
610
|
+
if matched is None:
|
|
611
|
+
raise click.UsageError(
|
|
612
|
+
f"--{option.replace('_', '-')} {value!r} is not a valid choice for "
|
|
613
|
+
f"{spec['title']}; valid: {', '.join(o for o in options if o)}"
|
|
614
|
+
)
|
|
615
|
+
resolved[option] = matched
|
|
616
|
+
roles = spec.get("roles")
|
|
617
|
+
role = resolved.get("role")
|
|
618
|
+
if roles and role is not None:
|
|
619
|
+
matched_role = match_option_value(role, roles)
|
|
620
|
+
if matched_role is None:
|
|
384
621
|
raise click.UsageError(
|
|
385
|
-
f"--
|
|
386
|
-
f"{spec['title']}; valid: {', '.join(o for o in options if o)}"
|
|
622
|
+
f"--role {role!r} is not valid here; valid: {', '.join(roles)}"
|
|
387
623
|
)
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
if roles and role is not None and role not in roles:
|
|
391
|
-
raise click.UsageError(
|
|
392
|
-
f"--role {role!r} is not valid here; valid: {', '.join(roles)}"
|
|
393
|
-
)
|
|
624
|
+
resolved["role"] = matched_role
|
|
625
|
+
return resolved
|
|
394
626
|
|
|
395
627
|
|
|
396
628
|
def monmouth_search(surname: str, town: str, category: str, match: str,
|
|
@@ -433,6 +665,7 @@ def emit(result: dict, as_json: bool, limit: int | None = None) -> None:
|
|
|
433
665
|
click.echo(f"{title}: no records found.")
|
|
434
666
|
return
|
|
435
667
|
click.echo(f"{title}: {len(rows)} result(s)" +
|
|
668
|
+
(" [cache]" if result.get("cache_hit") else "") +
|
|
436
669
|
(" (search capped at 500 records; narrow the criteria)"
|
|
437
670
|
if result.get("capped_500") and total >= 500 else "") +
|
|
438
671
|
(f" (pages read: {result.get('pages_read')})"
|
|
@@ -472,40 +705,64 @@ def databases_cmd(as_json: bool) -> None:
|
|
|
472
705
|
|
|
473
706
|
@cli.command("search")
|
|
474
707
|
@click.argument("database")
|
|
475
|
-
@click.option("--surname",
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
@click.option("--
|
|
708
|
+
@click.option("--surname", "--last", "--last-name", "surname", default=None,
|
|
709
|
+
help="Surname to search. Marriage databases accept --spouse-surname alone; "
|
|
710
|
+
"natguard-photos uses --keyword.")
|
|
711
|
+
@click.option("--given", "--first", "--first-name", "given", default=None, help="Given name.")
|
|
712
|
+
@click.option("--spouse-surname", "--spouse", "--bride-surname", "spouse_surname", default=None,
|
|
713
|
+
help="Spouse surname (marriage databases).")
|
|
714
|
+
@click.option("--spouse-given", "--bride-given", "spouse_given", default=None,
|
|
715
|
+
help="Spouse given name (marriage databases).")
|
|
479
716
|
@click.option("--county", default=None, help="County filter.")
|
|
480
717
|
@click.option("--location", default=None, help="Location filter.")
|
|
481
|
-
@click.option("--from-year", type=int, default=None, help="Earliest year.")
|
|
482
|
-
@click.option("--to-year", type=int, default=None, help="Latest year.")
|
|
718
|
+
@click.option("--from-year", "--start-year", "from_year", type=int, default=None, help="Earliest year.")
|
|
719
|
+
@click.option("--to-year", "--end-year", "to_year", type=int, default=None, help="Latest year.")
|
|
483
720
|
@click.option("--role", default=None, help="Role, e.g. Grantee (land) or Defendant (supreme-court).")
|
|
484
721
|
@click.option("--case-type", default=None, help="Case type (supreme-court).")
|
|
485
722
|
@click.option("--case-number", default=None, help="Case number (supreme-court).")
|
|
486
723
|
@click.option("--keyword", default=None, help="Keyword (natguard-photos).")
|
|
487
724
|
@click.option("--limit", type=int, default=None, help="Max rows to show.")
|
|
488
725
|
@click.option("--pages", type=int, default=1, show_default=True,
|
|
489
|
-
help="Result pages to read (
|
|
726
|
+
help="Result pages to read (stops cleanly if fewer pages exist).")
|
|
727
|
+
@click.option("--refresh", is_flag=True, help="Bypass the disk cache and re-query the portal.")
|
|
728
|
+
@click.option("--cache-ttl-hours", type=float, default=None,
|
|
729
|
+
help=f"Cache TTL in hours (default {DEFAULT_CACHE_TTL_HOURS:g}; "
|
|
730
|
+
"env KINLOOM_NJ_ARCHIVES_CACHE_TTL_HOURS).")
|
|
490
731
|
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
491
|
-
def search_cmd(database: str, surname: str, given: str | None,
|
|
732
|
+
def search_cmd(database: str, surname: str | None, given: str | None,
|
|
492
733
|
spouse_surname: str | None, spouse_given: str | None,
|
|
493
734
|
county: str | None, location: str | None,
|
|
494
735
|
from_year: int | None, to_year: int | None,
|
|
495
736
|
role: str | None, case_type: str | None,
|
|
496
737
|
case_number: str | None, keyword: str | None,
|
|
497
|
-
limit: int | None, pages: int,
|
|
498
|
-
|
|
738
|
+
limit: int | None, pages: int, refresh: bool,
|
|
739
|
+
cache_ttl_hours: float | None, as_json: bool) -> None:
|
|
740
|
+
"""Search one portal database, e.g. `nj-archives search land --surname Lincoln`.
|
|
741
|
+
|
|
742
|
+
Results are cached on disk (~/.cache/kinloom-nj-archives, 168 h TTL).
|
|
743
|
+
"""
|
|
744
|
+
database = resolve_database(database)
|
|
745
|
+
if database == "monmouth":
|
|
746
|
+
raise click.UsageError("Monmouth 1875 census is its own command: "
|
|
747
|
+
"`nj-archives monmouth --surname <name>`.")
|
|
499
748
|
if database in ORDER_ONLY:
|
|
500
749
|
title, page, _grid, _ctl = ORDER_ONLY[database]
|
|
501
750
|
raise click.UsageError(
|
|
502
751
|
f"{title} has no online search; it is a records-request (order) form. "
|
|
503
752
|
f"Open it in a browser: {PORTAL_BASE}{page}"
|
|
504
753
|
)
|
|
505
|
-
if database
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
754
|
+
if database == "natguard-photos":
|
|
755
|
+
if not keyword and not surname:
|
|
756
|
+
raise click.UsageError("natguard-photos requires --keyword (or --surname as keyword).")
|
|
757
|
+
if not keyword and surname:
|
|
758
|
+
keyword = surname
|
|
759
|
+
elif not surname:
|
|
760
|
+
if not (database in MARRIAGE_DATABASES and spouse_surname):
|
|
761
|
+
raise click.UsageError(
|
|
762
|
+
"Missing option '--surname'"
|
|
763
|
+
+ (" (or --spouse-surname for marriage databases)." if database in MARRIAGE_DATABASES
|
|
764
|
+
else ".")
|
|
765
|
+
)
|
|
509
766
|
criteria = {
|
|
510
767
|
"surname": surname, "given": given,
|
|
511
768
|
"spouse_surname": spouse_surname, "spouse_given": spouse_given,
|
|
@@ -515,18 +772,33 @@ def search_cmd(database: str, surname: str, given: str | None,
|
|
|
515
772
|
"role": role, "case_type": case_type, "case_number": case_number,
|
|
516
773
|
"keyword": keyword,
|
|
517
774
|
}
|
|
518
|
-
|
|
775
|
+
pages = max(1, pages)
|
|
776
|
+
|
|
777
|
+
def fetch() -> dict:
|
|
519
778
|
with Portal() as portal:
|
|
520
|
-
|
|
779
|
+
return portal.search(database, criteria, pages=pages)
|
|
780
|
+
|
|
781
|
+
try:
|
|
782
|
+
result, cache_hit = cached_call(
|
|
783
|
+
"search", {"database": database, "criteria": criteria, "pages": pages}, fetch,
|
|
784
|
+
refresh=refresh, ttl_hours=resolve_ttl_hours(cache_ttl_hours))
|
|
521
785
|
except httpx.HTTPStatusError as exc:
|
|
522
786
|
raise click.ClickException(
|
|
523
|
-
f"portal returned HTTP {exc.response.status_code} for {database}; "
|
|
524
|
-
"the portal may be down or
|
|
787
|
+
f"portal returned HTTP {exc.response.status_code} for {database} after one retry; "
|
|
788
|
+
"the portal may be briefly down. Retry later or drop --pages/--from-year filters."
|
|
789
|
+
) from exc
|
|
790
|
+
except httpx.TimeoutException as exc:
|
|
791
|
+
raise click.ClickException(
|
|
792
|
+
f"portal request timed out for {database}: {exc}"
|
|
793
|
+
) from exc
|
|
794
|
+
except httpx.HTTPError as exc:
|
|
795
|
+
raise click.ClickException(
|
|
796
|
+
f"portal request failed for {database}: {exc}"
|
|
525
797
|
) from exc
|
|
526
|
-
emit(result, as_json, limit)
|
|
798
|
+
emit({**result, "cache_hit": cache_hit}, as_json, limit)
|
|
527
799
|
|
|
528
800
|
@cli.command("monmouth")
|
|
529
|
-
@click.option("--surname", required=True, help="Person name to search.")
|
|
801
|
+
@click.option("--surname", "--last", "--name", "surname", required=True, help="Person name to search.")
|
|
530
802
|
@click.option("--town", default="ALL", show_default=True,
|
|
531
803
|
help="Town, or ALL. Choices: " + ", ".join(MONMOUTH_TOWNS))
|
|
532
804
|
@click.option("--category", default="ALL", show_default=True,
|
|
@@ -534,27 +806,38 @@ def search_cmd(database: str, surname: str, given: str | None,
|
|
|
534
806
|
@click.option("--match", type=click.Choice(["starts", "contains"]),
|
|
535
807
|
default="contains", show_default=True)
|
|
536
808
|
@click.option("--limit", type=int, default=None, help="Max rows to show.")
|
|
809
|
+
@click.option("--refresh", is_flag=True, help="Bypass the disk cache and re-query Monmouth OPRS.")
|
|
810
|
+
@click.option("--cache-ttl-hours", type=float, default=None, help="Cache TTL in hours (default 168).")
|
|
537
811
|
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
538
812
|
def monmouth_cmd(surname: str, town: str, category: str, match: str,
|
|
539
|
-
limit: int | None,
|
|
813
|
+
limit: int | None, refresh: bool, cache_ttl_hours: float | None,
|
|
814
|
+
as_json: bool) -> None:
|
|
540
815
|
"""Search the Monmouth County OPRS 1875 census by person name."""
|
|
541
|
-
|
|
816
|
+
town_match = match_option_value(town, ["ALL", *MONMOUTH_TOWNS])
|
|
817
|
+
if town_match is None:
|
|
542
818
|
raise click.UsageError(
|
|
543
819
|
f"--town {town!r} is not valid; valid: ALL, " + ", ".join(MONMOUTH_TOWNS)
|
|
544
820
|
)
|
|
545
|
-
|
|
821
|
+
category_match = match_option_value(category, ["ALL", *MONMOUTH_CATEGORIES])
|
|
822
|
+
if category_match is None:
|
|
546
823
|
raise click.UsageError(
|
|
547
824
|
f"--category {category!r} is not valid; valid: ALL, "
|
|
548
825
|
+ ", ".join(MONMOUTH_CATEGORIES)
|
|
549
826
|
)
|
|
550
827
|
try:
|
|
551
|
-
result =
|
|
828
|
+
result, cache_hit = cached_call(
|
|
829
|
+
"monmouth", {"surname": surname, "town": town_match, "category": category_match,
|
|
830
|
+
"match": match},
|
|
831
|
+
lambda: monmouth_search(surname, town_match, category_match, match, None),
|
|
832
|
+
refresh=refresh, ttl_hours=resolve_ttl_hours(cache_ttl_hours))
|
|
552
833
|
except httpx.HTTPStatusError as exc:
|
|
553
834
|
raise click.ClickException(
|
|
554
835
|
f"Monmouth OPRS returned HTTP {exc.response.status_code}; "
|
|
555
836
|
"the site may be down or blocking automated access"
|
|
556
837
|
) from exc
|
|
557
|
-
|
|
838
|
+
except httpx.HTTPError as exc:
|
|
839
|
+
raise click.ClickException(f"Monmouth OPRS request failed: {exc}") from exc
|
|
840
|
+
emit({**result, "cache_hit": cache_hit}, as_json, limit)
|
|
558
841
|
|
|
559
842
|
|
|
560
843
|
@cli.command("url")
|
|
@@ -565,6 +848,7 @@ def url_cmd(database: str | None) -> None:
|
|
|
565
848
|
click.echo(f"Portal index: {PORTAL_INDEX}")
|
|
566
849
|
click.echo(f"Monmouth County OPRS 1875 census: {MONMOUTH_SEARCH}")
|
|
567
850
|
return
|
|
851
|
+
database = resolve_database(database)
|
|
568
852
|
if database == "monmouth":
|
|
569
853
|
click.echo(MONMOUTH_SEARCH)
|
|
570
854
|
return
|
|
@@ -85,6 +85,13 @@ skills/openarchieven/scripts/openarchieven url --record "bhi:78a37833-d731-ffe5-
|
|
|
85
85
|
- **Follow `Bevolkingsregisters` across municipalities:** When a civil record shows a move or emigration, inspect the household entry with `show` to capture destination columns (`vertrokken naar`) before checking Rotterdam `Passagiersregisters` (`--archive srt`).
|
|
86
86
|
- **Verify against the original scan:** Indexed A2A transcripts occasionally misread handwritten dates or ages; open the `a2a_SourceAvailableScans` or `Original` URL from `show` before treating a date as final.
|
|
87
87
|
|
|
88
|
-
##
|
|
88
|
+
## Disk cache and environment variables
|
|
89
89
|
|
|
90
|
-
|
|
90
|
+
`search` and `show` cache successful responses on disk under `~/.cache/kinloom-openarchieven/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors, API `error_code` responses, and invalid payloads are never cached.
|
|
91
|
+
|
|
92
|
+
- `--refresh`: bypass cached reads and write the fresh response to disk.
|
|
93
|
+
- `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
|
|
94
|
+
- `KINLOOM_OPENARCHIEVEN_CACHE_DIR`: override the cache directory path.
|
|
95
|
+
- `KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS`: override the default TTL in hours.
|
|
96
|
+
|
|
97
|
+
No key or account is needed for OpenArchieven read queries.
|