@kinloom/cli 0.1.1 → 0.2.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.
Files changed (101) hide show
  1. package/dist/assets/cached-ocr.py +556 -0
  2. package/dist/assets/ocr.md +52 -0
  3. package/dist/assets/prep-scan.md +59 -0
  4. package/dist/assets/prep-scan.py +891 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +94 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +268 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +129 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +879 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +120 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +373 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +100 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +250 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +116 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +520 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +110 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +194 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +123 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +358 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +111 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +346 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +100 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +528 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +118 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +934 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +118 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +585 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +90 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +432 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +93 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +441 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +101 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +391 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +89 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +254 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +104 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +466 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +148 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +219 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +383 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.js +1 -1
  49. package/dist/commands/ops/audit.d.ts +138 -0
  50. package/dist/commands/ops/audit.d.ts.map +1 -0
  51. package/dist/commands/ops/audit.js +867 -0
  52. package/dist/commands/ops/audit.js.map +1 -0
  53. package/dist/commands/ops/context.d.ts +100 -0
  54. package/dist/commands/ops/context.d.ts.map +1 -0
  55. package/dist/commands/ops/context.js +917 -0
  56. package/dist/commands/ops/context.js.map +1 -0
  57. package/dist/commands/ops/help.d.ts +6 -0
  58. package/dist/commands/ops/help.d.ts.map +1 -0
  59. package/dist/commands/ops/help.js +74 -0
  60. package/dist/commands/ops/help.js.map +1 -0
  61. package/dist/commands/ops/index.d.ts +6 -0
  62. package/dist/commands/ops/index.d.ts.map +1 -0
  63. package/dist/commands/ops/index.js +6 -0
  64. package/dist/commands/ops/index.js.map +1 -0
  65. package/dist/commands/ops/integrate.d.ts +56 -0
  66. package/dist/commands/ops/integrate.d.ts.map +1 -0
  67. package/dist/commands/ops/integrate.js +872 -0
  68. package/dist/commands/ops/integrate.js.map +1 -0
  69. package/dist/commands/ops/sync.d.ts +177 -0
  70. package/dist/commands/ops/sync.d.ts.map +1 -0
  71. package/dist/commands/ops/sync.js +1078 -0
  72. package/dist/commands/ops/sync.js.map +1 -0
  73. package/dist/commands/ops/telemetry.d.ts +79 -0
  74. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  75. package/dist/commands/ops/telemetry.js +249 -0
  76. package/dist/commands/ops/telemetry.js.map +1 -0
  77. package/dist/commands/records/help.d.ts +18 -0
  78. package/dist/commands/records/help.d.ts.map +1 -0
  79. package/dist/commands/records/help.js +174 -0
  80. package/dist/commands/records/help.js.map +1 -0
  81. package/dist/commands/records/index.d.ts +5 -0
  82. package/dist/commands/records/index.d.ts.map +1 -0
  83. package/dist/commands/records/index.js +5 -0
  84. package/dist/commands/records/index.js.map +1 -0
  85. package/dist/commands/records/registry.d.ts +32 -0
  86. package/dist/commands/records/registry.d.ts.map +1 -0
  87. package/dist/commands/records/registry.js +227 -0
  88. package/dist/commands/records/registry.js.map +1 -0
  89. package/dist/commands/records/resolve.d.ts +14 -0
  90. package/dist/commands/records/resolve.d.ts.map +1 -0
  91. package/dist/commands/records/resolve.js +61 -0
  92. package/dist/commands/records/resolve.js.map +1 -0
  93. package/dist/commands/records/runner.d.ts +25 -0
  94. package/dist/commands/records/runner.d.ts.map +1 -0
  95. package/dist/commands/records/runner.js +224 -0
  96. package/dist/commands/records/runner.js.map +1 -0
  97. package/dist/index.d.ts +2 -0
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +2 -0
  100. package/dist/index.js.map +1 -1
  101. package/package.json +3 -3
@@ -0,0 +1,934 @@
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = [
5
+ # "click>=8.1",
6
+ # "httpx>=0.27",
7
+ # "playwright>=1.49",
8
+ # ]
9
+ # ///
10
+ """Compact CLI for searching, inspecting, and downloading National Archives Catalog records.
11
+
12
+ Uses the official NARA Catalog v2 API when NARA_API_KEY is set, and falls back
13
+ to headless Chromium against catalog.archives.gov when no key is configured.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ import json
20
+ import os
21
+ import re
22
+ import shutil
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import Any
26
+ from urllib.parse import quote, urlencode
27
+
28
+ import click
29
+ import httpx
30
+
31
+ CATALOG_WEB_BASE = "https://catalog.archives.gov"
32
+ CATALOG_API_BASE = "https://catalog.archives.gov/api/v2"
33
+ API_MAX_WORKERS = 6
34
+ USER_AGENT = (
35
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
36
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
37
+ )
38
+ VALID_LEVELS = ("recordGroup", "collection", "series", "fileUnit", "item")
39
+
40
+
41
+ class _NaraWafOrNonJsonError(RuntimeError):
42
+ """Raised when the NARA v2 API returns an HTML WAF page or non-JSON body."""
43
+
44
+ def __init__(self, url: str, content_type: str, detail: str = "") -> None:
45
+ self.url = url
46
+ self.content_type = content_type
47
+ msg = f"NARA v2 API returned non-JSON response ({content_type or 'unknown content-type'})"
48
+ if detail:
49
+ msg = f"{msg}: {detail}"
50
+ super().__init__(msg)
51
+
52
+
53
+ def _normalize_query_for_waf_retry(query: str) -> str | None:
54
+ """Strip double quotes and standalone boolean AND operators that trigger CloudFront WAF."""
55
+ stripped = query.replace('"', " ")
56
+ stripped = re.sub(r"\bAND\b", " ", stripped)
57
+ normalized = re.sub(r"\s+", " ", stripped).strip()
58
+ if not normalized or normalized == query.strip():
59
+ return None
60
+ return normalized
61
+
62
+
63
+ def _new_api_client() -> httpx.Client:
64
+ return httpx.Client(
65
+ timeout=15.0,
66
+ follow_redirects=True,
67
+ limits=httpx.Limits(
68
+ max_connections=API_MAX_WORKERS * 2,
69
+ max_keepalive_connections=API_MAX_WORKERS,
70
+ ),
71
+ )
72
+
73
+
74
+ def find_browser_executable() -> str | None:
75
+ env_exe = os.environ.get("NARA_BROWSER")
76
+ if env_exe and Path(env_exe).exists():
77
+ return env_exe
78
+ for candidate in ("chromium", "chromium-browser", "google-chrome", "google-chrome-stable"):
79
+ found = shutil.which(candidate)
80
+ if found:
81
+ return found
82
+ return None
83
+
84
+
85
+ def build_query_params(
86
+ query: str | None = None,
87
+ *,
88
+ levels: tuple[str, ...] = (),
89
+ record_groups: tuple[str, ...] = (),
90
+ online: bool = False,
91
+ material_type: str | None = None,
92
+ person: str | None = None,
93
+ title: str | None = None,
94
+ geo: str | None = None,
95
+ control: str | None = None,
96
+ start_date: str | None = None,
97
+ end_date: str | None = None,
98
+ page: int = 1,
99
+ limit: int = 20,
100
+ for_api: bool = False,
101
+ ) -> list[tuple[str, str]]:
102
+ """Build verified NARA Catalog query parameters (q first, comma-joined multi-values)."""
103
+ params: list[tuple[str, str]] = []
104
+ if query:
105
+ params.append(("q", query))
106
+ if title:
107
+ params.append(("title", title))
108
+ if person:
109
+ params.append(("personOrOrg", person))
110
+ if geo:
111
+ params.append(("geographicReference", geo))
112
+ if control:
113
+ params.append(("controlNumbers", control))
114
+ if levels:
115
+ flat = [p.strip() for item in levels for p in item.split(",") if p.strip()]
116
+ invalid = [lv for lv in flat if lv not in VALID_LEVELS]
117
+ if invalid:
118
+ raise click.BadParameter(
119
+ f"Invalid level(s): {', '.join(invalid)}. Choose from: {', '.join(VALID_LEVELS)}"
120
+ )
121
+ if flat:
122
+ params.append(("levelOfDescription", ",".join(flat)))
123
+ if record_groups:
124
+ flat_rg = [p.strip() for item in record_groups for p in item.split(",") if p.strip()]
125
+ if flat_rg:
126
+ params.append(("recordGroupNumber", ",".join(flat_rg)))
127
+ if online:
128
+ params.append(("availableOnline", "true"))
129
+ if not for_api:
130
+ params.append(("dataSource", "description"))
131
+ if material_type:
132
+ params.append(("typeOfMaterials", material_type))
133
+ if start_date:
134
+ params.append(("startDate", start_date))
135
+ if end_date:
136
+ params.append(("endDate", end_date))
137
+ if page > 1 or for_api:
138
+ params.append(("page", str(page)))
139
+ if for_api or limit != 20:
140
+ params.append(("limit", str(limit)))
141
+ return params
142
+
143
+
144
+ def encode_catalog_url(params: list[tuple[str, str]], *, for_api: bool = False) -> str:
145
+ base = f"{CATALOG_API_BASE}/records/search" if for_api else f"{CATALOG_WEB_BASE}/search"
146
+ qs = urlencode(params, quote_via=quote)
147
+ return f"{base}?{qs}" if qs else base
148
+
149
+
150
+ def parse_page_spec(spec: str | None, total: int) -> list[int]:
151
+ """Parse a 1-based page selection like '1-3,5,8-10' into sorted 1-based indices."""
152
+ if not spec or spec.strip().lower() == "all":
153
+ return list(range(1, total + 1))
154
+ chosen: set[int] = set()
155
+ for part in spec.split(","):
156
+ part = part.strip()
157
+ if not part:
158
+ continue
159
+ if "-" in part:
160
+ a_s, b_s = part.split("-", 1)
161
+ a = int(a_s.strip()) if a_s.strip() else 1
162
+ b = int(b_s.strip()) if b_s.strip() else total
163
+ if a > b:
164
+ a, b = b, a
165
+ chosen.update(range(max(1, a), min(total, b) + 1))
166
+ else:
167
+ idx = int(part)
168
+ if 1 <= idx <= total:
169
+ chosen.add(idx)
170
+ return sorted(chosen)
171
+
172
+
173
+ def _extract_record(
174
+ hit: dict[str, Any],
175
+ *,
176
+ include_objects: bool = False,
177
+ include_text: bool = False,
178
+ page_spec: str | None = None,
179
+ ) -> dict[str, Any]:
180
+ """Extract only high-signal archival fields (omitting nulls, empties, and raw bloat)."""
181
+ src = hit.get("_source", {}) if isinstance(hit, dict) else {}
182
+ rec = src.get("record", hit if isinstance(hit, dict) else {})
183
+ naid = str(rec.get("naId") or "")
184
+ ancestors = rec.get("ancestors") or []
185
+ rg = next((a for a in ancestors if a.get("levelOfDescription") == "recordGroup"), None)
186
+ series = next((a for a in ancestors if a.get("levelOfDescription") == "series"), None)
187
+ microforms = rec.get("microformPublications") or []
188
+ objs = rec.get("digitalObjects") or []
189
+
190
+ out: dict[str, Any] = {
191
+ "naId": naid,
192
+ "title": rec.get("title") or "",
193
+ "url": f"{CATALOG_WEB_BASE}/id/{naid}" if naid else "",
194
+ }
195
+ if rec.get("levelOfDescription"):
196
+ out["level"] = rec["levelOfDescription"]
197
+
198
+ rg_num = rg.get("recordGroupNumber") if rg else rec.get("recordGroupNumber")
199
+ if rg_num is not None:
200
+ out["rg"] = rg_num
201
+ if rg and rg.get("title"):
202
+ out["rgTitle"] = rg["title"]
203
+ if series and series.get("title"):
204
+ out["series"] = series["title"]
205
+ if series and series.get("naId"):
206
+ out["seriesNaId"] = str(series["naId"])
207
+
208
+ dates: list[str] = []
209
+ for k in ("inclusiveStartDate", "inclusiveEndDate", "productionDateArray", "coverageStartDate", "coverageEndDate"):
210
+ v = rec.get(k)
211
+ if isinstance(v, dict) and v.get("logicalDate"):
212
+ dates.append(str(v["logicalDate"]))
213
+ elif isinstance(v, list):
214
+ for entry in v:
215
+ if isinstance(entry, dict) and entry.get("logicalDate"):
216
+ dates.append(str(entry["logicalDate"]))
217
+ if dates:
218
+ out["dates"] = dates
219
+
220
+ mf_list = []
221
+ for m in microforms:
222
+ parts = [m.get("identifier"), m.get("title"), m.get("note")]
223
+ text = " | ".join(str(p).strip() for p in parts if p)
224
+ if text:
225
+ mf_list.append(text)
226
+ if mf_list:
227
+ out["microform"] = mf_list
228
+
229
+ access = (rec.get("accessRestriction") or {}).get("status")
230
+ use = (rec.get("useRestriction") or {}).get("status")
231
+ if access:
232
+ out["access"] = access
233
+ if use:
234
+ out["use"] = use
235
+
236
+ if rec.get("scopeAndContentNote"):
237
+ out["scope"] = rec["scopeAndContentNote"]
238
+
239
+ locations: list[str] = []
240
+ for po in rec.get("physicalOccurrences") or []:
241
+ for ru in po.get("referenceUnits") or []:
242
+ name = ru.get("name") if isinstance(ru, dict) else None
243
+ if name and name not in locations:
244
+ locations.append(name)
245
+ if locations:
246
+ out["location"] = locations[0] if len(locations) == 1 else locations
247
+
248
+ if objs:
249
+ out["objectCount"] = len(objs)
250
+ if include_objects:
251
+ selected = parse_page_spec(page_spec, len(objs))
252
+ out["objects"] = [
253
+ {
254
+ "page": p,
255
+ "filename": objs[p - 1].get("objectFilename") or str(objs[p - 1].get("objectId") or ""),
256
+ "url": objs[p - 1].get("objectUrl") or "",
257
+ }
258
+ for p in selected
259
+ ]
260
+ if include_text:
261
+ selected = parse_page_spec(page_spec, len(objs))
262
+ texts = []
263
+ for p in selected:
264
+ o = objs[p - 1]
265
+ txt = o.get("extractedText") or o.get("otherExtractedText")
266
+ if txt:
267
+ texts.append({"page": p, "filename": o.get("objectFilename") or "", "text": txt})
268
+ if texts:
269
+ out["extractedText"] = texts
270
+
271
+ return out
272
+
273
+
274
+ def _api_get_json(
275
+ url: str,
276
+ api_key: str,
277
+ *,
278
+ client: httpx.Client | None = None,
279
+ ) -> dict[str, Any]:
280
+ headers = {
281
+ "x-api-key": api_key,
282
+ "Accept": "application/json",
283
+ "User-Agent": USER_AGENT,
284
+ }
285
+ if client is None:
286
+ with _new_api_client() as local_client:
287
+ return _api_get_json(url, api_key, client=local_client)
288
+ resp = client.get(url, headers=headers)
289
+ content_type = resp.headers.get("content-type", "")
290
+ if resp.status_code == 403 and "html" in content_type.lower():
291
+ raise _NaraWafOrNonJsonError(url, content_type, "HTTP 403 HTML response")
292
+ resp.raise_for_status()
293
+ if "json" not in content_type.lower():
294
+ raise _NaraWafOrNonJsonError(url, content_type)
295
+ try:
296
+ data = resp.json()
297
+ except ValueError as exc:
298
+ raise _NaraWafOrNonJsonError(url, content_type, str(exc)) from exc
299
+ if not isinstance(data, dict):
300
+ raise _NaraWafOrNonJsonError(
301
+ url, content_type, f"expected JSON object, got {type(data).__name__}"
302
+ )
303
+ return data
304
+
305
+
306
+ def _browser_search_many(
307
+ items: list[tuple[str | None, str]], timeout_ms: int = 30000
308
+ ) -> list[dict[str, Any]]:
309
+ """Run one or more catalog searches sharing a single headless Chromium session."""
310
+ from playwright.sync_api import sync_playwright
311
+
312
+ exe = find_browser_executable()
313
+ results: list[dict[str, Any]] = []
314
+
315
+ with sync_playwright() as pw:
316
+ browser = pw.chromium.launch(headless=True, executable_path=exe)
317
+ context = browser.new_context(user_agent=USER_AGENT)
318
+ page = context.new_page()
319
+
320
+ for query, search_url in items:
321
+ captured: list[dict[str, Any]] = []
322
+
323
+ def on_response(resp: Any, bucket: list[dict[str, Any]] = captured) -> None:
324
+ u = resp.url
325
+ if "/proxy/" in u and "/records/search" in u and resp.status == 200:
326
+ try:
327
+ if "json" in resp.headers.get("content-type", ""):
328
+ bucket.append(resp.json())
329
+ except Exception:
330
+ pass
331
+
332
+ page.on("response", on_response)
333
+ page.goto(search_url, wait_until="domcontentloaded", timeout=timeout_ms)
334
+ try:
335
+ page.wait_for_function(
336
+ """() => {
337
+ const t = document.body.innerText || '';
338
+ return /\\d+\\s+results?\\s+for|No results|0 results|did not match/i.test(t);
339
+ }""",
340
+ timeout=min(timeout_ms, 20000),
341
+ )
342
+ except Exception:
343
+ pass
344
+ page.wait_for_timeout(500)
345
+ page.remove_listener("response", on_response)
346
+
347
+ entry: dict[str, Any] | None = None
348
+ for cap in reversed(captured):
349
+ body = cap.get("body", cap)
350
+ hits_obj = body.get("hits", {}) if isinstance(body, dict) else {}
351
+ hits = hits_obj.get("hits")
352
+ if isinstance(hits, list):
353
+ total_raw = hits_obj.get("total", len(hits))
354
+ total = total_raw.get("value", len(hits)) if isinstance(total_raw, dict) else int(total_raw)
355
+ entry = {
356
+ "query": query,
357
+ "searchUrl": search_url,
358
+ "total": total,
359
+ "results": [_extract_record(h) for h in hits],
360
+ }
361
+ break
362
+
363
+ if entry is None:
364
+ dom_items = page.evaluate(
365
+ """() => {
366
+ const items = [];
367
+ const seen = new Set();
368
+ for (const a of document.querySelectorAll('a[href*="/id/"]')) {
369
+ const m = (a.getAttribute('href') || '').match(/\\/id\\/(\\d+)/);
370
+ if (!m || seen.has(m[1])) continue;
371
+ const title = (a.textContent || '').trim();
372
+ if (!title) continue;
373
+ seen.add(m[1]);
374
+ items.push({ naId: m[1], title, url: 'https://catalog.archives.gov/id/' + m[1] });
375
+ }
376
+ return items;
377
+ }"""
378
+ )
379
+ entry = {
380
+ "query": query,
381
+ "searchUrl": search_url,
382
+ "total": len(dom_items),
383
+ "results": dom_items,
384
+ }
385
+ if entry.get("query") is None:
386
+ entry.pop("query", None)
387
+ results.append(entry)
388
+
389
+ browser.close()
390
+
391
+ return results
392
+
393
+
394
+ def _browser_get_records(
395
+ naids: list[str],
396
+ *,
397
+ include_objects: bool = False,
398
+ include_text: bool = False,
399
+ page_spec: str | None = None,
400
+ timeout_ms: int = 30000,
401
+ ) -> list[dict[str, Any]]:
402
+ from playwright.sync_api import sync_playwright
403
+
404
+ exe = find_browser_executable()
405
+ records: list[dict[str, Any]] = []
406
+
407
+ with sync_playwright() as pw:
408
+ browser = pw.chromium.launch(headless=True, executable_path=exe)
409
+ context = browser.new_context(user_agent=USER_AGENT)
410
+ page = context.new_page()
411
+
412
+ for naid in naids:
413
+ clean_id = re.sub(r"\D+", "", str(naid))
414
+ captured_record: dict[str, Any] | None = None
415
+ contributions: list[dict[str, Any]] = []
416
+
417
+ def on_response(resp: Any, target: str = clean_id) -> None:
418
+ nonlocal captured_record
419
+ u = resp.url
420
+ if resp.status != 200 or "json" not in resp.headers.get("content-type", ""):
421
+ return
422
+ if f"naId_is={target}" in u and "/records/search" in u:
423
+ try:
424
+ payload = resp.json()
425
+ hits = payload.get("body", payload).get("hits", {}).get("hits", [])
426
+ if hits:
427
+ captured_record = _extract_record(
428
+ hits[0],
429
+ include_objects=include_objects,
430
+ include_text=include_text,
431
+ page_spec=page_spec,
432
+ )
433
+ except Exception:
434
+ pass
435
+ elif include_text and f"targetNaId/{target}" in u and "/contributions/" in u:
436
+ try:
437
+ c = resp.json()
438
+ if isinstance(c, list):
439
+ contributions.extend(c)
440
+ except Exception:
441
+ pass
442
+
443
+ page.on("response", on_response)
444
+ url = f"{CATALOG_WEB_BASE}/id/{clean_id}"
445
+ page.goto(url, wait_until="domcontentloaded", timeout=timeout_ms)
446
+ try:
447
+ page.wait_for_function(
448
+ "() => /National Archives Identifier/i.test(document.body.innerText || '')",
449
+ timeout=min(timeout_ms, 20000),
450
+ )
451
+ except Exception:
452
+ pass
453
+ page.wait_for_timeout(600)
454
+ page.remove_listener("response", on_response)
455
+
456
+ if captured_record is None:
457
+ captured_record = {"naId": clean_id, "url": url, "error": "Record metadata not captured."}
458
+ elif include_text and contributions:
459
+ transcriptions = [
460
+ c.get("text") or c.get("transcription")
461
+ for c in contributions
462
+ if c.get("contributionType") == "transcription" and (c.get("text") or c.get("transcription"))
463
+ ]
464
+ if transcriptions:
465
+ captured_record["transcriptions"] = transcriptions
466
+ records.append(captured_record)
467
+
468
+ browser.close()
469
+
470
+ return records
471
+
472
+
473
+ def _format_record_text(rec: dict[str, Any]) -> str:
474
+ if rec.get("error"):
475
+ return f"NAID {rec.get('naId')}: ERROR - {rec['error']}"
476
+ header_parts = [f"NAID {rec['naId']}"]
477
+ if rec.get("level"):
478
+ header_parts.append(f"[{rec['level']}]")
479
+ if rec.get("rg") is not None:
480
+ header_parts.append(f"RG {rec['rg']}")
481
+ if rec.get("objectCount"):
482
+ header_parts.append(f"{rec['objectCount']} files")
483
+ lines = [f"{' '.join(header_parts)}: {rec.get('title')}", f" {rec.get('url')}"]
484
+ if rec.get("series"):
485
+ lines.append(f" Series: {rec['series']}")
486
+ if rec.get("dates"):
487
+ lines.append(f" Dates: {' .. '.join(rec['dates'])}")
488
+ for mf in rec.get("microform") or []:
489
+ lines.append(f" Microform: {mf}")
490
+ if rec.get("access") or rec.get("use"):
491
+ lines.append(f" Access/Use: {rec.get('access', '?')} / {rec.get('use', '?')}")
492
+ if rec.get("location"):
493
+ loc = rec["location"] if isinstance(rec["location"], str) else "; ".join(rec["location"])
494
+ lines.append(f" Location: {loc}")
495
+ if rec.get("scope"):
496
+ lines.append(f" Scope: {rec['scope']}")
497
+ for obj in rec.get("objects") or []:
498
+ lines.append(f" [{obj['page']:03d}] {obj['filename']}: {obj['url']}")
499
+ for item in rec.get("extractedText") or []:
500
+ lines.append(f" --- Page {item['page']} ({item['filename']}) ---\n{item['text']}")
501
+ for tr in rec.get("transcriptions") or []:
502
+ lines.append(f" --- Transcription ---\n{tr}")
503
+ return "\n".join(lines)
504
+
505
+
506
+ def _common_search_options(fn: Any) -> Any:
507
+ options = [
508
+ click.option("--level", "levels", multiple=True, help="Level(s): recordGroup, collection, series, fileUnit, item."),
509
+ click.option("--rg", "record_groups", multiple=True, help="Record Group number(s), e.g. 109 or 29,109."),
510
+ click.option("--online", is_flag=True, help="Limit to records with viewable digital objects."),
511
+ click.option("--type", "material_type", default=None, help="Type of material, e.g. 'Textual Records'."),
512
+ click.option("--person", default=None, help="Person or Organization authority heading."),
513
+ click.option("--title", default=None, help="Title search filter."),
514
+ click.option("--geo", default=None, help="Geographic reference filter."),
515
+ click.option("--control", default=None, help="Control number or microform identifier."),
516
+ click.option("--start-date", default=None, help="Beginning date (YYYY, YYYY-MM, or YYYY-MM-DD)."),
517
+ click.option("--end-date", default=None, help="Ending date (YYYY, YYYY-MM, or YYYY-MM-DD)."),
518
+ click.option("--page", default=1, show_default=True, type=int, help="Result page number."),
519
+ click.option("--limit", default=20, show_default=True, type=int, help="Results per page."),
520
+ ]
521
+ for opt in reversed(options):
522
+ fn = opt(fn)
523
+ return fn
524
+
525
+
526
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
527
+ def cli() -> None:
528
+ """Search, inspect, and download National Archives Catalog (NARA) records."""
529
+
530
+
531
+ @cli.command("url")
532
+ @click.argument("query", required=False, default=None)
533
+ @_common_search_options
534
+ @click.option("--api", "for_api", is_flag=True, help="Output the v2 API endpoint URL instead of the website URL.")
535
+ def cmd_url(
536
+ query: str | None,
537
+ levels: tuple[str, ...],
538
+ record_groups: tuple[str, ...],
539
+ online: bool,
540
+ material_type: str | None,
541
+ person: str | None,
542
+ title: str | None,
543
+ geo: str | None,
544
+ control: str | None,
545
+ start_date: str | None,
546
+ end_date: str | None,
547
+ page: int,
548
+ limit: int,
549
+ for_api: bool,
550
+ ) -> None:
551
+ """Build and print a verified NARA Catalog search URL."""
552
+ params = build_query_params(
553
+ query,
554
+ levels=levels,
555
+ record_groups=record_groups,
556
+ online=online,
557
+ material_type=material_type,
558
+ person=person,
559
+ title=title,
560
+ geo=geo,
561
+ control=control,
562
+ start_date=start_date,
563
+ end_date=end_date,
564
+ page=page,
565
+ limit=limit,
566
+ for_api=for_api,
567
+ )
568
+ click.echo(encode_catalog_url(params, for_api=for_api))
569
+
570
+
571
+ def _build_search_payload(
572
+ query: str | None,
573
+ web_url: str,
574
+ raw: dict[str, Any],
575
+ ) -> dict[str, Any]:
576
+ hits_obj = raw.get("body", raw).get("hits", {})
577
+ hits = hits_obj.get("hits", [])
578
+ total_raw = hits_obj.get("total", len(hits))
579
+ total = total_raw.get("value", len(hits)) if isinstance(total_raw, dict) else int(total_raw)
580
+ item: dict[str, Any] = {
581
+ "searchUrl": web_url,
582
+ "total": total,
583
+ "results": [_extract_record(h) for h in hits],
584
+ }
585
+ if query is not None:
586
+ item = {"query": query, **item}
587
+ return item
588
+
589
+
590
+ def _api_search_one(
591
+ query: str | None,
592
+ *,
593
+ api_key: str,
594
+ client: httpx.Client,
595
+ filter_kwargs: dict[str, Any],
596
+ ) -> tuple[dict[str, Any] | None, str]:
597
+ api_url = encode_catalog_url(
598
+ build_query_params(query, **filter_kwargs, for_api=True),
599
+ for_api=True,
600
+ )
601
+ web_url = encode_catalog_url(
602
+ build_query_params(query, **filter_kwargs, for_api=False),
603
+ for_api=False,
604
+ )
605
+ try:
606
+ raw = _api_get_json(api_url, api_key, client=client)
607
+ return _build_search_payload(query, web_url, raw), web_url
608
+ except _NaraWafOrNonJsonError:
609
+ retry_query = _normalize_query_for_waf_retry(query) if query else None
610
+ if retry_query is None:
611
+ return None, web_url
612
+ retry_api_url = encode_catalog_url(
613
+ build_query_params(retry_query, **filter_kwargs, for_api=True),
614
+ for_api=True,
615
+ )
616
+ try:
617
+ raw = _api_get_json(retry_api_url, api_key, client=client)
618
+ return _build_search_payload(query, web_url, raw), web_url
619
+ except _NaraWafOrNonJsonError:
620
+ return None, web_url
621
+
622
+
623
+ @cli.command("search")
624
+ @click.argument("queries", nargs=-1)
625
+ @_common_search_options
626
+ @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
627
+ @click.option("--browser", "force_browser", is_flag=True, help="Force headless Chromium website mode.")
628
+ @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
629
+ def cmd_search(
630
+ queries: tuple[str, ...],
631
+ levels: tuple[str, ...],
632
+ record_groups: tuple[str, ...],
633
+ online: bool,
634
+ material_type: str | None,
635
+ person: str | None,
636
+ title: str | None,
637
+ geo: str | None,
638
+ control: str | None,
639
+ start_date: str | None,
640
+ end_date: str | None,
641
+ page: int,
642
+ limit: int,
643
+ api_key: str | None,
644
+ force_browser: bool,
645
+ as_json: bool,
646
+ ) -> None:
647
+ """Search the NARA Catalog. Accepts one or multiple queries (parallel via API or shared browser)."""
648
+ query_list: list[str | None] = list(queries) if queries else [None]
649
+ use_api = bool(api_key) and not force_browser
650
+ filter_kwargs: dict[str, Any] = {
651
+ "levels": levels,
652
+ "record_groups": record_groups,
653
+ "online": online,
654
+ "material_type": material_type,
655
+ "person": person,
656
+ "title": title,
657
+ "geo": geo,
658
+ "control": control,
659
+ "start_date": start_date,
660
+ "end_date": end_date,
661
+ "page": page,
662
+ "limit": limit,
663
+ }
664
+
665
+ payloads: list[dict[str, Any]] = []
666
+ if use_api and api_key:
667
+ with _new_api_client() as client:
668
+ if len(query_list) == 1:
669
+ outcomes = [
670
+ _api_search_one(
671
+ query_list[0],
672
+ api_key=api_key,
673
+ client=client,
674
+ filter_kwargs=filter_kwargs,
675
+ )
676
+ ]
677
+ else:
678
+ workers = min(API_MAX_WORKERS, len(query_list))
679
+ with ThreadPoolExecutor(max_workers=workers) as executor:
680
+ outcomes = list(
681
+ executor.map(
682
+ lambda q: _api_search_one(
683
+ q,
684
+ api_key=api_key,
685
+ client=client,
686
+ filter_kwargs=filter_kwargs,
687
+ ),
688
+ query_list,
689
+ )
690
+ )
691
+
692
+ slots: list[dict[str, Any] | None] = [entry for entry, _ in outcomes]
693
+ fallback_indices: list[int] = []
694
+ fallback_pairs: list[tuple[str | None, str]] = []
695
+ for idx, (entry, web_url) in enumerate(outcomes):
696
+ if entry is None:
697
+ fallback_indices.append(idx)
698
+ fallback_pairs.append((query_list[idx], web_url))
699
+
700
+ if fallback_pairs:
701
+ fallback_results = _browser_search_many(fallback_pairs)
702
+ for idx, fb_entry in zip(fallback_indices, fallback_results, strict=True):
703
+ slots[idx] = fb_entry
704
+
705
+ payloads = [entry for entry in slots if entry is not None]
706
+ else:
707
+ url_pairs = [
708
+ (
709
+ q,
710
+ encode_catalog_url(
711
+ build_query_params(q, **filter_kwargs, for_api=False),
712
+ for_api=False,
713
+ ),
714
+ )
715
+ for q in query_list
716
+ ]
717
+ payloads = _browser_search_many(url_pairs)
718
+
719
+ if as_json:
720
+ click.echo(json.dumps(payloads[0] if len(payloads) == 1 else payloads, indent=2))
721
+ return
722
+
723
+ for p_idx, payload in enumerate(payloads):
724
+ if p_idx > 0:
725
+ click.echo("")
726
+ hdr = f"Query: {payload['query']} | " if payload.get("query") else ""
727
+ click.echo(f"{hdr}Total: {payload['total']} | {payload['searchUrl']}")
728
+ for idx, rec in enumerate(payload["results"], 1):
729
+ meta = " | ".join(
730
+ part
731
+ for part in (
732
+ rec.get("level"),
733
+ f"RG {rec['rg']}" if rec.get("rg") is not None else None,
734
+ f"{rec['objectCount']} files" if rec.get("objectCount") else None,
735
+ )
736
+ if part
737
+ )
738
+ series = f" [{rec['series']}]" if rec.get("series") else ""
739
+ click.echo(f" {idx:2d}. NAID {rec['naId']} ({meta}): {rec.get('title')}{series}")
740
+
741
+
742
+ def _api_get_one_record(
743
+ naid: str,
744
+ *,
745
+ api_key: str,
746
+ client: httpx.Client,
747
+ include_objects: bool,
748
+ include_text: bool,
749
+ page_spec: str,
750
+ ) -> dict[str, Any] | None:
751
+ clean_id = re.sub(r"\D+", "", naid)
752
+ url = (
753
+ f"{CATALOG_API_BASE}/records/search?"
754
+ f"naId_is={clean_id}&includeExtractedText={'true' if include_text else 'false'}"
755
+ f"&includeOtherExtractedText={'true' if include_text else 'false'}"
756
+ )
757
+ try:
758
+ raw = _api_get_json(url, api_key, client=client)
759
+ except _NaraWafOrNonJsonError:
760
+ return None
761
+ hits = raw.get("body", raw).get("hits", {}).get("hits", [])
762
+ if hits:
763
+ return _extract_record(
764
+ hits[0],
765
+ include_objects=include_objects,
766
+ include_text=include_text,
767
+ page_spec=page_spec,
768
+ )
769
+ return {"naId": clean_id, "url": f"{CATALOG_WEB_BASE}/id/{clean_id}", "error": "Not found"}
770
+
771
+
772
+ @cli.command("get")
773
+ @click.argument("naids", nargs=-1, required=True)
774
+ @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
775
+ @click.option("--browser", "force_browser", is_flag=True, help="Force headless Chromium website mode.")
776
+ @click.option("--objects", is_flag=True, help="Include compact digital object URLs (omitted by default to keep output small).")
777
+ @click.option("--pages", default="all", show_default=True, help="1-based page slice when using --objects or --text, e.g. '1-10'.")
778
+ @click.option("--text", is_flag=True, help="Include extracted OCR text and transcriptions if present.")
779
+ @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
780
+ def cmd_get(
781
+ naids: tuple[str, ...],
782
+ api_key: str | None,
783
+ force_browser: bool,
784
+ objects: bool,
785
+ pages: str,
786
+ text: bool,
787
+ as_json: bool,
788
+ ) -> None:
789
+ """Inspect one or more NARA records by NAID (compact metadata by default)."""
790
+ use_api = bool(api_key) and not force_browser
791
+ records: list[dict[str, Any]] = []
792
+ if use_api and api_key:
793
+ naid_list = list(naids)
794
+ with _new_api_client() as client:
795
+ if len(naid_list) == 1:
796
+ slots: list[dict[str, Any] | None] = [
797
+ _api_get_one_record(
798
+ naid_list[0],
799
+ api_key=api_key,
800
+ client=client,
801
+ include_objects=objects,
802
+ include_text=text,
803
+ page_spec=pages,
804
+ )
805
+ ]
806
+ else:
807
+ workers = min(API_MAX_WORKERS, len(naid_list))
808
+ with ThreadPoolExecutor(max_workers=workers) as executor:
809
+ slots = list(
810
+ executor.map(
811
+ lambda n: _api_get_one_record(
812
+ n,
813
+ api_key=api_key,
814
+ client=client,
815
+ include_objects=objects,
816
+ include_text=text,
817
+ page_spec=pages,
818
+ ),
819
+ naid_list,
820
+ )
821
+ )
822
+
823
+ fallback_indices = [idx for idx, rec in enumerate(slots) if rec is None]
824
+ if fallback_indices:
825
+ fallback_naids = [naid_list[idx] for idx in fallback_indices]
826
+ fallback_recs = _browser_get_records(
827
+ fallback_naids,
828
+ include_objects=objects,
829
+ include_text=text,
830
+ page_spec=pages,
831
+ )
832
+ for idx, fb_rec in zip(fallback_indices, fallback_recs, strict=True):
833
+ slots[idx] = fb_rec
834
+
835
+ records = [rec for rec in slots if rec is not None]
836
+ else:
837
+ records = _browser_get_records(
838
+ list(naids), include_objects=objects, include_text=text, page_spec=pages
839
+ )
840
+
841
+ if as_json:
842
+ click.echo(json.dumps(records[0] if len(records) == 1 else records, indent=2))
843
+ return
844
+
845
+ for idx, rec in enumerate(records):
846
+ if idx > 0:
847
+ click.echo("")
848
+ click.echo(_format_record_text(rec))
849
+
850
+
851
+ @cli.command("download")
852
+ @click.argument("naid")
853
+ @click.option("--out", "out_dir", default=None, type=click.Path(path_type=Path), help="Output directory (default: ./nara-<naid>).")
854
+ @click.option("--pages", default="all", show_default=True, help="1-based page selection, e.g. '1-5,10' or 'all'.")
855
+ @click.option("--metadata/--no-metadata", default=True, show_default=True, help="Save compact provenance metadata.json.")
856
+ @click.option("--overwrite", is_flag=True, help="Overwrite existing downloaded files.")
857
+ @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
858
+ @click.option("--browser", "force_browser", is_flag=True, help="Force headless Chromium website mode.")
859
+ def cmd_download(
860
+ naid: str,
861
+ out_dir: Path | None,
862
+ pages: str,
863
+ metadata: bool,
864
+ overwrite: bool,
865
+ api_key: str | None,
866
+ force_browser: bool,
867
+ ) -> None:
868
+ """Download digitized files for a NARA record (NAID) with compact provenance metadata."""
869
+ clean_id = re.sub(r"\D+", "", naid)
870
+ use_api = bool(api_key) and not force_browser
871
+ if use_api and api_key:
872
+ url = f"{CATALOG_API_BASE}/records/search?naId_is={clean_id}"
873
+ try:
874
+ raw = _api_get_json(url, api_key)
875
+ except _NaraWafOrNonJsonError:
876
+ rec = _browser_get_records([clean_id], include_objects=True, page_spec=pages)[0]
877
+ if rec.get("error"):
878
+ raise click.ClickException(f"NAID {clean_id}: {rec['error']}")
879
+ else:
880
+ hits = raw.get("body", raw).get("hits", {}).get("hits", [])
881
+ if not hits:
882
+ raise click.ClickException(f"NAID {clean_id} not found.")
883
+ rec = _extract_record(hits[0], include_objects=True, page_spec=pages)
884
+ else:
885
+ rec = _browser_get_records([clean_id], include_objects=True, page_spec=pages)[0]
886
+ if rec.get("error"):
887
+ raise click.ClickException(f"NAID {clean_id}: {rec['error']}")
888
+
889
+ selected_objs = rec.get("objects") or []
890
+ total_count = rec.get("objectCount") or len(selected_objs)
891
+ if not selected_objs:
892
+ raise click.ClickException(f"NAID {clean_id} ({rec.get('title')}) has no matching digital objects for '{pages}'.")
893
+
894
+ target_dir = out_dir or Path(f"nara-{clean_id}")
895
+ target_dir.mkdir(parents=True, exist_ok=True)
896
+
897
+ downloaded_manifest: list[dict[str, Any]] = []
898
+ with httpx.Client(timeout=60.0, follow_redirects=True, headers={"User-Agent": USER_AGENT}) as client:
899
+ for obj in selected_objs:
900
+ page_num = obj["page"]
901
+ obj_url = obj.get("url")
902
+ if not obj_url:
903
+ click.echo(f"Skipping page {page_num}: missing url", err=True)
904
+ continue
905
+ raw_name = obj.get("filename") or f"{page_num}.bin"
906
+ safe_name = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(raw_name).name)
907
+ dest = target_dir / f"{page_num:03d}_{safe_name}"
908
+ if dest.exists() and not overwrite:
909
+ click.echo(f"Exists (skip): {dest}")
910
+ else:
911
+ with client.stream("GET", obj_url) as resp:
912
+ resp.raise_for_status()
913
+ with dest.open("wb") as fh:
914
+ for chunk in resp.iter_bytes():
915
+ fh.write(chunk)
916
+ click.echo(f"Downloaded [{page_num}/{total_count}]: {dest} ({dest.stat().st_size:,} bytes)")
917
+ downloaded_manifest.append({"page": page_num, "file": dest.name, "url": obj_url})
918
+
919
+ if metadata:
920
+ compact_meta = {k: v for k, v in rec.items() if k != "objects"}
921
+ compact_meta["downloaded"] = downloaded_manifest
922
+ meta_path = target_dir / "metadata.json"
923
+ meta_path.write_text(json.dumps(compact_meta, indent=2) + "\n", encoding="utf-8")
924
+ click.echo(f"Saved metadata: {meta_path}")
925
+
926
+ click.echo(f"Done: {len(downloaded_manifest)} file(s) in {target_dir}")
927
+
928
+
929
+ if __name__ == "__main__":
930
+ try:
931
+ cli()
932
+ except httpx.HTTPStatusError as exc:
933
+ click.echo(f"HTTP error {exc.response.status_code}: {exc.request.url}", err=True)
934
+ sys.exit(1)