@kinloom/cli 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/assets/cached-ocr.py +786 -0
  2. package/dist/assets/ocr.md +76 -0
  3. package/dist/assets/prep-scan.md +97 -0
  4. package/dist/assets/prep-scan.py +1313 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +162 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +130 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +129 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +154 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +488 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +30 -5
  50. package/dist/client.js.map +1 -1
  51. package/dist/commands/ops/audit.d.ts +138 -0
  52. package/dist/commands/ops/audit.d.ts.map +1 -0
  53. package/dist/commands/ops/audit.js +872 -0
  54. package/dist/commands/ops/audit.js.map +1 -0
  55. package/dist/commands/ops/context.d.ts +100 -0
  56. package/dist/commands/ops/context.d.ts.map +1 -0
  57. package/dist/commands/ops/context.js +917 -0
  58. package/dist/commands/ops/context.js.map +1 -0
  59. package/dist/commands/ops/dates.d.ts +87 -0
  60. package/dist/commands/ops/dates.d.ts.map +1 -0
  61. package/dist/commands/ops/dates.js +228 -0
  62. package/dist/commands/ops/dates.js.map +1 -0
  63. package/dist/commands/ops/help.d.ts +8 -0
  64. package/dist/commands/ops/help.d.ts.map +1 -0
  65. package/dist/commands/ops/help.js +107 -0
  66. package/dist/commands/ops/help.js.map +1 -0
  67. package/dist/commands/ops/index.d.ts +8 -0
  68. package/dist/commands/ops/index.d.ts.map +1 -0
  69. package/dist/commands/ops/index.js +8 -0
  70. package/dist/commands/ops/index.js.map +1 -0
  71. package/dist/commands/ops/integrate.d.ts +61 -0
  72. package/dist/commands/ops/integrate.d.ts.map +1 -0
  73. package/dist/commands/ops/integrate.js +1063 -0
  74. package/dist/commands/ops/integrate.js.map +1 -0
  75. package/dist/commands/ops/sync.d.ts +194 -0
  76. package/dist/commands/ops/sync.d.ts.map +1 -0
  77. package/dist/commands/ops/sync.js +1251 -0
  78. package/dist/commands/ops/sync.js.map +1 -0
  79. package/dist/commands/ops/telemetry.d.ts +79 -0
  80. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  81. package/dist/commands/ops/telemetry.js +249 -0
  82. package/dist/commands/ops/telemetry.js.map +1 -0
  83. package/dist/commands/ops/verify.d.ts +76 -0
  84. package/dist/commands/ops/verify.d.ts.map +1 -0
  85. package/dist/commands/ops/verify.js +325 -0
  86. package/dist/commands/ops/verify.js.map +1 -0
  87. package/dist/commands/records/help.d.ts +18 -0
  88. package/dist/commands/records/help.d.ts.map +1 -0
  89. package/dist/commands/records/help.js +174 -0
  90. package/dist/commands/records/help.js.map +1 -0
  91. package/dist/commands/records/index.d.ts +5 -0
  92. package/dist/commands/records/index.d.ts.map +1 -0
  93. package/dist/commands/records/index.js +5 -0
  94. package/dist/commands/records/index.js.map +1 -0
  95. package/dist/commands/records/registry.d.ts +32 -0
  96. package/dist/commands/records/registry.d.ts.map +1 -0
  97. package/dist/commands/records/registry.js +227 -0
  98. package/dist/commands/records/registry.js.map +1 -0
  99. package/dist/commands/records/resolve.d.ts +14 -0
  100. package/dist/commands/records/resolve.d.ts.map +1 -0
  101. package/dist/commands/records/resolve.js +61 -0
  102. package/dist/commands/records/resolve.js.map +1 -0
  103. package/dist/commands/records/runner.d.ts +27 -0
  104. package/dist/commands/records/runner.d.ts.map +1 -0
  105. package/dist/commands/records/runner.js +255 -0
  106. package/dist/commands/records/runner.js.map +1 -0
  107. package/dist/index.d.ts +2 -0
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +2 -0
  110. package/dist/index.js.map +1 -1
  111. package/package.json +3 -3
@@ -0,0 +1,1576 @@
1
+ #!/usr/bin/env -S python3 -S
2
+ """Internet Archive CLI: search items, inspect metadata, grep cached books, and fetch pages.
3
+
4
+ Uses Python 3.11+ standard library only with lazy network/XML/lock imports for fast
5
+ cache-hit startup (~50 ms) and zero external dependency installation.
6
+ All APIs are public and read-only.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ from contextlib import contextmanager
13
+ import json
14
+ import math
15
+ import os
16
+ from pathlib import Path
17
+ import re
18
+ import sys
19
+ import time
20
+ from typing import Iterator
21
+ from urllib.parse import quote, urlencode
22
+
23
+ BASE = "https://archive.org"
24
+ ADVANCED_SEARCH = f"{BASE}/advancedsearch.php"
25
+ FULLTEXT_SEARCH = f"{BASE}/services/search/beta/page_production/"
26
+ USER_AGENT = "kinloom archive-org skill (research use)"
27
+ DEFAULT_FIELDS = ["identifier", "title", "creator", "date", "mediatype"]
28
+ DEFAULT_TIMEOUT = 25.0
29
+ SEARCH_TIMEOUT = 45.0
30
+ DOWNLOAD_TIMEOUT = 60.0
31
+ DEFAULT_QUERY_TTL_HOURS = 168.0
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
36
+ SAFE_ID_RE = re.compile(r"^[A-Za-z0-9._-]+$")
37
+ IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
38
+
39
+
40
+ def get_cache_root() -> Path:
41
+ override = os.environ.get("KINLOOM_IA_CACHE_DIR")
42
+ if override:
43
+ return Path(override).expanduser()
44
+ return Path.home() / ".cache" / "kinloom-ia"
45
+
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
+
64
+ def validate_identifier(identifier: str) -> str:
65
+ cleaned = identifier.strip()
66
+ if not cleaned or not SAFE_ID_RE.match(cleaned) or cleaned in (".", ".."):
67
+ fail(f"Invalid Internet Archive identifier: {identifier!r}")
68
+ return cleaned
69
+
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
+
87
+ def fail(message: str, code: int = 1) -> None:
88
+ sys.stderr.write(f"{message}\n")
89
+ raise SystemExit(code)
90
+
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
+
120
+ def atomic_write_bytes(dest: Path, data: bytes) -> None:
121
+ dest.parent.mkdir(parents=True, exist_ok=True)
122
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
123
+ try:
124
+ tmp.write_bytes(data)
125
+ os.replace(tmp, dest)
126
+ except Exception:
127
+ if tmp.exists():
128
+ tmp.unlink(missing_ok=True)
129
+ raise
130
+
131
+
132
+ def atomic_write_text(dest: Path, text: str) -> None:
133
+ atomic_write_bytes(dest, text.encode("utf-8"))
134
+
135
+
136
+ def atomic_write_json(dest: Path, payload: object) -> None:
137
+ atomic_write_text(dest, json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
138
+
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
+
156
+ def http_get_bytes(url: str, timeout: float = DEFAULT_TIMEOUT) -> bytes:
157
+ from urllib.error import HTTPError, URLError
158
+ from urllib.request import Request, urlopen
159
+
160
+ req = Request(url, headers={"User-Agent": USER_AGENT})
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}")
186
+
187
+
188
+ def http_get_json(url: str, timeout: float = DEFAULT_TIMEOUT) -> dict:
189
+ raw = http_get_bytes(url, timeout=timeout)
190
+ try:
191
+ data = json.loads(raw.decode("utf-8"))
192
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
193
+ raise RuntimeError(f"Invalid JSON response from {url}: {exc}") from exc
194
+ if not isinstance(data, dict):
195
+ raise RuntimeError(f"Expected JSON object from {url}")
196
+ return data
197
+
198
+
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]:
261
+ qs = urlencode(
262
+ [
263
+ ("user_query", query),
264
+ ("service_backend", "fts"),
265
+ ("hits_per_page", str(rows)),
266
+ ("page", str(page)),
267
+ ]
268
+ )
269
+ canonical_params = {
270
+ "kind": "fulltext",
271
+ "query": query,
272
+ "rows": rows,
273
+ "page": page,
274
+ }
275
+ try:
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
+ )
285
+ except (RuntimeError, FileNotFoundError) as exc:
286
+ fail(str(exc))
287
+ return {}, False
288
+
289
+
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]:
301
+ params: list[tuple[str, str]] = [
302
+ ("q", query),
303
+ ("output", "json"),
304
+ ("rows", str(rows)),
305
+ ]
306
+ if page > 1:
307
+ params.append(("page", str(page)))
308
+ for field in fields:
309
+ params.append(("fl[]", field))
310
+ for sort in sorts:
311
+ params.append(("sort[]", sort))
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
+ }
321
+ try:
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
+ )
331
+ except (RuntimeError, FileNotFoundError) as exc:
332
+ fail(str(exc))
333
+ return {}, False
334
+
335
+
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]:
392
+ try:
393
+ return ensure_item_metadata(
394
+ identifier, cache_root=cache_root, timeout=timeout, refresh=refresh
395
+ )
396
+ except FileNotFoundError:
397
+ fail(f"No item with identifier {identifier}")
398
+ except RuntimeError as exc:
399
+ fail(str(exc))
400
+ return {}, False
401
+
402
+
403
+ def item_url(identifier: str) -> str:
404
+ return f"{BASE}/details/{quote(identifier)}"
405
+
406
+
407
+ def page_image_url(identifier: str, leaf_n: int, *, scale: int | None = None, width: int | None = None) -> str:
408
+ if width is not None:
409
+ return f"{BASE}/download/{quote(identifier)}/page/n{leaf_n}_w{width}.jpg"
410
+ effective_scale = scale if scale is not None else 2
411
+ return f"{BASE}/download/{quote(identifier)}/page/n{leaf_n}_s{effective_scale}.jpg"
412
+
413
+
414
+ def page_details_url(identifier: str, leaf_n: int) -> str:
415
+ return f"{BASE}/details/{quote(identifier)}/page/n{leaf_n}"
416
+
417
+
418
+ def short(text: object, limit: int = 300) -> str:
419
+ if not text:
420
+ return ""
421
+ cleaned = " ".join(str(text).split())
422
+ if len(cleaned) <= limit:
423
+ return cleaned
424
+ return cleaned[:limit].rstrip() + " ..."
425
+
426
+
427
+ def find_item_file(files: list[dict], *, suffixes: tuple[str, ...], formats: tuple[str, ...] = ()) -> str | None:
428
+ for entry in files:
429
+ name = entry.get("name") or ""
430
+ if any(name.endswith(suf) for suf in suffixes):
431
+ return str(name)
432
+ if formats:
433
+ fmt_set = {f.lower() for f in formats}
434
+ for entry in files:
435
+ fmt = str(entry.get("format") or "").lower()
436
+ name = entry.get("name") or ""
437
+ if fmt in fmt_set and name:
438
+ return str(name)
439
+ return None
440
+
441
+
442
+ def parse_scandata_xml(xml_bytes: bytes) -> dict:
443
+ """Parse scandata.xml into compact bidirectional leaf/page lookup tables.
444
+
445
+ Internet Archive BookReader `/page/n<N>` indexes 0-based over leaves with
446
+ `addToAccessFormats == true` (excluding deleted leaves). Storing both raw
447
+ `leafNum` and BookReader `n` eliminates off-by-one page offset bugs.
448
+ """
449
+ import xml.etree.ElementTree as ET
450
+
451
+ root = ET.fromstring(xml_bytes)
452
+ pages = root.findall(".//pageData/page")
453
+ scandata_to_bookreader: dict[str, int] = {}
454
+ bookreader_to_scandata: dict[str, int] = {}
455
+ scandata_to_printed: dict[str, str] = {}
456
+ bookreader_to_printed: dict[str, str] = {}
457
+ printed_to_bookreader: dict[str, int] = {}
458
+ printed_to_bookreader_ci: dict[str, int] = {}
459
+ printed_to_scandata: dict[str, int] = {}
460
+
461
+ access_idx = 0
462
+ for seq_idx, page_el in enumerate(pages):
463
+ raw_leaf = page_el.attrib.get("leafNum")
464
+ try:
465
+ leaf_num = int(raw_leaf) if raw_leaf is not None else seq_idx
466
+ except ValueError:
467
+ leaf_num = seq_idx
468
+ page_type = (page_el.findtext("pageType") or "").strip()
469
+ add_access_raw = page_el.findtext("addToAccessFormats")
470
+ if add_access_raw is not None:
471
+ in_access = add_access_raw.strip().lower() == "true"
472
+ else:
473
+ in_access = page_type.lower() != "delete"
474
+
475
+ printed = (page_el.findtext("pageNumber") or "").strip()
476
+ leaf_key = str(leaf_num)
477
+ if printed:
478
+ scandata_to_printed[leaf_key] = printed
479
+ printed_to_scandata.setdefault(printed, leaf_num)
480
+
481
+ if in_access:
482
+ br_n = access_idx
483
+ access_idx += 1
484
+ scandata_to_bookreader[leaf_key] = br_n
485
+ bookreader_to_scandata[str(br_n)] = leaf_num
486
+ if printed:
487
+ bookreader_to_printed[str(br_n)] = printed
488
+ printed_to_bookreader.setdefault(printed, br_n)
489
+ printed_to_bookreader_ci.setdefault(printed.lower(), br_n)
490
+
491
+ return {
492
+ "leaf_count": len(pages),
493
+ "access_leaf_count": access_idx,
494
+ "scandata_to_bookreader": scandata_to_bookreader,
495
+ "bookreader_to_scandata": bookreader_to_scandata,
496
+ "scandata_to_printed": scandata_to_printed,
497
+ "bookreader_to_printed": bookreader_to_printed,
498
+ "printed_to_bookreader": printed_to_bookreader,
499
+ "printed_to_bookreader_ci": printed_to_bookreader_ci,
500
+ "printed_to_scandata": printed_to_scandata,
501
+ "segment_mode": "scandata",
502
+ }
503
+
504
+
505
+ def empty_page_index() -> dict:
506
+ return {
507
+ "leaf_count": 0,
508
+ "access_leaf_count": 0,
509
+ "scandata_to_bookreader": {},
510
+ "bookreader_to_scandata": {},
511
+ "scandata_to_printed": {},
512
+ "bookreader_to_printed": {},
513
+ "printed_to_bookreader": {},
514
+ "printed_to_bookreader_ci": {},
515
+ "printed_to_scandata": {},
516
+ "segment_mode": "bookreader",
517
+ }
518
+
519
+
520
+ def synthesize_djvu_from_hocr(searchtext_gz: bytes, pageindex_gz: bytes) -> str:
521
+ import gzip
522
+
523
+ text = gzip.decompress(searchtext_gz).decode("utf-8", errors="replace")
524
+ offsets = json.loads(gzip.decompress(pageindex_gz).decode("utf-8"))
525
+ if not isinstance(offsets, list) or not offsets:
526
+ return text
527
+ segments: list[str] = []
528
+ text_len = len(text)
529
+ for row in offsets:
530
+ if isinstance(row, list) and len(row) >= 2:
531
+ start = max(0, min(int(row[0]), text_len))
532
+ end = max(start, min(int(row[1]), text_len))
533
+ segments.append(text[start:end].replace("\x0c", " "))
534
+ else:
535
+ segments.append("")
536
+ return "\x0c".join(segments)
537
+
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
+
568
+ def ensure_item_cache(
569
+ identifier: str,
570
+ *,
571
+ need_djvu: bool,
572
+ cache_root: Path | None = None,
573
+ timeout: float = DEFAULT_TIMEOUT,
574
+ refresh: bool = False,
575
+ ) -> dict:
576
+ """Populate and return cached metadata, page_index, and optional djvu.txt."""
577
+ item_id = validate_identifier(identifier)
578
+ root = cache_root if cache_root is not None else get_cache_root()
579
+ item_dir = root / item_id
580
+ meta_path = item_dir / "metadata.json"
581
+ scandata_path = item_dir / "scandata.xml"
582
+ page_index_path = item_dir / "page_index.json"
583
+ djvu_path = item_dir / "djvu.txt"
584
+
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
+ )
592
+
593
+ if cache_ready():
594
+ return {
595
+ "identifier": item_id,
596
+ "item_dir": item_dir,
597
+ "metadata_path": meta_path,
598
+ "scandata_path": scandata_path,
599
+ "page_index_path": page_index_path,
600
+ "djvu_path": djvu_path,
601
+ "cached": True,
602
+ }
603
+
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
+ }
615
+
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()
622
+
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
+ )
634
+
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
653
+ else:
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
688
+ access_count = int(page_index.get("access_leaf_count") or 0)
689
+ leaf_count = int(page_index.get("leaf_count") or 0)
690
+ if access_count and abs(seg_count - access_count) < abs(seg_count - leaf_count):
691
+ segment_mode = "bookreader"
692
+ else:
693
+ segment_mode = "scandata"
694
+ elif "hocr_text" in fetched and "hocr_idx" in fetched:
695
+ djvu_bytes_out = synthesize_djvu_from_hocr(
696
+ fetched["hocr_text"], fetched["hocr_idx"]
697
+ ).encode("utf-8")
698
+ djvu_source = "hocr"
699
+ segment_mode = "scandata"
700
+ elif djvu_raw is not None:
701
+ djvu_bytes_out = djvu_raw
702
+ djvu_source = "djvu_txt"
703
+ segment_mode = "flat"
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)
718
+
719
+ return {
720
+ "identifier": item_id,
721
+ "item_dir": item_dir,
722
+ "metadata_path": meta_path,
723
+ "scandata_path": scandata_path,
724
+ "page_index_path": page_index_path,
725
+ "djvu_path": djvu_path,
726
+ "cached": False,
727
+ }
728
+
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
+
831
+ def resolve_segment_page(seg_idx: int, page_index: dict) -> tuple[int | None, int | None, str | None]:
832
+ """Map a 0-based `\x0c` segment index to (bookreader_leaf_n, scandata_leaf, printed_page)."""
833
+ mode = page_index.get("segment_mode", "scandata")
834
+ if mode == "flat":
835
+ return None, None, None
836
+ key = str(seg_idx)
837
+ if mode == "bookreader":
838
+ scandata_leaf = page_index.get("bookreader_to_scandata", {}).get(key)
839
+ printed = page_index.get("bookreader_to_printed", {}).get(key)
840
+ return seg_idx, scandata_leaf, printed
841
+ # scandata leaf indexing (e.g. hocr_pageindex or full-leaf djvu.txt)
842
+ scandata_to_br = page_index.get("scandata_to_bookreader", {})
843
+ br_n = scandata_to_br.get(key)
844
+ if br_n is None and not scandata_to_br:
845
+ br_n = seg_idx
846
+ printed = page_index.get("scandata_to_printed", {}).get(key)
847
+ return br_n, seg_idx, printed
848
+
849
+
850
+ def extract_snippet(page_text: str, match_start: int, match_end: int, context_chars: int) -> str:
851
+ half = max(20, context_chars // 2)
852
+ start = max(0, match_start - half)
853
+ end = min(len(page_text), match_end + half)
854
+ raw = page_text[start:end]
855
+ cleaned = " ".join(raw.split())
856
+ if start > 0:
857
+ cleaned = "..." + cleaned
858
+ if end < len(page_text):
859
+ cleaned = cleaned + "..."
860
+ return cleaned
861
+
862
+
863
+ def grep_cached_item(
864
+ identifier: str,
865
+ djvu_text: str,
866
+ page_index: dict,
867
+ compiled: re.Pattern[str],
868
+ *,
869
+ context_chars: int,
870
+ limit: int,
871
+ ) -> tuple[list[dict], int]:
872
+ """Search cached page-delimited text line by line without DOTALL backtracking."""
873
+ hits: list[dict] = []
874
+ total_matches = 0
875
+ pages = djvu_text.split("\x0c")
876
+
877
+ for seg_idx, page_text in enumerate(pages):
878
+ if not page_text or not compiled.search(page_text):
879
+ continue
880
+ # Search line by line on matching pages so multi-line DOTALL backtracking cannot happen.
881
+ offset = 0
882
+ for line in page_text.splitlines(keepends=True):
883
+ for match in compiled.finditer(line):
884
+ total_matches += 1
885
+ if len(hits) < limit:
886
+ leaf_n, scandata_leaf, printed_page = resolve_segment_page(seg_idx, page_index)
887
+ m_start = offset + match.start()
888
+ m_end = offset + match.end()
889
+ hits.append(
890
+ {
891
+ "identifier": identifier,
892
+ "leaf": leaf_n,
893
+ "scandata_leaf": scandata_leaf,
894
+ "printed_page": printed_page,
895
+ "match": match.group(0),
896
+ "snippet": extract_snippet(page_text, m_start, m_end, context_chars),
897
+ "image_url": page_image_url(identifier, leaf_n, scale=2)
898
+ if leaf_n is not None
899
+ else None,
900
+ "details_url": page_details_url(identifier, leaf_n)
901
+ if leaf_n is not None
902
+ else item_url(identifier),
903
+ }
904
+ )
905
+ offset += len(line)
906
+ return hits, total_matches
907
+
908
+
909
+ def resolve_printed_page_to_leaf(page_index: dict, printed_page: str) -> tuple[int, int | None]:
910
+ target = printed_page.strip()
911
+ p2b = page_index.get("printed_to_bookreader") or {}
912
+ if target in p2b:
913
+ br_n = int(p2b[target])
914
+ sc_leaf = page_index.get("bookreader_to_scandata", {}).get(str(br_n))
915
+ return br_n, sc_leaf
916
+ p2b_ci = page_index.get("printed_to_bookreader_ci") or {}
917
+ lower = target.lower()
918
+ if lower in p2b_ci:
919
+ br_n = int(p2b_ci[lower])
920
+ sc_leaf = page_index.get("bookreader_to_scandata", {}).get(str(br_n))
921
+ return br_n, sc_leaf
922
+ # Fallback to scandata_to_printed when access mapping is absent
923
+ p2s = page_index.get("printed_to_scandata") or {}
924
+ if target in p2s:
925
+ sc_leaf = int(p2s[target])
926
+ return sc_leaf, sc_leaf
927
+ sample_pages = list(p2b.keys())
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
+ )
933
+ raise KeyError(f"Printed page {printed_page!r} not found in page_index.json{hint}")
934
+
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
+
1120
+ def cmd_search(args: argparse.Namespace) -> int:
1121
+ query = args.query
1122
+ if args.mediatype:
1123
+ query = f"{query} AND mediatype:({args.mediatype})"
1124
+ chosen = list(args.fields) if args.fields else DEFAULT_FIELDS
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
+ )
1135
+ response = data.get("response") or {}
1136
+ if args.as_json:
1137
+ print(json.dumps(data, indent=2))
1138
+ return 0
1139
+ status = "cache-hit" if cached else "fetched"
1140
+ print(f"{response.get('numFound')} items ({status})")
1141
+ for doc in response.get("docs") or []:
1142
+ identifier = doc.get("identifier") or ""
1143
+ title = doc.get("title") or ""
1144
+ creator = doc.get("creator") or ""
1145
+ date = doc.get("date") or ""
1146
+ mediatype_out = doc.get("mediatype") or ""
1147
+ print(
1148
+ f"{identifier} | {title} | {creator} | {date} | "
1149
+ f"{mediatype_out} | {item_url(identifier)}"
1150
+ )
1151
+ return 0
1152
+
1153
+
1154
+ def cmd_get(args: argparse.Namespace) -> int:
1155
+ identifier = validate_identifier(args.identifier)
1156
+ data, cached = metadata_api(identifier, timeout=args.timeout, refresh=args.refresh)
1157
+ if args.as_json:
1158
+ print(json.dumps(data, indent=2))
1159
+ return 0
1160
+ meta = data.get("metadata") or {}
1161
+ status = "cache-hit" if cached else "fetched"
1162
+ print(f"{meta.get('title') or identifier}")
1163
+ print(f" Identifier: {meta.get('identifier')}")
1164
+ if meta.get("creator"):
1165
+ print(f" Creator: {meta.get('creator')}")
1166
+ if meta.get("date"):
1167
+ print(f" Date: {meta.get('date')}")
1168
+ if meta.get("mediatype"):
1169
+ print(f" Mediatype: {meta.get('mediatype')}")
1170
+ if meta.get("collection"):
1171
+ collection = meta.get("collection")
1172
+ if isinstance(collection, list):
1173
+ collection = ", ".join(collection)
1174
+ print(f" Collection: {collection}")
1175
+ if meta.get("description"):
1176
+ print(f" Description: {short(meta.get('description'))}")
1177
+ file_list = data.get("files") or []
1178
+ print(f" Files: {len(file_list)} | {item_url(identifier)} ({status})")
1179
+ if args.files:
1180
+ for entry in file_list:
1181
+ size = entry.get("size") or ""
1182
+ print(f" {entry.get('name')} | {entry.get('format')} | {size} bytes")
1183
+ return 0
1184
+
1185
+
1186
+ def cmd_download(args: argparse.Namespace) -> int:
1187
+ identifier = validate_identifier(args.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
+ )
1204
+ file_list = data.get("files") or []
1205
+ if args.list_only or not args.files:
1206
+ for entry in file_list:
1207
+ size = entry.get("size") or ""
1208
+ print(f"{entry.get('name')} | {entry.get('format')} | {size} bytes")
1209
+ return 0
1210
+
1211
+ by_name = {entry.get("name"): entry for entry in file_list if entry.get("name")}
1212
+ out_dir = Path(args.out)
1213
+ out_dir.mkdir(parents=True, exist_ok=True)
1214
+ for name, rel in validated_names:
1215
+ file_entry = by_name.get(name)
1216
+ if file_entry is None:
1217
+ fail(f"File not in item {identifier}: {name}")
1218
+ try:
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)
1230
+ except (RuntimeError, FileNotFoundError) as exc:
1231
+ fail(str(exc))
1232
+ dest = out_dir / rel.name
1233
+ atomic_write_bytes(dest, content)
1234
+ status = "cache-hit" if cached else "fetched"
1235
+ print(f"{dest} ({len(content)} bytes, {status})")
1236
+ return 0
1237
+
1238
+
1239
+ def cmd_fulltext(args: argparse.Namespace) -> int:
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
+ )
1248
+ if args.as_json:
1249
+ print(json.dumps(data, indent=2, ensure_ascii=False))
1250
+ return 0
1251
+ hits_block = ((data.get("response") or {}).get("body") or {}).get("hits") or {}
1252
+ total = hits_block.get("total", 0)
1253
+ hits = hits_block.get("hits") or []
1254
+ status = "cache-hit" if cached else "fetched"
1255
+ print(f"{total} full-text matches (showing {len(hits)}, {status})")
1256
+ for hit in hits:
1257
+ fields = hit.get("fields") or {}
1258
+ identifier = fields.get("identifier") or ""
1259
+ title = fields.get("title") or ""
1260
+ year = fields.get("year") or fields.get("date") or ""
1261
+ snippets = (hit.get("highlight") or {}).get("text") or []
1262
+ snippet = short(snippets[0].replace("{{{", "").replace("}}}", ""), 200) if snippets else ""
1263
+ print(f"- {identifier} | {title} | {year} | {item_url(identifier)}")
1264
+ if snippet:
1265
+ print(f" OCR: {snippet}")
1266
+ return 0
1267
+
1268
+
1269
+ def cmd_grep(args: argparse.Namespace) -> int:
1270
+ t0 = time.perf_counter()
1271
+ flags = re.IGNORECASE if args.ignore_case else 0
1272
+ try:
1273
+ compiled = re.compile(args.pattern, flags)
1274
+ except re.error as exc:
1275
+ fail(f"Invalid regex pattern {args.pattern!r}: {exc}", code=2)
1276
+
1277
+ identifiers = [validate_identifier(item) for item in args.identifiers]
1278
+ cache_root = get_cache_root()
1279
+
1280
+ # Fetch missing items in parallel (max_workers=6, timeout=25).
1281
+ def prepare(item_id: str) -> dict:
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
+ )
1289
+
1290
+ if len(identifiers) == 1:
1291
+ try:
1292
+ cache_entries = [prepare(identifiers[0])]
1293
+ except Exception as exc:
1294
+ fail(str(exc))
1295
+ else:
1296
+ from concurrent.futures import ThreadPoolExecutor
1297
+
1298
+ cache_entries = []
1299
+ with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(identifiers))) as pool:
1300
+ futures = [(item_id, pool.submit(prepare, item_id)) for item_id in identifiers]
1301
+ for item_id, fut in futures:
1302
+ try:
1303
+ cache_entries.append(fut.result())
1304
+ except Exception as exc:
1305
+ fail(f"{item_id}: {exc}")
1306
+
1307
+ all_hits: list[dict] = []
1308
+ item_summaries: list[dict] = []
1309
+ remaining = max(0, args.limit)
1310
+ total_matches = 0
1311
+ all_cached = True
1312
+
1313
+ for entry in cache_entries:
1314
+ item_id = entry["identifier"]
1315
+ was_cached = bool(entry["cached"])
1316
+ all_cached = all_cached and was_cached
1317
+ page_index = json.loads(entry["page_index_path"].read_text(encoding="utf-8"))
1318
+ djvu_text = entry["djvu_path"].read_text(encoding="utf-8", errors="replace")
1319
+ hits, item_total = grep_cached_item(
1320
+ item_id,
1321
+ djvu_text,
1322
+ page_index,
1323
+ compiled,
1324
+ context_chars=args.context,
1325
+ limit=remaining,
1326
+ )
1327
+ for h in hits:
1328
+ h["cached"] = was_cached
1329
+ all_hits.extend(hits)
1330
+ remaining = max(0, args.limit - len(all_hits))
1331
+ total_matches += item_total
1332
+ item_summaries.append(
1333
+ {
1334
+ "identifier": item_id,
1335
+ "cached": was_cached,
1336
+ "matches": item_total,
1337
+ "returned": len(hits),
1338
+ "cache_dir": str(entry["item_dir"]),
1339
+ }
1340
+ )
1341
+
1342
+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2)
1343
+ payload = {
1344
+ "pattern": args.pattern,
1345
+ "ignore_case": bool(args.ignore_case),
1346
+ "cached": all_cached,
1347
+ "elapsed_ms": elapsed_ms,
1348
+ "total_matches": total_matches,
1349
+ "returned": len(all_hits),
1350
+ "items": item_summaries,
1351
+ "hits": all_hits,
1352
+ }
1353
+
1354
+ if args.as_json:
1355
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
1356
+ return 0
1357
+
1358
+ status = "cache-hit" if all_cached else "fetched"
1359
+ print(f"{total_matches} matches across {len(identifiers)} item(s) (showing {len(all_hits)}, {status}, {elapsed_ms} ms)")
1360
+ for hit in all_hits:
1361
+ pp = f"p.{hit['printed_page']}" if hit["printed_page"] else "p.?"
1362
+ lf = f"n{hit['leaf']}" if hit["leaf"] is not None else "n?"
1363
+ print(f"- {hit['identifier']} | {lf} ({pp}) | {hit['image_url'] or hit['details_url']}")
1364
+ print(f" {hit['snippet']}")
1365
+ return 0
1366
+
1367
+
1368
+ def cmd_page(args: argparse.Namespace) -> int:
1369
+ t0 = time.perf_counter()
1370
+ identifier = validate_identifier(args.identifier)
1371
+ cache_root = get_cache_root()
1372
+
1373
+ # Support both legacy positional `<leaf>` and new `--leaf` / `--printed-page`.
1374
+ leaf_from_pos = args.leaf_pos
1375
+ leaf_from_flag = args.leaf
1376
+ printed_page = args.printed_page
1377
+
1378
+ if printed_page is not None and (leaf_from_pos is not None or leaf_from_flag is not None):
1379
+ fail("Pass either --printed-page or --leaf (not both).", code=2)
1380
+ if leaf_from_pos is not None and leaf_from_flag is not None:
1381
+ fail("Pass either positional <leaf> or --leaf (not both).", code=2)
1382
+
1383
+ target_leaf: int | None = leaf_from_flag if leaf_from_flag is not None else leaf_from_pos
1384
+ scandata_leaf: int | None = None
1385
+ resolved_printed: str | None = printed_page
1386
+ index_cached: bool | None = None
1387
+
1388
+ if printed_page is not None:
1389
+ try:
1390
+ cache_entry = ensure_item_cache(
1391
+ identifier,
1392
+ need_djvu=False,
1393
+ cache_root=cache_root,
1394
+ timeout=args.timeout,
1395
+ refresh=args.refresh,
1396
+ )
1397
+ index_cached = bool(cache_entry["cached"])
1398
+ page_index = json.loads(cache_entry["page_index_path"].read_text(encoding="utf-8"))
1399
+ target_leaf, scandata_leaf = resolve_printed_page_to_leaf(page_index, printed_page)
1400
+ except Exception as exc:
1401
+ fail(str(exc))
1402
+ elif target_leaf is None:
1403
+ fail("Specify a target page with --printed-page <str>, --leaf <int>, or positional <leaf>.", code=2)
1404
+
1405
+ assert target_leaf is not None
1406
+ if target_leaf < 0:
1407
+ fail(f"Leaf index must be >= 0, got {target_leaf}.", code=2)
1408
+
1409
+ # Determine URL: explicit --scale uses _s<scale>.jpg; otherwise --width uses _w<width>.jpg.
1410
+ if args.scale is not None:
1411
+ url = page_image_url(identifier, target_leaf, scale=args.scale)
1412
+ suffix_tag = f"s{args.scale}"
1413
+ else:
1414
+ width = args.width if args.width is not None else 2400
1415
+ url = page_image_url(identifier, target_leaf, width=width)
1416
+ suffix_tag = f"w{width}"
1417
+
1418
+ try:
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
+ )
1428
+ except (RuntimeError, FileNotFoundError) as exc:
1429
+ fail(str(exc))
1430
+
1431
+ out_path = Path(args.out)
1432
+ if out_path.suffix.lower() in IMAGE_EXTS and not out_path.is_dir():
1433
+ dest = out_path
1434
+ else:
1435
+ out_path.mkdir(parents=True, exist_ok=True)
1436
+ dest = out_path / f"{identifier}_n{target_leaf}_{suffix_tag}.jpg"
1437
+
1438
+ if dest.resolve() != page_cache_path.resolve():
1439
+ atomic_write_bytes(dest, content)
1440
+
1441
+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2)
1442
+ payload = {
1443
+ "identifier": identifier,
1444
+ "leaf": target_leaf,
1445
+ "scandata_leaf": scandata_leaf,
1446
+ "printed_page": resolved_printed,
1447
+ "url": url,
1448
+ "path": str(dest),
1449
+ "cache_path": str(page_cache_path),
1450
+ "bytes": len(content),
1451
+ "index_cached": index_cached,
1452
+ "page_cached": page_cached,
1453
+ "elapsed_ms": elapsed_ms,
1454
+ }
1455
+ if args.as_json:
1456
+ print(json.dumps(payload, indent=2))
1457
+ else:
1458
+ extra = f" [p.{resolved_printed} -> n{target_leaf}]" if resolved_printed is not None else f" [n{target_leaf}]"
1459
+ status = "cache-hit" if page_cached else "fetched"
1460
+ print(f"{dest} ({len(content)} bytes){extra} ({status})")
1461
+ return 0
1462
+
1463
+
1464
+ def cmd_url(args: argparse.Namespace) -> int:
1465
+ full = args.query
1466
+ if args.mediatype:
1467
+ full = f"{args.query} AND mediatype:({args.mediatype})"
1468
+ print(f"{ADVANCED_SEARCH}?q={quote(full)}")
1469
+ return 0
1470
+
1471
+
1472
+ def build_parser() -> argparse.ArgumentParser:
1473
+ parser = argparse.ArgumentParser(
1474
+ prog="archive-org",
1475
+ description="Search, inspect, grep cached OCR, and download pages from Internet Archive.",
1476
+ )
1477
+ sub = parser.add_subparsers(dest="command", required=True)
1478
+
1479
+ p_search = sub.add_parser("search", help="Search items with a Lucene query.")
1480
+ p_search.add_argument("query")
1481
+ p_search.add_argument("--mediatype", default=None, help="e.g. texts, movies, audio, software, collection.")
1482
+ p_search.add_argument("--rows", type=int, default=10, help="Results per page (default: 10).")
1483
+ p_search.add_argument("--page", type=int, default=1, help="Results page (default: 1).")
1484
+ p_search.add_argument("--sort", dest="sorts", action="append", default=[], help="Repeatable, e.g. --sort 'downloads desc'.")
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.")
1488
+ p_search.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
1489
+ p_search.set_defaults(func=cmd_search)
1490
+
1491
+ p_get = sub.add_parser("get", help="Read an item's metadata and file list by identifier.")
1492
+ p_get.add_argument("identifier")
1493
+ p_get.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
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.")
1497
+ p_get.set_defaults(func=cmd_get)
1498
+
1499
+ p_dl = sub.add_parser("download", help="Download files of an item, or list them with no FILE given.")
1500
+ p_dl.add_argument("identifier")
1501
+ p_dl.add_argument("files", nargs="*")
1502
+ p_dl.add_argument("--out", default=".", help="Directory to save files into (default: .).")
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.")
1506
+ p_dl.set_defaults(func=cmd_download)
1507
+
1508
+ p_ft = sub.add_parser("fulltext", help="Search OCR full text across digitized books and periodicals.")
1509
+ p_ft.add_argument("query")
1510
+ p_ft.add_argument("--rows", type=int, default=10, help="Hits per page (default: 10).")
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.")
1514
+ p_ft.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
1515
+ p_ft.set_defaults(func=cmd_fulltext)
1516
+
1517
+ p_grep = sub.add_parser("grep", help="Search cached full-text OCR inside one or more items with exact page mapping.")
1518
+ p_grep.add_argument("identifiers", nargs="+", help="One or more Internet Archive item identifiers.")
1519
+ p_grep.add_argument("--pattern", required=True, help="Regular expression pattern (searched line by line).")
1520
+ p_grep.add_argument("--context", type=int, default=240, help="Context characters per hit snippet (default: 240).")
1521
+ p_grep.add_argument("--limit", type=int, default=25, help="Maximum hits returned (default: 25).")
1522
+ p_grep.add_argument("-i", "--ignore-case", action="store_true", help="Case-insensitive regex matching.")
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.")
1525
+ p_grep.add_argument("--json", dest="as_json", action="store_true", help="Structured JSON output.")
1526
+ p_grep.set_defaults(func=cmd_grep)
1527
+
1528
+ p_page = sub.add_parser("page", help="Download one rendered page JPEG by printed page number or BookReader leaf.")
1529
+ p_page.add_argument("identifier")
1530
+ p_page.add_argument("leaf_pos", nargs="?", type=int, default=None, help="Legacy positional BookReader leaf index.")
1531
+ p_page.add_argument("--printed-page", default=None, help="Printed page label resolved via cached page_index.json.")
1532
+ p_page.add_argument("--leaf", type=int, default=None, help="BookReader leaf index (n<LEAF>).")
1533
+ p_page.add_argument("--scale", type=int, default=None, help="BookReader scale factor (e.g. 1=full, 2=half, 4=quarter).")
1534
+ p_page.add_argument("--width", type=int, default=None, help="Rendered JPEG width in pixels (default 2400 when --scale is omitted).")
1535
+ p_page.add_argument("--out", default=".", help="Output file path (.jpg) or directory (default: .).")
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.")
1538
+ p_page.add_argument("--json", dest="as_json", action="store_true", help="Structured JSON output.")
1539
+ p_page.set_defaults(func=cmd_page)
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
+
1561
+ p_url = sub.add_parser("url", help="Print the website advanced-search URL for a query.")
1562
+ p_url.add_argument("query")
1563
+ p_url.add_argument("--mediatype", default=None)
1564
+ p_url.set_defaults(func=cmd_url)
1565
+
1566
+ return parser
1567
+
1568
+
1569
+ def main(argv: list[str] | None = None) -> int:
1570
+ parser = build_parser()
1571
+ args = parser.parse_args(argv)
1572
+ return int(args.func(args))
1573
+
1574
+
1575
+ if __name__ == "__main__":
1576
+ raise SystemExit(main())