@kinloom/cli 0.2.0 → 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 (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 +217 -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
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env -S python3 -S
2
2
  """Internet Archive CLI: search items, inspect metadata, grep cached books, and fetch pages.
3
3
 
4
- Uses Python 3.11+ standard library only with lazy network/XML imports for fast
4
+ Uses Python 3.11+ standard library only with lazy network/XML/lock imports for fast
5
5
  cache-hit startup (~50 ms) and zero external dependency installation.
6
6
  All APIs are public and read-only.
7
7
  """
@@ -9,12 +9,15 @@ All APIs are public and read-only.
9
9
  from __future__ import annotations
10
10
 
11
11
  import argparse
12
+ from contextlib import contextmanager
12
13
  import json
14
+ import math
13
15
  import os
14
16
  from pathlib import Path
15
17
  import re
16
18
  import sys
17
19
  import time
20
+ from typing import Iterator
18
21
  from urllib.parse import quote, urlencode
19
22
 
20
23
  BASE = "https://archive.org"
@@ -24,7 +27,12 @@ USER_AGENT = "kinloom archive-org skill (research use)"
24
27
  DEFAULT_FIELDS = ["identifier", "title", "creator", "date", "mediatype"]
25
28
  DEFAULT_TIMEOUT = 25.0
26
29
  SEARCH_TIMEOUT = 45.0
30
+ DOWNLOAD_TIMEOUT = 60.0
31
+ DEFAULT_QUERY_TTL_HOURS = 168.0
27
32
  MAX_WORKERS = 6
33
+ RETRYABLE_HTTP_CODES = frozenset({429, 502, 503, 504})
34
+ MAX_HTTP_RETRIES = 2
35
+ MAX_RETRY_AFTER_SECONDS = 5.0
28
36
  SAFE_ID_RE = re.compile(r"^[A-Za-z0-9._-]+$")
29
37
  IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
30
38
 
@@ -36,6 +44,23 @@ def get_cache_root() -> Path:
36
44
  return Path.home() / ".cache" / "kinloom-ia"
37
45
 
38
46
 
47
+ def resolve_query_ttl_hours(cli_ttl: float | None) -> float:
48
+ if cli_ttl is not None:
49
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
50
+ fail(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).", code=2)
51
+ return float(cli_ttl)
52
+ raw = os.environ.get("KINLOOM_IA_QUERY_TTL_HOURS")
53
+ if raw is not None and raw.strip():
54
+ try:
55
+ parsed = float(raw.strip())
56
+ except ValueError:
57
+ fail(f"Invalid KINLOOM_IA_QUERY_TTL_HOURS value: {raw!r}.", code=2)
58
+ if not math.isfinite(parsed) or parsed < 0:
59
+ fail(f"Invalid KINLOOM_IA_QUERY_TTL_HOURS value: {raw!r} (must be >= 0).", code=2)
60
+ return parsed
61
+ return DEFAULT_QUERY_TTL_HOURS
62
+
63
+
39
64
  def validate_identifier(identifier: str) -> str:
40
65
  cleaned = identifier.strip()
41
66
  if not cleaned or not SAFE_ID_RE.match(cleaned) or cleaned in (".", ".."):
@@ -43,11 +68,55 @@ def validate_identifier(identifier: str) -> str:
43
68
  return cleaned
44
69
 
45
70
 
71
+ def validate_relative_item_path(name: str, files_root: Path) -> tuple[Path, Path]:
72
+ """Validate an item-relative filename and resolve it strictly inside files_root."""
73
+ if not name or "\x00" in name or "\\" in name or name.startswith("/"):
74
+ raise ValueError(f"Unsafe file path in item: {name!r}")
75
+ parts = name.split("/")
76
+ for part in parts:
77
+ if not part or part in (".", "..") or ":" in part:
78
+ raise ValueError(f"Unsafe file path in item: {name!r}")
79
+ rel = Path(*parts)
80
+ root_resolved = files_root.resolve()
81
+ dest = (root_resolved / rel).resolve()
82
+ if dest == root_resolved or not dest.is_relative_to(root_resolved):
83
+ raise ValueError(f"Unsafe file path in item: {name!r}")
84
+ return rel, dest
85
+
86
+
46
87
  def fail(message: str, code: int = 1) -> None:
47
88
  sys.stderr.write(f"{message}\n")
48
89
  raise SystemExit(code)
49
90
 
50
91
 
92
+ @contextmanager
93
+ def file_lock(lock_path: Path) -> Iterator[None]:
94
+ """Advisory exclusive file lock (POSIX flock) with safe fallback on non-POSIX."""
95
+ try:
96
+ import fcntl
97
+ except ImportError:
98
+ yield
99
+ return
100
+
101
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
102
+ with open(lock_path, "a+b") as lock_file:
103
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
104
+ try:
105
+ yield
106
+ finally:
107
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
108
+
109
+
110
+ def read_json_if_valid(path: Path) -> dict | None:
111
+ if not path.is_file():
112
+ return None
113
+ try:
114
+ parsed = json.loads(path.read_text(encoding="utf-8"))
115
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
116
+ return None
117
+ return parsed if isinstance(parsed, dict) else None
118
+
119
+
51
120
  def atomic_write_bytes(dest: Path, data: bytes) -> None:
52
121
  dest.parent.mkdir(parents=True, exist_ok=True)
53
122
  tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
@@ -68,24 +137,52 @@ def atomic_write_json(dest: Path, payload: object) -> None:
68
137
  atomic_write_text(dest, json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
69
138
 
70
139
 
140
+ def parse_retry_after_seconds(headers: object, attempt: int) -> float:
141
+ default_delay = min(MAX_RETRY_AFTER_SECONDS, 0.5 * (2**attempt))
142
+ if headers is None or not hasattr(headers, "get"):
143
+ return default_delay
144
+ raw = headers.get("Retry-After")
145
+ if raw is None:
146
+ return default_delay
147
+ try:
148
+ parsed = float(str(raw).strip())
149
+ except ValueError:
150
+ return default_delay
151
+ if not math.isfinite(parsed) or parsed < 0:
152
+ return default_delay
153
+ return min(MAX_RETRY_AFTER_SECONDS, parsed)
154
+
155
+
71
156
  def http_get_bytes(url: str, timeout: float = DEFAULT_TIMEOUT) -> bytes:
72
157
  from urllib.error import HTTPError, URLError
73
158
  from urllib.request import Request, urlopen
74
159
 
75
160
  req = Request(url, headers={"User-Agent": USER_AGENT})
76
- try:
77
- with urlopen(req, timeout=timeout) as resp:
78
- return resp.read()
79
- except HTTPError as exc:
80
- if exc.code == 403:
81
- raise RuntimeError(
82
- f"HTTP 403 from {url}. This item may be access-restricted or borrow-only."
83
- ) from exc
84
- if exc.code == 404:
85
- raise FileNotFoundError(f"HTTP 404 from {url}") from exc
86
- raise RuntimeError(f"HTTP {exc.code} from {url}") from exc
87
- except (URLError, TimeoutError, OSError) as exc:
88
- raise RuntimeError(f"Request failed for {url}: {exc}") from exc
161
+ for attempt in range(MAX_HTTP_RETRIES + 1):
162
+ try:
163
+ with urlopen(req, timeout=timeout) as resp:
164
+ return resp.read()
165
+ except HTTPError as exc:
166
+ code = exc.code
167
+ headers = exc.headers
168
+ try:
169
+ exc.close()
170
+ except Exception:
171
+ pass
172
+ if code == 403:
173
+ raise RuntimeError(
174
+ f"HTTP 403 from {url}. This item may be access-restricted or borrow-only."
175
+ ) from exc
176
+ if code == 404:
177
+ raise FileNotFoundError(f"HTTP 404 from {url}") from exc
178
+ if code in RETRYABLE_HTTP_CODES and attempt < MAX_HTTP_RETRIES:
179
+ time.sleep(parse_retry_after_seconds(headers, attempt))
180
+ continue
181
+ raise RuntimeError(f"HTTP {code} from {url}") from exc
182
+ except (URLError, TimeoutError, OSError) as exc:
183
+ # Stay fail-fast on ReadTimeout and socket/connection errors.
184
+ raise RuntimeError(f"Request failed for {url}: {exc}") from exc
185
+ raise RuntimeError(f"Request failed for {url}")
89
186
 
90
187
 
91
188
  def http_get_json(url: str, timeout: float = DEFAULT_TIMEOUT) -> dict:
@@ -99,7 +196,68 @@ def http_get_json(url: str, timeout: float = DEFAULT_TIMEOUT) -> dict:
99
196
  return data
100
197
 
101
198
 
102
- def fulltext_api(query: str, rows: int, page: int) -> dict:
199
+ def query_cache_path(kind: str, canonical_params: dict, cache_root: Path) -> tuple[str, Path]:
200
+ import hashlib
201
+
202
+ canonical = json.dumps(canonical_params, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
203
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
204
+ return digest, cache_root / "_queries" / kind / f"{digest}.json"
205
+
206
+
207
+ def cached_query_json(
208
+ kind: str,
209
+ canonical_params: dict,
210
+ url: str,
211
+ *,
212
+ cache_root: Path | None = None,
213
+ ttl_hours: float = DEFAULT_QUERY_TTL_HOURS,
214
+ refresh: bool = False,
215
+ timeout: float = SEARCH_TIMEOUT,
216
+ ) -> tuple[dict, bool]:
217
+ root = cache_root if cache_root is not None else get_cache_root()
218
+ digest, cache_path = query_cache_path(kind, canonical_params, root)
219
+ ttl_seconds = ttl_hours * 3600.0
220
+
221
+ def read_fresh() -> dict | None:
222
+ if refresh or ttl_seconds <= 0:
223
+ return None
224
+ envelope = read_json_if_valid(cache_path)
225
+ if envelope is None:
226
+ return None
227
+ cached_at = envelope.get("cached_at")
228
+ data = envelope.get("data")
229
+ if not isinstance(cached_at, (int, float)) or not isinstance(data, dict):
230
+ return None
231
+ if (time.time() - float(cached_at)) <= ttl_seconds:
232
+ return data
233
+ return None
234
+
235
+ cached = read_fresh()
236
+ if cached is not None:
237
+ return cached, True
238
+
239
+ lock_path = root / "_queries" / "_locks" / f"{kind}_{digest}.lock"
240
+ with file_lock(lock_path):
241
+ cached = read_fresh()
242
+ if cached is not None:
243
+ return cached, True
244
+ data = http_get_json(url, timeout=timeout)
245
+ atomic_write_json(
246
+ cache_path,
247
+ {"cached_at": time.time(), "params": canonical_params, "data": data},
248
+ )
249
+ return data, False
250
+
251
+
252
+ def fulltext_api(
253
+ query: str,
254
+ rows: int,
255
+ page: int,
256
+ *,
257
+ cache_root: Path | None = None,
258
+ ttl_hours: float = DEFAULT_QUERY_TTL_HOURS,
259
+ refresh: bool = False,
260
+ ) -> tuple[dict, bool]:
103
261
  qs = urlencode(
104
262
  [
105
263
  ("user_query", query),
@@ -108,14 +266,38 @@ def fulltext_api(query: str, rows: int, page: int) -> dict:
108
266
  ("page", str(page)),
109
267
  ]
110
268
  )
269
+ canonical_params = {
270
+ "kind": "fulltext",
271
+ "query": query,
272
+ "rows": rows,
273
+ "page": page,
274
+ }
111
275
  try:
112
- return http_get_json(f"{FULLTEXT_SEARCH}?{qs}", timeout=SEARCH_TIMEOUT)
276
+ return cached_query_json(
277
+ "fulltext",
278
+ canonical_params,
279
+ f"{FULLTEXT_SEARCH}?{qs}",
280
+ cache_root=cache_root,
281
+ ttl_hours=ttl_hours,
282
+ refresh=refresh,
283
+ timeout=SEARCH_TIMEOUT,
284
+ )
113
285
  except (RuntimeError, FileNotFoundError) as exc:
114
286
  fail(str(exc))
115
- return {}
287
+ return {}, False
116
288
 
117
289
 
118
- def search_api(query: str, fields: list[str], rows: int, page: int, sorts: list[str]) -> dict:
290
+ def search_api(
291
+ query: str,
292
+ fields: list[str],
293
+ rows: int,
294
+ page: int,
295
+ sorts: list[str],
296
+ *,
297
+ cache_root: Path | None = None,
298
+ ttl_hours: float = DEFAULT_QUERY_TTL_HOURS,
299
+ refresh: bool = False,
300
+ ) -> tuple[dict, bool]:
119
301
  params: list[tuple[str, str]] = [
120
302
  ("q", query),
121
303
  ("output", "json"),
@@ -128,24 +310,94 @@ def search_api(query: str, fields: list[str], rows: int, page: int, sorts: list[
128
310
  for sort in sorts:
129
311
  params.append(("sort[]", sort))
130
312
  qs = urlencode(params)
313
+ canonical_params = {
314
+ "kind": "search",
315
+ "query": query,
316
+ "fields": list(fields),
317
+ "rows": rows,
318
+ "page": page,
319
+ "sorts": list(sorts),
320
+ }
131
321
  try:
132
- return http_get_json(f"{ADVANCED_SEARCH}?{qs}", timeout=SEARCH_TIMEOUT)
322
+ return cached_query_json(
323
+ "search",
324
+ canonical_params,
325
+ f"{ADVANCED_SEARCH}?{qs}",
326
+ cache_root=cache_root,
327
+ ttl_hours=ttl_hours,
328
+ refresh=refresh,
329
+ timeout=SEARCH_TIMEOUT,
330
+ )
133
331
  except (RuntimeError, FileNotFoundError) as exc:
134
332
  fail(str(exc))
135
- return {}
333
+ return {}, False
136
334
 
137
335
 
138
- def metadata_api(identifier: str, timeout: float = DEFAULT_TIMEOUT) -> dict:
139
- url = f"{BASE}/metadata/{quote(identifier)}"
336
+ def _is_valid_metadata(data: dict | None) -> bool:
337
+ return bool(data and (data.get("metadata") or data.get("files")))
338
+
339
+
340
+ def _load_or_fetch_metadata_unlocked(
341
+ item_id: str,
342
+ meta_path: Path,
343
+ *,
344
+ timeout: float = DEFAULT_TIMEOUT,
345
+ refresh: bool = False,
346
+ ) -> tuple[dict, bool]:
347
+ if not refresh:
348
+ cached = read_json_if_valid(meta_path)
349
+ if _is_valid_metadata(cached):
350
+ assert cached is not None
351
+ return cached, True
352
+ url = f"{BASE}/metadata/{quote(item_id)}"
353
+ data = http_get_json(url, timeout=timeout)
354
+ if not _is_valid_metadata(data):
355
+ raise FileNotFoundError(f"No item with identifier {item_id}")
356
+ atomic_write_json(meta_path, data)
357
+ return data, False
358
+
359
+
360
+ def ensure_item_metadata(
361
+ identifier: str,
362
+ *,
363
+ cache_root: Path | None = None,
364
+ timeout: float = DEFAULT_TIMEOUT,
365
+ refresh: bool = False,
366
+ ) -> tuple[dict, bool]:
367
+ """Return cached or freshly fetched /metadata/<id> JSON and cache-hit flag."""
368
+ item_id = validate_identifier(identifier)
369
+ root = cache_root if cache_root is not None else get_cache_root()
370
+ item_dir = root / item_id
371
+ meta_path = item_dir / "metadata.json"
372
+
373
+ if not refresh:
374
+ cached = read_json_if_valid(meta_path)
375
+ if _is_valid_metadata(cached):
376
+ assert cached is not None
377
+ return cached, True
378
+
379
+ with file_lock(item_dir / ".lock"):
380
+ return _load_or_fetch_metadata_unlocked(
381
+ item_id, meta_path, timeout=timeout, refresh=refresh
382
+ )
383
+
384
+
385
+ def metadata_api(
386
+ identifier: str,
387
+ timeout: float = DEFAULT_TIMEOUT,
388
+ *,
389
+ cache_root: Path | None = None,
390
+ refresh: bool = False,
391
+ ) -> tuple[dict, bool]:
140
392
  try:
141
- data = http_get_json(url, timeout=timeout)
393
+ return ensure_item_metadata(
394
+ identifier, cache_root=cache_root, timeout=timeout, refresh=refresh
395
+ )
142
396
  except FileNotFoundError:
143
397
  fail(f"No item with identifier {identifier}")
144
398
  except RuntimeError as exc:
145
399
  fail(str(exc))
146
- if not data or (not data.get("metadata") and not data.get("files")):
147
- fail(f"No item with identifier {identifier}")
148
- return data
400
+ return {}, False
149
401
 
150
402
 
151
403
  def item_url(identifier: str) -> str:
@@ -284,12 +536,42 @@ def synthesize_djvu_from_hocr(searchtext_gz: bytes, pageindex_gz: bytes) -> str:
284
536
  return "\x0c".join(segments)
285
537
 
286
538
 
539
+ def _fetch_urls_map(
540
+ tasks: dict[str, str], timeout: float
541
+ ) -> tuple[dict[str, bytes], dict[str, Exception]]:
542
+ fetched: dict[str, bytes] = {}
543
+ fetch_errors: dict[str, Exception] = {}
544
+ if not tasks:
545
+ return fetched, fetch_errors
546
+ if len(tasks) == 1:
547
+ key, url = next(iter(tasks.items()))
548
+ try:
549
+ fetched[key] = http_get_bytes(url, timeout=timeout)
550
+ except Exception as exc:
551
+ fetch_errors[key] = exc
552
+ return fetched, fetch_errors
553
+
554
+ from concurrent.futures import ThreadPoolExecutor
555
+
556
+ with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(tasks))) as pool:
557
+ future_map = {
558
+ key: pool.submit(http_get_bytes, url, timeout) for key, url in tasks.items()
559
+ }
560
+ for key, fut in future_map.items():
561
+ try:
562
+ fetched[key] = fut.result()
563
+ except Exception as exc:
564
+ fetch_errors[key] = exc
565
+ return fetched, fetch_errors
566
+
567
+
287
568
  def ensure_item_cache(
288
569
  identifier: str,
289
570
  *,
290
571
  need_djvu: bool,
291
572
  cache_root: Path | None = None,
292
573
  timeout: float = DEFAULT_TIMEOUT,
574
+ refresh: bool = False,
293
575
  ) -> dict:
294
576
  """Populate and return cached metadata, page_index, and optional djvu.txt."""
295
577
  item_id = validate_identifier(identifier)
@@ -300,11 +582,15 @@ def ensure_item_cache(
300
582
  page_index_path = item_dir / "page_index.json"
301
583
  djvu_path = item_dir / "djvu.txt"
302
584
 
303
- has_meta = meta_path.is_file()
304
- has_page_index = page_index_path.is_file()
305
- has_djvu = djvu_path.is_file()
585
+ def cache_ready() -> bool:
586
+ return (
587
+ not refresh
588
+ and _is_valid_metadata(read_json_if_valid(meta_path))
589
+ and read_json_if_valid(page_index_path) is not None
590
+ and (not need_djvu or djvu_path.is_file())
591
+ )
306
592
 
307
- if has_meta and has_page_index and (not need_djvu or has_djvu):
593
+ if cache_ready():
308
594
  return {
309
595
  "identifier": item_id,
310
596
  "item_dir": item_dir,
@@ -315,69 +601,90 @@ def ensure_item_cache(
315
601
  "cached": True,
316
602
  }
317
603
 
318
- # Fetch metadata if missing.
319
- if has_meta:
320
- meta_data = json.loads(meta_path.read_text(encoding="utf-8"))
321
- else:
322
- url = f"{BASE}/metadata/{quote(item_id)}"
323
- meta_data = http_get_json(url, timeout=timeout)
324
- if not meta_data or (not meta_data.get("metadata") and not meta_data.get("files")):
325
- raise FileNotFoundError(f"No item with identifier {item_id}")
326
- atomic_write_json(meta_path, meta_data)
327
-
328
- files = meta_data.get("files") or []
329
- scandata_name = find_item_file(files, suffixes=("_scandata.xml", "scandata.xml"), formats=("scandata",))
330
- djvu_name = find_item_file(files, suffixes=("_djvu.txt",), formats=("djvutxt",))
331
- hocr_text_name = find_item_file(files, suffixes=("_hocr_searchtext.txt.gz",), formats=("ocr search text",))
332
- hocr_idx_name = find_item_file(files, suffixes=("_hocr_pageindex.json.gz",), formats=("ocr page index",))
333
-
334
- tasks: dict[str, str] = {}
335
- if not has_page_index and scandata_name and not scandata_path.is_file():
336
- tasks["scandata"] = f"{BASE}/download/{quote(item_id)}/{quote(scandata_name)}"
337
- if need_djvu and not has_djvu:
338
- if djvu_name:
339
- tasks["djvu"] = f"{BASE}/download/{quote(item_id)}/{quote(djvu_name)}"
340
- if hocr_text_name and hocr_idx_name:
341
- tasks["hocr_text"] = f"{BASE}/download/{quote(item_id)}/{quote(hocr_text_name)}"
342
- tasks["hocr_idx"] = f"{BASE}/download/{quote(item_id)}/{quote(hocr_idx_name)}"
604
+ with file_lock(item_dir / ".lock"):
605
+ if cache_ready():
606
+ return {
607
+ "identifier": item_id,
608
+ "item_dir": item_dir,
609
+ "metadata_path": meta_path,
610
+ "scandata_path": scandata_path,
611
+ "page_index_path": page_index_path,
612
+ "djvu_path": djvu_path,
613
+ "cached": True,
614
+ }
343
615
 
344
- fetched: dict[str, bytes] = {}
345
- fetch_errors: dict[str, Exception] = {}
346
- if tasks:
347
- from concurrent.futures import ThreadPoolExecutor
616
+ meta_data, _ = _load_or_fetch_metadata_unlocked(
617
+ item_id, meta_path, timeout=timeout, refresh=refresh
618
+ )
619
+ existing_page_index = None if refresh else read_json_if_valid(page_index_path)
620
+ has_page_index = existing_page_index is not None
621
+ has_djvu = (not refresh) and djvu_path.is_file()
348
622
 
349
- with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(tasks))) as pool:
350
- future_map = {
351
- key: pool.submit(http_get_bytes, url, timeout) for key, url in tasks.items()
352
- }
353
- for key, fut in future_map.items():
354
- try:
355
- fetched[key] = fut.result()
356
- except Exception as exc:
357
- fetch_errors[key] = exc
623
+ files = meta_data.get("files") or []
624
+ scandata_name = find_item_file(
625
+ files, suffixes=("_scandata.xml", "scandata.xml"), formats=("scandata",)
626
+ )
627
+ djvu_name = find_item_file(files, suffixes=("_djvu.txt",), formats=("djvutxt",))
628
+ hocr_text_name = find_item_file(
629
+ files, suffixes=("_hocr_searchtext.txt.gz",), formats=("ocr search text",)
630
+ )
631
+ hocr_idx_name = find_item_file(
632
+ files, suffixes=("_hocr_pageindex.json.gz",), formats=("ocr page index",)
633
+ )
358
634
 
359
- page_index: dict
360
- if has_page_index:
361
- page_index = json.loads(page_index_path.read_text(encoding="utf-8"))
362
- else:
363
- scandata_bytes = fetched.get("scandata")
364
- if scandata_bytes is None and scandata_path.is_file():
365
- scandata_bytes = scandata_path.read_bytes()
366
- if scandata_bytes is not None:
367
- atomic_write_bytes(scandata_path, scandata_bytes)
368
- page_index = parse_scandata_xml(scandata_bytes)
635
+ # Stage 1: fetch scandata and _djvu.txt first. Only fetch hOCR immediately when
636
+ # _djvu.txt is absent, avoiding eager triple-downloads on healthy items.
637
+ stage1_tasks: dict[str, str] = {}
638
+ if not has_page_index and scandata_name and (refresh or not scandata_path.is_file()):
639
+ stage1_tasks["scandata"] = f"{BASE}/download/{quote(item_id)}/{quote(scandata_name)}"
640
+ if need_djvu and not has_djvu:
641
+ if djvu_name:
642
+ stage1_tasks["djvu"] = f"{BASE}/download/{quote(item_id)}/{quote(djvu_name)}"
643
+ elif hocr_text_name and hocr_idx_name:
644
+ stage1_tasks["hocr_text"] = f"{BASE}/download/{quote(item_id)}/{quote(hocr_text_name)}"
645
+ stage1_tasks["hocr_idx"] = f"{BASE}/download/{quote(item_id)}/{quote(hocr_idx_name)}"
646
+
647
+ fetched, fetch_errors = _fetch_urls_map(stage1_tasks, timeout=timeout)
648
+
649
+ page_index: dict
650
+ if has_page_index:
651
+ assert existing_page_index is not None
652
+ page_index = existing_page_index
369
653
  else:
370
- page_index = empty_page_index()
371
-
372
- if need_djvu and not has_djvu:
373
- djvu_raw = fetched.get("djvu")
374
- djvu_text: str | None = None
375
- segment_mode = page_index.get("segment_mode", "scandata")
376
- if djvu_raw is not None:
377
- decoded = djvu_raw.decode("utf-8", errors="replace")
378
- if "\x0c" in decoded:
379
- djvu_text = decoded
380
- seg_count = decoded.count("\x0c") + 1
654
+ scandata_bytes = fetched.get("scandata")
655
+ if scandata_bytes is None and not refresh and scandata_path.is_file():
656
+ scandata_bytes = scandata_path.read_bytes()
657
+ if scandata_bytes is not None:
658
+ atomic_write_bytes(scandata_path, scandata_bytes)
659
+ page_index = parse_scandata_xml(scandata_bytes)
660
+ else:
661
+ page_index = empty_page_index()
662
+
663
+ if need_djvu and not has_djvu:
664
+ djvu_raw = fetched.get("djvu")
665
+ decoded_djvu = djvu_raw.decode("utf-8", errors="replace") if djvu_raw is not None else None
666
+ has_form_feeds = decoded_djvu is not None and "\x0c" in decoded_djvu
667
+
668
+ # Stage 2 fallback: fetch hOCR pair only when _djvu.txt failed or lacked \x0c breaks.
669
+ if not has_form_feeds and hocr_text_name and hocr_idx_name:
670
+ hocr_tasks: dict[str, str] = {}
671
+ if "hocr_text" not in fetched:
672
+ hocr_tasks["hocr_text"] = f"{BASE}/download/{quote(item_id)}/{quote(hocr_text_name)}"
673
+ if "hocr_idx" not in fetched:
674
+ hocr_tasks["hocr_idx"] = f"{BASE}/download/{quote(item_id)}/{quote(hocr_idx_name)}"
675
+ if hocr_tasks:
676
+ hocr_fetched, hocr_errors = _fetch_urls_map(hocr_tasks, timeout=timeout)
677
+ fetched.update(hocr_fetched)
678
+ fetch_errors.update(hocr_errors)
679
+
680
+ djvu_bytes_out: bytes | None = None
681
+ djvu_source: str | None = None
682
+ segment_mode = page_index.get("segment_mode", "scandata")
683
+
684
+ if has_form_feeds and djvu_raw is not None and decoded_djvu is not None:
685
+ djvu_bytes_out = djvu_raw
686
+ djvu_source = "djvu_txt"
687
+ seg_count = decoded_djvu.count("\x0c") + 1
381
688
  access_count = int(page_index.get("access_leaf_count") or 0)
382
689
  leaf_count = int(page_index.get("leaf_count") or 0)
383
690
  if access_count and abs(seg_count - access_count) < abs(seg_count - leaf_count):
@@ -385,26 +692,29 @@ def ensure_item_cache(
385
692
  else:
386
693
  segment_mode = "scandata"
387
694
  elif "hocr_text" in fetched and "hocr_idx" in fetched:
388
- djvu_text = synthesize_djvu_from_hocr(fetched["hocr_text"], fetched["hocr_idx"])
695
+ djvu_bytes_out = synthesize_djvu_from_hocr(
696
+ fetched["hocr_text"], fetched["hocr_idx"]
697
+ ).encode("utf-8")
698
+ djvu_source = "hocr"
389
699
  segment_mode = "scandata"
390
- else:
391
- djvu_text = decoded
700
+ elif djvu_raw is not None:
701
+ djvu_bytes_out = djvu_raw
702
+ djvu_source = "djvu_txt"
392
703
  segment_mode = "flat"
393
- elif "hocr_text" in fetched and "hocr_idx" in fetched:
394
- djvu_text = synthesize_djvu_from_hocr(fetched["hocr_text"], fetched["hocr_idx"])
395
- segment_mode = "scandata"
396
-
397
- if djvu_text is None:
398
- err_detail = "; ".join(f"{k}: {v}" for k, v in fetch_errors.items())
399
- raise RuntimeError(
400
- f"Item {item_id} has no downloadable OCR text (_djvu.txt or _hocr_searchtext.txt.gz)"
401
- + (f" ({err_detail})" if err_detail else "")
402
- )
403
- page_index["segment_mode"] = segment_mode
404
- atomic_write_text(djvu_path, djvu_text)
405
- atomic_write_json(page_index_path, page_index)
406
- elif not has_page_index:
407
- atomic_write_json(page_index_path, page_index)
704
+
705
+ if djvu_bytes_out is None:
706
+ err_detail = "; ".join(f"{k}: {v}" for k, v in fetch_errors.items())
707
+ raise RuntimeError(
708
+ f"Item {item_id} has no downloadable OCR text (_djvu.txt or _hocr_searchtext.txt.gz)"
709
+ + (f" ({err_detail})" if err_detail else "")
710
+ )
711
+ page_index["segment_mode"] = segment_mode
712
+ if djvu_source is not None:
713
+ page_index["djvu_source"] = djvu_source
714
+ atomic_write_bytes(djvu_path, djvu_bytes_out)
715
+ atomic_write_json(page_index_path, page_index)
716
+ elif not has_page_index:
717
+ atomic_write_json(page_index_path, page_index)
408
718
 
409
719
  return {
410
720
  "identifier": item_id,
@@ -417,6 +727,107 @@ def ensure_item_cache(
417
727
  }
418
728
 
419
729
 
730
+ def _reuse_existing_item_artifact(
731
+ item_dir: Path,
732
+ file_name: str,
733
+ file_list: list[dict],
734
+ file_entry: dict,
735
+ ) -> bytes | None:
736
+ """Reuse scandata.xml or djvu.txt from item cache when it matches the raw file."""
737
+ scandata_name = find_item_file(
738
+ file_list, suffixes=("_scandata.xml", "scandata.xml"), formats=("scandata",)
739
+ )
740
+ scandata_path = item_dir / "scandata.xml"
741
+ if scandata_name and file_name == scandata_name and scandata_path.is_file():
742
+ return scandata_path.read_bytes()
743
+
744
+ djvu_name = find_item_file(file_list, suffixes=("_djvu.txt",), formats=("djvutxt",))
745
+ djvu_path = item_dir / "djvu.txt"
746
+ if djvu_name and file_name == djvu_name and djvu_path.is_file():
747
+ page_index = read_json_if_valid(item_dir / "page_index.json") or {}
748
+ djvu_source = page_index.get("djvu_source")
749
+ if djvu_source == "djvu_txt":
750
+ return djvu_path.read_bytes()
751
+ if djvu_source is None:
752
+ raw_size = file_entry.get("size")
753
+ if raw_size is not None:
754
+ try:
755
+ if djvu_path.stat().st_size == int(raw_size):
756
+ return djvu_path.read_bytes()
757
+ except (ValueError, OSError):
758
+ pass
759
+ elif not find_item_file(
760
+ file_list, suffixes=("_hocr_searchtext.txt.gz",), formats=("ocr search text",)
761
+ ):
762
+ return djvu_path.read_bytes()
763
+ return None
764
+
765
+
766
+ def ensure_downloaded_file(
767
+ identifier: str,
768
+ file_name: str,
769
+ file_list: list[dict],
770
+ file_entry: dict,
771
+ *,
772
+ cache_root: Path | None = None,
773
+ timeout: float = DOWNLOAD_TIMEOUT,
774
+ refresh: bool = False,
775
+ ) -> tuple[bytes, Path, bool]:
776
+ """Return file bytes, cache path, and cache-hit flag for an item file."""
777
+ item_id = validate_identifier(identifier)
778
+ root = cache_root if cache_root is not None else get_cache_root()
779
+ item_dir = root / item_id
780
+ files_root = item_dir / "files"
781
+ _, cache_path = validate_relative_item_path(file_name, files_root)
782
+
783
+ if not refresh:
784
+ if cache_path.is_file():
785
+ return cache_path.read_bytes(), cache_path, True
786
+ reused = _reuse_existing_item_artifact(item_dir, file_name, file_list, file_entry)
787
+ if reused is not None:
788
+ return reused, item_dir, True
789
+
790
+ with file_lock(item_dir / ".lock"):
791
+ if not refresh:
792
+ if cache_path.is_file():
793
+ return cache_path.read_bytes(), cache_path, True
794
+ reused = _reuse_existing_item_artifact(item_dir, file_name, file_list, file_entry)
795
+ if reused is not None:
796
+ return reused, item_dir, True
797
+
798
+ url = f"{BASE}/download/{quote(item_id)}/{quote(file_name)}"
799
+ content = http_get_bytes(url, timeout=timeout)
800
+ atomic_write_bytes(cache_path, content)
801
+ return content, cache_path, False
802
+
803
+
804
+ def ensure_page_image_cache(
805
+ identifier: str,
806
+ leaf_n: int,
807
+ suffix_tag: str,
808
+ url: str,
809
+ *,
810
+ cache_root: Path | None = None,
811
+ timeout: float = DEFAULT_TIMEOUT,
812
+ refresh: bool = False,
813
+ ) -> tuple[bytes, Path, bool]:
814
+ """Return rendered page JPEG bytes, cache path, and cache-hit flag."""
815
+ item_id = validate_identifier(identifier)
816
+ root = cache_root if cache_root is not None else get_cache_root()
817
+ item_dir = root / item_id
818
+ page_cache_path = item_dir / "pages" / f"n{leaf_n}_{suffix_tag}.jpg"
819
+
820
+ if not refresh and page_cache_path.is_file() and page_cache_path.stat().st_size > 0:
821
+ return page_cache_path.read_bytes(), page_cache_path, True
822
+
823
+ with file_lock(item_dir / ".lock"):
824
+ if not refresh and page_cache_path.is_file() and page_cache_path.stat().st_size > 0:
825
+ return page_cache_path.read_bytes(), page_cache_path, True
826
+ content = http_get_bytes(url, timeout=timeout)
827
+ atomic_write_bytes(page_cache_path, content)
828
+ return content, page_cache_path, False
829
+
830
+
420
831
  def resolve_segment_page(seg_idx: int, page_index: dict) -> tuple[int | None, int | None, str | None]:
421
832
  """Map a 0-based `\x0c` segment index to (bookreader_leaf_n, scandata_leaf, printed_page)."""
422
833
  mode = page_index.get("segment_mode", "scandata")
@@ -514,21 +925,219 @@ def resolve_printed_page_to_leaf(page_index: dict, printed_page: str) -> tuple[i
514
925
  sc_leaf = int(p2s[target])
515
926
  return sc_leaf, sc_leaf
516
927
  sample_pages = list(p2b.keys())
517
- hint = f" (known printed pages: {sample_pages[0]}..{sample_pages[-1]}, total {len(sample_pages)})" if sample_pages else " (no printed page numbers in scandata.xml)"
928
+ hint = (
929
+ f" (known printed pages: {sample_pages[0]}..{sample_pages[-1]}, total {len(sample_pages)})"
930
+ if sample_pages
931
+ else " (no printed page numbers in scandata.xml)"
932
+ )
518
933
  raise KeyError(f"Printed page {printed_page!r} not found in page_index.json{hint}")
519
934
 
520
935
 
936
+ def describe_leaf(page_index: dict, leaf_n: int) -> dict:
937
+ """Return BookReader leaf, scandata leaf, and printed page for one BookReader leaf."""
938
+ key = str(leaf_n)
939
+ scandata_leaf = page_index.get("bookreader_to_scandata", {}).get(key)
940
+ printed = page_index.get("bookreader_to_printed", {}).get(key)
941
+ return {"leaf": leaf_n, "scandata_leaf": scandata_leaf, "printed_page": printed}
942
+
943
+
944
+ def validate_leaf_in_index(page_index: dict, leaf_n: int) -> None:
945
+ if leaf_n < 0:
946
+ raise ValueError(f"Leaf index must be >= 0, got {leaf_n}.")
947
+ access_count = int(page_index.get("access_leaf_count") or 0)
948
+ if access_count and leaf_n >= access_count:
949
+ raise ValueError(
950
+ f"Leaf n{leaf_n} is out of range (item has {access_count} BookReader leaves: n0..n{access_count - 1})."
951
+ )
952
+
953
+
954
+ def leaf_from_scandata_leaf(page_index: dict, scandata_leaf: int) -> int:
955
+ s2b = page_index.get("scandata_to_bookreader") or {}
956
+ if str(scandata_leaf) in s2b:
957
+ return int(s2b[str(scandata_leaf)])
958
+ if not s2b:
959
+ raise KeyError(f"Scandata leaf {scandata_leaf} cannot be resolved (no scandata.xml mapping cached).")
960
+ raise KeyError(f"Scandata leaf {scandata_leaf} is not an access leaf (deleted or unknown) in page_index.json.")
961
+
962
+
963
+ def segment_for_leaf(page_index: dict, leaf_n: int, scandata_leaf: int | None) -> int | None:
964
+ """Map a BookReader leaf to its 0-based `\\x0c` segment index in cached djvu.txt."""
965
+ mode = page_index.get("segment_mode", "scandata")
966
+ if mode == "flat":
967
+ return None
968
+ if mode == "bookreader":
969
+ return leaf_n
970
+ if scandata_leaf is not None:
971
+ return int(scandata_leaf)
972
+ if not page_index.get("scandata_to_bookreader"):
973
+ return leaf_n
974
+ return None
975
+
976
+
977
+ def parse_printed_range(page_index: dict, spec: str) -> list[int]:
978
+ """Resolve a printed page range `p1-p2` (or a single label) to inclusive BookReader leaves."""
979
+ cleaned = spec.strip()
980
+ if not cleaned:
981
+ raise ValueError("Empty --pages range.")
982
+ try:
983
+ leaf, _ = resolve_printed_page_to_leaf(page_index, cleaned)
984
+ return [leaf]
985
+ except KeyError:
986
+ pass
987
+ if "-" not in cleaned:
988
+ leaf, _ = resolve_printed_page_to_leaf(page_index, cleaned)
989
+ return [leaf]
990
+ start_label, _, end_label = cleaned.partition("-")
991
+ if not start_label.strip() or not end_label.strip():
992
+ raise ValueError(f"Invalid --pages range {spec!r}; expected <p1>-<p2>.")
993
+ start_leaf, _ = resolve_printed_page_to_leaf(page_index, start_label)
994
+ end_leaf, _ = resolve_printed_page_to_leaf(page_index, end_label)
995
+ if end_leaf < start_leaf:
996
+ raise ValueError(
997
+ f"Invalid --pages range {spec!r}: printed page {end_label.strip()!r} (n{end_leaf}) precedes "
998
+ f"{start_label.strip()!r} (n{start_leaf})."
999
+ )
1000
+ return list(range(start_leaf, end_leaf + 1))
1001
+
1002
+
1003
+ def cmd_text(args: argparse.Namespace) -> int:
1004
+ identifier = validate_identifier(args.identifier)
1005
+ selectors = [s for s in (args.printed_page, args.leaf, args.pages) if s is not None]
1006
+ if len(selectors) != 1:
1007
+ fail("Pass exactly one of --printed-page <p>, --leaf <n>, or --pages <p1-p2>.", code=2)
1008
+
1009
+ try:
1010
+ cache_entry = ensure_item_cache(
1011
+ identifier,
1012
+ need_djvu=True,
1013
+ cache_root=get_cache_root(),
1014
+ timeout=args.timeout,
1015
+ refresh=args.refresh,
1016
+ )
1017
+ page_index = json.loads(cache_entry["page_index_path"].read_text(encoding="utf-8"))
1018
+ djvu_text = cache_entry["djvu_path"].read_text(encoding="utf-8", errors="replace")
1019
+ except Exception as exc:
1020
+ fail(str(exc))
1021
+
1022
+ try:
1023
+ if args.printed_page is not None:
1024
+ leaf, _ = resolve_printed_page_to_leaf(page_index, args.printed_page)
1025
+ leaves = [leaf]
1026
+ elif args.leaf is not None:
1027
+ leaves = [args.leaf]
1028
+ else:
1029
+ leaves = parse_printed_range(page_index, args.pages)
1030
+ for leaf in leaves:
1031
+ validate_leaf_in_index(page_index, leaf)
1032
+ except (KeyError, ValueError) as exc:
1033
+ fail(str(exc.args[0]) if exc.args else str(exc))
1034
+
1035
+ if page_index.get("segment_mode") == "flat":
1036
+ fail(
1037
+ f"Item {identifier} OCR text has no page breaks; per-page text is unavailable. "
1038
+ "Use `grep` or `download` for the full text."
1039
+ )
1040
+ segments = djvu_text.split("\x0c")
1041
+ pages_out: list[dict] = []
1042
+ for leaf in leaves:
1043
+ info = describe_leaf(page_index, leaf)
1044
+ seg_idx = segment_for_leaf(page_index, leaf, info["scandata_leaf"])
1045
+ if seg_idx is None or seg_idx < 0 or seg_idx >= len(segments):
1046
+ fail(f"No OCR text segment found for leaf n{leaf} in {identifier} (djvu.txt has {len(segments)} pages).")
1047
+ info["text"] = segments[seg_idx].strip("\n")
1048
+ info["image_url"] = page_image_url(identifier, leaf, scale=2)
1049
+ info["details_url"] = page_details_url(identifier, leaf)
1050
+ pages_out.append(info)
1051
+
1052
+ payload = {
1053
+ "identifier": identifier,
1054
+ "cached": bool(cache_entry["cached"]),
1055
+ "pages": pages_out,
1056
+ }
1057
+ if args.as_json:
1058
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
1059
+ return 0
1060
+ for idx, page in enumerate(pages_out):
1061
+ if idx:
1062
+ print()
1063
+ pp = f"p.{page['printed_page']}" if page["printed_page"] else "p.?"
1064
+ sc = f", scandata leaf {page['scandata_leaf']}" if page["scandata_leaf"] is not None else ""
1065
+ print(f"== {identifier} | n{page['leaf']} ({pp}{sc})")
1066
+ print(f" image: {page['image_url']}")
1067
+ print(f" details: {page['details_url']}")
1068
+ print(page["text"])
1069
+ return 0
1070
+
1071
+
1072
+ def cmd_lookup(args: argparse.Namespace) -> int:
1073
+ identifier = validate_identifier(args.identifier)
1074
+ selectors = [s for s in (args.printed_page, args.leaf, args.scandata_leaf) if s is not None]
1075
+ if len(selectors) != 1:
1076
+ fail("Pass exactly one of --printed-page <p>, --leaf <n>, or --scandata-leaf <n>.", code=2)
1077
+
1078
+ try:
1079
+ cache_entry = ensure_item_cache(
1080
+ identifier,
1081
+ need_djvu=False,
1082
+ cache_root=get_cache_root(),
1083
+ timeout=args.timeout,
1084
+ refresh=args.refresh,
1085
+ )
1086
+ page_index = json.loads(cache_entry["page_index_path"].read_text(encoding="utf-8"))
1087
+ except Exception as exc:
1088
+ fail(str(exc))
1089
+
1090
+ try:
1091
+ if args.printed_page is not None:
1092
+ leaf, _ = resolve_printed_page_to_leaf(page_index, args.printed_page)
1093
+ elif args.leaf is not None:
1094
+ leaf = args.leaf
1095
+ else:
1096
+ leaf = leaf_from_scandata_leaf(page_index, args.scandata_leaf)
1097
+ validate_leaf_in_index(page_index, leaf)
1098
+ except (KeyError, ValueError) as exc:
1099
+ fail(str(exc.args[0]) if exc.args else str(exc))
1100
+
1101
+ info = describe_leaf(page_index, leaf)
1102
+ payload = {
1103
+ "identifier": identifier,
1104
+ "cached": bool(cache_entry["cached"]),
1105
+ **info,
1106
+ "image_url": page_image_url(identifier, leaf, scale=2),
1107
+ "details_url": page_details_url(identifier, leaf),
1108
+ }
1109
+ if args.as_json:
1110
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
1111
+ return 0
1112
+ pp = info["printed_page"] if info["printed_page"] else "?"
1113
+ sc = info["scandata_leaf"] if info["scandata_leaf"] is not None else "?"
1114
+ print(f"{identifier}: printed page {pp} | BookReader leaf n{leaf} | scandata leaf {sc}")
1115
+ print(f" image: {payload['image_url']}")
1116
+ print(f" details: {payload['details_url']}")
1117
+ return 0
1118
+
1119
+
521
1120
  def cmd_search(args: argparse.Namespace) -> int:
522
1121
  query = args.query
523
1122
  if args.mediatype:
524
1123
  query = f"{query} AND mediatype:({args.mediatype})"
525
1124
  chosen = list(args.fields) if args.fields else DEFAULT_FIELDS
526
- data = search_api(query, chosen, args.rows, args.page, list(args.sorts))
1125
+ ttl_hours = resolve_query_ttl_hours(args.cache_ttl_hours)
1126
+ data, cached = search_api(
1127
+ query,
1128
+ chosen,
1129
+ args.rows,
1130
+ args.page,
1131
+ list(args.sorts),
1132
+ ttl_hours=ttl_hours,
1133
+ refresh=args.refresh,
1134
+ )
527
1135
  response = data.get("response") or {}
528
1136
  if args.as_json:
529
1137
  print(json.dumps(data, indent=2))
530
1138
  return 0
531
- print(f"{response.get('numFound')} items")
1139
+ status = "cache-hit" if cached else "fetched"
1140
+ print(f"{response.get('numFound')} items ({status})")
532
1141
  for doc in response.get("docs") or []:
533
1142
  identifier = doc.get("identifier") or ""
534
1143
  title = doc.get("title") or ""
@@ -543,12 +1152,14 @@ def cmd_search(args: argparse.Namespace) -> int:
543
1152
 
544
1153
 
545
1154
  def cmd_get(args: argparse.Namespace) -> int:
546
- data = metadata_api(validate_identifier(args.identifier))
1155
+ identifier = validate_identifier(args.identifier)
1156
+ data, cached = metadata_api(identifier, timeout=args.timeout, refresh=args.refresh)
547
1157
  if args.as_json:
548
1158
  print(json.dumps(data, indent=2))
549
1159
  return 0
550
1160
  meta = data.get("metadata") or {}
551
- print(f"{meta.get('title') or args.identifier}")
1161
+ status = "cache-hit" if cached else "fetched"
1162
+ print(f"{meta.get('title') or identifier}")
552
1163
  print(f" Identifier: {meta.get('identifier')}")
553
1164
  if meta.get("creator"):
554
1165
  print(f" Creator: {meta.get('creator')}")
@@ -564,7 +1175,7 @@ def cmd_get(args: argparse.Namespace) -> int:
564
1175
  if meta.get("description"):
565
1176
  print(f" Description: {short(meta.get('description'))}")
566
1177
  file_list = data.get("files") or []
567
- print(f" Files: {len(file_list)} | {item_url(args.identifier)}")
1178
+ print(f" Files: {len(file_list)} | {item_url(identifier)} ({status})")
568
1179
  if args.files:
569
1180
  for entry in file_list:
570
1181
  size = entry.get("size") or ""
@@ -574,39 +1185,74 @@ def cmd_get(args: argparse.Namespace) -> int:
574
1185
 
575
1186
  def cmd_download(args: argparse.Namespace) -> int:
576
1187
  identifier = validate_identifier(args.identifier)
577
- data = metadata_api(identifier)
1188
+ cache_root = get_cache_root()
1189
+ files_root = cache_root / identifier / "files"
1190
+
1191
+ # Validate requested filenames at the CLI boundary before hitting metadata or disk.
1192
+ validated_names: list[tuple[str, Path]] = []
1193
+ if not args.list_only and args.files:
1194
+ for name in args.files:
1195
+ try:
1196
+ rel, _ = validate_relative_item_path(name, files_root)
1197
+ except ValueError as exc:
1198
+ fail(str(exc), code=2)
1199
+ validated_names.append((name, rel))
1200
+
1201
+ data, _ = metadata_api(
1202
+ identifier, cache_root=cache_root, timeout=args.timeout, refresh=args.refresh
1203
+ )
578
1204
  file_list = data.get("files") or []
579
1205
  if args.list_only or not args.files:
580
1206
  for entry in file_list:
581
1207
  size = entry.get("size") or ""
582
1208
  print(f"{entry.get('name')} | {entry.get('format')} | {size} bytes")
583
1209
  return 0
584
- available = {entry.get("name") for entry in file_list}
1210
+
1211
+ by_name = {entry.get("name"): entry for entry in file_list if entry.get("name")}
585
1212
  out_dir = Path(args.out)
586
1213
  out_dir.mkdir(parents=True, exist_ok=True)
587
- for name in args.files:
588
- if name not in available:
1214
+ for name, rel in validated_names:
1215
+ file_entry = by_name.get(name)
1216
+ if file_entry is None:
589
1217
  fail(f"File not in item {identifier}: {name}")
590
- url = f"{BASE}/download/{quote(identifier)}/{quote(name)}"
591
1218
  try:
592
- content = http_get_bytes(url, timeout=60.0)
1219
+ content, _, cached = ensure_downloaded_file(
1220
+ identifier,
1221
+ name,
1222
+ file_list,
1223
+ file_entry,
1224
+ cache_root=cache_root,
1225
+ timeout=args.timeout,
1226
+ refresh=args.refresh,
1227
+ )
1228
+ except ValueError as exc:
1229
+ fail(str(exc), code=2)
593
1230
  except (RuntimeError, FileNotFoundError) as exc:
594
1231
  fail(str(exc))
595
- dest = out_dir / Path(name).name
1232
+ dest = out_dir / rel.name
596
1233
  atomic_write_bytes(dest, content)
597
- print(f"{dest} ({len(content)} bytes)")
1234
+ status = "cache-hit" if cached else "fetched"
1235
+ print(f"{dest} ({len(content)} bytes, {status})")
598
1236
  return 0
599
1237
 
600
1238
 
601
1239
  def cmd_fulltext(args: argparse.Namespace) -> int:
602
- data = fulltext_api(args.query, args.rows, args.page)
1240
+ ttl_hours = resolve_query_ttl_hours(args.cache_ttl_hours)
1241
+ data, cached = fulltext_api(
1242
+ args.query,
1243
+ args.rows,
1244
+ args.page,
1245
+ ttl_hours=ttl_hours,
1246
+ refresh=args.refresh,
1247
+ )
603
1248
  if args.as_json:
604
1249
  print(json.dumps(data, indent=2, ensure_ascii=False))
605
1250
  return 0
606
1251
  hits_block = ((data.get("response") or {}).get("body") or {}).get("hits") or {}
607
1252
  total = hits_block.get("total", 0)
608
1253
  hits = hits_block.get("hits") or []
609
- print(f"{total} full-text matches (showing {len(hits)})")
1254
+ status = "cache-hit" if cached else "fetched"
1255
+ print(f"{total} full-text matches (showing {len(hits)}, {status})")
610
1256
  for hit in hits:
611
1257
  fields = hit.get("fields") or {}
612
1258
  identifier = fields.get("identifier") or ""
@@ -633,7 +1279,13 @@ def cmd_grep(args: argparse.Namespace) -> int:
633
1279
 
634
1280
  # Fetch missing items in parallel (max_workers=6, timeout=25).
635
1281
  def prepare(item_id: str) -> dict:
636
- return ensure_item_cache(item_id, need_djvu=True, cache_root=cache_root, timeout=args.timeout)
1282
+ return ensure_item_cache(
1283
+ item_id,
1284
+ need_djvu=True,
1285
+ cache_root=cache_root,
1286
+ timeout=args.timeout,
1287
+ refresh=args.refresh,
1288
+ )
637
1289
 
638
1290
  if len(identifiers) == 1:
639
1291
  try:
@@ -716,6 +1368,7 @@ def cmd_grep(args: argparse.Namespace) -> int:
716
1368
  def cmd_page(args: argparse.Namespace) -> int:
717
1369
  t0 = time.perf_counter()
718
1370
  identifier = validate_identifier(args.identifier)
1371
+ cache_root = get_cache_root()
719
1372
 
720
1373
  # Support both legacy positional `<leaf>` and new `--leaf` / `--printed-page`.
721
1374
  leaf_from_pos = args.leaf_pos
@@ -737,8 +1390,9 @@ def cmd_page(args: argparse.Namespace) -> int:
737
1390
  cache_entry = ensure_item_cache(
738
1391
  identifier,
739
1392
  need_djvu=False,
740
- cache_root=get_cache_root(),
1393
+ cache_root=cache_root,
741
1394
  timeout=args.timeout,
1395
+ refresh=args.refresh,
742
1396
  )
743
1397
  index_cached = bool(cache_entry["cached"])
744
1398
  page_index = json.loads(cache_entry["page_index_path"].read_text(encoding="utf-8"))
@@ -762,7 +1416,15 @@ def cmd_page(args: argparse.Namespace) -> int:
762
1416
  suffix_tag = f"w{width}"
763
1417
 
764
1418
  try:
765
- content = http_get_bytes(url, timeout=args.timeout)
1419
+ content, page_cache_path, page_cached = ensure_page_image_cache(
1420
+ identifier,
1421
+ target_leaf,
1422
+ suffix_tag,
1423
+ url,
1424
+ cache_root=cache_root,
1425
+ timeout=args.timeout,
1426
+ refresh=args.refresh,
1427
+ )
766
1428
  except (RuntimeError, FileNotFoundError) as exc:
767
1429
  fail(str(exc))
768
1430
 
@@ -773,7 +1435,9 @@ def cmd_page(args: argparse.Namespace) -> int:
773
1435
  out_path.mkdir(parents=True, exist_ok=True)
774
1436
  dest = out_path / f"{identifier}_n{target_leaf}_{suffix_tag}.jpg"
775
1437
 
776
- atomic_write_bytes(dest, content)
1438
+ if dest.resolve() != page_cache_path.resolve():
1439
+ atomic_write_bytes(dest, content)
1440
+
777
1441
  elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2)
778
1442
  payload = {
779
1443
  "identifier": identifier,
@@ -782,15 +1446,18 @@ def cmd_page(args: argparse.Namespace) -> int:
782
1446
  "printed_page": resolved_printed,
783
1447
  "url": url,
784
1448
  "path": str(dest),
1449
+ "cache_path": str(page_cache_path),
785
1450
  "bytes": len(content),
786
1451
  "index_cached": index_cached,
1452
+ "page_cached": page_cached,
787
1453
  "elapsed_ms": elapsed_ms,
788
1454
  }
789
1455
  if args.as_json:
790
1456
  print(json.dumps(payload, indent=2))
791
1457
  else:
792
1458
  extra = f" [p.{resolved_printed} -> n{target_leaf}]" if resolved_printed is not None else f" [n{target_leaf}]"
793
- print(f"{dest} ({len(content)} bytes){extra}")
1459
+ status = "cache-hit" if page_cached else "fetched"
1460
+ print(f"{dest} ({len(content)} bytes){extra} ({status})")
794
1461
  return 0
795
1462
 
796
1463
 
@@ -816,6 +1483,8 @@ def build_parser() -> argparse.ArgumentParser:
816
1483
  p_search.add_argument("--page", type=int, default=1, help="Results page (default: 1).")
817
1484
  p_search.add_argument("--sort", dest="sorts", action="append", default=[], help="Repeatable, e.g. --sort 'downloads desc'.")
818
1485
  p_search.add_argument("--field", dest="fields", action="append", default=[], help="Repeatable metadata field.")
1486
+ p_search.add_argument("--cache-ttl-hours", type=float, default=None, help="Query cache TTL in hours (default: 168 or KINLOOM_IA_QUERY_TTL_HOURS).")
1487
+ p_search.add_argument("--refresh", action="store_true", help="Bypass local cache and fetch fresh results.")
819
1488
  p_search.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
820
1489
  p_search.set_defaults(func=cmd_search)
821
1490
 
@@ -823,6 +1492,8 @@ def build_parser() -> argparse.ArgumentParser:
823
1492
  p_get.add_argument("identifier")
824
1493
  p_get.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
825
1494
  p_get.add_argument("--files", action="store_true", help="List the item's files.")
1495
+ p_get.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="HTTP timeout seconds on cache miss (default: 25).")
1496
+ p_get.add_argument("--refresh", action="store_true", help="Bypass local metadata cache and fetch fresh metadata.")
826
1497
  p_get.set_defaults(func=cmd_get)
827
1498
 
828
1499
  p_dl = sub.add_parser("download", help="Download files of an item, or list them with no FILE given.")
@@ -830,12 +1501,16 @@ def build_parser() -> argparse.ArgumentParser:
830
1501
  p_dl.add_argument("files", nargs="*")
831
1502
  p_dl.add_argument("--out", default=".", help="Directory to save files into (default: .).")
832
1503
  p_dl.add_argument("--list", dest="list_only", action="store_true", help="Only list files, do not download.")
1504
+ p_dl.add_argument("--timeout", type=float, default=DOWNLOAD_TIMEOUT, help="HTTP timeout seconds on cache miss (default: 60).")
1505
+ p_dl.add_argument("--refresh", action="store_true", help="Bypass local cache and re-download metadata and files.")
833
1506
  p_dl.set_defaults(func=cmd_download)
834
1507
 
835
1508
  p_ft = sub.add_parser("fulltext", help="Search OCR full text across digitized books and periodicals.")
836
1509
  p_ft.add_argument("query")
837
1510
  p_ft.add_argument("--rows", type=int, default=10, help="Hits per page (default: 10).")
838
1511
  p_ft.add_argument("--page", type=int, default=1, help="Results page, 1-based (default: 1).")
1512
+ p_ft.add_argument("--cache-ttl-hours", type=float, default=None, help="Query cache TTL in hours (default: 168 or KINLOOM_IA_QUERY_TTL_HOURS).")
1513
+ p_ft.add_argument("--refresh", action="store_true", help="Bypass local cache and fetch fresh results.")
839
1514
  p_ft.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
840
1515
  p_ft.set_defaults(func=cmd_fulltext)
841
1516
 
@@ -846,6 +1521,7 @@ def build_parser() -> argparse.ArgumentParser:
846
1521
  p_grep.add_argument("--limit", type=int, default=25, help="Maximum hits returned (default: 25).")
847
1522
  p_grep.add_argument("-i", "--ignore-case", action="store_true", help="Case-insensitive regex matching.")
848
1523
  p_grep.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="HTTP timeout seconds on cache miss (default: 25).")
1524
+ p_grep.add_argument("--refresh", action="store_true", help="Bypass local cache and re-fetch metadata, scandata, and OCR text.")
849
1525
  p_grep.add_argument("--json", dest="as_json", action="store_true", help="Structured JSON output.")
850
1526
  p_grep.set_defaults(func=cmd_grep)
851
1527
 
@@ -858,9 +1534,30 @@ def build_parser() -> argparse.ArgumentParser:
858
1534
  p_page.add_argument("--width", type=int, default=None, help="Rendered JPEG width in pixels (default 2400 when --scale is omitted).")
859
1535
  p_page.add_argument("--out", default=".", help="Output file path (.jpg) or directory (default: .).")
860
1536
  p_page.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="HTTP timeout seconds (default: 25).")
1537
+ p_page.add_argument("--refresh", action="store_true", help="Bypass local cache and re-fetch index and page JPEG.")
861
1538
  p_page.add_argument("--json", dest="as_json", action="store_true", help="Structured JSON output.")
862
1539
  p_page.set_defaults(func=cmd_page)
863
1540
 
1541
+ p_text = sub.add_parser("text", help="Print cached OCR text for a printed page, leaf, or printed-page range (no JPEG download).")
1542
+ p_text.add_argument("identifier")
1543
+ p_text.add_argument("--printed-page", default=None, help="Printed page label resolved via cached page_index.json.")
1544
+ p_text.add_argument("--leaf", type=int, default=None, help="BookReader leaf index (n<LEAF>).")
1545
+ p_text.add_argument("--pages", default=None, help="Inclusive printed-page range, e.g. 12-14.")
1546
+ p_text.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="HTTP timeout seconds on cache miss (default: 25).")
1547
+ p_text.add_argument("--refresh", action="store_true", help="Bypass local cache and re-fetch metadata, scandata, and OCR text.")
1548
+ p_text.add_argument("--json", dest="as_json", action="store_true", help="Structured JSON output.")
1549
+ p_text.set_defaults(func=cmd_text)
1550
+
1551
+ p_lookup = sub.add_parser("lookup", help="Resolve printed page <-> BookReader leaf <-> scandata leaf from cached page_index.json.")
1552
+ p_lookup.add_argument("identifier")
1553
+ p_lookup.add_argument("--printed-page", default=None, help="Printed page label.")
1554
+ p_lookup.add_argument("--leaf", type=int, default=None, help="BookReader leaf index (n<LEAF>).")
1555
+ p_lookup.add_argument("--scandata-leaf", type=int, default=None, help="Raw scandata.xml leafNum.")
1556
+ p_lookup.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="HTTP timeout seconds on cache miss (default: 25).")
1557
+ p_lookup.add_argument("--refresh", action="store_true", help="Bypass local cache and re-fetch metadata and scandata.")
1558
+ p_lookup.add_argument("--json", dest="as_json", action="store_true", help="Structured JSON output.")
1559
+ p_lookup.set_defaults(func=cmd_lookup)
1560
+
864
1561
  p_url = sub.add_parser("url", help="Print the website advanced-search URL for a query.")
865
1562
  p_url.add_argument("query")
866
1563
  p_url.add_argument("--mediatype", default=None)