@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
@@ -9,49 +9,314 @@
9
9
  """Search Library of Congress Chronicling America historic newspapers.
10
10
 
11
11
  Uses the public loc.gov JSON API (no key, no account). The retired
12
- chroniclingamerica.loc.gov search API returns 404 as of 2026-11-24;
13
- do not use it or third-party docs that describe it.
12
+ chroniclingamerica.loc.gov search API now 308-redirects away; do not use it
13
+ or third-party docs that describe it.
14
+
15
+ loc.gov collection searches are slow on the server side: measured
16
+ 2026-11-25, connect + TLS took < 0.1 s but time-to-first-byte was 19-43 s
17
+ for every search (with or without q, dates, state, dl, at). The default
18
+ timeout budget is therefore 120 s, and every successful search is cached on
19
+ disk so a repeat never hits loc.gov again.
14
20
  """
15
21
 
16
22
  from __future__ import annotations
17
23
 
24
+ import hashlib
18
25
  import json
26
+ import math
27
+ import os
19
28
  import re
20
29
  import sys
21
30
  import time
31
+ from contextlib import contextmanager
22
32
  from pathlib import Path
33
+ from typing import Any, Iterator
23
34
  from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
24
35
 
25
36
  import click
26
37
  import httpx
27
38
 
28
39
  COLLECTION_BASE = "https://www.loc.gov/collections/chronicling-america/"
29
- HEADERS = {"User-Agent": "kinloom/1.0 (genealogy research)"}
40
+ HEADERS = {
41
+ "User-Agent": "kinloom/1.0 (genealogy research)",
42
+ "Accept": "application/json",
43
+ }
30
44
  # tile.loc.gov (storage-services PDFs) rejects hotlinking: it requires a
31
45
  # loc.gov Referer. Send one for all file downloads; harmless elsewhere.
32
46
  DOWNLOAD_HEADERS = dict(HEADERS, Referer="https://www.loc.gov/")
33
- TIMEOUT = 25.0
34
-
35
-
36
- def _get_json(url: str, params: dict | list[tuple[str, str]] | None = None) -> dict:
37
- last_exc: Exception | None = None
38
- for attempt in range(2):
47
+ # Measured 2026-11-25: loc.gov search TTFB is 19-43 s. An 8 s budget made
48
+ # 80%+ of searches fail. One probe under 6 parallel requests took 70 s,
49
+ # so 120 s covers the observed tail with headroom.
50
+ DEFAULT_TIMEOUT = 120.0
51
+ DOWNLOAD_TIMEOUT = 60.0
52
+ RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504, 520, 522, 524}
53
+ MAX_RETRY_AFTER_S = 30.0
54
+ COLLECTION_START_YEAR = "1736"
55
+ COLLECTION_END_YEAR = "1963"
56
+ DEFAULT_CACHE_TTL_HOURS = 168.0
57
+ CACHE_SCHEMA = 1
58
+
59
+ US_STATES = {
60
+ "AL": "alabama", "AK": "alaska", "AZ": "arizona", "AR": "arkansas",
61
+ "CA": "california", "CO": "colorado", "CT": "connecticut", "DE": "delaware",
62
+ "DC": "district of columbia", "FL": "florida", "GA": "georgia", "HI": "hawaii",
63
+ "ID": "idaho", "IL": "illinois", "IN": "indiana", "IA": "iowa", "KS": "kansas",
64
+ "KY": "kentucky", "LA": "louisiana", "ME": "maine", "MD": "maryland",
65
+ "MA": "massachusetts", "MI": "michigan", "MN": "minnesota", "MS": "mississippi",
66
+ "MO": "missouri", "MT": "montana", "NE": "nebraska", "NV": "nevada",
67
+ "NH": "new hampshire", "NJ": "new jersey", "NM": "new mexico", "NY": "new york",
68
+ "NC": "north carolina", "ND": "north dakota", "OH": "ohio", "OK": "oklahoma",
69
+ "OR": "oregon", "PA": "pennsylvania", "PR": "puerto rico", "RI": "rhode island",
70
+ "SC": "south carolina", "SD": "south dakota", "TN": "tennessee", "TX": "texas",
71
+ "UT": "utah", "VT": "vermont", "VA": "virginia", "VI": "virgin islands",
72
+ "WA": "washington", "WV": "west virginia", "WI": "wisconsin", "WY": "wyoming",
73
+ }
74
+
75
+
76
+ # --- disk cache ---------------------------------------------------------------
77
+
78
+ def cache_dir() -> Path:
79
+ override = os.environ.get("KINLOOM_CHRONAM_CACHE_DIR")
80
+ if override:
81
+ return Path(override).expanduser()
82
+ return Path.home() / ".cache" / "kinloom-chronam"
83
+
84
+
85
+ def resolve_ttl_hours(cli_ttl: float | None) -> float:
86
+ if cli_ttl is not None:
87
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
88
+ raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
89
+ return float(cli_ttl)
90
+ raw = os.environ.get("KINLOOM_CHRONAM_CACHE_TTL_HOURS")
91
+ if raw is not None and raw.strip():
92
+ try:
93
+ parsed = float(raw.strip())
94
+ except ValueError as exc:
95
+ raise click.BadParameter(f"Invalid KINLOOM_CHRONAM_CACHE_TTL_HOURS value: {raw!r}.") from exc
96
+ if not math.isfinite(parsed) or parsed < 0:
97
+ raise click.BadParameter(
98
+ f"Invalid KINLOOM_CHRONAM_CACHE_TTL_HOURS value: {raw!r} (must be >= 0).")
99
+ return parsed
100
+ return DEFAULT_CACHE_TTL_HOURS
101
+
102
+
103
+ @contextmanager
104
+ def file_lock(lock_path: Path) -> Iterator[None]:
105
+ """Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
106
+ try:
107
+ import fcntl
108
+ except ImportError:
109
+ yield
110
+ return
111
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
112
+ with open(lock_path, "a+b") as lock_file:
113
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
39
114
  try:
40
- with httpx.Client(headers=HEADERS, timeout=TIMEOUT, follow_redirects=True) as client:
41
- resp = client.get(url, params=params)
115
+ yield
116
+ finally:
117
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
118
+
119
+
120
+ def atomic_write_json(dest: Path, payload: Any) -> None:
121
+ dest.parent.mkdir(parents=True, exist_ok=True)
122
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
123
+ try:
124
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
125
+ os.replace(tmp, dest)
126
+ except Exception:
127
+ tmp.unlink(missing_ok=True)
128
+ raise
129
+
130
+
131
+ def cache_key(url: str, params: list[tuple[str, str]] | None) -> str:
132
+ canonical = json.dumps([url, sorted(params or [])], separators=(",", ":"))
133
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
134
+
135
+
136
+ def read_cache(path: Path, ttl_hours: float) -> dict | None:
137
+ if not path.is_file():
138
+ return None
139
+ try:
140
+ entry = json.loads(path.read_text(encoding="utf-8"))
141
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
142
+ return None
143
+ if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
144
+ return None
145
+ fetched = entry.get("fetched_at")
146
+ if not isinstance(fetched, (int, float)):
147
+ return None
148
+ if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
149
+ return None
150
+ data = entry.get("data")
151
+ return data if isinstance(data, dict) else None
152
+
153
+
154
+ def cached_get_json(
155
+ url: str,
156
+ params: list[tuple[str, str]] | None,
157
+ *,
158
+ timeout: float,
159
+ refresh: bool,
160
+ ttl_hours: float,
161
+ cacheable=lambda data: True,
162
+ ) -> tuple[dict, bool]:
163
+ """Return (data, cache_hit). Concurrent callers of one query serialize on
164
+ a per-key flock, so the second caller reads the first caller's result."""
165
+ key = cache_key(url, params)
166
+ root = cache_dir()
167
+ path = root / f"{key}.json"
168
+ if not refresh:
169
+ hit = read_cache(path, ttl_hours)
170
+ if hit is not None:
171
+ return hit, True
172
+ with file_lock(root / f"{key}.lock"):
173
+ if not refresh:
174
+ hit = read_cache(path, ttl_hours)
175
+ if hit is not None:
176
+ return hit, True
177
+ data = _get_json(url, params=params, timeout=timeout)
178
+ if cacheable(data):
179
+ atomic_write_json(path, {"schema": CACHE_SCHEMA, "fetched_at": time.time(),
180
+ "url": url, "params": params or [], "data": data})
181
+ return data, False
182
+
183
+
184
+ # --- HTTP -----------------------------------------------------------------------
185
+
186
+ def _retry_after_seconds(resp: httpx.Response) -> float:
187
+ raw = resp.headers.get("retry-after", "").strip()
188
+ try:
189
+ return max(0.0, min(float(raw), MAX_RETRY_AFTER_S))
190
+ except ValueError:
191
+ return 1.0
192
+
193
+
194
+ def _get_json(
195
+ url: str,
196
+ params: dict | list[tuple[str, str]] | None = None,
197
+ *,
198
+ timeout: float = DEFAULT_TIMEOUT,
199
+ client: httpx.Client | None = None,
200
+ ) -> dict:
201
+ deadline = time.monotonic() + timeout
202
+ last_exc: Exception | None = None
203
+
204
+ def _run(http_client: httpx.Client) -> dict:
205
+ nonlocal last_exc
206
+ for attempt in range(2):
207
+ remaining = deadline - time.monotonic()
208
+ if remaining <= 0.25:
209
+ break
210
+ try:
211
+ resp = http_client.get(url, params=params, timeout=remaining)
212
+ except httpx.TimeoutException as exc:
213
+ raise click.ClickException(
214
+ f"loc.gov request timed out after {timeout:.1f}s ({exc}). "
215
+ "loc.gov searches normally take 20-45 s; increase --timeout, "
216
+ "narrow with --state, --dates, or --lccn, "
217
+ "or open the browser URL from `chronam url`."
218
+ ) from exc
219
+ except (httpx.RemoteProtocolError, httpx.ConnectError) as exc:
220
+ last_exc = exc
221
+ if attempt == 0 and (deadline - time.monotonic()) >= 2.0:
222
+ time.sleep(0.4)
223
+ continue
224
+ raise click.ClickException(
225
+ f"loc.gov connection error: {exc}. "
226
+ "Retry once or narrow with --state/--dates/--lccn."
227
+ ) from exc
228
+ except httpx.HTTPError as exc:
229
+ raise click.ClickException(f"loc.gov request failed: {exc}") from exc
230
+
231
+ if resp.status_code in RETRYABLE_STATUS_CODES:
232
+ last_exc = httpx.HTTPStatusError(
233
+ f"HTTP {resp.status_code}", request=resp.request, response=resp
234
+ )
235
+ wait = _retry_after_seconds(resp) if resp.status_code in (429, 503) else 0.4
236
+ if attempt == 0 and (deadline - time.monotonic()) >= wait + 2.0:
237
+ time.sleep(wait)
238
+ continue
239
+ kind = "rate limited" if resp.status_code == 429 else "transient service error"
240
+ raise click.ClickException(
241
+ f"loc.gov returned HTTP {resp.status_code} ({kind}). "
242
+ "Wait and retry, narrow with --state/--dates/--lccn, or open `chronam url` in a browser."
243
+ )
244
+
245
+ try:
42
246
  resp.raise_for_status()
247
+ except httpx.HTTPStatusError as exc:
248
+ raise click.ClickException(
249
+ f"loc.gov returned HTTP {resp.status_code} for {resp.request.url}"
250
+ ) from exc
251
+
252
+ try:
43
253
  return resp.json()
44
- except (httpx.RemoteProtocolError, httpx.ReadTimeout) as exc:
45
- last_exc = exc
46
- if attempt == 0:
47
- time.sleep(1.5)
48
- continue
49
- raise click.ClickException(f"loc.gov request failed after retry: {exc}") from exc
50
- raise click.ClickException(f"loc.gov request failed: {last_exc}")
254
+ except ValueError as exc:
255
+ raise click.ClickException(
256
+ f"loc.gov returned non-JSON response (HTTP {resp.status_code}, "
257
+ f"content-type={resp.headers.get('content-type', 'unknown')})."
258
+ ) from exc
259
+
260
+ raise click.ClickException(
261
+ f"loc.gov request failed after {timeout:.1f}s: {last_exc}"
262
+ )
51
263
 
264
+ if client is not None:
265
+ return _run(client)
266
+ with httpx.Client(headers=HEADERS, timeout=timeout, follow_redirects=True) as managed_client:
267
+ return _run(managed_client)
52
268
 
53
- def _as_jsonable(value):
54
- return value
269
+
270
+ # --- query building ----------------------------------------------------------
271
+
272
+ def _resolve_query(words: tuple[str, ...], terms_opt: str | None) -> str:
273
+ query = " ".join(w for w in words if w).strip() or (terms_opt or "").strip()
274
+ if not query:
275
+ raise click.UsageError("Provide QUERY words as positional arguments or via --terms/--query.")
276
+ return query
277
+
278
+
279
+ def _resolve_dates(dates: str | None, date_from: str | None, date_to: str | None) -> str | None:
280
+ if dates:
281
+ cleaned = dates.strip().replace("-", "/")
282
+ if re.fullmatch(r"\d{4}", cleaned):
283
+ return f"{cleaned}/{cleaned}"
284
+ if not re.fullmatch(r"\d{4}/\d{4}", cleaned):
285
+ raise click.BadParameter(f"--dates {dates!r}: expected YYYY/YYYY (or YYYY).", param_hint="--dates")
286
+ return cleaned
287
+ if date_from or date_to:
288
+ start = (date_from or COLLECTION_START_YEAR).strip()[:4]
289
+ end = (date_to or COLLECTION_END_YEAR).strip()[:4]
290
+ for label, year in (("start", start), ("end", end)):
291
+ if not re.fullmatch(r"\d{4}", year):
292
+ raise click.BadParameter(f"{label} year {year!r}: expected YYYY.")
293
+ return f"{start}/{end}"
294
+ return None
295
+
296
+
297
+ def normalize_state(state: str) -> str:
298
+ cleaned = state.strip()
299
+ return US_STATES.get(cleaned.upper(), cleaned).lower()
300
+
301
+
302
+ def build_search_params(query: str, *, dates: str | None, level: str, limit: int, page: int,
303
+ state: str | None, lccn: str | None) -> list[tuple[str, str]]:
304
+ params: list[tuple[str, str]] = [
305
+ ("q", query),
306
+ ("fo", "json"),
307
+ ("at", "search,results"),
308
+ ("c", str(limit)),
309
+ ("sp", str(page)),
310
+ ]
311
+ if level != "all":
312
+ params.append(("dl", level))
313
+ if dates:
314
+ params.append(("dates", dates))
315
+ if state:
316
+ params.append(("fa", f"location_state:{normalize_state(state)}"))
317
+ if lccn:
318
+ params.append(("fa", f"number_lccn:{lccn.strip()}"))
319
+ return params
55
320
 
56
321
 
57
322
  def _first(value):
@@ -74,65 +339,95 @@ def _compact_result(item: dict) -> dict:
74
339
  }
75
340
 
76
341
 
77
- def _print_search(data: dict, as_json: bool) -> None:
342
+ def _print_search(data: dict, as_json: bool, cache_hit: bool) -> None:
78
343
  search = data.get("search") or {}
79
344
  hits = search.get("hits")
80
345
  results = data.get("results") or []
81
346
  if as_json:
82
347
  click.echo(json.dumps(
83
- {"hits": hits, "results": [_compact_result(r) for r in results]},
348
+ {"hits": hits, "cache_hit": cache_hit, "results": [_compact_result(r) for r in results]},
84
349
  indent=2, ensure_ascii=False))
85
350
  return
86
- click.echo(f"hits: {hits} (showing {len(results)} on this page)")
351
+ click.echo(f"hits: {hits} (showing {len(results)} on this page){' [cache]' if cache_hit else ''}")
87
352
  for item in results:
88
353
  c = _compact_result(item)
89
354
  click.echo(f"- {c['date']} | {c['title']} | {c['state']} | {c['url']}")
90
355
 
91
356
 
92
- def _resource_json(resource_url: str) -> dict:
357
+ def _search_cacheable(data: dict) -> bool:
358
+ # loc.gov sometimes answers a valid query with a transient 0-hit page
359
+ # (measured 2026-11-25: "Abraham Lincoln" gave 0, then 25,392 on rerun).
360
+ # Never cache an empty answer, so the next call asks loc.gov again.
361
+ hits = (data.get("search") or {}).get("hits")
362
+ return bool(hits) and bool(data.get("results"))
363
+
364
+
365
+ def _resource_url_json(resource_url: str) -> str:
93
366
  parsed = urlparse(resource_url)
94
367
  qs = parse_qs(parsed.query)
95
368
  qs["fo"] = ["json"]
96
- url = urlunparse(parsed._replace(query=urlencode(qs, doseq=True)))
97
- return _get_json(url)
369
+ return urlunparse(parsed._replace(query=urlencode(qs, doseq=True)))
98
370
 
99
371
 
100
372
  def _build_resource_url(lccn: str, date: str, edition: str, seq: str) -> str:
101
373
  return f"https://www.loc.gov/resource/{lccn}/{date}/ed-{edition}/?sp={seq}"
102
374
 
103
375
 
376
+ def _cache_options(f):
377
+ f = click.option("--cache-ttl-hours", type=float, default=None,
378
+ help=f"Cache TTL in hours (default {DEFAULT_CACHE_TTL_HOURS:g}; "
379
+ "env KINLOOM_CHRONAM_CACHE_TTL_HOURS).")(f)
380
+ f = click.option("--refresh", is_flag=True, help="Bypass the disk cache and re-query loc.gov.")(f)
381
+ return f
382
+
383
+
384
+ def _query_options(f):
385
+ for decorator in reversed([
386
+ click.argument("query", nargs=-1),
387
+ click.option("--terms", "--query", "-q", "terms_opt", default=None,
388
+ help="Alias for positional QUERY."),
389
+ click.option("--dates", default=None, help="Date range YYYY/YYYY (or one year YYYY)."),
390
+ click.option("--date-from", "--from-year", "--date1", "--year1", "--start", "date_from",
391
+ default=None, help="Start year YYYY (alternative to --dates)."),
392
+ click.option("--date-to", "--to-year", "--date2", "--year2", "--end", "date_to",
393
+ default=None, help="End year YYYY (alternative to --dates)."),
394
+ click.option("--level", default="page", type=click.Choice(["page", "issue", "title", "all"]),
395
+ show_default=True, help="Display level (dl=)."),
396
+ click.option("--state", default=None,
397
+ help="State name or postal code (CA, NJ); sent as fa=location_state:<state>."),
398
+ click.option("--lccn", default=None, help="Filter by newspaper LCCN via fa=number_lccn:<lccn>."),
399
+ ]):
400
+ f = decorator(f)
401
+ return f
402
+
403
+
104
404
  @click.group()
105
405
  def cli() -> None:
106
406
  """Search Chronicling America historic newspapers (Library of Congress)."""
107
407
 
108
408
 
109
409
  @cli.command()
110
- @click.argument("query")
111
- @click.option("--dates", default=None, help="Date range YYYY/YYYY, e.g. 1880/1920.")
112
- @click.option("--level", default="page", type=click.Choice(["page", "issue", "title", "all"]),
113
- show_default=True, help="Display level (dl=).")
114
- @click.option("--limit", "-n", default=10, show_default=True, help="Results per page (c=).")
410
+ @_query_options
411
+ @click.option("--limit", "--per-page", "--rows", "-n", default=10, show_default=True,
412
+ help="Results per page (c=).")
115
413
  @click.option("--page", "-p", default=1, show_default=True, help="Results page (sp=).")
116
- @click.option("--state", default=None, help="Filter by state server-side via fa=location_state:<state>.")
117
- @click.option("--lccn", default=None, help="Filter by newspaper LCCN server-side via fa=number_lccn:<lccn>.")
414
+ @click.option("--timeout", default=DEFAULT_TIMEOUT, show_default=True, type=float,
415
+ help="Request timeout budget in seconds (loc.gov search takes 20-45 s).")
416
+ @_cache_options
118
417
  @click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of compact text.")
119
- def search(query, dates, level, limit, page, state, lccn, as_json):
120
- """Search newspaper pages for QUERY (full-text, e.g. a surname)."""
121
- params: list[tuple[str, str]] = [
122
- ("q", query),
123
- ("fo", "json"),
124
- ("c", str(limit)),
125
- ("sp", str(page)),
126
- ]
127
- if level != "all":
128
- params.append(("dl", level))
129
- if dates:
130
- params.append(("dates", dates))
131
- if state:
132
- params.append(("fa", f"location_state:{state.strip().lower()}"))
133
- if lccn:
134
- params.append(("fa", f"number_lccn:{lccn.strip()}"))
135
- data = _get_json(COLLECTION_BASE, params=params)
418
+ def search(query, terms_opt, dates, date_from, date_to, level, state, lccn, limit, page,
419
+ timeout, refresh, cache_ttl_hours, as_json):
420
+ """Search newspaper pages for QUERY (full-text, e.g. a surname).
421
+
422
+ Multi-word queries need no quotes: `chronam search Abraham Lincoln`.
423
+ Results are cached on disk (~/.cache/kinloom-chronam, 168 h TTL).
424
+ """
425
+ resolved_query = _resolve_query(query, terms_opt)
426
+ params = build_search_params(resolved_query, dates=_resolve_dates(dates, date_from, date_to),
427
+ level=level, limit=limit, page=page, state=state, lccn=lccn)
428
+ ttl = resolve_ttl_hours(cache_ttl_hours)
429
+ data, cache_hit = cached_get_json(COLLECTION_BASE, params, timeout=timeout, refresh=refresh,
430
+ ttl_hours=ttl, cacheable=_search_cacheable)
136
431
  results = data.get("results") or []
137
432
  hits = (data.get("search") or {}).get("hits")
138
433
  if hits and not results:
@@ -141,8 +436,14 @@ def search(query, dates, level, limit, page, state, lccn, as_json):
141
436
  "Check --page or retry once if loc.gov dropped facet results.",
142
437
  err=True,
143
438
  )
439
+ elif not hits:
440
+ click.echo(
441
+ "Note: 0 hits. loc.gov sometimes returns a transient empty answer; empty results are "
442
+ "never cached, so one rerun confirms a true zero.",
443
+ err=True,
444
+ )
144
445
  data["results"] = results
145
- _print_search(data, as_json)
446
+ _print_search(data, as_json, cache_hit)
146
447
 
147
448
 
148
449
  @cli.command()
@@ -151,8 +452,11 @@ def search(query, dates, level, limit, page, state, lccn, as_json):
151
452
  @click.option("--date", default=None, help="Issue date YYYY-MM-DD.")
152
453
  @click.option("--edition", default="1", show_default=True)
153
454
  @click.option("--seq", default="1", show_default=True, help="Page sequence within the issue (?sp=).")
455
+ @click.option("--timeout", default=DEFAULT_TIMEOUT, show_default=True, type=float,
456
+ help="Request timeout budget in seconds.")
457
+ @_cache_options
154
458
  @click.option("--json", "as_json", is_flag=True, help="Emit the raw item JSON.")
155
- def get(resource_url, lccn, date, edition, seq, as_json):
459
+ def get(resource_url, lccn, date, edition, seq, timeout, refresh, cache_ttl_hours, as_json):
156
460
  """Show metadata and download links for one newspaper page.
157
461
 
158
462
  Give a loc.gov resource URL, or build one with --lccn --date [--edition --seq].
@@ -161,7 +465,8 @@ def get(resource_url, lccn, date, edition, seq, as_json):
161
465
  if not lccn or not date:
162
466
  raise click.UsageError("Give a resource URL or both --lccn and --date.")
163
467
  resource_url = _build_resource_url(lccn, date, edition, seq)
164
- data = _resource_json(resource_url)
468
+ data, _hit = cached_get_json(_resource_url_json(resource_url), None, timeout=timeout,
469
+ refresh=refresh, ttl_hours=resolve_ttl_hours(cache_ttl_hours))
165
470
  if as_json:
166
471
  click.echo(json.dumps(data, indent=2, ensure_ascii=False))
167
472
  return
@@ -184,19 +489,24 @@ def get(resource_url, lccn, date, edition, seq, as_json):
184
489
  @click.option("--date", default=None, help="Issue date YYYY-MM-DD.")
185
490
  @click.option("--edition", default="1", show_default=True)
186
491
  @click.option("--seq", default="1", show_default=True)
187
- @click.option("--out", "-o", default=".", show_default=True, help="Output directory.")
492
+ @click.option("--out", "--out-dir", "-o", "out", default=".", show_default=True, help="Output directory.")
188
493
  @click.option("--pdf/--no-pdf", default=True, show_default=True, help="Download the page PDF.")
189
494
  @click.option("--image/--no-image", default=False, show_default=True,
190
495
  help="Download the IIIF image URL as served (reduced-size rendition).")
191
496
  @click.option("--text/--no-text", default=False, show_default=True,
192
497
  help="Download the ALTO XML word-coordinates file (OCR full text).")
193
- def download(resource_url, lccn, date, edition, seq, out, pdf, image, text):
498
+ @click.option("--timeout", default=DOWNLOAD_TIMEOUT, show_default=True, type=float,
499
+ help="Download timeout in seconds.")
500
+ @_cache_options
501
+ def download(resource_url, lccn, date, edition, seq, out, pdf, image, text, timeout, refresh,
502
+ cache_ttl_hours):
194
503
  """Download a newspaper page (PDF, image, OCR) plus metadata.json."""
195
504
  if resource_url is None:
196
505
  if not lccn or not date:
197
506
  raise click.UsageError("Give a resource URL or both --lccn and --date.")
198
507
  resource_url = _build_resource_url(lccn, date, edition, seq)
199
- data = _resource_json(resource_url)
508
+ data, _hit = cached_get_json(_resource_url_json(resource_url), None, timeout=timeout,
509
+ refresh=refresh, ttl_hours=resolve_ttl_hours(cache_ttl_hours))
200
510
  item = data.get("item") or {}
201
511
  outdir = Path(out)
202
512
  outdir.mkdir(parents=True, exist_ok=True)
@@ -213,10 +523,13 @@ def download(resource_url, lccn, date, edition, seq, out, pdf, image, text):
213
523
  if not jobs:
214
524
  click.echo("No downloadable resources found for this page.", err=True)
215
525
  sys.exit(1)
216
- with httpx.Client(headers=DOWNLOAD_HEADERS, timeout=TIMEOUT, follow_redirects=True) as client:
526
+ with httpx.Client(headers=DOWNLOAD_HEADERS, timeout=timeout, follow_redirects=True) as client:
217
527
  for kind, url, filename in jobs:
218
- resp = client.get(url)
219
- resp.raise_for_status()
528
+ try:
529
+ resp = client.get(url)
530
+ resp.raise_for_status()
531
+ except httpx.HTTPError as exc:
532
+ raise click.ClickException(f"Failed downloading {kind} from {url}: {exc}") from exc
220
533
  (outdir / filename).write_bytes(resp.content)
221
534
  click.echo(f"{kind}: {outdir / filename} ({len(resp.content)} bytes)")
222
535
  (outdir / f"{stem}.metadata.json").write_text(
@@ -226,24 +539,14 @@ def download(resource_url, lccn, date, edition, seq, out, pdf, image, text):
226
539
 
227
540
 
228
541
  @cli.command()
229
- @click.argument("query")
230
- @click.option("--dates", default=None, help="Date range YYYY/YYYY.")
231
- @click.option("--level", default="page", type=click.Choice(["page", "issue", "title", "all"]),
232
- show_default=True)
233
- @click.option("--state", default=None, help="Filter by state via fa=location_state:<state>.")
234
- @click.option("--lccn", default=None, help="Filter by newspaper LCCN via fa=number_lccn:<lccn>.")
235
- def url(query, dates, level, state, lccn):
542
+ @_query_options
543
+ def url(query, terms_opt, dates, date_from, date_to, level, state, lccn):
236
544
  """Print the loc.gov website search URL for QUERY (open in a browser)."""
237
- params: list[tuple[str, str]] = [("q", query)]
238
- if level != "all":
239
- params.append(("dl", level))
240
- if dates:
241
- params.append(("dates", dates))
242
- if state:
243
- params.append(("fa", f"location_state:{state.strip().lower()}"))
244
- if lccn:
245
- params.append(("fa", f"number_lccn:{lccn.strip()}"))
246
- click.echo(COLLECTION_BASE + "?" + urlencode(params))
545
+ resolved_query = _resolve_query(query, terms_opt)
546
+ params = build_search_params(resolved_query, dates=_resolve_dates(dates, date_from, date_to),
547
+ level=level, limit=10, page=1, state=state, lccn=lccn)
548
+ browser = [(k, v) for k, v in params if k not in ("fo", "at", "c", "sp")]
549
+ click.echo(COLLECTION_BASE + "?" + urlencode(browser))
247
550
 
248
551
 
249
552
  if __name__ == "__main__":
@@ -11,6 +11,17 @@ This skill includes a standalone executable Python CLI at `skills/findagrave/scr
11
11
 
12
12
  Path: `skills/findagrave/scripts/findagrave`
13
13
 
14
+ ### Persistent local disk cache
15
+
16
+ `get`/`memorial`, `cemetery`, `photo`, `search`, and `place` cache responses atomically under `~/.cache/kinloom-findagrave/` (overrideable via `KINLOOM_FINDAGRAVE_CACHE_DIR`) using advisory file locks (`fcntl.flock` on POSIX, safe fallback elsewhere) so concurrent research threads never re-download shared memorials, cemeteries, or gravestone photos. Pass `--refresh` on any command to bypass the local cache and fetch fresh data.
17
+
18
+ Cache layout:
19
+
20
+ - `memorials/<id>.json`: parsed memorial JSON shared by `get`/`memorial` and `photo` (168-hour default TTL via `--cache-ttl-hours` or `KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS`).
21
+ - `cemeteries/<id>.json`: parsed cemetery JSON for `cemetery <id>` (168-hour default TTL).
22
+ - `photos/<memorial_id>/<photo_id><ext>`: downloaded gravestone and portrait image files reused across `--out` directories and `--prefix` flags with zero HTTP requests.
23
+ - `_queries/<search|cemetery_search|place>/<sha256>.json`: cached search and typeahead JSON responses (168-hour default TTL).
24
+
14
25
  ### Search memorials
15
26
 
16
27
  ```bash
@@ -35,15 +46,15 @@ Names match the site's default matching unless `--exact` is passed. Married wome
35
46
  ### Read one or more memorials in full
36
47
 
37
48
  ```bash
38
- # Read one memorial by id from search output
49
+ # Read one memorial by id from search output (alias: memorial)
39
50
  skills/findagrave/scripts/findagrave get <memorial-id>
40
51
 
41
- # Full bio/inscription text, photo list, and JSON output
52
+ # Full bio/inscription text, photo list, and JSON output (includes cemetery_lat / cemetery_lng and coordinates)
42
53
  skills/findagrave/scripts/findagrave get <memorial-id> --full --photos
43
54
  skills/findagrave/scripts/findagrave get <memorial-id-1> <memorial-id-2> --json
44
55
  ```
45
56
 
46
- A `get` returns name (with maiden name separate), birth/death dates and places, cemetery, plot, inscription, bio, veteran flag, grave-photo flag, photo count, linked relationships (each with its own memorial id to read next), and created/modified dates. `familyRelations` is usually null in search-shaped responses; use `relationships` for linked family. In `--json` output, `bio` and `inscription` are returned as `{"value": "..."}` objects or `null` (matching the GraphQL schema).
57
+ A `get` (or `memorial`) returns name (with maiden name separate), birth/death dates and places, memorial GPS `coordinates`, cemetery (with `coordinates`, `lat`/`lng`, `physicalAddress`, and top-level `cemetery_lat`/`cemetery_lng` in JSON), plot, inscription, bio, veteran flag, grave-photo flag, photo count, linked relationships (each with its own memorial id to read next), and created/modified dates. `familyRelations` is usually null in search-shaped responses; use `relationships` for linked family. In `--json` output, `bio` and `inscription` are returned as `{"value": "..."}` objects or `null` (matching the GraphQL schema).
47
58
 
48
59
  ### Cemeteries and places
49
60
 
@@ -52,7 +63,8 @@ A `get` returns name (with maiden name separate), birth/death dates and places,
52
63
  skills/findagrave/scripts/findagrave cemetery --name "Oak Ridge"
53
64
  skills/findagrave/scripts/findagrave cemetery --name "Oak Ridge" --place "Sangamon County, Illinois"
54
65
 
55
- # One cemetery by id
66
+ # One cemetery by id (positional id or --id both work; JSON includes coordinates, lat, lng, physicalAddress)
67
+ skills/findagrave/scripts/findagrave cemetery <cemetery-id> --json
56
68
  skills/findagrave/scripts/findagrave cemetery --id <cemetery-id>
57
69
 
58
70
  # Resolve a place name to ids (for use with search --location-id)
@@ -113,4 +125,5 @@ Find a Grave is contributor-written. Dates, family links, and biographies are cl
113
125
 
114
126
  ## Environment variables
115
127
 
116
- None. No key, login, or account is needed for anything in this skill.
128
+ - `KINLOOM_FINDAGRAVE_CACHE_DIR`: optional override for the local disk cache directory (default `~/.cache/kinloom-findagrave`).
129
+ - `KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS`: optional override for memorial, cemetery, and query cache TTL in hours (default `168`). No API key, login, or account is needed for anything in this skill.