@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.
Files changed (80) hide show
  1. package/dist/assets/cached-ocr.py +346 -116
  2. package/dist/assets/ocr.md +25 -1
  3. package/dist/assets/prep-scan.md +42 -4
  4. package/dist/assets/prep-scan.py +432 -10
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
  7. package/dist/bundled-skills/archive-org/SKILL.md +40 -7
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
  9. package/dist/bundled-skills/california-archives/SKILL.md +10 -0
  10. package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
  11. package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
  12. package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
  13. package/dist/bundled-skills/findagrave/SKILL.md +18 -5
  14. package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
  15. package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
  16. package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
  17. package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
  18. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
  19. package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
  20. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
  21. package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
  22. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
  23. package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
  24. package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
  25. package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
  26. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
  27. package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
  28. package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
  29. package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
  30. package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
  31. package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
  32. package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
  33. package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
  34. package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
  35. package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
  36. package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
  37. package/dist/bundled-skills/wikitree/SKILL.md +7 -1
  38. package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +107 -2
  41. package/dist/cli.js.map +1 -1
  42. package/dist/client.d.ts.map +1 -1
  43. package/dist/client.js +30 -5
  44. package/dist/client.js.map +1 -1
  45. package/dist/commands/ops/audit.d.ts.map +1 -1
  46. package/dist/commands/ops/audit.js +5 -0
  47. package/dist/commands/ops/audit.js.map +1 -1
  48. package/dist/commands/ops/dates.d.ts +87 -0
  49. package/dist/commands/ops/dates.d.ts.map +1 -0
  50. package/dist/commands/ops/dates.js +228 -0
  51. package/dist/commands/ops/dates.js.map +1 -0
  52. package/dist/commands/ops/help.d.ts +3 -1
  53. package/dist/commands/ops/help.d.ts.map +1 -1
  54. package/dist/commands/ops/help.js +33 -0
  55. package/dist/commands/ops/help.js.map +1 -1
  56. package/dist/commands/ops/index.d.ts +3 -1
  57. package/dist/commands/ops/index.d.ts.map +1 -1
  58. package/dist/commands/ops/index.js +2 -0
  59. package/dist/commands/ops/index.js.map +1 -1
  60. package/dist/commands/ops/integrate.d.ts +5 -0
  61. package/dist/commands/ops/integrate.d.ts.map +1 -1
  62. package/dist/commands/ops/integrate.js +272 -26
  63. package/dist/commands/ops/integrate.js.map +1 -1
  64. package/dist/commands/ops/sync.d.ts +17 -0
  65. package/dist/commands/ops/sync.d.ts.map +1 -1
  66. package/dist/commands/ops/sync.js +173 -0
  67. package/dist/commands/ops/sync.js.map +1 -1
  68. package/dist/commands/ops/verify.d.ts +76 -0
  69. package/dist/commands/ops/verify.d.ts.map +1 -0
  70. package/dist/commands/ops/verify.js +325 -0
  71. package/dist/commands/ops/verify.js.map +1 -0
  72. package/dist/commands/records/index.d.ts +1 -1
  73. package/dist/commands/records/index.d.ts.map +1 -1
  74. package/dist/commands/records/index.js +1 -1
  75. package/dist/commands/records/index.js.map +1 -1
  76. package/dist/commands/records/runner.d.ts +2 -0
  77. package/dist/commands/records/runner.d.ts.map +1 -1
  78. package/dist/commands/records/runner.js +33 -2
  79. package/dist/commands/records/runner.js.map +1 -1
  80. package/package.json +2 -2
@@ -93,9 +93,16 @@ Check the rights string before promising a readable copy. A title can be in Hath
93
93
  - URL scheme: `https://babel.hathitrust.org/cgi/htd/<resource>/<id>[/<fileid|seq>]`.
94
94
  - The CLI does not implement the Data API. If a Full View volume is needed as OCR text, first try the item URL in a browser; request a key only if programmatic bulk access is genuinely needed.
95
95
 
96
- ## Environment variables
96
+ ## Disk cache and environment variables
97
97
 
98
- - None. The Bibliographic API needs no key and the CLI reads no environment variables.
98
+ `bib` caches successful non-empty Bibliographic API lookups per identifier on disk under `~/.cache/kinloom-hathi/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors, non-JSON responses, and empty/error payloads are never cached.
99
+
100
+ - `--refresh`: bypass cached reads and write the fresh response to disk.
101
+ - `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
102
+ - `KINLOOM_HATHI_CACHE_DIR`: override the cache directory path.
103
+ - `KINLOOM_HATHI_CACHE_TTL_HOURS`: override the default TTL in hours.
104
+
105
+ No API key or login is needed for the Bibliographic API.
99
106
 
100
107
  ## Research workflow notes
101
108
 
@@ -18,13 +18,22 @@ search URL instead of fetching results.
18
18
 
19
19
  from __future__ import annotations
20
20
 
21
+ import hashlib
21
22
  import json
22
- import sys
23
+ import math
24
+ import os
25
+ import time
26
+ from contextlib import contextmanager
27
+ from pathlib import Path
28
+ from typing import Any, Callable, Iterator
23
29
  from urllib.parse import quote, urlencode
24
30
 
25
31
  import click
26
32
  import httpx
27
33
 
34
+ DEFAULT_CACHE_TTL_HOURS = 168.0
35
+ CACHE_SCHEMA = 1
36
+
28
37
  BIB_API_BASE = "https://catalog.hathitrust.org/api/volumes"
29
38
  CATALOG_SEARCH_BASE = "https://catalog.hathitrust.org/Search/Home"
30
39
  USER_AGENT = (
@@ -35,6 +44,149 @@ VALID_ID_TYPES = ("oclc", "lccn", "issn", "isbn", "htid", "recordnumber")
35
44
  VALID_SEARCH_TYPES = ("all", "title", "author", "subject")
36
45
 
37
46
 
47
+ def cache_dir() -> Path:
48
+ override = os.environ.get("KINLOOM_HATHI_CACHE_DIR")
49
+ if override:
50
+ return Path(override).expanduser()
51
+ return Path.home() / ".cache" / "kinloom-hathi"
52
+
53
+
54
+ def resolve_ttl_hours(cli_ttl: float | None) -> float:
55
+ if cli_ttl is not None:
56
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
57
+ raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
58
+ return float(cli_ttl)
59
+ raw = os.environ.get("KINLOOM_HATHI_CACHE_TTL_HOURS")
60
+ if raw is not None and raw.strip():
61
+ try:
62
+ parsed = float(raw.strip())
63
+ except ValueError as exc:
64
+ raise click.BadParameter(f"Invalid KINLOOM_HATHI_CACHE_TTL_HOURS value: {raw!r}.") from exc
65
+ if not math.isfinite(parsed) or parsed < 0:
66
+ raise click.BadParameter(
67
+ f"Invalid KINLOOM_HATHI_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
68
+ )
69
+ return parsed
70
+ return DEFAULT_CACHE_TTL_HOURS
71
+
72
+
73
+ @contextmanager
74
+ def file_lock(lock_path: Path) -> Iterator[None]:
75
+ """Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
76
+ try:
77
+ import fcntl
78
+ except ImportError:
79
+ yield
80
+ return
81
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
82
+ with open(lock_path, "a+b") as lock_file:
83
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
84
+ try:
85
+ yield
86
+ finally:
87
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
88
+
89
+
90
+ def atomic_write_json(dest: Path, payload: Any) -> None:
91
+ dest.parent.mkdir(parents=True, exist_ok=True)
92
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
93
+ try:
94
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
95
+ os.replace(tmp, dest)
96
+ except Exception:
97
+ tmp.unlink(missing_ok=True)
98
+ raise
99
+
100
+
101
+ def cache_key(kind: str, payload: dict) -> str:
102
+ canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
103
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
104
+
105
+
106
+ def read_cache(path: Path, ttl_hours: float) -> dict | None:
107
+ if not path.is_file():
108
+ return None
109
+ try:
110
+ entry = json.loads(path.read_text(encoding="utf-8"))
111
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
112
+ return None
113
+ if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
114
+ return None
115
+ fetched = entry.get("fetched_at")
116
+ if not isinstance(fetched, (int, float)):
117
+ return None
118
+ if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
119
+ return None
120
+ result = entry.get("result")
121
+ return result if isinstance(result, dict) else None
122
+
123
+
124
+ def cached_call(
125
+ kind: str,
126
+ payload: dict,
127
+ fetch: Callable[[], dict],
128
+ *,
129
+ refresh: bool,
130
+ ttl_hours: float,
131
+ cacheable: Callable[[dict], bool] = lambda _r: True,
132
+ ) -> tuple[dict, bool]:
133
+ """Return (result, cache_hit) with per-key flock and atomic JSON writes."""
134
+ key = cache_key(kind, payload)
135
+ root = cache_dir()
136
+ path = root / f"{key}.json"
137
+ if not refresh:
138
+ hit = read_cache(path, ttl_hours)
139
+ if hit is not None:
140
+ return hit, True
141
+ with file_lock(root / f"{key}.lock"):
142
+ if not refresh:
143
+ hit = read_cache(path, ttl_hours)
144
+ if hit is not None:
145
+ return hit, True
146
+ result = fetch()
147
+ if cacheable(result):
148
+ atomic_write_json(
149
+ path,
150
+ {
151
+ "schema": CACHE_SCHEMA,
152
+ "fetched_at": time.time(),
153
+ "kind": kind,
154
+ "query": payload,
155
+ "result": result,
156
+ },
157
+ )
158
+ return result, False
159
+
160
+
161
+ def cache_options(func: Callable) -> Callable:
162
+ func = click.option(
163
+ "--cache-ttl-hours",
164
+ type=float,
165
+ default=None,
166
+ help="Cache TTL in hours (default 168, env KINLOOM_HATHI_CACHE_TTL_HOURS; 0 disables reads).",
167
+ )(func)
168
+ func = click.option(
169
+ "--refresh",
170
+ is_flag=True,
171
+ help="Bypass the disk cache for this request (the fresh result is still cached).",
172
+ )(func)
173
+ return func
174
+
175
+
176
+ def _client() -> httpx.Client:
177
+ return httpx.Client(headers={"User-Agent": USER_AGENT})
178
+
179
+
180
+ def _bib_cacheable(data: dict) -> bool:
181
+ if not isinstance(data, dict) or data.get("error"):
182
+ return False
183
+ records = data.get("records")
184
+ items = data.get("items")
185
+ if not isinstance(records, dict) or not isinstance(items, list):
186
+ return False
187
+ return bool(records) or bool(items)
188
+
189
+
38
190
  def bib_url(id_type: str, value: str, full: bool) -> str:
39
191
  brevity = "full" if full else "brief"
40
192
  return f"{BIB_API_BASE}/{brevity}/{id_type}/{quote(value, safe='')}.json"
@@ -52,9 +204,12 @@ def fetch_bib(client: httpx.Client, id_type: str, value: str, full: bool) -> dic
52
204
  except httpx.HTTPError as exc:
53
205
  raise click.ClickException(f"Bib API request failed: {exc}") from exc
54
206
  try:
55
- return resp.json()
207
+ data = resp.json()
56
208
  except ValueError as exc:
57
209
  raise click.ClickException(f"Bib API returned non-JSON for {url}") from exc
210
+ if not isinstance(data, dict):
211
+ raise click.ClickException(f"Bib API returned unexpected JSON shape for {url}")
212
+ return data
58
213
 
59
214
 
60
215
  def parse_id(spec: str) -> tuple[str, str]:
@@ -73,15 +228,19 @@ def parse_id(spec: str) -> tuple[str, str]:
73
228
  return id_type, value
74
229
 
75
230
 
76
- def compact_bib(data: dict, full: bool) -> str:
231
+ def compact_bib(data: dict, full: bool, *, cache_hit: bool = False) -> str:
232
+ marker = " [cache]" if cache_hit else ""
77
233
  lines: list[str] = []
78
234
  records = data.get("records") or {}
79
235
  items = data.get("items") or []
80
236
  if not records and not items:
81
- return "No matching HathiTrust record (empty records and items)."
237
+ return f"No matching HathiTrust record (empty records and items).{marker}"
238
+ first = True
82
239
  for rec_no, rec in records.items():
83
240
  titles = rec.get("titles") or []
84
- lines.append(f"Record {rec_no}: {titles[0] if titles else '(no title)'}")
241
+ suffix = marker if first else ""
242
+ first = False
243
+ lines.append(f"Record {rec_no}: {titles[0] if titles else '(no title)'}{suffix}")
85
244
  if len(titles) > 1:
86
245
  lines.append(f" alt titles: {'; '.join(titles[1:])}")
87
246
  lines.append(f" record URL: {rec.get('recordURL', '')}")
@@ -94,9 +253,11 @@ def compact_bib(data: dict, full: bool) -> str:
94
253
  lines.append(" marc-xml:")
95
254
  lines.append(rec["marc-xml"])
96
255
  for item in items:
256
+ suffix = marker if first else ""
257
+ first = False
97
258
  lines.append(
98
259
  f"Item {item.get('htid', '')} ({item.get('orig', '')}): "
99
- f"{item.get('usRightsString', '')}"
260
+ f"{item.get('usRightsString', '')}{suffix}"
100
261
  )
101
262
  lines.append(f" item URL: {item.get('itemURL', '')}")
102
263
  if item.get("enumcron"):
@@ -122,12 +283,15 @@ def cli() -> None:
122
283
  )
123
284
  @click.option("--full", is_flag=True, help="Full record with MARC-XML.")
124
285
  @click.option("--json", "as_json", is_flag=True, help="Print raw API JSON.")
286
+ @cache_options
125
287
  def bib(
126
288
  id_type: str | None,
127
289
  value: str | None,
128
290
  ids: tuple[str, ...],
129
291
  full: bool,
130
292
  as_json: bool,
293
+ refresh: bool,
294
+ cache_ttl_hours: float | None,
131
295
  ) -> None:
132
296
  """Look up record(s) by identifier.
133
297
 
@@ -154,16 +318,37 @@ def bib(
154
318
  "Give an identifier: hathi bib <type> <value> "
155
319
  "or hathi bib --id type:value [--id type:value ...]"
156
320
  )
157
- merged: dict = {"records": {}, "items": []}
158
- with httpx.Client(headers={"User-Agent": USER_AGENT}) as client:
159
- for id_type, value in specs:
160
- data = fetch_bib(client, id_type, value, full)
321
+ ttl = resolve_ttl_hours(cache_ttl_hours)
322
+ merged: dict[str, Any] = {"records": {}, "items": []}
323
+ hits: list[bool] = []
324
+ client: httpx.Client | None = None
325
+ try:
326
+ for spec_type, spec_value in specs:
327
+ def _fetch(t: str = spec_type, v: str = spec_value) -> dict:
328
+ nonlocal client
329
+ if client is None:
330
+ client = _client()
331
+ return fetch_bib(client, t, v, full)
332
+
333
+ data, hit = cached_call(
334
+ "bib",
335
+ {"id_type": spec_type, "value": spec_value, "full": full},
336
+ _fetch,
337
+ refresh=refresh,
338
+ ttl_hours=ttl,
339
+ cacheable=_bib_cacheable,
340
+ )
341
+ hits.append(hit)
161
342
  merged["records"].update(data.get("records") or {})
162
343
  merged["items"].extend(data.get("items") or [])
344
+ finally:
345
+ if client is not None:
346
+ client.close()
347
+ all_cached = bool(hits) and all(hits)
163
348
  if as_json:
164
- click.echo(json.dumps(merged, indent=2, ensure_ascii=False))
349
+ click.echo(json.dumps({**merged, "cache_hit": all_cached}, indent=2, ensure_ascii=False))
165
350
  else:
166
- click.echo(compact_bib(merged, full))
351
+ click.echo(compact_bib(merged, full, cache_hit=all_cached))
167
352
 
168
353
 
169
354
  @cli.command()
@@ -29,6 +29,7 @@ Notes on the interfaces:
29
29
  - The Land Office form is ASP.NET with `__VIEWSTATE`/`__EVENTVALIDATION`; the CLI does the three-request dance (GET, postback to reveal the advanced panel, search POST) and parses the results table into patent, grantee, grant book/page, acreage, county, watercourse, survey name, survey/grant dates, and grant note.
30
30
  - The Preservica host has no public Preservica search API (`/wp-json/` returns a Preservica "Page Not Found" page). The WordPress search RSS feed is the machine route; it returns up to 100 items per query. The site's search is full-text over titles, descriptions, creators, and document contents, so a hit's title often does not show why it matched: open the hit to confirm. Viewing a packet's scans needs the browser.
31
31
  - No account or API key is needed to search any portal in this skill. Fees apply only to ordering copies, noted per repository below.
32
+ - **Disk cache:** `cdm`, `cdm-item`, `collections`, `land`, `land-patent`, and `preservica` cache successful responses under `~/.cache/kinloom-ky-archives/` (default TTL `168` hours, per-key `flock`, atomic JSON writes). Pass `--refresh` to force a fresh fetch or `--cache-ttl-hours <hours>` (`0` disables reads). Override with `KINLOOM_KY_ARCHIVES_CACHE_DIR` and `KINLOOM_KY_ARCHIVES_CACHE_TTL_HOURS`. HTTP errors and unverified 0-hit error pages are never cached.
32
33
 
33
34
  ## Kentucky Historical Society (KHS)
34
35