@kinloom/cli 0.1.1 → 0.3.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 (111) hide show
  1. package/dist/assets/cached-ocr.py +786 -0
  2. package/dist/assets/ocr.md +76 -0
  3. package/dist/assets/prep-scan.md +97 -0
  4. package/dist/assets/prep-scan.py +1313 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +162 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +130 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +129 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -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 +135 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +154 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +488 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +30 -5
  50. package/dist/client.js.map +1 -1
  51. package/dist/commands/ops/audit.d.ts +138 -0
  52. package/dist/commands/ops/audit.d.ts.map +1 -0
  53. package/dist/commands/ops/audit.js +872 -0
  54. package/dist/commands/ops/audit.js.map +1 -0
  55. package/dist/commands/ops/context.d.ts +100 -0
  56. package/dist/commands/ops/context.d.ts.map +1 -0
  57. package/dist/commands/ops/context.js +917 -0
  58. package/dist/commands/ops/context.js.map +1 -0
  59. package/dist/commands/ops/dates.d.ts +87 -0
  60. package/dist/commands/ops/dates.d.ts.map +1 -0
  61. package/dist/commands/ops/dates.js +228 -0
  62. package/dist/commands/ops/dates.js.map +1 -0
  63. package/dist/commands/ops/help.d.ts +8 -0
  64. package/dist/commands/ops/help.d.ts.map +1 -0
  65. package/dist/commands/ops/help.js +107 -0
  66. package/dist/commands/ops/help.js.map +1 -0
  67. package/dist/commands/ops/index.d.ts +8 -0
  68. package/dist/commands/ops/index.d.ts.map +1 -0
  69. package/dist/commands/ops/index.js +8 -0
  70. package/dist/commands/ops/index.js.map +1 -0
  71. package/dist/commands/ops/integrate.d.ts +61 -0
  72. package/dist/commands/ops/integrate.d.ts.map +1 -0
  73. package/dist/commands/ops/integrate.js +1063 -0
  74. package/dist/commands/ops/integrate.js.map +1 -0
  75. package/dist/commands/ops/sync.d.ts +194 -0
  76. package/dist/commands/ops/sync.d.ts.map +1 -0
  77. package/dist/commands/ops/sync.js +1251 -0
  78. package/dist/commands/ops/sync.js.map +1 -0
  79. package/dist/commands/ops/telemetry.d.ts +79 -0
  80. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  81. package/dist/commands/ops/telemetry.js +249 -0
  82. package/dist/commands/ops/telemetry.js.map +1 -0
  83. package/dist/commands/ops/verify.d.ts +76 -0
  84. package/dist/commands/ops/verify.d.ts.map +1 -0
  85. package/dist/commands/ops/verify.js +325 -0
  86. package/dist/commands/ops/verify.js.map +1 -0
  87. package/dist/commands/records/help.d.ts +18 -0
  88. package/dist/commands/records/help.d.ts.map +1 -0
  89. package/dist/commands/records/help.js +174 -0
  90. package/dist/commands/records/help.js.map +1 -0
  91. package/dist/commands/records/index.d.ts +5 -0
  92. package/dist/commands/records/index.d.ts.map +1 -0
  93. package/dist/commands/records/index.js +5 -0
  94. package/dist/commands/records/index.js.map +1 -0
  95. package/dist/commands/records/registry.d.ts +32 -0
  96. package/dist/commands/records/registry.d.ts.map +1 -0
  97. package/dist/commands/records/registry.js +227 -0
  98. package/dist/commands/records/registry.js.map +1 -0
  99. package/dist/commands/records/resolve.d.ts +14 -0
  100. package/dist/commands/records/resolve.d.ts.map +1 -0
  101. package/dist/commands/records/resolve.js +61 -0
  102. package/dist/commands/records/resolve.js.map +1 -0
  103. package/dist/commands/records/runner.d.ts +27 -0
  104. package/dist/commands/records/runner.d.ts.map +1 -0
  105. package/dist/commands/records/runner.js +255 -0
  106. package/dist/commands/records/runner.js.map +1 -0
  107. package/dist/index.d.ts +2 -0
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +2 -0
  110. package/dist/index.js.map +1 -1
  111. package/package.json +3 -3
@@ -0,0 +1,1387 @@
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
+ from contextlib import contextmanager
20
+ import hashlib
21
+ import json
22
+ import math
23
+ import os
24
+ import re
25
+ import shutil
26
+ import sys
27
+ import time
28
+ from pathlib import Path
29
+ from typing import Any, Iterator
30
+ from urllib.parse import quote, urlencode
31
+
32
+ import click
33
+ import httpx
34
+
35
+ CATALOG_WEB_BASE = "https://catalog.archives.gov"
36
+ CATALOG_API_BASE = "https://catalog.archives.gov/api/v2"
37
+ API_MAX_WORKERS = 6
38
+ DEFAULT_QUERY_TTL_HOURS = 168.0
39
+ USER_AGENT = (
40
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
41
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
42
+ )
43
+ VALID_LEVELS = ("recordGroup", "collection", "series", "fileUnit", "item")
44
+
45
+
46
+ def get_cache_root() -> Path:
47
+ override = os.environ.get("KINLOOM_NARA_CACHE_DIR")
48
+ if override:
49
+ return Path(override).expanduser()
50
+ return Path.home() / ".cache" / "kinloom-nara"
51
+
52
+
53
+ def resolve_query_ttl_hours(cli_ttl: float | None) -> float:
54
+ if cli_ttl is not None:
55
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
56
+ raise click.BadParameter(
57
+ f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0)."
58
+ )
59
+ return float(cli_ttl)
60
+ raw = os.environ.get("KINLOOM_NARA_QUERY_TTL_HOURS")
61
+ if raw is not None and raw.strip():
62
+ try:
63
+ parsed = float(raw.strip())
64
+ except ValueError as exc:
65
+ raise click.BadParameter(
66
+ f"Invalid KINLOOM_NARA_QUERY_TTL_HOURS value: {raw!r}."
67
+ ) from exc
68
+ if not math.isfinite(parsed) or parsed < 0:
69
+ raise click.BadParameter(
70
+ f"Invalid KINLOOM_NARA_QUERY_TTL_HOURS value: {raw!r} (must be >= 0)."
71
+ )
72
+ return parsed
73
+ return DEFAULT_QUERY_TTL_HOURS
74
+
75
+
76
+ def validate_naid(naid: str) -> str:
77
+ raw = str(naid).strip()
78
+ if not raw or "\x00" in raw or "/" in raw or "\\" in raw or ".." in raw:
79
+ raise click.BadParameter(f"Invalid NAID: {naid!r}")
80
+ match = re.fullmatch(r"(?:NAID[\s:-]*)?(\d+)", raw, re.IGNORECASE)
81
+ if not match:
82
+ raise click.BadParameter(f"Invalid NAID (expected digits): {naid!r}")
83
+ return match.group(1)
84
+
85
+
86
+ def safe_object_filename(page_num: int, raw_name: str | None) -> str:
87
+ """Build a traversal-safe per-page filename prefixed with 1-based page number."""
88
+ if page_num < 1:
89
+ raise ValueError(f"Invalid page number: {page_num!r}")
90
+ candidate = (raw_name or "").replace("\\", "/")
91
+ base = candidate.rsplit("/", 1)[-1].strip()
92
+ if not base or base in (".", "..") or "\x00" in base:
93
+ safe_base = f"{page_num}.bin"
94
+ else:
95
+ safe_base = re.sub(r"[^A-Za-z0-9._-]+", "_", base).lstrip(".")
96
+ if not safe_base or safe_base in (".", ".."):
97
+ safe_base = f"{page_num}.bin"
98
+ return f"{page_num:03d}_{safe_base}"
99
+
100
+
101
+ def resolve_safe_child(root: Path, filename: str) -> Path:
102
+ """Resolve a single filename strictly inside root (rejecting traversal)."""
103
+ if (
104
+ not filename
105
+ or "\x00" in filename
106
+ or "/" in filename
107
+ or "\\" in filename
108
+ or ":" in filename
109
+ or filename in (".", "..")
110
+ ):
111
+ raise ValueError(f"Unsafe filename: {filename!r}")
112
+ root_resolved = root.resolve()
113
+ dest = (root_resolved / filename).resolve()
114
+ if dest == root_resolved or not dest.is_relative_to(root_resolved):
115
+ raise ValueError(f"Unsafe path escaping root: {filename!r}")
116
+ return dest
117
+
118
+
119
+ @contextmanager
120
+ def file_lock(lock_path: Path) -> Iterator[None]:
121
+ """Advisory exclusive file lock (POSIX flock) with safe fallback on non-POSIX."""
122
+ try:
123
+ import fcntl
124
+ except ImportError:
125
+ yield
126
+ return
127
+
128
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
129
+ with open(lock_path, "a+b") as lock_file:
130
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
131
+ try:
132
+ yield
133
+ finally:
134
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
135
+
136
+
137
+ def read_json_if_valid(path: Path) -> dict[str, Any] | None:
138
+ if not path.is_file():
139
+ return None
140
+ try:
141
+ parsed = json.loads(path.read_text(encoding="utf-8"))
142
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
143
+ return None
144
+ return parsed if isinstance(parsed, dict) else None
145
+
146
+
147
+ def atomic_write_bytes(dest: Path, data: bytes) -> None:
148
+ dest.parent.mkdir(parents=True, exist_ok=True)
149
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
150
+ try:
151
+ tmp.write_bytes(data)
152
+ os.replace(tmp, dest)
153
+ except Exception:
154
+ tmp.unlink(missing_ok=True)
155
+ raise
156
+
157
+
158
+ def atomic_write_text(dest: Path, text: str) -> None:
159
+ atomic_write_bytes(dest, text.encode("utf-8"))
160
+
161
+
162
+ def atomic_write_json(dest: Path, payload: Any) -> None:
163
+ atomic_write_text(dest, json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
164
+
165
+
166
+ def atomic_copy_file(src: Path, dest: Path) -> None:
167
+ dest.parent.mkdir(parents=True, exist_ok=True)
168
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
169
+ try:
170
+ shutil.copyfile(src, tmp)
171
+ os.replace(tmp, dest)
172
+ except Exception:
173
+ tmp.unlink(missing_ok=True)
174
+ raise
175
+
176
+
177
+ def query_cache_path(canonical_params: dict[str, Any], cache_root: Path) -> tuple[str, Path]:
178
+ canonical = json.dumps(
179
+ canonical_params, sort_keys=True, separators=(",", ":"), ensure_ascii=False
180
+ )
181
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
182
+ return digest, resolve_safe_child(cache_root / "_queries", f"{digest}.json")
183
+
184
+
185
+ def _canonical_search_params(
186
+ query: str | None, filter_kwargs: dict[str, Any]
187
+ ) -> dict[str, Any]:
188
+ levels = [
189
+ p.strip()
190
+ for item in filter_kwargs["levels"]
191
+ for p in item.split(",")
192
+ if p.strip()
193
+ ]
194
+ record_groups = [
195
+ p.strip()
196
+ for item in filter_kwargs["record_groups"]
197
+ for p in item.split(",")
198
+ if p.strip()
199
+ ]
200
+ return {
201
+ "query": query,
202
+ "levels": levels,
203
+ "record_groups": record_groups,
204
+ "online": bool(filter_kwargs["online"]),
205
+ "material_type": filter_kwargs["material_type"],
206
+ "person": filter_kwargs["person"],
207
+ "title": filter_kwargs["title"],
208
+ "geo": filter_kwargs["geo"],
209
+ "control": filter_kwargs["control"],
210
+ "start_date": filter_kwargs["start_date"],
211
+ "end_date": filter_kwargs["end_date"],
212
+ "page": int(filter_kwargs["page"]),
213
+ "limit": int(filter_kwargs["limit"]),
214
+ }
215
+
216
+
217
+ def _read_cached_search(
218
+ canonical_params: dict[str, Any],
219
+ *,
220
+ cache_root: Path,
221
+ ttl_hours: float,
222
+ ) -> dict[str, Any] | None:
223
+ ttl_seconds = ttl_hours * 3600.0
224
+ if ttl_seconds <= 0:
225
+ return None
226
+ _, path = query_cache_path(canonical_params, cache_root)
227
+ envelope = read_json_if_valid(path)
228
+ if envelope is None:
229
+ return None
230
+ cached_at = envelope.get("cached_at")
231
+ data = envelope.get("data")
232
+ if not isinstance(cached_at, (int, float)) or not isinstance(data, dict):
233
+ return None
234
+ if not isinstance(data.get("results"), list):
235
+ return None
236
+ if (time.time() - float(cached_at)) <= ttl_seconds:
237
+ return data
238
+ return None
239
+
240
+
241
+ def _write_cached_search(
242
+ canonical_params: dict[str, Any],
243
+ payload: dict[str, Any],
244
+ *,
245
+ cache_root: Path,
246
+ ) -> None:
247
+ if not isinstance(payload.get("results"), list):
248
+ return
249
+ digest, path = query_cache_path(canonical_params, cache_root)
250
+ lock_path = resolve_safe_child(cache_root / "_locks", f"query_{digest}.lock")
251
+ with file_lock(lock_path):
252
+ atomic_write_json(
253
+ path,
254
+ {"cached_at": time.time(), "params": canonical_params, "data": payload},
255
+ )
256
+
257
+
258
+ def _record_cache_path(clean_id: str, cache_root: Path) -> Path:
259
+ return resolve_safe_child(cache_root / "records", f"{clean_id}.json")
260
+
261
+
262
+ def _read_cached_record(
263
+ clean_id: str, *, cache_root: Path, require_text: bool
264
+ ) -> dict[str, Any] | None:
265
+ envelope = read_json_if_valid(_record_cache_path(clean_id, cache_root))
266
+ if envelope is None:
267
+ return None
268
+ record = envelope.get("record")
269
+ if not isinstance(record, dict) or record.get("error"):
270
+ return None
271
+ if require_text and not envelope.get("has_text"):
272
+ return None
273
+ return record
274
+
275
+
276
+ def _write_cached_record(
277
+ clean_id: str,
278
+ full_record: dict[str, Any],
279
+ *,
280
+ cache_root: Path,
281
+ has_text: bool,
282
+ ) -> None:
283
+ if full_record.get("error"):
284
+ return
285
+ path = _record_cache_path(clean_id, cache_root)
286
+ lock_path = resolve_safe_child(cache_root / "_locks", f"record_{clean_id}.lock")
287
+ with file_lock(lock_path):
288
+ atomic_write_json(
289
+ path,
290
+ {
291
+ "cached_at": time.time(),
292
+ "naId": clean_id,
293
+ "has_text": bool(has_text),
294
+ "record": full_record,
295
+ },
296
+ )
297
+
298
+
299
+ def _project_record(
300
+ full_record: dict[str, Any],
301
+ *,
302
+ include_objects: bool = False,
303
+ include_text: bool = False,
304
+ page_spec: str | None = None,
305
+ ) -> dict[str, Any]:
306
+ """Slice a cached full record into the exact shape requested by CLI flags."""
307
+ out = {
308
+ k: v
309
+ for k, v in full_record.items()
310
+ if k not in ("objects", "extractedText", "transcriptions")
311
+ }
312
+ total = int(full_record.get("objectCount") or len(full_record.get("objects") or []))
313
+ if include_objects and full_record.get("objects"):
314
+ selected_pages = set(parse_page_spec(page_spec, total))
315
+ out["objects"] = [
316
+ obj for obj in full_record["objects"] if obj.get("page") in selected_pages
317
+ ]
318
+ if include_text:
319
+ if full_record.get("extractedText"):
320
+ selected_pages = set(parse_page_spec(page_spec, total)) if total > 0 else set()
321
+ texts = [
322
+ item
323
+ for item in full_record["extractedText"]
324
+ if not selected_pages or item.get("page") in selected_pages
325
+ ]
326
+ if texts:
327
+ out["extractedText"] = texts
328
+ if full_record.get("transcriptions"):
329
+ out["transcriptions"] = list(full_record["transcriptions"])
330
+ return out
331
+
332
+
333
+ class _NaraWafOrNonJsonError(RuntimeError):
334
+ """Raised when the NARA v2 API returns an HTML WAF page or non-JSON body."""
335
+
336
+ def __init__(self, url: str, content_type: str, detail: str = "") -> None:
337
+ self.url = url
338
+ self.content_type = content_type
339
+ msg = f"NARA v2 API returned non-JSON response ({content_type or 'unknown content-type'})"
340
+ if detail:
341
+ msg = f"{msg}: {detail}"
342
+ super().__init__(msg)
343
+
344
+
345
+ def _normalize_query_for_waf_retry(query: str) -> str | None:
346
+ """Strip double quotes and standalone boolean AND operators that trigger CloudFront WAF."""
347
+ stripped = query.replace('"', " ")
348
+ stripped = re.sub(r"\bAND\b", " ", stripped)
349
+ normalized = re.sub(r"\s+", " ", stripped).strip()
350
+ if not normalized or normalized == query.strip():
351
+ return None
352
+ return normalized
353
+
354
+
355
+ def _new_api_client() -> httpx.Client:
356
+ return httpx.Client(
357
+ timeout=15.0,
358
+ follow_redirects=True,
359
+ limits=httpx.Limits(
360
+ max_connections=API_MAX_WORKERS * 2,
361
+ max_keepalive_connections=API_MAX_WORKERS,
362
+ ),
363
+ )
364
+
365
+
366
+ def find_browser_executable() -> str | None:
367
+ env_exe = os.environ.get("NARA_BROWSER")
368
+ if env_exe and Path(env_exe).exists():
369
+ return env_exe
370
+ for candidate in ("chromium", "chromium-browser", "google-chrome", "google-chrome-stable"):
371
+ found = shutil.which(candidate)
372
+ if found:
373
+ return found
374
+ return None
375
+
376
+
377
+ def build_query_params(
378
+ query: str | None = None,
379
+ *,
380
+ levels: tuple[str, ...] = (),
381
+ record_groups: tuple[str, ...] = (),
382
+ online: bool = False,
383
+ material_type: str | None = None,
384
+ person: str | None = None,
385
+ title: str | None = None,
386
+ geo: str | None = None,
387
+ control: str | None = None,
388
+ start_date: str | None = None,
389
+ end_date: str | None = None,
390
+ page: int = 1,
391
+ limit: int = 20,
392
+ for_api: bool = False,
393
+ ) -> list[tuple[str, str]]:
394
+ """Build verified NARA Catalog query parameters (q first, comma-joined multi-values)."""
395
+ params: list[tuple[str, str]] = []
396
+ if query:
397
+ params.append(("q", query))
398
+ if title:
399
+ params.append(("title", title))
400
+ if person:
401
+ params.append(("personOrOrg", person))
402
+ if geo:
403
+ params.append(("geographicReference", geo))
404
+ if control:
405
+ params.append(("controlNumbers", control))
406
+ if levels:
407
+ flat = [p.strip() for item in levels for p in item.split(",") if p.strip()]
408
+ invalid = [lv for lv in flat if lv not in VALID_LEVELS]
409
+ if invalid:
410
+ raise click.BadParameter(
411
+ f"Invalid level(s): {', '.join(invalid)}. Choose from: {', '.join(VALID_LEVELS)}"
412
+ )
413
+ if flat:
414
+ params.append(("levelOfDescription", ",".join(flat)))
415
+ if record_groups:
416
+ flat_rg = [p.strip() for item in record_groups for p in item.split(",") if p.strip()]
417
+ if flat_rg:
418
+ params.append(("recordGroupNumber", ",".join(flat_rg)))
419
+ if online:
420
+ params.append(("availableOnline", "true"))
421
+ if not for_api:
422
+ params.append(("dataSource", "description"))
423
+ if material_type:
424
+ params.append(("typeOfMaterials", material_type))
425
+ if start_date:
426
+ params.append(("startDate", start_date))
427
+ if end_date:
428
+ params.append(("endDate", end_date))
429
+ if page > 1 or for_api:
430
+ params.append(("page", str(page)))
431
+ if for_api or limit != 20:
432
+ params.append(("limit", str(limit)))
433
+ return params
434
+
435
+
436
+ def encode_catalog_url(params: list[tuple[str, str]], *, for_api: bool = False) -> str:
437
+ base = f"{CATALOG_API_BASE}/records/search" if for_api else f"{CATALOG_WEB_BASE}/search"
438
+ qs = urlencode(params, quote_via=quote)
439
+ return f"{base}?{qs}" if qs else base
440
+
441
+
442
+ def parse_page_spec(spec: str | None, total: int) -> list[int]:
443
+ """Parse a 1-based page selection like '1-3,5,8-10' into sorted 1-based indices."""
444
+ if not spec or spec.strip().lower() == "all":
445
+ return list(range(1, total + 1))
446
+ chosen: set[int] = set()
447
+ for part in spec.split(","):
448
+ part = part.strip()
449
+ if not part:
450
+ continue
451
+ if "-" in part:
452
+ a_s, b_s = part.split("-", 1)
453
+ a = int(a_s.strip()) if a_s.strip() else 1
454
+ b = int(b_s.strip()) if b_s.strip() else total
455
+ if a > b:
456
+ a, b = b, a
457
+ chosen.update(range(max(1, a), min(total, b) + 1))
458
+ else:
459
+ idx = int(part)
460
+ if 1 <= idx <= total:
461
+ chosen.add(idx)
462
+ return sorted(chosen)
463
+
464
+
465
+ def _extract_record(
466
+ hit: dict[str, Any],
467
+ *,
468
+ include_objects: bool = False,
469
+ include_text: bool = False,
470
+ page_spec: str | None = None,
471
+ ) -> dict[str, Any]:
472
+ """Extract only high-signal archival fields (omitting nulls, empties, and raw bloat)."""
473
+ src = hit.get("_source", {}) if isinstance(hit, dict) else {}
474
+ rec = src.get("record", hit if isinstance(hit, dict) else {})
475
+ naid = str(rec.get("naId") or "")
476
+ ancestors = rec.get("ancestors") or []
477
+ rg = next((a for a in ancestors if a.get("levelOfDescription") == "recordGroup"), None)
478
+ series = next((a for a in ancestors if a.get("levelOfDescription") == "series"), None)
479
+ microforms = rec.get("microformPublications") or []
480
+ objs = rec.get("digitalObjects") or []
481
+
482
+ out: dict[str, Any] = {
483
+ "naId": naid,
484
+ "title": rec.get("title") or "",
485
+ "url": f"{CATALOG_WEB_BASE}/id/{naid}" if naid else "",
486
+ }
487
+ if rec.get("levelOfDescription"):
488
+ out["level"] = rec["levelOfDescription"]
489
+
490
+ rg_num = rg.get("recordGroupNumber") if rg else rec.get("recordGroupNumber")
491
+ if rg_num is not None:
492
+ out["rg"] = rg_num
493
+ if rg and rg.get("title"):
494
+ out["rgTitle"] = rg["title"]
495
+ if series and series.get("title"):
496
+ out["series"] = series["title"]
497
+ if series and series.get("naId"):
498
+ out["seriesNaId"] = str(series["naId"])
499
+
500
+ dates: list[str] = []
501
+ for k in ("inclusiveStartDate", "inclusiveEndDate", "productionDateArray", "coverageStartDate", "coverageEndDate"):
502
+ v = rec.get(k)
503
+ if isinstance(v, dict) and v.get("logicalDate"):
504
+ dates.append(str(v["logicalDate"]))
505
+ elif isinstance(v, list):
506
+ for entry in v:
507
+ if isinstance(entry, dict) and entry.get("logicalDate"):
508
+ dates.append(str(entry["logicalDate"]))
509
+ if dates:
510
+ out["dates"] = dates
511
+
512
+ mf_list = []
513
+ for m in microforms:
514
+ parts = [m.get("identifier"), m.get("title"), m.get("note")]
515
+ text = " | ".join(str(p).strip() for p in parts if p)
516
+ if text:
517
+ mf_list.append(text)
518
+ if mf_list:
519
+ out["microform"] = mf_list
520
+
521
+ access = (rec.get("accessRestriction") or {}).get("status")
522
+ use = (rec.get("useRestriction") or {}).get("status")
523
+ if access:
524
+ out["access"] = access
525
+ if use:
526
+ out["use"] = use
527
+
528
+ if rec.get("scopeAndContentNote"):
529
+ out["scope"] = rec["scopeAndContentNote"]
530
+
531
+ locations: list[str] = []
532
+ for po in rec.get("physicalOccurrences") or []:
533
+ for ru in po.get("referenceUnits") or []:
534
+ name = ru.get("name") if isinstance(ru, dict) else None
535
+ if name and name not in locations:
536
+ locations.append(name)
537
+ if locations:
538
+ out["location"] = locations[0] if len(locations) == 1 else locations
539
+
540
+ if objs:
541
+ out["objectCount"] = len(objs)
542
+ if include_objects:
543
+ selected = parse_page_spec(page_spec, len(objs))
544
+ out["objects"] = [
545
+ {
546
+ "page": p,
547
+ "filename": objs[p - 1].get("objectFilename") or str(objs[p - 1].get("objectId") or ""),
548
+ "url": objs[p - 1].get("objectUrl") or "",
549
+ }
550
+ for p in selected
551
+ ]
552
+ if include_text:
553
+ selected = parse_page_spec(page_spec, len(objs))
554
+ texts = []
555
+ for p in selected:
556
+ o = objs[p - 1]
557
+ txt = o.get("extractedText") or o.get("otherExtractedText")
558
+ if txt:
559
+ texts.append({"page": p, "filename": o.get("objectFilename") or "", "text": txt})
560
+ if texts:
561
+ out["extractedText"] = texts
562
+
563
+ return out
564
+
565
+
566
+ def _api_get_json(
567
+ url: str,
568
+ api_key: str,
569
+ *,
570
+ client: httpx.Client | None = None,
571
+ ) -> dict[str, Any]:
572
+ headers = {
573
+ "x-api-key": api_key,
574
+ "Accept": "application/json",
575
+ "User-Agent": USER_AGENT,
576
+ }
577
+ if client is None:
578
+ with _new_api_client() as local_client:
579
+ return _api_get_json(url, api_key, client=local_client)
580
+ resp = client.get(url, headers=headers)
581
+ content_type = resp.headers.get("content-type", "")
582
+ if resp.status_code == 403 and "html" in content_type.lower():
583
+ raise _NaraWafOrNonJsonError(url, content_type, "HTTP 403 HTML response")
584
+ resp.raise_for_status()
585
+ if "json" not in content_type.lower():
586
+ raise _NaraWafOrNonJsonError(url, content_type)
587
+ try:
588
+ data = resp.json()
589
+ except ValueError as exc:
590
+ raise _NaraWafOrNonJsonError(url, content_type, str(exc)) from exc
591
+ if not isinstance(data, dict):
592
+ raise _NaraWafOrNonJsonError(
593
+ url, content_type, f"expected JSON object, got {type(data).__name__}"
594
+ )
595
+ return data
596
+
597
+
598
+ def _browser_search_many(
599
+ items: list[tuple[str | None, str]], timeout_ms: int = 30000
600
+ ) -> list[dict[str, Any]]:
601
+ """Run one or more catalog searches sharing a single headless Chromium session."""
602
+ from playwright.sync_api import sync_playwright
603
+
604
+ exe = find_browser_executable()
605
+ results: list[dict[str, Any]] = []
606
+
607
+ with sync_playwright() as pw:
608
+ browser = pw.chromium.launch(headless=True, executable_path=exe)
609
+ context = browser.new_context(user_agent=USER_AGENT)
610
+ page = context.new_page()
611
+
612
+ for query, search_url in items:
613
+ captured: list[dict[str, Any]] = []
614
+
615
+ def on_response(resp: Any, bucket: list[dict[str, Any]] = captured) -> None:
616
+ u = resp.url
617
+ if "/proxy/" in u and "/records/search" in u and resp.status == 200:
618
+ try:
619
+ if "json" in resp.headers.get("content-type", ""):
620
+ bucket.append(resp.json())
621
+ except Exception:
622
+ pass
623
+
624
+ page.on("response", on_response)
625
+ page.goto(search_url, wait_until="domcontentloaded", timeout=timeout_ms)
626
+ try:
627
+ page.wait_for_function(
628
+ """() => {
629
+ const t = document.body.innerText || '';
630
+ return /\\d+\\s+results?\\s+for|No results|0 results|did not match/i.test(t);
631
+ }""",
632
+ timeout=min(timeout_ms, 20000),
633
+ )
634
+ except Exception:
635
+ pass
636
+ page.wait_for_timeout(500)
637
+ page.remove_listener("response", on_response)
638
+
639
+ entry: dict[str, Any] | None = None
640
+ for cap in reversed(captured):
641
+ body = cap.get("body", cap)
642
+ hits_obj = body.get("hits", {}) if isinstance(body, dict) else {}
643
+ hits = hits_obj.get("hits")
644
+ if isinstance(hits, list):
645
+ total_raw = hits_obj.get("total", len(hits))
646
+ total = total_raw.get("value", len(hits)) if isinstance(total_raw, dict) else int(total_raw)
647
+ entry = {
648
+ "query": query,
649
+ "searchUrl": search_url,
650
+ "total": total,
651
+ "results": [_extract_record(h) for h in hits],
652
+ }
653
+ break
654
+
655
+ if entry is None:
656
+ dom_items = page.evaluate(
657
+ """() => {
658
+ const items = [];
659
+ const seen = new Set();
660
+ for (const a of document.querySelectorAll('a[href*="/id/"]')) {
661
+ const m = (a.getAttribute('href') || '').match(/\\/id\\/(\\d+)/);
662
+ if (!m || seen.has(m[1])) continue;
663
+ const title = (a.textContent || '').trim();
664
+ if (!title) continue;
665
+ seen.add(m[1]);
666
+ items.push({ naId: m[1], title, url: 'https://catalog.archives.gov/id/' + m[1] });
667
+ }
668
+ return items;
669
+ }"""
670
+ )
671
+ entry = {
672
+ "query": query,
673
+ "searchUrl": search_url,
674
+ "total": len(dom_items),
675
+ "results": dom_items,
676
+ }
677
+ if entry.get("query") is None:
678
+ entry.pop("query", None)
679
+ results.append(entry)
680
+
681
+ browser.close()
682
+
683
+ return results
684
+
685
+
686
+ def _browser_get_records(
687
+ naids: list[str],
688
+ *,
689
+ include_objects: bool = False,
690
+ include_text: bool = False,
691
+ page_spec: str | None = None,
692
+ timeout_ms: int = 30000,
693
+ ) -> list[dict[str, Any]]:
694
+ from playwright.sync_api import sync_playwright
695
+
696
+ exe = find_browser_executable()
697
+ records: list[dict[str, Any]] = []
698
+
699
+ with sync_playwright() as pw:
700
+ browser = pw.chromium.launch(headless=True, executable_path=exe)
701
+ context = browser.new_context(user_agent=USER_AGENT)
702
+ page = context.new_page()
703
+
704
+ for naid in naids:
705
+ clean_id = re.sub(r"\D+", "", str(naid))
706
+ captured_record: dict[str, Any] | None = None
707
+ contributions: list[dict[str, Any]] = []
708
+
709
+ def on_response(resp: Any, target: str = clean_id) -> None:
710
+ nonlocal captured_record
711
+ u = resp.url
712
+ if resp.status != 200 or "json" not in resp.headers.get("content-type", ""):
713
+ return
714
+ if f"naId_is={target}" in u and "/records/search" in u:
715
+ try:
716
+ payload = resp.json()
717
+ hits = payload.get("body", payload).get("hits", {}).get("hits", [])
718
+ if hits:
719
+ captured_record = _extract_record(
720
+ hits[0],
721
+ include_objects=include_objects,
722
+ include_text=include_text,
723
+ page_spec=page_spec,
724
+ )
725
+ except Exception:
726
+ pass
727
+ elif include_text and f"targetNaId/{target}" in u and "/contributions/" in u:
728
+ try:
729
+ c = resp.json()
730
+ if isinstance(c, list):
731
+ contributions.extend(c)
732
+ except Exception:
733
+ pass
734
+
735
+ page.on("response", on_response)
736
+ url = f"{CATALOG_WEB_BASE}/id/{clean_id}"
737
+ page.goto(url, wait_until="domcontentloaded", timeout=timeout_ms)
738
+ try:
739
+ page.wait_for_function(
740
+ "() => /National Archives Identifier/i.test(document.body.innerText || '')",
741
+ timeout=min(timeout_ms, 20000),
742
+ )
743
+ except Exception:
744
+ pass
745
+ page.wait_for_timeout(600)
746
+ page.remove_listener("response", on_response)
747
+
748
+ if captured_record is None:
749
+ captured_record = {"naId": clean_id, "url": url, "error": "Record metadata not captured."}
750
+ elif include_text and contributions:
751
+ transcriptions = [
752
+ c.get("text") or c.get("transcription")
753
+ for c in contributions
754
+ if c.get("contributionType") == "transcription" and (c.get("text") or c.get("transcription"))
755
+ ]
756
+ if transcriptions:
757
+ captured_record["transcriptions"] = transcriptions
758
+ records.append(captured_record)
759
+
760
+ browser.close()
761
+
762
+ return records
763
+
764
+
765
+ def _format_record_text(rec: dict[str, Any]) -> str:
766
+ if rec.get("error"):
767
+ return f"NAID {rec.get('naId')}: ERROR - {rec['error']}"
768
+ header_parts = [f"NAID {rec['naId']}"]
769
+ if rec.get("level"):
770
+ header_parts.append(f"[{rec['level']}]")
771
+ if rec.get("rg") is not None:
772
+ header_parts.append(f"RG {rec['rg']}")
773
+ if rec.get("objectCount"):
774
+ header_parts.append(f"{rec['objectCount']} files")
775
+ lines = [f"{' '.join(header_parts)}: {rec.get('title')}", f" {rec.get('url')}"]
776
+ if rec.get("series"):
777
+ lines.append(f" Series: {rec['series']}")
778
+ if rec.get("dates"):
779
+ lines.append(f" Dates: {' .. '.join(rec['dates'])}")
780
+ for mf in rec.get("microform") or []:
781
+ lines.append(f" Microform: {mf}")
782
+ if rec.get("access") or rec.get("use"):
783
+ lines.append(f" Access/Use: {rec.get('access', '?')} / {rec.get('use', '?')}")
784
+ if rec.get("location"):
785
+ loc = rec["location"] if isinstance(rec["location"], str) else "; ".join(rec["location"])
786
+ lines.append(f" Location: {loc}")
787
+ if rec.get("scope"):
788
+ lines.append(f" Scope: {rec['scope']}")
789
+ for obj in rec.get("objects") or []:
790
+ lines.append(f" [{obj['page']:03d}] {obj['filename']}: {obj['url']}")
791
+ for item in rec.get("extractedText") or []:
792
+ lines.append(f" --- Page {item['page']} ({item['filename']}) ---\n{item['text']}")
793
+ for tr in rec.get("transcriptions") or []:
794
+ lines.append(f" --- Transcription ---\n{tr}")
795
+ return "\n".join(lines)
796
+
797
+
798
+ def _common_search_options(fn: Any) -> Any:
799
+ options = [
800
+ click.option("--level", "levels", multiple=True, help="Level(s): recordGroup, collection, series, fileUnit, item."),
801
+ click.option("--rg", "record_groups", multiple=True, help="Record Group number(s), e.g. 109 or 29,109."),
802
+ click.option("--online", is_flag=True, help="Limit to records with viewable digital objects."),
803
+ click.option("--type", "material_type", default=None, help="Type of material, e.g. 'Textual Records'."),
804
+ click.option("--person", default=None, help="Person or Organization authority heading."),
805
+ click.option("--title", default=None, help="Title search filter."),
806
+ click.option("--geo", default=None, help="Geographic reference filter."),
807
+ click.option("--control", default=None, help="Control number or microform identifier."),
808
+ click.option("--start-date", default=None, help="Beginning date (YYYY, YYYY-MM, or YYYY-MM-DD)."),
809
+ click.option("--end-date", default=None, help="Ending date (YYYY, YYYY-MM, or YYYY-MM-DD)."),
810
+ click.option("--page", default=1, show_default=True, type=int, help="Result page number."),
811
+ click.option("--limit", default=20, show_default=True, type=int, help="Results per page."),
812
+ ]
813
+ for opt in reversed(options):
814
+ fn = opt(fn)
815
+ return fn
816
+
817
+
818
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
819
+ def cli() -> None:
820
+ """Search, inspect, and download National Archives Catalog (NARA) records."""
821
+
822
+
823
+ @cli.command("url")
824
+ @click.argument("query", required=False, default=None)
825
+ @_common_search_options
826
+ @click.option("--api", "for_api", is_flag=True, help="Output the v2 API endpoint URL instead of the website URL.")
827
+ def cmd_url(
828
+ query: str | None,
829
+ levels: tuple[str, ...],
830
+ record_groups: tuple[str, ...],
831
+ online: bool,
832
+ material_type: str | None,
833
+ person: str | None,
834
+ title: str | None,
835
+ geo: str | None,
836
+ control: str | None,
837
+ start_date: str | None,
838
+ end_date: str | None,
839
+ page: int,
840
+ limit: int,
841
+ for_api: bool,
842
+ ) -> None:
843
+ """Build and print a verified NARA Catalog search URL."""
844
+ params = build_query_params(
845
+ query,
846
+ levels=levels,
847
+ record_groups=record_groups,
848
+ online=online,
849
+ material_type=material_type,
850
+ person=person,
851
+ title=title,
852
+ geo=geo,
853
+ control=control,
854
+ start_date=start_date,
855
+ end_date=end_date,
856
+ page=page,
857
+ limit=limit,
858
+ for_api=for_api,
859
+ )
860
+ click.echo(encode_catalog_url(params, for_api=for_api))
861
+
862
+
863
+ def _build_search_payload(
864
+ query: str | None,
865
+ web_url: str,
866
+ raw: dict[str, Any],
867
+ ) -> dict[str, Any]:
868
+ hits_obj = raw.get("body", raw).get("hits", {})
869
+ hits = hits_obj.get("hits", [])
870
+ total_raw = hits_obj.get("total", len(hits))
871
+ total = total_raw.get("value", len(hits)) if isinstance(total_raw, dict) else int(total_raw)
872
+ item: dict[str, Any] = {
873
+ "searchUrl": web_url,
874
+ "total": total,
875
+ "results": [_extract_record(h) for h in hits],
876
+ }
877
+ if query is not None:
878
+ item = {"query": query, **item}
879
+ return item
880
+
881
+
882
+ def _api_search_one(
883
+ query: str | None,
884
+ *,
885
+ api_key: str,
886
+ client: httpx.Client,
887
+ filter_kwargs: dict[str, Any],
888
+ ) -> tuple[dict[str, Any] | None, str]:
889
+ api_url = encode_catalog_url(
890
+ build_query_params(query, **filter_kwargs, for_api=True),
891
+ for_api=True,
892
+ )
893
+ web_url = encode_catalog_url(
894
+ build_query_params(query, **filter_kwargs, for_api=False),
895
+ for_api=False,
896
+ )
897
+ try:
898
+ raw = _api_get_json(api_url, api_key, client=client)
899
+ return _build_search_payload(query, web_url, raw), web_url
900
+ except _NaraWafOrNonJsonError:
901
+ retry_query = _normalize_query_for_waf_retry(query) if query else None
902
+ if retry_query is None:
903
+ return None, web_url
904
+ retry_api_url = encode_catalog_url(
905
+ build_query_params(retry_query, **filter_kwargs, for_api=True),
906
+ for_api=True,
907
+ )
908
+ try:
909
+ raw = _api_get_json(retry_api_url, api_key, client=client)
910
+ return _build_search_payload(query, web_url, raw), web_url
911
+ except _NaraWafOrNonJsonError:
912
+ return None, web_url
913
+
914
+
915
+ @cli.command("search")
916
+ @click.argument("queries", nargs=-1)
917
+ @_common_search_options
918
+ @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
919
+ @click.option("--browser", "force_browser", is_flag=True, help="Force headless Chromium website mode.")
920
+ @click.option("--refresh", is_flag=True, help="Bypass the local disk cache and fetch fresh search results.")
921
+ @click.option(
922
+ "--cache-ttl-hours",
923
+ type=float,
924
+ default=None,
925
+ help="Override search query cache TTL in hours (default: 168 or $KINLOOM_NARA_QUERY_TTL_HOURS).",
926
+ )
927
+ @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
928
+ def cmd_search(
929
+ queries: tuple[str, ...],
930
+ levels: tuple[str, ...],
931
+ record_groups: tuple[str, ...],
932
+ online: bool,
933
+ material_type: str | None,
934
+ person: str | None,
935
+ title: str | None,
936
+ geo: str | None,
937
+ control: str | None,
938
+ start_date: str | None,
939
+ end_date: str | None,
940
+ page: int,
941
+ limit: int,
942
+ api_key: str | None,
943
+ force_browser: bool,
944
+ refresh: bool,
945
+ cache_ttl_hours: float | None,
946
+ as_json: bool,
947
+ ) -> None:
948
+ """Search the NARA Catalog. Accepts one or multiple queries (parallel via API or shared browser)."""
949
+ query_list: list[str | None] = list(queries) if queries else [None]
950
+ use_api = bool(api_key) and not force_browser
951
+ ttl_hours = resolve_query_ttl_hours(cache_ttl_hours)
952
+ cache_root = get_cache_root()
953
+ filter_kwargs: dict[str, Any] = {
954
+ "levels": levels,
955
+ "record_groups": record_groups,
956
+ "online": online,
957
+ "material_type": material_type,
958
+ "person": person,
959
+ "title": title,
960
+ "geo": geo,
961
+ "control": control,
962
+ "start_date": start_date,
963
+ "end_date": end_date,
964
+ "page": page,
965
+ "limit": limit,
966
+ }
967
+
968
+ # Validate query parameters at the boundary before consulting cache.
969
+ build_query_params(query_list[0], **filter_kwargs, for_api=use_api)
970
+
971
+ canonical_list = [_canonical_search_params(q, filter_kwargs) for q in query_list]
972
+ slots: list[dict[str, Any] | None] = [None] * len(query_list)
973
+ miss_indices: list[int] = []
974
+ for idx, canonical in enumerate(canonical_list):
975
+ if not refresh:
976
+ cached = _read_cached_search(canonical, cache_root=cache_root, ttl_hours=ttl_hours)
977
+ if cached is not None:
978
+ slots[idx] = cached
979
+ continue
980
+ miss_indices.append(idx)
981
+
982
+ if miss_indices:
983
+ miss_queries = [query_list[idx] for idx in miss_indices]
984
+ if use_api and api_key:
985
+ with _new_api_client() as client:
986
+ if len(miss_queries) == 1:
987
+ outcomes = [
988
+ _api_search_one(
989
+ miss_queries[0],
990
+ api_key=api_key,
991
+ client=client,
992
+ filter_kwargs=filter_kwargs,
993
+ )
994
+ ]
995
+ else:
996
+ workers = min(API_MAX_WORKERS, len(miss_queries))
997
+ with ThreadPoolExecutor(max_workers=workers) as executor:
998
+ outcomes = list(
999
+ executor.map(
1000
+ lambda q: _api_search_one(
1001
+ q,
1002
+ api_key=api_key,
1003
+ client=client,
1004
+ filter_kwargs=filter_kwargs,
1005
+ ),
1006
+ miss_queries,
1007
+ )
1008
+ )
1009
+
1010
+ fallback_slots: list[int] = []
1011
+ fallback_pairs: list[tuple[str | None, str]] = []
1012
+ for slot_idx, (entry, web_url) in zip(miss_indices, outcomes, strict=True):
1013
+ if entry is None:
1014
+ fallback_slots.append(slot_idx)
1015
+ fallback_pairs.append((query_list[slot_idx], web_url))
1016
+ else:
1017
+ slots[slot_idx] = entry
1018
+ _write_cached_search(
1019
+ canonical_list[slot_idx], entry, cache_root=cache_root
1020
+ )
1021
+
1022
+ if fallback_pairs:
1023
+ fallback_results = _browser_search_many(fallback_pairs)
1024
+ for slot_idx, fb_entry in zip(fallback_slots, fallback_results, strict=True):
1025
+ slots[slot_idx] = fb_entry
1026
+ _write_cached_search(
1027
+ canonical_list[slot_idx], fb_entry, cache_root=cache_root
1028
+ )
1029
+ else:
1030
+ url_pairs = [
1031
+ (
1032
+ q,
1033
+ encode_catalog_url(
1034
+ build_query_params(q, **filter_kwargs, for_api=False),
1035
+ for_api=False,
1036
+ ),
1037
+ )
1038
+ for q in miss_queries
1039
+ ]
1040
+ fetched = _browser_search_many(url_pairs)
1041
+ for slot_idx, entry in zip(miss_indices, fetched, strict=True):
1042
+ slots[slot_idx] = entry
1043
+ _write_cached_search(
1044
+ canonical_list[slot_idx], entry, cache_root=cache_root
1045
+ )
1046
+
1047
+ payloads = [entry for entry in slots if entry is not None]
1048
+
1049
+ if as_json:
1050
+ click.echo(json.dumps(payloads[0] if len(payloads) == 1 else payloads, indent=2))
1051
+ return
1052
+
1053
+ for p_idx, payload in enumerate(payloads):
1054
+ if p_idx > 0:
1055
+ click.echo("")
1056
+ hdr = f"Query: {payload['query']} | " if payload.get("query") else ""
1057
+ click.echo(f"{hdr}Total: {payload['total']} | {payload['searchUrl']}")
1058
+ for idx, rec in enumerate(payload["results"], 1):
1059
+ meta = " | ".join(
1060
+ part
1061
+ for part in (
1062
+ rec.get("level"),
1063
+ f"RG {rec['rg']}" if rec.get("rg") is not None else None,
1064
+ f"{rec['objectCount']} files" if rec.get("objectCount") else None,
1065
+ )
1066
+ if part
1067
+ )
1068
+ series = f" [{rec['series']}]" if rec.get("series") else ""
1069
+ click.echo(f" {idx:2d}. NAID {rec['naId']} ({meta}): {rec.get('title')}{series}")
1070
+
1071
+
1072
+ def _api_get_one_record(
1073
+ naid: str,
1074
+ *,
1075
+ api_key: str,
1076
+ client: httpx.Client,
1077
+ include_objects: bool,
1078
+ include_text: bool,
1079
+ page_spec: str,
1080
+ ) -> dict[str, Any] | None:
1081
+ clean_id = validate_naid(naid)
1082
+ url = (
1083
+ f"{CATALOG_API_BASE}/records/search?"
1084
+ f"naId_is={clean_id}&includeExtractedText={'true' if include_text else 'false'}"
1085
+ f"&includeOtherExtractedText={'true' if include_text else 'false'}"
1086
+ )
1087
+ try:
1088
+ raw = _api_get_json(url, api_key, client=client)
1089
+ except _NaraWafOrNonJsonError:
1090
+ return None
1091
+ hits = raw.get("body", raw).get("hits", {}).get("hits", [])
1092
+ if hits:
1093
+ return _extract_record(
1094
+ hits[0],
1095
+ include_objects=include_objects,
1096
+ include_text=include_text,
1097
+ page_spec=page_spec,
1098
+ )
1099
+ return {"naId": clean_id, "url": f"{CATALOG_WEB_BASE}/id/{clean_id}", "error": "Not found"}
1100
+
1101
+
1102
+ def _load_or_fetch_full_records(
1103
+ naids: list[str],
1104
+ *,
1105
+ api_key: str | None,
1106
+ force_browser: bool,
1107
+ include_text: bool,
1108
+ refresh: bool,
1109
+ cache_root: Path,
1110
+ ) -> list[dict[str, Any]]:
1111
+ clean_ids = [validate_naid(n) for n in naids]
1112
+ use_api = bool(api_key) and not force_browser
1113
+ slots: list[dict[str, Any] | None] = [None] * len(clean_ids)
1114
+ miss_indices: list[int] = []
1115
+
1116
+ for idx, clean_id in enumerate(clean_ids):
1117
+ if not refresh:
1118
+ cached = _read_cached_record(
1119
+ clean_id, cache_root=cache_root, require_text=include_text
1120
+ )
1121
+ if cached is not None:
1122
+ slots[idx] = cached
1123
+ continue
1124
+ miss_indices.append(idx)
1125
+
1126
+ if miss_indices:
1127
+ miss_ids = [clean_ids[idx] for idx in miss_indices]
1128
+ if use_api and api_key:
1129
+ with _new_api_client() as client:
1130
+ if len(miss_ids) == 1:
1131
+ fetched_slots: list[dict[str, Any] | None] = [
1132
+ _api_get_one_record(
1133
+ miss_ids[0],
1134
+ api_key=api_key,
1135
+ client=client,
1136
+ include_objects=True,
1137
+ include_text=include_text,
1138
+ page_spec="all",
1139
+ )
1140
+ ]
1141
+ else:
1142
+ workers = min(API_MAX_WORKERS, len(miss_ids))
1143
+ with ThreadPoolExecutor(max_workers=workers) as executor:
1144
+ fetched_slots = list(
1145
+ executor.map(
1146
+ lambda n: _api_get_one_record(
1147
+ n,
1148
+ api_key=api_key,
1149
+ client=client,
1150
+ include_objects=True,
1151
+ include_text=include_text,
1152
+ page_spec="all",
1153
+ ),
1154
+ miss_ids,
1155
+ )
1156
+ )
1157
+
1158
+ fallback_slots: list[int] = []
1159
+ fallback_naids: list[str] = []
1160
+ for slot_idx, rec in zip(miss_indices, fetched_slots, strict=True):
1161
+ if rec is None:
1162
+ fallback_slots.append(slot_idx)
1163
+ fallback_naids.append(clean_ids[slot_idx])
1164
+ else:
1165
+ slots[slot_idx] = rec
1166
+ _write_cached_record(
1167
+ clean_ids[slot_idx],
1168
+ rec,
1169
+ cache_root=cache_root,
1170
+ has_text=include_text,
1171
+ )
1172
+
1173
+ if fallback_naids:
1174
+ fallback_recs = _browser_get_records(
1175
+ fallback_naids,
1176
+ include_objects=True,
1177
+ include_text=include_text,
1178
+ page_spec="all",
1179
+ )
1180
+ for slot_idx, fb_rec in zip(fallback_slots, fallback_recs, strict=True):
1181
+ slots[slot_idx] = fb_rec
1182
+ _write_cached_record(
1183
+ clean_ids[slot_idx],
1184
+ fb_rec,
1185
+ cache_root=cache_root,
1186
+ has_text=include_text,
1187
+ )
1188
+ else:
1189
+ fetched_recs = _browser_get_records(
1190
+ miss_ids,
1191
+ include_objects=True,
1192
+ include_text=include_text,
1193
+ page_spec="all",
1194
+ )
1195
+ for slot_idx, rec in zip(miss_indices, fetched_recs, strict=True):
1196
+ slots[slot_idx] = rec
1197
+ _write_cached_record(
1198
+ clean_ids[slot_idx],
1199
+ rec,
1200
+ cache_root=cache_root,
1201
+ has_text=include_text,
1202
+ )
1203
+
1204
+ return [rec for rec in slots if rec is not None]
1205
+
1206
+
1207
+ @cli.command("get")
1208
+ @click.argument("naids", nargs=-1, required=True)
1209
+ @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
1210
+ @click.option("--browser", "force_browser", is_flag=True, help="Force headless Chromium website mode.")
1211
+ @click.option("--objects", is_flag=True, help="Include compact digital object URLs (omitted by default to keep output small).")
1212
+ @click.option("--pages", default="all", show_default=True, help="1-based page slice when using --objects or --text, e.g. '1-10'.")
1213
+ @click.option("--text", is_flag=True, help="Include extracted OCR text and transcriptions if present.")
1214
+ @click.option("--refresh", is_flag=True, help="Bypass the local disk cache and fetch fresh record metadata.")
1215
+ @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
1216
+ def cmd_get(
1217
+ naids: tuple[str, ...],
1218
+ api_key: str | None,
1219
+ force_browser: bool,
1220
+ objects: bool,
1221
+ pages: str,
1222
+ text: bool,
1223
+ refresh: bool,
1224
+ as_json: bool,
1225
+ ) -> None:
1226
+ """Inspect one or more NARA records by NAID (compact metadata by default)."""
1227
+ cache_root = get_cache_root()
1228
+ full_records = _load_or_fetch_full_records(
1229
+ list(naids),
1230
+ api_key=api_key,
1231
+ force_browser=force_browser,
1232
+ include_text=text,
1233
+ refresh=refresh,
1234
+ cache_root=cache_root,
1235
+ )
1236
+ records = [
1237
+ rec
1238
+ if rec.get("error")
1239
+ else _project_record(
1240
+ rec, include_objects=objects, include_text=text, page_spec=pages
1241
+ )
1242
+ for rec in full_records
1243
+ ]
1244
+
1245
+ if as_json:
1246
+ click.echo(json.dumps(records[0] if len(records) == 1 else records, indent=2))
1247
+ return
1248
+
1249
+ for idx, rec in enumerate(records):
1250
+ if idx > 0:
1251
+ click.echo("")
1252
+ click.echo(_format_record_text(rec))
1253
+
1254
+
1255
+ def _new_download_client() -> httpx.Client:
1256
+ return httpx.Client(
1257
+ timeout=60.0,
1258
+ follow_redirects=True,
1259
+ headers={"User-Agent": USER_AGENT},
1260
+ )
1261
+
1262
+
1263
+ def _download_object_to_cache(
1264
+ client: httpx.Client, obj_url: str, cached_obj_path: Path
1265
+ ) -> None:
1266
+ cached_obj_path.parent.mkdir(parents=True, exist_ok=True)
1267
+ tmp = cached_obj_path.with_name(
1268
+ f".{cached_obj_path.name}.{os.getpid()}.{time.time_ns()}.tmp"
1269
+ )
1270
+ try:
1271
+ with client.stream("GET", obj_url) as resp:
1272
+ resp.raise_for_status()
1273
+ with tmp.open("wb") as fh:
1274
+ for chunk in resp.iter_bytes():
1275
+ fh.write(chunk)
1276
+ os.replace(tmp, cached_obj_path)
1277
+ except Exception:
1278
+ tmp.unlink(missing_ok=True)
1279
+ raise
1280
+
1281
+
1282
+ @cli.command("download")
1283
+ @click.argument("naid")
1284
+ @click.option("--out", "out_dir", default=None, type=click.Path(path_type=Path), help="Output directory (default: ./nara-<naid>).")
1285
+ @click.option("--pages", default="all", show_default=True, help="1-based page selection, e.g. '1-5,10' or 'all'.")
1286
+ @click.option("--metadata/--no-metadata", default=True, show_default=True, help="Save compact provenance metadata.json.")
1287
+ @click.option("--overwrite", is_flag=True, help="Overwrite existing downloaded files.")
1288
+ @click.option("--refresh", is_flag=True, help="Bypass local metadata and object caches and re-download from NARA.")
1289
+ @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
1290
+ @click.option("--browser", "force_browser", is_flag=True, help="Force headless Chromium website mode.")
1291
+ def cmd_download(
1292
+ naid: str,
1293
+ out_dir: Path | None,
1294
+ pages: str,
1295
+ metadata: bool,
1296
+ overwrite: bool,
1297
+ refresh: bool,
1298
+ api_key: str | None,
1299
+ force_browser: bool,
1300
+ ) -> None:
1301
+ """Download digitized files for a NARA record (NAID) with compact provenance metadata."""
1302
+ clean_id = validate_naid(naid)
1303
+ cache_root = get_cache_root()
1304
+ full_rec = _load_or_fetch_full_records(
1305
+ [clean_id],
1306
+ api_key=api_key,
1307
+ force_browser=force_browser,
1308
+ include_text=False,
1309
+ refresh=refresh,
1310
+ cache_root=cache_root,
1311
+ )[0]
1312
+ if full_rec.get("error"):
1313
+ raise click.ClickException(f"NAID {clean_id}: {full_rec['error']}")
1314
+
1315
+ rec = _project_record(full_rec, include_objects=True, include_text=False, page_spec=pages)
1316
+ selected_objs = rec.get("objects") or []
1317
+ total_count = rec.get("objectCount") or len(selected_objs)
1318
+ if not selected_objs:
1319
+ raise click.ClickException(f"NAID {clean_id} ({rec.get('title')}) has no matching digital objects for '{pages}'.")
1320
+
1321
+ target_dir = out_dir or Path(f"nara-{clean_id}")
1322
+ target_dir.mkdir(parents=True, exist_ok=True)
1323
+ obj_cache_dir = cache_root / "objects" / clean_id
1324
+
1325
+ downloaded_manifest: list[dict[str, Any]] = []
1326
+ client: httpx.Client | None = None
1327
+ try:
1328
+ for obj in selected_objs:
1329
+ page_num = obj["page"]
1330
+ obj_url = obj.get("url")
1331
+ if not obj_url:
1332
+ click.echo(f"Skipping page {page_num}: missing url", err=True)
1333
+ continue
1334
+ cache_filename = safe_object_filename(page_num, obj.get("filename"))
1335
+ cached_obj_path = resolve_safe_child(obj_cache_dir, cache_filename)
1336
+ dest = resolve_safe_child(target_dir, cache_filename)
1337
+
1338
+ if not refresh and cached_obj_path.is_file():
1339
+ if dest.exists() and not overwrite:
1340
+ click.echo(f"Exists (skip): {dest}")
1341
+ else:
1342
+ atomic_copy_file(cached_obj_path, dest)
1343
+ click.echo(
1344
+ f"Cached [{page_num}/{total_count}]: {dest} ({dest.stat().st_size:,} bytes)"
1345
+ )
1346
+ else:
1347
+ lock_path = resolve_safe_child(
1348
+ cache_root / "_locks", f"object_{clean_id}_{cache_filename}.lock"
1349
+ )
1350
+ served_from_cache = False
1351
+ with file_lock(lock_path):
1352
+ if not refresh and cached_obj_path.is_file():
1353
+ served_from_cache = True
1354
+ else:
1355
+ if client is None:
1356
+ client = _new_download_client()
1357
+ _download_object_to_cache(client, obj_url, cached_obj_path)
1358
+ if dest.exists() and not overwrite and not refresh:
1359
+ click.echo(f"Exists (skip): {dest}")
1360
+ else:
1361
+ atomic_copy_file(cached_obj_path, dest)
1362
+ verb = "Cached" if served_from_cache else "Downloaded"
1363
+ click.echo(
1364
+ f"{verb} [{page_num}/{total_count}]: {dest} ({dest.stat().st_size:,} bytes)"
1365
+ )
1366
+
1367
+ downloaded_manifest.append({"page": page_num, "file": dest.name, "url": obj_url})
1368
+ finally:
1369
+ if client is not None:
1370
+ client.close()
1371
+
1372
+ if metadata:
1373
+ compact_meta = {k: v for k, v in rec.items() if k != "objects"}
1374
+ compact_meta["downloaded"] = downloaded_manifest
1375
+ meta_path = target_dir / "metadata.json"
1376
+ atomic_write_text(meta_path, json.dumps(compact_meta, indent=2) + "\n")
1377
+ click.echo(f"Saved metadata: {meta_path}")
1378
+
1379
+ click.echo(f"Done: {len(downloaded_manifest)} file(s) in {target_dir}")
1380
+
1381
+
1382
+ if __name__ == "__main__":
1383
+ try:
1384
+ cli()
1385
+ except httpx.HTTPStatusError as exc:
1386
+ click.echo(f"HTTP error {exc.response.status_code}: {exc.request.url}", err=True)
1387
+ sys.exit(1)