@kinloom/cli 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/assets/cached-ocr.py +556 -0
  2. package/dist/assets/ocr.md +52 -0
  3. package/dist/assets/prep-scan.md +59 -0
  4. package/dist/assets/prep-scan.py +891 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +94 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +268 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +129 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +879 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +120 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +373 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +100 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +250 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +116 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +520 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +110 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +194 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +123 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +358 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +111 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +346 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +100 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +528 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +118 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +934 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +118 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +585 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +90 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +432 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +93 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +441 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +101 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +391 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +89 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +254 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +104 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +466 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +148 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +219 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +383 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.js +1 -1
  49. package/dist/commands/ops/audit.d.ts +138 -0
  50. package/dist/commands/ops/audit.d.ts.map +1 -0
  51. package/dist/commands/ops/audit.js +867 -0
  52. package/dist/commands/ops/audit.js.map +1 -0
  53. package/dist/commands/ops/context.d.ts +100 -0
  54. package/dist/commands/ops/context.d.ts.map +1 -0
  55. package/dist/commands/ops/context.js +917 -0
  56. package/dist/commands/ops/context.js.map +1 -0
  57. package/dist/commands/ops/help.d.ts +6 -0
  58. package/dist/commands/ops/help.d.ts.map +1 -0
  59. package/dist/commands/ops/help.js +74 -0
  60. package/dist/commands/ops/help.js.map +1 -0
  61. package/dist/commands/ops/index.d.ts +6 -0
  62. package/dist/commands/ops/index.d.ts.map +1 -0
  63. package/dist/commands/ops/index.js +6 -0
  64. package/dist/commands/ops/index.js.map +1 -0
  65. package/dist/commands/ops/integrate.d.ts +56 -0
  66. package/dist/commands/ops/integrate.d.ts.map +1 -0
  67. package/dist/commands/ops/integrate.js +872 -0
  68. package/dist/commands/ops/integrate.js.map +1 -0
  69. package/dist/commands/ops/sync.d.ts +177 -0
  70. package/dist/commands/ops/sync.d.ts.map +1 -0
  71. package/dist/commands/ops/sync.js +1078 -0
  72. package/dist/commands/ops/sync.js.map +1 -0
  73. package/dist/commands/ops/telemetry.d.ts +79 -0
  74. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  75. package/dist/commands/ops/telemetry.js +249 -0
  76. package/dist/commands/ops/telemetry.js.map +1 -0
  77. package/dist/commands/records/help.d.ts +18 -0
  78. package/dist/commands/records/help.d.ts.map +1 -0
  79. package/dist/commands/records/help.js +174 -0
  80. package/dist/commands/records/help.js.map +1 -0
  81. package/dist/commands/records/index.d.ts +5 -0
  82. package/dist/commands/records/index.d.ts.map +1 -0
  83. package/dist/commands/records/index.js +5 -0
  84. package/dist/commands/records/index.js.map +1 -0
  85. package/dist/commands/records/registry.d.ts +32 -0
  86. package/dist/commands/records/registry.d.ts.map +1 -0
  87. package/dist/commands/records/registry.js +227 -0
  88. package/dist/commands/records/registry.js.map +1 -0
  89. package/dist/commands/records/resolve.d.ts +14 -0
  90. package/dist/commands/records/resolve.d.ts.map +1 -0
  91. package/dist/commands/records/resolve.js +61 -0
  92. package/dist/commands/records/resolve.js.map +1 -0
  93. package/dist/commands/records/runner.d.ts +25 -0
  94. package/dist/commands/records/runner.d.ts.map +1 -0
  95. package/dist/commands/records/runner.js +224 -0
  96. package/dist/commands/records/runner.js.map +1 -0
  97. package/dist/index.d.ts +2 -0
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +2 -0
  100. package/dist/index.js.map +1 -1
  101. package/package.json +3 -3
@@ -0,0 +1,879 @@
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 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
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import re
16
+ import sys
17
+ import time
18
+ from urllib.parse import quote, urlencode
19
+
20
+ BASE = "https://archive.org"
21
+ ADVANCED_SEARCH = f"{BASE}/advancedsearch.php"
22
+ FULLTEXT_SEARCH = f"{BASE}/services/search/beta/page_production/"
23
+ USER_AGENT = "kinloom archive-org skill (research use)"
24
+ DEFAULT_FIELDS = ["identifier", "title", "creator", "date", "mediatype"]
25
+ DEFAULT_TIMEOUT = 25.0
26
+ SEARCH_TIMEOUT = 45.0
27
+ MAX_WORKERS = 6
28
+ SAFE_ID_RE = re.compile(r"^[A-Za-z0-9._-]+$")
29
+ IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
30
+
31
+
32
+ def get_cache_root() -> Path:
33
+ override = os.environ.get("KINLOOM_IA_CACHE_DIR")
34
+ if override:
35
+ return Path(override).expanduser()
36
+ return Path.home() / ".cache" / "kinloom-ia"
37
+
38
+
39
+ def validate_identifier(identifier: str) -> str:
40
+ cleaned = identifier.strip()
41
+ if not cleaned or not SAFE_ID_RE.match(cleaned) or cleaned in (".", ".."):
42
+ fail(f"Invalid Internet Archive identifier: {identifier!r}")
43
+ return cleaned
44
+
45
+
46
+ def fail(message: str, code: int = 1) -> None:
47
+ sys.stderr.write(f"{message}\n")
48
+ raise SystemExit(code)
49
+
50
+
51
+ def atomic_write_bytes(dest: Path, data: bytes) -> None:
52
+ dest.parent.mkdir(parents=True, exist_ok=True)
53
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
54
+ try:
55
+ tmp.write_bytes(data)
56
+ os.replace(tmp, dest)
57
+ except Exception:
58
+ if tmp.exists():
59
+ tmp.unlink(missing_ok=True)
60
+ raise
61
+
62
+
63
+ def atomic_write_text(dest: Path, text: str) -> None:
64
+ atomic_write_bytes(dest, text.encode("utf-8"))
65
+
66
+
67
+ def atomic_write_json(dest: Path, payload: object) -> None:
68
+ atomic_write_text(dest, json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
69
+
70
+
71
+ def http_get_bytes(url: str, timeout: float = DEFAULT_TIMEOUT) -> bytes:
72
+ from urllib.error import HTTPError, URLError
73
+ from urllib.request import Request, urlopen
74
+
75
+ 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
89
+
90
+
91
+ def http_get_json(url: str, timeout: float = DEFAULT_TIMEOUT) -> dict:
92
+ raw = http_get_bytes(url, timeout=timeout)
93
+ try:
94
+ data = json.loads(raw.decode("utf-8"))
95
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
96
+ raise RuntimeError(f"Invalid JSON response from {url}: {exc}") from exc
97
+ if not isinstance(data, dict):
98
+ raise RuntimeError(f"Expected JSON object from {url}")
99
+ return data
100
+
101
+
102
+ def fulltext_api(query: str, rows: int, page: int) -> dict:
103
+ qs = urlencode(
104
+ [
105
+ ("user_query", query),
106
+ ("service_backend", "fts"),
107
+ ("hits_per_page", str(rows)),
108
+ ("page", str(page)),
109
+ ]
110
+ )
111
+ try:
112
+ return http_get_json(f"{FULLTEXT_SEARCH}?{qs}", timeout=SEARCH_TIMEOUT)
113
+ except (RuntimeError, FileNotFoundError) as exc:
114
+ fail(str(exc))
115
+ return {}
116
+
117
+
118
+ def search_api(query: str, fields: list[str], rows: int, page: int, sorts: list[str]) -> dict:
119
+ params: list[tuple[str, str]] = [
120
+ ("q", query),
121
+ ("output", "json"),
122
+ ("rows", str(rows)),
123
+ ]
124
+ if page > 1:
125
+ params.append(("page", str(page)))
126
+ for field in fields:
127
+ params.append(("fl[]", field))
128
+ for sort in sorts:
129
+ params.append(("sort[]", sort))
130
+ qs = urlencode(params)
131
+ try:
132
+ return http_get_json(f"{ADVANCED_SEARCH}?{qs}", timeout=SEARCH_TIMEOUT)
133
+ except (RuntimeError, FileNotFoundError) as exc:
134
+ fail(str(exc))
135
+ return {}
136
+
137
+
138
+ def metadata_api(identifier: str, timeout: float = DEFAULT_TIMEOUT) -> dict:
139
+ url = f"{BASE}/metadata/{quote(identifier)}"
140
+ try:
141
+ data = http_get_json(url, timeout=timeout)
142
+ except FileNotFoundError:
143
+ fail(f"No item with identifier {identifier}")
144
+ except RuntimeError as exc:
145
+ 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
149
+
150
+
151
+ def item_url(identifier: str) -> str:
152
+ return f"{BASE}/details/{quote(identifier)}"
153
+
154
+
155
+ def page_image_url(identifier: str, leaf_n: int, *, scale: int | None = None, width: int | None = None) -> str:
156
+ if width is not None:
157
+ return f"{BASE}/download/{quote(identifier)}/page/n{leaf_n}_w{width}.jpg"
158
+ effective_scale = scale if scale is not None else 2
159
+ return f"{BASE}/download/{quote(identifier)}/page/n{leaf_n}_s{effective_scale}.jpg"
160
+
161
+
162
+ def page_details_url(identifier: str, leaf_n: int) -> str:
163
+ return f"{BASE}/details/{quote(identifier)}/page/n{leaf_n}"
164
+
165
+
166
+ def short(text: object, limit: int = 300) -> str:
167
+ if not text:
168
+ return ""
169
+ cleaned = " ".join(str(text).split())
170
+ if len(cleaned) <= limit:
171
+ return cleaned
172
+ return cleaned[:limit].rstrip() + " ..."
173
+
174
+
175
+ def find_item_file(files: list[dict], *, suffixes: tuple[str, ...], formats: tuple[str, ...] = ()) -> str | None:
176
+ for entry in files:
177
+ name = entry.get("name") or ""
178
+ if any(name.endswith(suf) for suf in suffixes):
179
+ return str(name)
180
+ if formats:
181
+ fmt_set = {f.lower() for f in formats}
182
+ for entry in files:
183
+ fmt = str(entry.get("format") or "").lower()
184
+ name = entry.get("name") or ""
185
+ if fmt in fmt_set and name:
186
+ return str(name)
187
+ return None
188
+
189
+
190
+ def parse_scandata_xml(xml_bytes: bytes) -> dict:
191
+ """Parse scandata.xml into compact bidirectional leaf/page lookup tables.
192
+
193
+ Internet Archive BookReader `/page/n<N>` indexes 0-based over leaves with
194
+ `addToAccessFormats == true` (excluding deleted leaves). Storing both raw
195
+ `leafNum` and BookReader `n` eliminates off-by-one page offset bugs.
196
+ """
197
+ import xml.etree.ElementTree as ET
198
+
199
+ root = ET.fromstring(xml_bytes)
200
+ pages = root.findall(".//pageData/page")
201
+ scandata_to_bookreader: dict[str, int] = {}
202
+ bookreader_to_scandata: dict[str, int] = {}
203
+ scandata_to_printed: dict[str, str] = {}
204
+ bookreader_to_printed: dict[str, str] = {}
205
+ printed_to_bookreader: dict[str, int] = {}
206
+ printed_to_bookreader_ci: dict[str, int] = {}
207
+ printed_to_scandata: dict[str, int] = {}
208
+
209
+ access_idx = 0
210
+ for seq_idx, page_el in enumerate(pages):
211
+ raw_leaf = page_el.attrib.get("leafNum")
212
+ try:
213
+ leaf_num = int(raw_leaf) if raw_leaf is not None else seq_idx
214
+ except ValueError:
215
+ leaf_num = seq_idx
216
+ page_type = (page_el.findtext("pageType") or "").strip()
217
+ add_access_raw = page_el.findtext("addToAccessFormats")
218
+ if add_access_raw is not None:
219
+ in_access = add_access_raw.strip().lower() == "true"
220
+ else:
221
+ in_access = page_type.lower() != "delete"
222
+
223
+ printed = (page_el.findtext("pageNumber") or "").strip()
224
+ leaf_key = str(leaf_num)
225
+ if printed:
226
+ scandata_to_printed[leaf_key] = printed
227
+ printed_to_scandata.setdefault(printed, leaf_num)
228
+
229
+ if in_access:
230
+ br_n = access_idx
231
+ access_idx += 1
232
+ scandata_to_bookreader[leaf_key] = br_n
233
+ bookreader_to_scandata[str(br_n)] = leaf_num
234
+ if printed:
235
+ bookreader_to_printed[str(br_n)] = printed
236
+ printed_to_bookreader.setdefault(printed, br_n)
237
+ printed_to_bookreader_ci.setdefault(printed.lower(), br_n)
238
+
239
+ return {
240
+ "leaf_count": len(pages),
241
+ "access_leaf_count": access_idx,
242
+ "scandata_to_bookreader": scandata_to_bookreader,
243
+ "bookreader_to_scandata": bookreader_to_scandata,
244
+ "scandata_to_printed": scandata_to_printed,
245
+ "bookreader_to_printed": bookreader_to_printed,
246
+ "printed_to_bookreader": printed_to_bookreader,
247
+ "printed_to_bookreader_ci": printed_to_bookreader_ci,
248
+ "printed_to_scandata": printed_to_scandata,
249
+ "segment_mode": "scandata",
250
+ }
251
+
252
+
253
+ def empty_page_index() -> dict:
254
+ return {
255
+ "leaf_count": 0,
256
+ "access_leaf_count": 0,
257
+ "scandata_to_bookreader": {},
258
+ "bookreader_to_scandata": {},
259
+ "scandata_to_printed": {},
260
+ "bookreader_to_printed": {},
261
+ "printed_to_bookreader": {},
262
+ "printed_to_bookreader_ci": {},
263
+ "printed_to_scandata": {},
264
+ "segment_mode": "bookreader",
265
+ }
266
+
267
+
268
+ def synthesize_djvu_from_hocr(searchtext_gz: bytes, pageindex_gz: bytes) -> str:
269
+ import gzip
270
+
271
+ text = gzip.decompress(searchtext_gz).decode("utf-8", errors="replace")
272
+ offsets = json.loads(gzip.decompress(pageindex_gz).decode("utf-8"))
273
+ if not isinstance(offsets, list) or not offsets:
274
+ return text
275
+ segments: list[str] = []
276
+ text_len = len(text)
277
+ for row in offsets:
278
+ if isinstance(row, list) and len(row) >= 2:
279
+ start = max(0, min(int(row[0]), text_len))
280
+ end = max(start, min(int(row[1]), text_len))
281
+ segments.append(text[start:end].replace("\x0c", " "))
282
+ else:
283
+ segments.append("")
284
+ return "\x0c".join(segments)
285
+
286
+
287
+ def ensure_item_cache(
288
+ identifier: str,
289
+ *,
290
+ need_djvu: bool,
291
+ cache_root: Path | None = None,
292
+ timeout: float = DEFAULT_TIMEOUT,
293
+ ) -> dict:
294
+ """Populate and return cached metadata, page_index, and optional djvu.txt."""
295
+ item_id = validate_identifier(identifier)
296
+ root = cache_root if cache_root is not None else get_cache_root()
297
+ item_dir = root / item_id
298
+ meta_path = item_dir / "metadata.json"
299
+ scandata_path = item_dir / "scandata.xml"
300
+ page_index_path = item_dir / "page_index.json"
301
+ djvu_path = item_dir / "djvu.txt"
302
+
303
+ has_meta = meta_path.is_file()
304
+ has_page_index = page_index_path.is_file()
305
+ has_djvu = djvu_path.is_file()
306
+
307
+ if has_meta and has_page_index and (not need_djvu or has_djvu):
308
+ return {
309
+ "identifier": item_id,
310
+ "item_dir": item_dir,
311
+ "metadata_path": meta_path,
312
+ "scandata_path": scandata_path,
313
+ "page_index_path": page_index_path,
314
+ "djvu_path": djvu_path,
315
+ "cached": True,
316
+ }
317
+
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)}"
343
+
344
+ fetched: dict[str, bytes] = {}
345
+ fetch_errors: dict[str, Exception] = {}
346
+ if tasks:
347
+ from concurrent.futures import ThreadPoolExecutor
348
+
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
358
+
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)
369
+ 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
381
+ access_count = int(page_index.get("access_leaf_count") or 0)
382
+ leaf_count = int(page_index.get("leaf_count") or 0)
383
+ if access_count and abs(seg_count - access_count) < abs(seg_count - leaf_count):
384
+ segment_mode = "bookreader"
385
+ else:
386
+ segment_mode = "scandata"
387
+ elif "hocr_text" in fetched and "hocr_idx" in fetched:
388
+ djvu_text = synthesize_djvu_from_hocr(fetched["hocr_text"], fetched["hocr_idx"])
389
+ segment_mode = "scandata"
390
+ else:
391
+ djvu_text = decoded
392
+ 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)
408
+
409
+ return {
410
+ "identifier": item_id,
411
+ "item_dir": item_dir,
412
+ "metadata_path": meta_path,
413
+ "scandata_path": scandata_path,
414
+ "page_index_path": page_index_path,
415
+ "djvu_path": djvu_path,
416
+ "cached": False,
417
+ }
418
+
419
+
420
+ def resolve_segment_page(seg_idx: int, page_index: dict) -> tuple[int | None, int | None, str | None]:
421
+ """Map a 0-based `\x0c` segment index to (bookreader_leaf_n, scandata_leaf, printed_page)."""
422
+ mode = page_index.get("segment_mode", "scandata")
423
+ if mode == "flat":
424
+ return None, None, None
425
+ key = str(seg_idx)
426
+ if mode == "bookreader":
427
+ scandata_leaf = page_index.get("bookreader_to_scandata", {}).get(key)
428
+ printed = page_index.get("bookreader_to_printed", {}).get(key)
429
+ return seg_idx, scandata_leaf, printed
430
+ # scandata leaf indexing (e.g. hocr_pageindex or full-leaf djvu.txt)
431
+ scandata_to_br = page_index.get("scandata_to_bookreader", {})
432
+ br_n = scandata_to_br.get(key)
433
+ if br_n is None and not scandata_to_br:
434
+ br_n = seg_idx
435
+ printed = page_index.get("scandata_to_printed", {}).get(key)
436
+ return br_n, seg_idx, printed
437
+
438
+
439
+ def extract_snippet(page_text: str, match_start: int, match_end: int, context_chars: int) -> str:
440
+ half = max(20, context_chars // 2)
441
+ start = max(0, match_start - half)
442
+ end = min(len(page_text), match_end + half)
443
+ raw = page_text[start:end]
444
+ cleaned = " ".join(raw.split())
445
+ if start > 0:
446
+ cleaned = "..." + cleaned
447
+ if end < len(page_text):
448
+ cleaned = cleaned + "..."
449
+ return cleaned
450
+
451
+
452
+ def grep_cached_item(
453
+ identifier: str,
454
+ djvu_text: str,
455
+ page_index: dict,
456
+ compiled: re.Pattern[str],
457
+ *,
458
+ context_chars: int,
459
+ limit: int,
460
+ ) -> tuple[list[dict], int]:
461
+ """Search cached page-delimited text line by line without DOTALL backtracking."""
462
+ hits: list[dict] = []
463
+ total_matches = 0
464
+ pages = djvu_text.split("\x0c")
465
+
466
+ for seg_idx, page_text in enumerate(pages):
467
+ if not page_text or not compiled.search(page_text):
468
+ continue
469
+ # Search line by line on matching pages so multi-line DOTALL backtracking cannot happen.
470
+ offset = 0
471
+ for line in page_text.splitlines(keepends=True):
472
+ for match in compiled.finditer(line):
473
+ total_matches += 1
474
+ if len(hits) < limit:
475
+ leaf_n, scandata_leaf, printed_page = resolve_segment_page(seg_idx, page_index)
476
+ m_start = offset + match.start()
477
+ m_end = offset + match.end()
478
+ hits.append(
479
+ {
480
+ "identifier": identifier,
481
+ "leaf": leaf_n,
482
+ "scandata_leaf": scandata_leaf,
483
+ "printed_page": printed_page,
484
+ "match": match.group(0),
485
+ "snippet": extract_snippet(page_text, m_start, m_end, context_chars),
486
+ "image_url": page_image_url(identifier, leaf_n, scale=2)
487
+ if leaf_n is not None
488
+ else None,
489
+ "details_url": page_details_url(identifier, leaf_n)
490
+ if leaf_n is not None
491
+ else item_url(identifier),
492
+ }
493
+ )
494
+ offset += len(line)
495
+ return hits, total_matches
496
+
497
+
498
+ def resolve_printed_page_to_leaf(page_index: dict, printed_page: str) -> tuple[int, int | None]:
499
+ target = printed_page.strip()
500
+ p2b = page_index.get("printed_to_bookreader") or {}
501
+ if target in p2b:
502
+ br_n = int(p2b[target])
503
+ sc_leaf = page_index.get("bookreader_to_scandata", {}).get(str(br_n))
504
+ return br_n, sc_leaf
505
+ p2b_ci = page_index.get("printed_to_bookreader_ci") or {}
506
+ lower = target.lower()
507
+ if lower in p2b_ci:
508
+ br_n = int(p2b_ci[lower])
509
+ sc_leaf = page_index.get("bookreader_to_scandata", {}).get(str(br_n))
510
+ return br_n, sc_leaf
511
+ # Fallback to scandata_to_printed when access mapping is absent
512
+ p2s = page_index.get("printed_to_scandata") or {}
513
+ if target in p2s:
514
+ sc_leaf = int(p2s[target])
515
+ return sc_leaf, sc_leaf
516
+ 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)"
518
+ raise KeyError(f"Printed page {printed_page!r} not found in page_index.json{hint}")
519
+
520
+
521
+ def cmd_search(args: argparse.Namespace) -> int:
522
+ query = args.query
523
+ if args.mediatype:
524
+ query = f"{query} AND mediatype:({args.mediatype})"
525
+ chosen = list(args.fields) if args.fields else DEFAULT_FIELDS
526
+ data = search_api(query, chosen, args.rows, args.page, list(args.sorts))
527
+ response = data.get("response") or {}
528
+ if args.as_json:
529
+ print(json.dumps(data, indent=2))
530
+ return 0
531
+ print(f"{response.get('numFound')} items")
532
+ for doc in response.get("docs") or []:
533
+ identifier = doc.get("identifier") or ""
534
+ title = doc.get("title") or ""
535
+ creator = doc.get("creator") or ""
536
+ date = doc.get("date") or ""
537
+ mediatype_out = doc.get("mediatype") or ""
538
+ print(
539
+ f"{identifier} | {title} | {creator} | {date} | "
540
+ f"{mediatype_out} | {item_url(identifier)}"
541
+ )
542
+ return 0
543
+
544
+
545
+ def cmd_get(args: argparse.Namespace) -> int:
546
+ data = metadata_api(validate_identifier(args.identifier))
547
+ if args.as_json:
548
+ print(json.dumps(data, indent=2))
549
+ return 0
550
+ meta = data.get("metadata") or {}
551
+ print(f"{meta.get('title') or args.identifier}")
552
+ print(f" Identifier: {meta.get('identifier')}")
553
+ if meta.get("creator"):
554
+ print(f" Creator: {meta.get('creator')}")
555
+ if meta.get("date"):
556
+ print(f" Date: {meta.get('date')}")
557
+ if meta.get("mediatype"):
558
+ print(f" Mediatype: {meta.get('mediatype')}")
559
+ if meta.get("collection"):
560
+ collection = meta.get("collection")
561
+ if isinstance(collection, list):
562
+ collection = ", ".join(collection)
563
+ print(f" Collection: {collection}")
564
+ if meta.get("description"):
565
+ print(f" Description: {short(meta.get('description'))}")
566
+ file_list = data.get("files") or []
567
+ print(f" Files: {len(file_list)} | {item_url(args.identifier)}")
568
+ if args.files:
569
+ for entry in file_list:
570
+ size = entry.get("size") or ""
571
+ print(f" {entry.get('name')} | {entry.get('format')} | {size} bytes")
572
+ return 0
573
+
574
+
575
+ def cmd_download(args: argparse.Namespace) -> int:
576
+ identifier = validate_identifier(args.identifier)
577
+ data = metadata_api(identifier)
578
+ file_list = data.get("files") or []
579
+ if args.list_only or not args.files:
580
+ for entry in file_list:
581
+ size = entry.get("size") or ""
582
+ print(f"{entry.get('name')} | {entry.get('format')} | {size} bytes")
583
+ return 0
584
+ available = {entry.get("name") for entry in file_list}
585
+ out_dir = Path(args.out)
586
+ out_dir.mkdir(parents=True, exist_ok=True)
587
+ for name in args.files:
588
+ if name not in available:
589
+ fail(f"File not in item {identifier}: {name}")
590
+ url = f"{BASE}/download/{quote(identifier)}/{quote(name)}"
591
+ try:
592
+ content = http_get_bytes(url, timeout=60.0)
593
+ except (RuntimeError, FileNotFoundError) as exc:
594
+ fail(str(exc))
595
+ dest = out_dir / Path(name).name
596
+ atomic_write_bytes(dest, content)
597
+ print(f"{dest} ({len(content)} bytes)")
598
+ return 0
599
+
600
+
601
+ def cmd_fulltext(args: argparse.Namespace) -> int:
602
+ data = fulltext_api(args.query, args.rows, args.page)
603
+ if args.as_json:
604
+ print(json.dumps(data, indent=2, ensure_ascii=False))
605
+ return 0
606
+ hits_block = ((data.get("response") or {}).get("body") or {}).get("hits") or {}
607
+ total = hits_block.get("total", 0)
608
+ hits = hits_block.get("hits") or []
609
+ print(f"{total} full-text matches (showing {len(hits)})")
610
+ for hit in hits:
611
+ fields = hit.get("fields") or {}
612
+ identifier = fields.get("identifier") or ""
613
+ title = fields.get("title") or ""
614
+ year = fields.get("year") or fields.get("date") or ""
615
+ snippets = (hit.get("highlight") or {}).get("text") or []
616
+ snippet = short(snippets[0].replace("{{{", "").replace("}}}", ""), 200) if snippets else ""
617
+ print(f"- {identifier} | {title} | {year} | {item_url(identifier)}")
618
+ if snippet:
619
+ print(f" OCR: {snippet}")
620
+ return 0
621
+
622
+
623
+ def cmd_grep(args: argparse.Namespace) -> int:
624
+ t0 = time.perf_counter()
625
+ flags = re.IGNORECASE if args.ignore_case else 0
626
+ try:
627
+ compiled = re.compile(args.pattern, flags)
628
+ except re.error as exc:
629
+ fail(f"Invalid regex pattern {args.pattern!r}: {exc}", code=2)
630
+
631
+ identifiers = [validate_identifier(item) for item in args.identifiers]
632
+ cache_root = get_cache_root()
633
+
634
+ # Fetch missing items in parallel (max_workers=6, timeout=25).
635
+ def prepare(item_id: str) -> dict:
636
+ return ensure_item_cache(item_id, need_djvu=True, cache_root=cache_root, timeout=args.timeout)
637
+
638
+ if len(identifiers) == 1:
639
+ try:
640
+ cache_entries = [prepare(identifiers[0])]
641
+ except Exception as exc:
642
+ fail(str(exc))
643
+ else:
644
+ from concurrent.futures import ThreadPoolExecutor
645
+
646
+ cache_entries = []
647
+ with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(identifiers))) as pool:
648
+ futures = [(item_id, pool.submit(prepare, item_id)) for item_id in identifiers]
649
+ for item_id, fut in futures:
650
+ try:
651
+ cache_entries.append(fut.result())
652
+ except Exception as exc:
653
+ fail(f"{item_id}: {exc}")
654
+
655
+ all_hits: list[dict] = []
656
+ item_summaries: list[dict] = []
657
+ remaining = max(0, args.limit)
658
+ total_matches = 0
659
+ all_cached = True
660
+
661
+ for entry in cache_entries:
662
+ item_id = entry["identifier"]
663
+ was_cached = bool(entry["cached"])
664
+ all_cached = all_cached and was_cached
665
+ page_index = json.loads(entry["page_index_path"].read_text(encoding="utf-8"))
666
+ djvu_text = entry["djvu_path"].read_text(encoding="utf-8", errors="replace")
667
+ hits, item_total = grep_cached_item(
668
+ item_id,
669
+ djvu_text,
670
+ page_index,
671
+ compiled,
672
+ context_chars=args.context,
673
+ limit=remaining,
674
+ )
675
+ for h in hits:
676
+ h["cached"] = was_cached
677
+ all_hits.extend(hits)
678
+ remaining = max(0, args.limit - len(all_hits))
679
+ total_matches += item_total
680
+ item_summaries.append(
681
+ {
682
+ "identifier": item_id,
683
+ "cached": was_cached,
684
+ "matches": item_total,
685
+ "returned": len(hits),
686
+ "cache_dir": str(entry["item_dir"]),
687
+ }
688
+ )
689
+
690
+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2)
691
+ payload = {
692
+ "pattern": args.pattern,
693
+ "ignore_case": bool(args.ignore_case),
694
+ "cached": all_cached,
695
+ "elapsed_ms": elapsed_ms,
696
+ "total_matches": total_matches,
697
+ "returned": len(all_hits),
698
+ "items": item_summaries,
699
+ "hits": all_hits,
700
+ }
701
+
702
+ if args.as_json:
703
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
704
+ return 0
705
+
706
+ status = "cache-hit" if all_cached else "fetched"
707
+ print(f"{total_matches} matches across {len(identifiers)} item(s) (showing {len(all_hits)}, {status}, {elapsed_ms} ms)")
708
+ for hit in all_hits:
709
+ pp = f"p.{hit['printed_page']}" if hit["printed_page"] else "p.?"
710
+ lf = f"n{hit['leaf']}" if hit["leaf"] is not None else "n?"
711
+ print(f"- {hit['identifier']} | {lf} ({pp}) | {hit['image_url'] or hit['details_url']}")
712
+ print(f" {hit['snippet']}")
713
+ return 0
714
+
715
+
716
+ def cmd_page(args: argparse.Namespace) -> int:
717
+ t0 = time.perf_counter()
718
+ identifier = validate_identifier(args.identifier)
719
+
720
+ # Support both legacy positional `<leaf>` and new `--leaf` / `--printed-page`.
721
+ leaf_from_pos = args.leaf_pos
722
+ leaf_from_flag = args.leaf
723
+ printed_page = args.printed_page
724
+
725
+ if printed_page is not None and (leaf_from_pos is not None or leaf_from_flag is not None):
726
+ fail("Pass either --printed-page or --leaf (not both).", code=2)
727
+ if leaf_from_pos is not None and leaf_from_flag is not None:
728
+ fail("Pass either positional <leaf> or --leaf (not both).", code=2)
729
+
730
+ target_leaf: int | None = leaf_from_flag if leaf_from_flag is not None else leaf_from_pos
731
+ scandata_leaf: int | None = None
732
+ resolved_printed: str | None = printed_page
733
+ index_cached: bool | None = None
734
+
735
+ if printed_page is not None:
736
+ try:
737
+ cache_entry = ensure_item_cache(
738
+ identifier,
739
+ need_djvu=False,
740
+ cache_root=get_cache_root(),
741
+ timeout=args.timeout,
742
+ )
743
+ index_cached = bool(cache_entry["cached"])
744
+ page_index = json.loads(cache_entry["page_index_path"].read_text(encoding="utf-8"))
745
+ target_leaf, scandata_leaf = resolve_printed_page_to_leaf(page_index, printed_page)
746
+ except Exception as exc:
747
+ fail(str(exc))
748
+ elif target_leaf is None:
749
+ fail("Specify a target page with --printed-page <str>, --leaf <int>, or positional <leaf>.", code=2)
750
+
751
+ assert target_leaf is not None
752
+ if target_leaf < 0:
753
+ fail(f"Leaf index must be >= 0, got {target_leaf}.", code=2)
754
+
755
+ # Determine URL: explicit --scale uses _s<scale>.jpg; otherwise --width uses _w<width>.jpg.
756
+ if args.scale is not None:
757
+ url = page_image_url(identifier, target_leaf, scale=args.scale)
758
+ suffix_tag = f"s{args.scale}"
759
+ else:
760
+ width = args.width if args.width is not None else 2400
761
+ url = page_image_url(identifier, target_leaf, width=width)
762
+ suffix_tag = f"w{width}"
763
+
764
+ try:
765
+ content = http_get_bytes(url, timeout=args.timeout)
766
+ except (RuntimeError, FileNotFoundError) as exc:
767
+ fail(str(exc))
768
+
769
+ out_path = Path(args.out)
770
+ if out_path.suffix.lower() in IMAGE_EXTS and not out_path.is_dir():
771
+ dest = out_path
772
+ else:
773
+ out_path.mkdir(parents=True, exist_ok=True)
774
+ dest = out_path / f"{identifier}_n{target_leaf}_{suffix_tag}.jpg"
775
+
776
+ atomic_write_bytes(dest, content)
777
+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2)
778
+ payload = {
779
+ "identifier": identifier,
780
+ "leaf": target_leaf,
781
+ "scandata_leaf": scandata_leaf,
782
+ "printed_page": resolved_printed,
783
+ "url": url,
784
+ "path": str(dest),
785
+ "bytes": len(content),
786
+ "index_cached": index_cached,
787
+ "elapsed_ms": elapsed_ms,
788
+ }
789
+ if args.as_json:
790
+ print(json.dumps(payload, indent=2))
791
+ else:
792
+ 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}")
794
+ return 0
795
+
796
+
797
+ def cmd_url(args: argparse.Namespace) -> int:
798
+ full = args.query
799
+ if args.mediatype:
800
+ full = f"{args.query} AND mediatype:({args.mediatype})"
801
+ print(f"{ADVANCED_SEARCH}?q={quote(full)}")
802
+ return 0
803
+
804
+
805
+ def build_parser() -> argparse.ArgumentParser:
806
+ parser = argparse.ArgumentParser(
807
+ prog="archive-org",
808
+ description="Search, inspect, grep cached OCR, and download pages from Internet Archive.",
809
+ )
810
+ sub = parser.add_subparsers(dest="command", required=True)
811
+
812
+ p_search = sub.add_parser("search", help="Search items with a Lucene query.")
813
+ p_search.add_argument("query")
814
+ p_search.add_argument("--mediatype", default=None, help="e.g. texts, movies, audio, software, collection.")
815
+ p_search.add_argument("--rows", type=int, default=10, help="Results per page (default: 10).")
816
+ p_search.add_argument("--page", type=int, default=1, help="Results page (default: 1).")
817
+ p_search.add_argument("--sort", dest="sorts", action="append", default=[], help="Repeatable, e.g. --sort 'downloads desc'.")
818
+ p_search.add_argument("--field", dest="fields", action="append", default=[], help="Repeatable metadata field.")
819
+ p_search.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
820
+ p_search.set_defaults(func=cmd_search)
821
+
822
+ p_get = sub.add_parser("get", help="Read an item's metadata and file list by identifier.")
823
+ p_get.add_argument("identifier")
824
+ p_get.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
825
+ p_get.add_argument("--files", action="store_true", help="List the item's files.")
826
+ p_get.set_defaults(func=cmd_get)
827
+
828
+ p_dl = sub.add_parser("download", help="Download files of an item, or list them with no FILE given.")
829
+ p_dl.add_argument("identifier")
830
+ p_dl.add_argument("files", nargs="*")
831
+ p_dl.add_argument("--out", default=".", help="Directory to save files into (default: .).")
832
+ p_dl.add_argument("--list", dest="list_only", action="store_true", help="Only list files, do not download.")
833
+ p_dl.set_defaults(func=cmd_download)
834
+
835
+ p_ft = sub.add_parser("fulltext", help="Search OCR full text across digitized books and periodicals.")
836
+ p_ft.add_argument("query")
837
+ p_ft.add_argument("--rows", type=int, default=10, help="Hits per page (default: 10).")
838
+ p_ft.add_argument("--page", type=int, default=1, help="Results page, 1-based (default: 1).")
839
+ p_ft.add_argument("--json", dest="as_json", action="store_true", help="Full JSON output.")
840
+ p_ft.set_defaults(func=cmd_fulltext)
841
+
842
+ p_grep = sub.add_parser("grep", help="Search cached full-text OCR inside one or more items with exact page mapping.")
843
+ p_grep.add_argument("identifiers", nargs="+", help="One or more Internet Archive item identifiers.")
844
+ p_grep.add_argument("--pattern", required=True, help="Regular expression pattern (searched line by line).")
845
+ p_grep.add_argument("--context", type=int, default=240, help="Context characters per hit snippet (default: 240).")
846
+ p_grep.add_argument("--limit", type=int, default=25, help="Maximum hits returned (default: 25).")
847
+ p_grep.add_argument("-i", "--ignore-case", action="store_true", help="Case-insensitive regex matching.")
848
+ p_grep.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="HTTP timeout seconds on cache miss (default: 25).")
849
+ p_grep.add_argument("--json", dest="as_json", action="store_true", help="Structured JSON output.")
850
+ p_grep.set_defaults(func=cmd_grep)
851
+
852
+ p_page = sub.add_parser("page", help="Download one rendered page JPEG by printed page number or BookReader leaf.")
853
+ p_page.add_argument("identifier")
854
+ p_page.add_argument("leaf_pos", nargs="?", type=int, default=None, help="Legacy positional BookReader leaf index.")
855
+ p_page.add_argument("--printed-page", default=None, help="Printed page label resolved via cached page_index.json.")
856
+ p_page.add_argument("--leaf", type=int, default=None, help="BookReader leaf index (n<LEAF>).")
857
+ p_page.add_argument("--scale", type=int, default=None, help="BookReader scale factor (e.g. 1=full, 2=half, 4=quarter).")
858
+ p_page.add_argument("--width", type=int, default=None, help="Rendered JPEG width in pixels (default 2400 when --scale is omitted).")
859
+ p_page.add_argument("--out", default=".", help="Output file path (.jpg) or directory (default: .).")
860
+ p_page.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="HTTP timeout seconds (default: 25).")
861
+ p_page.add_argument("--json", dest="as_json", action="store_true", help="Structured JSON output.")
862
+ p_page.set_defaults(func=cmd_page)
863
+
864
+ p_url = sub.add_parser("url", help="Print the website advanced-search URL for a query.")
865
+ p_url.add_argument("query")
866
+ p_url.add_argument("--mediatype", default=None)
867
+ p_url.set_defaults(func=cmd_url)
868
+
869
+ return parser
870
+
871
+
872
+ def main(argv: list[str] | None = None) -> int:
873
+ parser = build_parser()
874
+ args = parser.parse_args(argv)
875
+ return int(args.func(args))
876
+
877
+
878
+ if __name__ == "__main__":
879
+ raise SystemExit(main())