@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
|
@@ -15,15 +15,125 @@ the 4 requests/second IP rate limit.
|
|
|
15
15
|
|
|
16
16
|
from __future__ import annotations
|
|
17
17
|
|
|
18
|
+
import hashlib
|
|
18
19
|
import json
|
|
20
|
+
import math
|
|
21
|
+
import os
|
|
19
22
|
import re
|
|
20
23
|
import time
|
|
21
|
-
from
|
|
24
|
+
from contextlib import contextmanager
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, Callable, Iterator
|
|
22
27
|
from urllib.parse import urlencode
|
|
23
28
|
|
|
24
29
|
import click
|
|
25
30
|
import httpx
|
|
26
31
|
|
|
32
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
33
|
+
CACHE_SCHEMA = 1
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def cache_dir() -> Path:
|
|
37
|
+
override = os.environ.get("KINLOOM_OPENARCHIEVEN_CACHE_DIR")
|
|
38
|
+
if override:
|
|
39
|
+
return Path(override).expanduser()
|
|
40
|
+
return Path.home() / ".cache" / "kinloom-openarchieven"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
44
|
+
if cli_ttl is not None:
|
|
45
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
46
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
47
|
+
return float(cli_ttl)
|
|
48
|
+
raw = os.environ.get("KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS")
|
|
49
|
+
if raw is not None and raw.strip():
|
|
50
|
+
try:
|
|
51
|
+
parsed = float(raw.strip())
|
|
52
|
+
except ValueError as exc:
|
|
53
|
+
raise click.BadParameter(f"Invalid KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
54
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
55
|
+
raise click.BadParameter(
|
|
56
|
+
f"Invalid KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS value: {raw!r} (must be >= 0).")
|
|
57
|
+
return parsed
|
|
58
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@contextmanager
|
|
62
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
63
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
64
|
+
try:
|
|
65
|
+
import fcntl
|
|
66
|
+
except ImportError:
|
|
67
|
+
yield
|
|
68
|
+
return
|
|
69
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
with open(lock_path, "a+b") as lock_file:
|
|
71
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
72
|
+
try:
|
|
73
|
+
yield
|
|
74
|
+
finally:
|
|
75
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
79
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
81
|
+
try:
|
|
82
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
83
|
+
os.replace(tmp, dest)
|
|
84
|
+
except Exception:
|
|
85
|
+
tmp.unlink(missing_ok=True)
|
|
86
|
+
raise
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
90
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
91
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
95
|
+
if not path.is_file():
|
|
96
|
+
return None
|
|
97
|
+
try:
|
|
98
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
99
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
100
|
+
return None
|
|
101
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
102
|
+
return None
|
|
103
|
+
fetched = entry.get("fetched_at")
|
|
104
|
+
if not isinstance(fetched, (int, float)):
|
|
105
|
+
return None
|
|
106
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
107
|
+
return None
|
|
108
|
+
result = entry.get("result")
|
|
109
|
+
return result if isinstance(result, dict) else None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def cached_call(kind: str, payload: dict, fetch: Callable[[], dict], *,
|
|
113
|
+
refresh: bool, ttl_hours: float,
|
|
114
|
+
cacheable: Callable[[dict], bool] = lambda _r: True) -> tuple[dict, bool]:
|
|
115
|
+
"""Return (result, cache_hit). Concurrent callers of one query serialize
|
|
116
|
+
on a per-key flock, so the second caller reads the first caller's file.
|
|
117
|
+
Failures raise out of fetch() and are never written; results rejected by
|
|
118
|
+
`cacheable` are returned but not stored."""
|
|
119
|
+
key = cache_key(kind, payload)
|
|
120
|
+
root = cache_dir()
|
|
121
|
+
path = root / f"{key}.json"
|
|
122
|
+
if not refresh:
|
|
123
|
+
hit = read_cache(path, ttl_hours)
|
|
124
|
+
if hit is not None:
|
|
125
|
+
return hit, True
|
|
126
|
+
with file_lock(root / f"{key}.lock"):
|
|
127
|
+
if not refresh:
|
|
128
|
+
hit = read_cache(path, ttl_hours)
|
|
129
|
+
if hit is not None:
|
|
130
|
+
return hit, True
|
|
131
|
+
result = fetch()
|
|
132
|
+
if cacheable(result):
|
|
133
|
+
atomic_write_json(path, {"schema": CACHE_SCHEMA, "fetched_at": time.time(),
|
|
134
|
+
"kind": kind, "query": payload, "result": result})
|
|
135
|
+
return result, False
|
|
136
|
+
|
|
27
137
|
API_BASE = "https://api.openarch.nl/1.0/records"
|
|
28
138
|
WEB_BASE = "https://www.openarchieven.nl"
|
|
29
139
|
USER_AGENT = "kinloom/1.0 (genealogy research; https://github.com/tiberriver256/kinloom)"
|
|
@@ -49,16 +159,36 @@ def _fail(message: str) -> None:
|
|
|
49
159
|
raise SystemExit(1)
|
|
50
160
|
|
|
51
161
|
|
|
162
|
+
def cache_options(func: Callable) -> Callable:
|
|
163
|
+
func = click.option(
|
|
164
|
+
"--cache-ttl-hours",
|
|
165
|
+
type=float,
|
|
166
|
+
default=None,
|
|
167
|
+
help="Cache TTL in hours (default 168, env KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS; 0 disables reads).",
|
|
168
|
+
)(func)
|
|
169
|
+
func = click.option(
|
|
170
|
+
"--refresh",
|
|
171
|
+
is_flag=True,
|
|
172
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).",
|
|
173
|
+
)(func)
|
|
174
|
+
return func
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _client() -> httpx.Client:
|
|
178
|
+
return httpx.Client(
|
|
179
|
+
timeout=TIMEOUT,
|
|
180
|
+
follow_redirects=True,
|
|
181
|
+
headers={"User-Agent": USER_AGENT, "Accept": "application/json"},
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
52
185
|
def _get_json(endpoint: str, params: dict[str, Any]) -> Any:
|
|
53
186
|
"""Fetch one JSON response from api.openarch.nl with boundary validation."""
|
|
54
|
-
|
|
187
|
+
if MIN_INTERVAL_S > 0:
|
|
188
|
+
time.sleep(MIN_INTERVAL_S)
|
|
55
189
|
url = f"{API_BASE}/{endpoint}"
|
|
56
190
|
try:
|
|
57
|
-
with
|
|
58
|
-
timeout=TIMEOUT,
|
|
59
|
-
follow_redirects=True,
|
|
60
|
-
headers={"User-Agent": USER_AGENT, "Accept": "application/json"},
|
|
61
|
-
) as client:
|
|
191
|
+
with _client() as client:
|
|
62
192
|
resp = client.get(url, params=params)
|
|
63
193
|
except httpx.HTTPError as exc:
|
|
64
194
|
_fail(f"OpenArchieven request failed: {exc}")
|
|
@@ -74,6 +204,24 @@ def _get_json(endpoint: str, params: dict[str, Any]) -> Any:
|
|
|
74
204
|
return data
|
|
75
205
|
|
|
76
206
|
|
|
207
|
+
def _search_cacheable(result: dict[str, Any]) -> bool:
|
|
208
|
+
resp = result.get("response")
|
|
209
|
+
if not isinstance(resp, dict):
|
|
210
|
+
return False
|
|
211
|
+
docs = resp.get("docs")
|
|
212
|
+
found = resp.get("number_found")
|
|
213
|
+
return isinstance(docs, list) and isinstance(found, int) and found >= 0 and (bool(docs) or found == 0)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _show_cacheable(result: dict[str, Any]) -> bool:
|
|
217
|
+
data = result.get("data")
|
|
218
|
+
if isinstance(data, dict):
|
|
219
|
+
return bool(data)
|
|
220
|
+
if isinstance(data, list):
|
|
221
|
+
return len(data) > 0
|
|
222
|
+
return False
|
|
223
|
+
|
|
224
|
+
|
|
77
225
|
def _is_source_type(value: str) -> bool:
|
|
78
226
|
low = value.strip().lower()
|
|
79
227
|
return low.startswith("bs ") or low.startswith("dtb ") or low in KNOWN_SOURCE_TYPES
|
|
@@ -304,6 +452,7 @@ def cli() -> None:
|
|
|
304
452
|
@click.option("--limit", "-n", type=int, default=10, show_default=True, help="Results to return (max 100).")
|
|
305
453
|
@click.option("--start", type=int, default=0, show_default=True, help="Offset for paging (max 10000).")
|
|
306
454
|
@click.option("--json", "as_json", is_flag=True, help="Emit raw API JSON output.")
|
|
455
|
+
@cache_options
|
|
307
456
|
def search(
|
|
308
457
|
name_arg: str | None,
|
|
309
458
|
name_opt: str | None,
|
|
@@ -319,6 +468,8 @@ def search(
|
|
|
319
468
|
limit: int,
|
|
320
469
|
start: int,
|
|
321
470
|
as_json: bool,
|
|
471
|
+
refresh: bool,
|
|
472
|
+
cache_ttl_hours: float | None,
|
|
322
473
|
) -> None:
|
|
323
474
|
"""Search OpenArchieven records.
|
|
324
475
|
|
|
@@ -354,15 +505,31 @@ def search(
|
|
|
354
505
|
if country:
|
|
355
506
|
params["country_code"] = country
|
|
356
507
|
|
|
357
|
-
|
|
508
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
509
|
+
|
|
510
|
+
def _fetch() -> dict[str, Any]:
|
|
511
|
+
fetched = _get_json("search.json", params)
|
|
512
|
+
if not isinstance(fetched, dict):
|
|
513
|
+
_fail(f"Unexpected non-object search response from {API_BASE}/search.json")
|
|
514
|
+
return fetched
|
|
515
|
+
|
|
516
|
+
data, hit = cached_call(
|
|
517
|
+
"search",
|
|
518
|
+
params,
|
|
519
|
+
_fetch,
|
|
520
|
+
refresh=refresh,
|
|
521
|
+
ttl_hours=ttl,
|
|
522
|
+
cacheable=_search_cacheable,
|
|
523
|
+
)
|
|
358
524
|
if as_json:
|
|
359
|
-
click.echo(json.dumps(data, indent=2, ensure_ascii=False))
|
|
525
|
+
click.echo(json.dumps({**data, "cache_hit": hit}, indent=2, ensure_ascii=False))
|
|
360
526
|
return
|
|
361
527
|
|
|
362
528
|
resp = data.get("response") or {}
|
|
363
529
|
total = resp.get("number_found", 0)
|
|
364
530
|
docs = resp.get("docs") or []
|
|
365
|
-
|
|
531
|
+
marker = " [cache]" if hit else ""
|
|
532
|
+
click.echo(f"Found {total} records (showing {len(docs)} from offset {start}){marker}")
|
|
366
533
|
for doc in docs:
|
|
367
534
|
code = doc.get("archive_code") or ""
|
|
368
535
|
ident = doc.get("identifier") or ""
|
|
@@ -390,12 +557,33 @@ def search(
|
|
|
390
557
|
help="Language for returned labels.",
|
|
391
558
|
)
|
|
392
559
|
@click.option("--json", "as_json", is_flag=True, help="Emit raw A2A JSON output.")
|
|
393
|
-
|
|
560
|
+
@cache_options
|
|
561
|
+
def show(
|
|
562
|
+
archive: str,
|
|
563
|
+
identifier: str | None,
|
|
564
|
+
lang: str,
|
|
565
|
+
as_json: bool,
|
|
566
|
+
refresh: bool,
|
|
567
|
+
cache_ttl_hours: float | None,
|
|
568
|
+
) -> None:
|
|
394
569
|
"""Fetch full A2A details for one record by ARCHIVE IDENTIFIER, archive:uuid, or URL."""
|
|
395
570
|
code, ident = _parse_record_ref(archive, identifier)
|
|
396
|
-
|
|
571
|
+
params = {"archive": code, "identifier": ident, "lang": lang}
|
|
572
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
573
|
+
wrapped, hit = cached_call(
|
|
574
|
+
"show",
|
|
575
|
+
params,
|
|
576
|
+
lambda: {"data": _get_json("show.json", params)},
|
|
577
|
+
refresh=refresh,
|
|
578
|
+
ttl_hours=ttl,
|
|
579
|
+
cacheable=_show_cacheable,
|
|
580
|
+
)
|
|
581
|
+
data = wrapped.get("data")
|
|
397
582
|
if as_json:
|
|
398
|
-
|
|
583
|
+
if isinstance(data, dict):
|
|
584
|
+
click.echo(json.dumps({**data, "cache_hit": hit}, indent=2, ensure_ascii=False))
|
|
585
|
+
else:
|
|
586
|
+
click.echo(json.dumps({"records": data, "cache_hit": hit}, indent=2, ensure_ascii=False))
|
|
399
587
|
return
|
|
400
588
|
records = data if isinstance(data, list) else [data]
|
|
401
589
|
if not records:
|
|
@@ -405,7 +593,11 @@ def show(archive: str, identifier: str | None, lang: str, as_json: bool) -> None
|
|
|
405
593
|
if idx > 0:
|
|
406
594
|
click.echo("")
|
|
407
595
|
if isinstance(rec, dict):
|
|
408
|
-
|
|
596
|
+
formatted = _format_a2a_record(code, ident, rec)
|
|
597
|
+
if idx == 0 and hit:
|
|
598
|
+
first_line, sep, rest = formatted.partition("\n")
|
|
599
|
+
formatted = f"{first_line} [cache]{sep}{rest}"
|
|
600
|
+
click.echo(formatted)
|
|
409
601
|
|
|
410
602
|
|
|
411
603
|
@cli.command()
|
|
@@ -85,6 +85,15 @@ Worked order for tracing a person or family in Texas:
|
|
|
85
85
|
- `https://www.tsl.texas.gov/` — HTTP 200.
|
|
86
86
|
- CLI `texas-archives --help`, `portal search`, `portal item`, `tda`, `url` — all exited 0 on verification runs.
|
|
87
87
|
|
|
88
|
+
## Disk cache and environment variables
|
|
89
|
+
|
|
90
|
+
`portal search` (per OpenSearch page), `portal item`, and `tda` cache successful responses on disk under `~/.cache/kinloom-texas-archives/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors, curl failures, OAI errors, and empty/unverified 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_TEXAS_ARCHIVES_CACHE_DIR`: override the cache directory path.
|
|
95
|
+
- `KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS`: override the default TTL in hours.
|
|
96
|
+
|
|
88
97
|
## What this skill does not cover
|
|
89
98
|
|
|
90
99
|
- Federal BLM GLO (public-land states) — see `blm-glo`; Texas state land is separate.
|