@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
|
@@ -18,18 +18,138 @@ Verified live 2026-11-24: simple search returns server-rendered HTML results.
|
|
|
18
18
|
|
|
19
19
|
from __future__ import annotations
|
|
20
20
|
|
|
21
|
+
import hashlib
|
|
21
22
|
import html as htmlmod
|
|
22
23
|
import json
|
|
24
|
+
import math
|
|
25
|
+
import os
|
|
23
26
|
import re
|
|
24
27
|
import shutil
|
|
25
28
|
import subprocess
|
|
26
29
|
import tempfile
|
|
30
|
+
import time
|
|
31
|
+
from contextlib import contextmanager
|
|
27
32
|
from html.parser import HTMLParser
|
|
28
33
|
from pathlib import Path
|
|
34
|
+
from typing import Any, Callable, Iterator
|
|
29
35
|
from urllib.parse import quote_plus, unquote
|
|
30
36
|
|
|
31
37
|
import click
|
|
32
38
|
|
|
39
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
40
|
+
CACHE_SCHEMA = 1
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cache_dir() -> Path:
|
|
44
|
+
override = os.environ.get("KINLOOM_MICHIGANOLOGY_CACHE_DIR")
|
|
45
|
+
if override:
|
|
46
|
+
return Path(override).expanduser()
|
|
47
|
+
return Path.home() / ".cache" / "kinloom-michiganology"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
51
|
+
if cli_ttl is not None:
|
|
52
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
53
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
54
|
+
return float(cli_ttl)
|
|
55
|
+
raw = os.environ.get("KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS")
|
|
56
|
+
if raw is not None and raw.strip():
|
|
57
|
+
try:
|
|
58
|
+
parsed = float(raw.strip())
|
|
59
|
+
except ValueError as exc:
|
|
60
|
+
raise click.BadParameter(
|
|
61
|
+
f"Invalid KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
62
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
63
|
+
raise click.BadParameter(
|
|
64
|
+
f"Invalid KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS value: {raw!r} (must be >= 0).")
|
|
65
|
+
return parsed
|
|
66
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@contextmanager
|
|
70
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
71
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
72
|
+
try:
|
|
73
|
+
import fcntl
|
|
74
|
+
except ImportError:
|
|
75
|
+
yield
|
|
76
|
+
return
|
|
77
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
with open(lock_path, "a+b") as lock_file:
|
|
79
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
80
|
+
try:
|
|
81
|
+
yield
|
|
82
|
+
finally:
|
|
83
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
87
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
88
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
89
|
+
try:
|
|
90
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
91
|
+
os.replace(tmp, dest)
|
|
92
|
+
except Exception:
|
|
93
|
+
tmp.unlink(missing_ok=True)
|
|
94
|
+
raise
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
98
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
99
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
103
|
+
if not path.is_file():
|
|
104
|
+
return None
|
|
105
|
+
try:
|
|
106
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
107
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
108
|
+
return None
|
|
109
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
110
|
+
return None
|
|
111
|
+
fetched = entry.get("fetched_at")
|
|
112
|
+
if not isinstance(fetched, (int, float)):
|
|
113
|
+
return None
|
|
114
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
115
|
+
return None
|
|
116
|
+
result = entry.get("result")
|
|
117
|
+
return result if isinstance(result, dict) else None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def cached_call(kind: str, payload: dict, fetch: Callable[[], dict], *,
|
|
121
|
+
refresh: bool, ttl_hours: float,
|
|
122
|
+
cacheable: Callable[[dict], bool] = lambda _r: True) -> 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
|
+
Exceptions from fetch propagate and write nothing; results rejected by
|
|
126
|
+
`cacheable` (doubtful empties) are returned but not stored."""
|
|
127
|
+
key = cache_key(kind, payload)
|
|
128
|
+
root = cache_dir()
|
|
129
|
+
path = root / f"{key}.json"
|
|
130
|
+
if not refresh:
|
|
131
|
+
hit = read_cache(path, ttl_hours)
|
|
132
|
+
if hit is not None:
|
|
133
|
+
return hit, True
|
|
134
|
+
with file_lock(root / f"{key}.lock"):
|
|
135
|
+
if not refresh:
|
|
136
|
+
hit = read_cache(path, ttl_hours)
|
|
137
|
+
if hit is not None:
|
|
138
|
+
return hit, True
|
|
139
|
+
result = fetch()
|
|
140
|
+
if cacheable(result):
|
|
141
|
+
atomic_write_json(path, {"schema": CACHE_SCHEMA, "fetched_at": time.time(),
|
|
142
|
+
"kind": kind, "query": payload, "result": result})
|
|
143
|
+
return result, False
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def cache_options(func: Callable) -> Callable:
|
|
147
|
+
func = click.option("--cache-ttl-hours", type=float, default=None,
|
|
148
|
+
help="Cache TTL in hours (default 168, env KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS; 0 disables reads).")(func)
|
|
149
|
+
func = click.option("--refresh", is_flag=True,
|
|
150
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).")(func)
|
|
151
|
+
return func
|
|
152
|
+
|
|
33
153
|
BASE = "https://michigan.access.preservica.com"
|
|
34
154
|
# Preservica 403s python-httpx's default header set. Plain curl-style headers
|
|
35
155
|
# (short UA, Accept */*) return 200 consistently.
|
|
@@ -150,11 +270,16 @@ def _require_curl() -> str:
|
|
|
150
270
|
return curl
|
|
151
271
|
|
|
152
272
|
|
|
273
|
+
_STATUS_MARKER = "\n__KINLOOM_HTTP_STATUS__:"
|
|
274
|
+
|
|
275
|
+
|
|
153
276
|
def _curl_get_text(url: str) -> str:
|
|
277
|
+
"""GET a page via curl; raise ClickException on transport or non-200 status."""
|
|
154
278
|
curl = _require_curl()
|
|
155
279
|
try:
|
|
156
280
|
proc = subprocess.run(
|
|
157
|
-
[curl, "-sSL", "-A", USER_AGENT, "--max-time", "60",
|
|
281
|
+
[curl, "-sSL", "-A", USER_AGENT, "--max-time", "60",
|
|
282
|
+
"-w", _STATUS_MARKER + "%{http_code}", url],
|
|
158
283
|
capture_output=True,
|
|
159
284
|
text=True,
|
|
160
285
|
timeout=70,
|
|
@@ -166,7 +291,13 @@ def _curl_get_text(url: str) -> str:
|
|
|
166
291
|
f"Michiganology request failed (curl exit {proc.returncode}): "
|
|
167
292
|
f"{proc.stderr.strip()[:300]}"
|
|
168
293
|
)
|
|
169
|
-
|
|
294
|
+
body, sep, status = proc.stdout.rpartition(_STATUS_MARKER)
|
|
295
|
+
if not sep:
|
|
296
|
+
raise click.ClickException("Michiganology request failed: no HTTP status from curl.")
|
|
297
|
+
status = status.strip()
|
|
298
|
+
if status != "200":
|
|
299
|
+
raise click.ClickException(f"Michiganology returned HTTP {status} for {url}")
|
|
300
|
+
return body
|
|
170
301
|
|
|
171
302
|
|
|
172
303
|
def _resolve_item_ref(url_or_id: str) -> tuple[str, str]:
|
|
@@ -208,6 +339,39 @@ def total_results(page: str) -> int | None:
|
|
|
208
339
|
return int(match.group(1).replace(",", "")) if match else None
|
|
209
340
|
|
|
210
341
|
|
|
342
|
+
def search_page(query: str) -> dict:
|
|
343
|
+
"""Fetch + parse the first search results page into a JSON-able dict."""
|
|
344
|
+
page = fetch_search(query)
|
|
345
|
+
parser = ResultParser()
|
|
346
|
+
parser.feed(page)
|
|
347
|
+
return {"query": query, "total": total_results(page), "results": parser.results}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _search_cacheable(result: dict) -> bool:
|
|
351
|
+
# Cache hits; cache an empty result only when the page was clearly a real
|
|
352
|
+
# search page reporting a total (e.g. "0 total results").
|
|
353
|
+
return bool(result.get("results")) or result.get("total") is not None
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def item_details(item_id: str, item_url: str) -> dict:
|
|
357
|
+
"""Fetch + parse an item page into a JSON-able dict."""
|
|
358
|
+
page = _curl_get_text(item_url)
|
|
359
|
+
parser = ItemMetadataParser()
|
|
360
|
+
parser.feed(page)
|
|
361
|
+
title = " ".join(parser.title.split())
|
|
362
|
+
download_url = parser.download_url
|
|
363
|
+
if not download_url and item_id.startswith("IO_"):
|
|
364
|
+
download_url = f"{BASE}/download/file/{item_id}"
|
|
365
|
+
return {
|
|
366
|
+
"id": item_id,
|
|
367
|
+
"title": title or item_id,
|
|
368
|
+
"url": item_url,
|
|
369
|
+
"download_url": download_url,
|
|
370
|
+
"fields": [[k, v] for k, v in parser.fields],
|
|
371
|
+
"parsed": bool(title or parser.fields),
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
|
|
211
375
|
@click.group()
|
|
212
376
|
def cli() -> None:
|
|
213
377
|
"""Search Michiganology (Archives of Michigan digital collections)."""
|
|
@@ -217,17 +381,20 @@ def cli() -> None:
|
|
|
217
381
|
@click.argument("query")
|
|
218
382
|
@click.option("--limit", default=10, show_default=True, help="Max results to show (first page only).")
|
|
219
383
|
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
220
|
-
|
|
384
|
+
@cache_options
|
|
385
|
+
def search(query: str, limit: int, as_json: bool, refresh: bool, cache_ttl_hours: float | None) -> None:
|
|
221
386
|
"""Search all Michiganology collections, e.g. michiganology search Lincoln."""
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
total =
|
|
226
|
-
results =
|
|
387
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
388
|
+
data, hit = cached_call("search", {"query": query}, lambda: search_page(query),
|
|
389
|
+
refresh=refresh, ttl_hours=ttl, cacheable=_search_cacheable)
|
|
390
|
+
total = data.get("total")
|
|
391
|
+
results = list(data.get("results") or [])[:limit]
|
|
227
392
|
if as_json:
|
|
228
|
-
click.echo(json.dumps({"query": query, "total": total, "results": results
|
|
393
|
+
click.echo(json.dumps({"query": query, "total": total, "results": results,
|
|
394
|
+
"cache_hit": hit}, indent=2))
|
|
229
395
|
return
|
|
230
|
-
|
|
396
|
+
marker = " [cache]" if hit else ""
|
|
397
|
+
click.echo(f"Query: {query} | Total results: {total if total is not None else 'unknown'}{marker}")
|
|
231
398
|
if not results:
|
|
232
399
|
click.echo("No results on the first page.")
|
|
233
400
|
return
|
|
@@ -239,18 +406,19 @@ def search(query: str, limit: int, as_json: bool) -> None:
|
|
|
239
406
|
@cli.command()
|
|
240
407
|
@click.argument("url_or_id")
|
|
241
408
|
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
242
|
-
|
|
409
|
+
@cache_options
|
|
410
|
+
def get(url_or_id: str, as_json: bool, refresh: bool, cache_ttl_hours: float | None) -> None:
|
|
243
411
|
"""Inspect a Michiganology item page (Item Data fields and file download URL)."""
|
|
244
412
|
item_id, item_url = _resolve_item_ref(url_or_id)
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
413
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
414
|
+
data, hit = cached_call("get", {"id": item_id, "url": item_url},
|
|
415
|
+
lambda: item_details(item_id, item_url), refresh=refresh,
|
|
416
|
+
ttl_hours=ttl, cacheable=lambda r: bool(r.get("parsed")))
|
|
417
|
+
title = data["title"]
|
|
418
|
+
download_url = data.get("download_url")
|
|
419
|
+
fields = [(k, v) for k, v in data.get("fields") or []]
|
|
252
420
|
metadata: dict[str, str | list[str]] = {}
|
|
253
|
-
for key, val in
|
|
421
|
+
for key, val in fields:
|
|
254
422
|
if key in metadata:
|
|
255
423
|
prev = metadata[key]
|
|
256
424
|
metadata[key] = [*prev, val] if isinstance(prev, list) else [prev, val]
|
|
@@ -262,15 +430,16 @@ def get(url_or_id: str, as_json: bool) -> None:
|
|
|
262
430
|
"url": item_url,
|
|
263
431
|
"download_url": download_url,
|
|
264
432
|
"metadata": metadata,
|
|
433
|
+
"cache_hit": hit,
|
|
265
434
|
}
|
|
266
435
|
if as_json:
|
|
267
436
|
click.echo(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
268
437
|
return
|
|
269
|
-
click.echo(f"Item {item_id}: {title}")
|
|
438
|
+
click.echo(f"Item {item_id}: {title}{' [cache]' if hit else ''}")
|
|
270
439
|
click.echo(f" URL: {item_url}")
|
|
271
440
|
if download_url:
|
|
272
441
|
click.echo(f" Download: {download_url}")
|
|
273
|
-
for key, val in
|
|
442
|
+
for key, val in fields:
|
|
274
443
|
click.echo(f" {key}: {val}")
|
|
275
444
|
|
|
276
445
|
|
|
@@ -64,6 +64,15 @@ skills/missouri-archives/scripts/mo-archives mdh
|
|
|
64
64
|
|
|
65
65
|
Prints the MDH home page, Advanced Search, and Archives URLs. MDH has no verified machine interface; do the search in the browser.
|
|
66
66
|
|
|
67
|
+
### Disk cache and environment variables
|
|
68
|
+
|
|
69
|
+
`death`, `pre1910`, and `detail` cache successful responses on disk under `~/.cache/kinloom-mo-archives/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors and unverified 0-hit error pages are never cached.
|
|
70
|
+
|
|
71
|
+
- `--refresh`: bypass cached reads and write the fresh response to disk.
|
|
72
|
+
- `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
|
|
73
|
+
- `KINLOOM_MO_ARCHIVES_CACHE_DIR`: override the cache directory path.
|
|
74
|
+
- `KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS`: override the default TTL in hours.
|
|
75
|
+
|
|
67
76
|
## Verified interface (verified live 2026-11-24)
|
|
68
77
|
|
|
69
78
|
- Portal: https://www.sos.mo.gov/mdh. Missouri State Archives: https://www.sos.mo.gov/archives. Address: 600 West Main Street, Jefferson City, MO 65102. Research room open Monday-Friday 8:00 AM-5:00 PM. Email archref@sos.mo.gov.
|