@kinloom/cli 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/assets/cached-ocr.py +346 -116
  2. package/dist/assets/ocr.md +25 -1
  3. package/dist/assets/prep-scan.md +42 -4
  4. package/dist/assets/prep-scan.py +432 -10
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
  7. package/dist/bundled-skills/archive-org/SKILL.md +40 -7
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
  9. package/dist/bundled-skills/california-archives/SKILL.md +10 -0
  10. package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
  11. package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
  12. package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
  13. package/dist/bundled-skills/findagrave/SKILL.md +18 -5
  14. package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
  15. package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
  16. package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
  17. package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
  18. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
  19. package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
  20. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
  21. package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
  22. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
  23. package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
  24. package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
  25. package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
  26. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
  27. package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
  28. package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
  29. package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
  30. package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
  31. package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
  32. package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
  33. package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
  34. package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
  35. package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
  36. package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
  37. package/dist/bundled-skills/wikitree/SKILL.md +7 -1
  38. package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +107 -2
  41. package/dist/cli.js.map +1 -1
  42. package/dist/client.d.ts.map +1 -1
  43. package/dist/client.js +30 -5
  44. package/dist/client.js.map +1 -1
  45. package/dist/commands/ops/audit.d.ts.map +1 -1
  46. package/dist/commands/ops/audit.js +5 -0
  47. package/dist/commands/ops/audit.js.map +1 -1
  48. package/dist/commands/ops/dates.d.ts +87 -0
  49. package/dist/commands/ops/dates.d.ts.map +1 -0
  50. package/dist/commands/ops/dates.js +228 -0
  51. package/dist/commands/ops/dates.js.map +1 -0
  52. package/dist/commands/ops/help.d.ts +3 -1
  53. package/dist/commands/ops/help.d.ts.map +1 -1
  54. package/dist/commands/ops/help.js +33 -0
  55. package/dist/commands/ops/help.js.map +1 -1
  56. package/dist/commands/ops/index.d.ts +3 -1
  57. package/dist/commands/ops/index.d.ts.map +1 -1
  58. package/dist/commands/ops/index.js +2 -0
  59. package/dist/commands/ops/index.js.map +1 -1
  60. package/dist/commands/ops/integrate.d.ts +5 -0
  61. package/dist/commands/ops/integrate.d.ts.map +1 -1
  62. package/dist/commands/ops/integrate.js +272 -26
  63. package/dist/commands/ops/integrate.js.map +1 -1
  64. package/dist/commands/ops/sync.d.ts +17 -0
  65. package/dist/commands/ops/sync.d.ts.map +1 -1
  66. package/dist/commands/ops/sync.js +173 -0
  67. package/dist/commands/ops/sync.js.map +1 -1
  68. package/dist/commands/ops/verify.d.ts +76 -0
  69. package/dist/commands/ops/verify.d.ts.map +1 -0
  70. package/dist/commands/ops/verify.js +325 -0
  71. package/dist/commands/ops/verify.js.map +1 -0
  72. package/dist/commands/records/index.d.ts +1 -1
  73. package/dist/commands/records/index.d.ts.map +1 -1
  74. package/dist/commands/records/index.js +1 -1
  75. package/dist/commands/records/index.js.map +1 -1
  76. package/dist/commands/records/runner.d.ts +2 -0
  77. package/dist/commands/records/runner.d.ts.map +1 -1
  78. package/dist/commands/records/runner.js +33 -2
  79. package/dist/commands/records/runner.js.map +1 -1
  80. package/package.json +2 -2
@@ -16,13 +16,17 @@ to headless Chromium against catalog.archives.gov when no key is configured.
16
16
  from __future__ import annotations
17
17
 
18
18
  from concurrent.futures import ThreadPoolExecutor
19
+ from contextlib import contextmanager
20
+ import hashlib
19
21
  import json
22
+ import math
20
23
  import os
21
24
  import re
22
25
  import shutil
23
26
  import sys
27
+ import time
24
28
  from pathlib import Path
25
- from typing import Any
29
+ from typing import Any, Iterator
26
30
  from urllib.parse import quote, urlencode
27
31
 
28
32
  import click
@@ -31,6 +35,7 @@ import httpx
31
35
  CATALOG_WEB_BASE = "https://catalog.archives.gov"
32
36
  CATALOG_API_BASE = "https://catalog.archives.gov/api/v2"
33
37
  API_MAX_WORKERS = 6
38
+ DEFAULT_QUERY_TTL_HOURS = 168.0
34
39
  USER_AGENT = (
35
40
  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
36
41
  "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
@@ -38,6 +43,293 @@ USER_AGENT = (
38
43
  VALID_LEVELS = ("recordGroup", "collection", "series", "fileUnit", "item")
39
44
 
40
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
+
41
333
  class _NaraWafOrNonJsonError(RuntimeError):
42
334
  """Raised when the NARA v2 API returns an HTML WAF page or non-JSON body."""
43
335
 
@@ -625,6 +917,13 @@ def _api_search_one(
625
917
  @_common_search_options
626
918
  @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
627
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
+ )
628
927
  @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
629
928
  def cmd_search(
630
929
  queries: tuple[str, ...],
@@ -642,11 +941,15 @@ def cmd_search(
642
941
  limit: int,
643
942
  api_key: str | None,
644
943
  force_browser: bool,
944
+ refresh: bool,
945
+ cache_ttl_hours: float | None,
645
946
  as_json: bool,
646
947
  ) -> None:
647
948
  """Search the NARA Catalog. Accepts one or multiple queries (parallel via API or shared browser)."""
648
949
  query_list: list[str | None] = list(queries) if queries else [None]
649
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()
650
953
  filter_kwargs: dict[str, Any] = {
651
954
  "levels": levels,
652
955
  "record_groups": record_groups,
@@ -662,59 +965,86 @@ def cmd_search(
662
965
  "limit": limit,
663
966
  }
664
967
 
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,
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
+ )
689
1008
  )
690
- )
691
1009
 
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))
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
+ )
699
1021
 
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
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
+ )
704
1046
 
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)
1047
+ payloads = [entry for entry in slots if entry is not None]
718
1048
 
719
1049
  if as_json:
720
1050
  click.echo(json.dumps(payloads[0] if len(payloads) == 1 else payloads, indent=2))
@@ -748,7 +1078,7 @@ def _api_get_one_record(
748
1078
  include_text: bool,
749
1079
  page_spec: str,
750
1080
  ) -> dict[str, Any] | None:
751
- clean_id = re.sub(r"\D+", "", naid)
1081
+ clean_id = validate_naid(naid)
752
1082
  url = (
753
1083
  f"{CATALOG_API_BASE}/records/search?"
754
1084
  f"naId_is={clean_id}&includeExtractedText={'true' if include_text else 'false'}"
@@ -769,6 +1099,111 @@ def _api_get_one_record(
769
1099
  return {"naId": clean_id, "url": f"{CATALOG_WEB_BASE}/id/{clean_id}", "error": "Not found"}
770
1100
 
771
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
+
772
1207
  @cli.command("get")
773
1208
  @click.argument("naids", nargs=-1, required=True)
774
1209
  @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
@@ -776,6 +1211,7 @@ def _api_get_one_record(
776
1211
  @click.option("--objects", is_flag=True, help="Include compact digital object URLs (omitted by default to keep output small).")
777
1212
  @click.option("--pages", default="all", show_default=True, help="1-based page slice when using --objects or --text, e.g. '1-10'.")
778
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.")
779
1215
  @click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
780
1216
  def cmd_get(
781
1217
  naids: tuple[str, ...],
@@ -784,59 +1220,27 @@ def cmd_get(
784
1220
  objects: bool,
785
1221
  pages: str,
786
1222
  text: bool,
1223
+ refresh: bool,
787
1224
  as_json: bool,
788
1225
  ) -> None:
789
1226
  """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
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
839
1241
  )
1242
+ for rec in full_records
1243
+ ]
840
1244
 
841
1245
  if as_json:
842
1246
  click.echo(json.dumps(records[0] if len(records) == 1 else records, indent=2))
@@ -848,12 +1252,40 @@ def cmd_get(
848
1252
  click.echo(_format_record_text(rec))
849
1253
 
850
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
+
851
1282
  @cli.command("download")
852
1283
  @click.argument("naid")
853
1284
  @click.option("--out", "out_dir", default=None, type=click.Path(path_type=Path), help="Output directory (default: ./nara-<naid>).")
854
1285
  @click.option("--pages", default="all", show_default=True, help="1-based page selection, e.g. '1-5,10' or 'all'.")
855
1286
  @click.option("--metadata/--no-metadata", default=True, show_default=True, help="Save compact provenance metadata.json.")
856
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.")
857
1289
  @click.option("--api-key", envvar="NARA_API_KEY", default=None, help="NARA Catalog v2 API key (defaults to $NARA_API_KEY).")
858
1290
  @click.option("--browser", "force_browser", is_flag=True, help="Force headless Chromium website mode.")
859
1291
  def cmd_download(
@@ -862,30 +1294,25 @@ def cmd_download(
862
1294
  pages: str,
863
1295
  metadata: bool,
864
1296
  overwrite: bool,
1297
+ refresh: bool,
865
1298
  api_key: str | None,
866
1299
  force_browser: bool,
867
1300
  ) -> None:
868
1301
  """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
-
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)
889
1316
  selected_objs = rec.get("objects") or []
890
1317
  total_count = rec.get("objectCount") or len(selected_objs)
891
1318
  if not selected_objs:
@@ -893,34 +1320,60 @@ def cmd_download(
893
1320
 
894
1321
  target_dir = out_dir or Path(f"nara-{clean_id}")
895
1322
  target_dir.mkdir(parents=True, exist_ok=True)
1323
+ obj_cache_dir = cache_root / "objects" / clean_id
896
1324
 
897
1325
  downloaded_manifest: list[dict[str, Any]] = []
898
- with httpx.Client(timeout=60.0, follow_redirects=True, headers={"User-Agent": USER_AGENT}) as client:
1326
+ client: httpx.Client | None = None
1327
+ try:
899
1328
  for obj in selected_objs:
900
1329
  page_num = obj["page"]
901
1330
  obj_url = obj.get("url")
902
1331
  if not obj_url:
903
1332
  click.echo(f"Skipping page {page_num}: missing url", err=True)
904
1333
  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}")
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
+ )
910
1346
  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)")
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
+
917
1367
  downloaded_manifest.append({"page": page_num, "file": dest.name, "url": obj_url})
1368
+ finally:
1369
+ if client is not None:
1370
+ client.close()
918
1371
 
919
1372
  if metadata:
920
1373
  compact_meta = {k: v for k, v in rec.items() if k != "objects"}
921
1374
  compact_meta["downloaded"] = downloaded_manifest
922
1375
  meta_path = target_dir / "metadata.json"
923
- meta_path.write_text(json.dumps(compact_meta, indent=2) + "\n", encoding="utf-8")
1376
+ atomic_write_text(meta_path, json.dumps(compact_meta, indent=2) + "\n")
924
1377
  click.echo(f"Saved metadata: {meta_path}")
925
1378
 
926
1379
  click.echo(f"Done: {len(downloaded_manifest)} file(s) in {target_dir}")