@kinloom/cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/assets/cached-ocr.py +346 -116
  2. package/dist/assets/ocr.md +25 -1
  3. package/dist/assets/prep-scan.md +42 -4
  4. package/dist/assets/prep-scan.py +432 -10
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
  7. package/dist/bundled-skills/archive-org/SKILL.md +40 -7
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
  9. package/dist/bundled-skills/california-archives/SKILL.md +10 -0
  10. package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
  11. package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
  12. package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
  13. package/dist/bundled-skills/findagrave/SKILL.md +18 -5
  14. package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
  15. package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
  16. package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
  17. package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
  18. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
  19. package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
  20. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
  21. package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
  22. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
  23. package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
  24. package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
  25. package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
  26. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
  27. package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
  28. package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
  29. package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
  30. package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
  31. package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
  32. package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
  33. package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
  34. package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
  35. package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
  36. package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
  37. package/dist/bundled-skills/wikitree/SKILL.md +7 -1
  38. package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +107 -2
  41. package/dist/cli.js.map +1 -1
  42. package/dist/client.d.ts.map +1 -1
  43. package/dist/client.js +30 -5
  44. package/dist/client.js.map +1 -1
  45. package/dist/commands/ops/audit.d.ts.map +1 -1
  46. package/dist/commands/ops/audit.js +5 -0
  47. package/dist/commands/ops/audit.js.map +1 -1
  48. package/dist/commands/ops/dates.d.ts +87 -0
  49. package/dist/commands/ops/dates.d.ts.map +1 -0
  50. package/dist/commands/ops/dates.js +228 -0
  51. package/dist/commands/ops/dates.js.map +1 -0
  52. package/dist/commands/ops/help.d.ts +3 -1
  53. package/dist/commands/ops/help.d.ts.map +1 -1
  54. package/dist/commands/ops/help.js +33 -0
  55. package/dist/commands/ops/help.js.map +1 -1
  56. package/dist/commands/ops/index.d.ts +3 -1
  57. package/dist/commands/ops/index.d.ts.map +1 -1
  58. package/dist/commands/ops/index.js +2 -0
  59. package/dist/commands/ops/index.js.map +1 -1
  60. package/dist/commands/ops/integrate.d.ts +5 -0
  61. package/dist/commands/ops/integrate.d.ts.map +1 -1
  62. package/dist/commands/ops/integrate.js +217 -26
  63. package/dist/commands/ops/integrate.js.map +1 -1
  64. package/dist/commands/ops/sync.d.ts +17 -0
  65. package/dist/commands/ops/sync.d.ts.map +1 -1
  66. package/dist/commands/ops/sync.js +173 -0
  67. package/dist/commands/ops/sync.js.map +1 -1
  68. package/dist/commands/ops/verify.d.ts +76 -0
  69. package/dist/commands/ops/verify.d.ts.map +1 -0
  70. package/dist/commands/ops/verify.js +325 -0
  71. package/dist/commands/ops/verify.js.map +1 -0
  72. package/dist/commands/records/index.d.ts +1 -1
  73. package/dist/commands/records/index.d.ts.map +1 -1
  74. package/dist/commands/records/index.js +1 -1
  75. package/dist/commands/records/index.js.map +1 -1
  76. package/dist/commands/records/runner.d.ts +2 -0
  77. package/dist/commands/records/runner.d.ts.map +1 -1
  78. package/dist/commands/records/runner.js +33 -2
  79. package/dist/commands/records/runner.js.map +1 -1
  80. package/package.json +2 -2
@@ -20,22 +20,30 @@ live 2026-11-24. No account, key, or sign-in is required.
20
20
 
21
21
  from __future__ import annotations
22
22
 
23
- import html as htmlmod
23
+ import hashlib
24
24
  import json
25
+ import math
26
+ import os
25
27
  import sys
26
28
  import time
29
+ from contextlib import contextmanager
27
30
  from html.parser import HTMLParser
28
- from urllib.parse import urlencode
31
+ from pathlib import Path
32
+ from typing import Any, Callable, Iterator
29
33
 
30
34
  import click
31
35
  import httpx
32
36
 
37
+ DEFAULT_CACHE_TTL_HOURS = 168.0
38
+ CACHE_SCHEMA = 1
39
+
33
40
  BASE = "https://www.genealogycenter.info"
34
41
  SEARCH_PAGE = BASE + "/persi/"
35
42
  SURNAME_URL = BASE + "/results_persisurname.php"
36
43
  TITLE_URL = BASE + "/results_persiarttitle.php"
37
44
  LOCATION_URL = BASE + "/results_persilocation.php"
38
45
  USER_AGENT = "Mozilla/5.0"
46
+ RETRY_WAIT_S = 5.0
39
47
  # The Genealogy Center's front door intermittently 412/429s python-httpx's
40
48
  # default header set. Plain curl-style headers (short UA, Accept */*) plus
41
49
  # a Referer return 200 consistently; fetch() also retries once on 412/429.
@@ -49,6 +57,139 @@ US_STATES = {
49
57
  }
50
58
 
51
59
 
60
+ def cache_dir() -> Path:
61
+ override = os.environ.get("KINLOOM_PERSI_CACHE_DIR")
62
+ if override:
63
+ return Path(override).expanduser()
64
+ return Path.home() / ".cache" / "kinloom-persi"
65
+
66
+
67
+ def resolve_ttl_hours(cli_ttl: float | None) -> float:
68
+ if cli_ttl is not None:
69
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
70
+ raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
71
+ return float(cli_ttl)
72
+ raw = os.environ.get("KINLOOM_PERSI_CACHE_TTL_HOURS")
73
+ if raw is not None and raw.strip():
74
+ try:
75
+ parsed = float(raw.strip())
76
+ except ValueError as exc:
77
+ raise click.BadParameter(f"Invalid KINLOOM_PERSI_CACHE_TTL_HOURS value: {raw!r}.") from exc
78
+ if not math.isfinite(parsed) or parsed < 0:
79
+ raise click.BadParameter(
80
+ f"Invalid KINLOOM_PERSI_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
81
+ )
82
+ return parsed
83
+ return DEFAULT_CACHE_TTL_HOURS
84
+
85
+
86
+ @contextmanager
87
+ def file_lock(lock_path: Path) -> Iterator[None]:
88
+ """Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
89
+ try:
90
+ import fcntl
91
+ except ImportError:
92
+ yield
93
+ return
94
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
95
+ with open(lock_path, "a+b") as lock_file:
96
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
97
+ try:
98
+ yield
99
+ finally:
100
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
101
+
102
+
103
+ def atomic_write_json(dest: Path, payload: Any) -> None:
104
+ dest.parent.mkdir(parents=True, exist_ok=True)
105
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
106
+ try:
107
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
108
+ os.replace(tmp, dest)
109
+ except Exception:
110
+ tmp.unlink(missing_ok=True)
111
+ raise
112
+
113
+
114
+ def cache_key(kind: str, payload: dict) -> str:
115
+ canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
116
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
117
+
118
+
119
+ def read_cache(path: Path, ttl_hours: float) -> dict | None:
120
+ if not path.is_file():
121
+ return None
122
+ try:
123
+ entry = json.loads(path.read_text(encoding="utf-8"))
124
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
125
+ return None
126
+ if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
127
+ return None
128
+ fetched = entry.get("fetched_at")
129
+ if not isinstance(fetched, (int, float)):
130
+ return None
131
+ if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
132
+ return None
133
+ result = entry.get("result")
134
+ return result if isinstance(result, dict) else None
135
+
136
+
137
+ def cached_call(
138
+ kind: str,
139
+ payload: dict,
140
+ fetch: Callable[[], dict],
141
+ *,
142
+ refresh: bool,
143
+ ttl_hours: float,
144
+ cacheable: Callable[[dict], bool] = lambda _r: True,
145
+ ) -> tuple[dict, bool]:
146
+ """Return (result, cache_hit) with per-key flock and atomic JSON writes."""
147
+ key = cache_key(kind, payload)
148
+ root = cache_dir()
149
+ path = root / f"{key}.json"
150
+ if not refresh:
151
+ hit = read_cache(path, ttl_hours)
152
+ if hit is not None:
153
+ return hit, True
154
+ with file_lock(root / f"{key}.lock"):
155
+ if not refresh:
156
+ hit = read_cache(path, ttl_hours)
157
+ if hit is not None:
158
+ return hit, True
159
+ result = fetch()
160
+ if cacheable(result):
161
+ atomic_write_json(
162
+ path,
163
+ {
164
+ "schema": CACHE_SCHEMA,
165
+ "fetched_at": time.time(),
166
+ "kind": kind,
167
+ "query": payload,
168
+ "result": result,
169
+ },
170
+ )
171
+ return result, False
172
+
173
+
174
+ def cache_options(func: Callable) -> Callable:
175
+ func = click.option(
176
+ "--cache-ttl-hours",
177
+ type=float,
178
+ default=None,
179
+ help="Cache TTL in hours (default 168, env KINLOOM_PERSI_CACHE_TTL_HOURS; 0 disables reads).",
180
+ )(func)
181
+ func = click.option(
182
+ "--refresh",
183
+ is_flag=True,
184
+ help="Bypass the disk cache for this request (the fresh result is still cached).",
185
+ )(func)
186
+ return func
187
+
188
+
189
+ def _client(headers: dict[str, str]) -> httpx.Client:
190
+ return httpx.Client(headers=headers, timeout=60.0, follow_redirects=True)
191
+
192
+
52
193
  class TableParser(HTMLParser):
53
194
  """Collect rows of the first <table> whose cells look like PERSI results."""
54
195
 
@@ -113,12 +254,11 @@ def fetch(url: str, data: dict, referer: str) -> str:
113
254
  last_exc: Exception | None = None
114
255
  for attempt in (1, 2):
115
256
  try:
116
- with httpx.Client(
117
- headers=headers, timeout=60.0, follow_redirects=True
118
- ) as client:
257
+ with _client(headers) as client:
119
258
  resp = client.post(url, data=data)
120
259
  if resp.status_code in (412, 429) and attempt == 1:
121
- time.sleep(5)
260
+ if RETRY_WAIT_S > 0:
261
+ time.sleep(RETRY_WAIT_S)
122
262
  continue
123
263
  resp.raise_for_status()
124
264
  return resp.text
@@ -170,13 +310,14 @@ def parse_categories(page: str) -> list[dict]:
170
310
  return categories
171
311
 
172
312
 
173
- def emit(items: list[dict], as_json: bool, limit: int) -> None:
313
+ def emit(items: list[dict], as_json: bool, limit: int, *, cache_hit: bool = False) -> None:
174
314
  items = items[:limit]
175
315
  if as_json:
176
316
  click.echo(json.dumps(items, indent=2))
177
317
  return
318
+ marker = " [cache]" if cache_hit else ""
178
319
  if not items:
179
- click.echo("No results.")
320
+ click.echo(f"No results.{marker}")
180
321
  return
181
322
  for item in items:
182
323
  if "articles" in item:
@@ -189,7 +330,7 @@ def emit(items: list[dict], as_json: bool, limit: int) -> None:
189
330
  click.echo(line)
190
331
  if item.get("free_link"):
191
332
  click.echo(f" free online: {item['free_link']}")
192
- click.echo(f"({len(items)} shown)")
333
+ click.echo(f"({len(items)} shown){marker}")
193
334
 
194
335
 
195
336
  @click.group()
@@ -201,27 +342,82 @@ def cli() -> None:
201
342
  @click.argument("surname")
202
343
  @click.option("--limit", default=25, show_default=True, help="Max results to show.")
203
344
  @click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
204
- def surname(surname: str, limit: int, as_json: bool) -> None:
345
+ @cache_options
346
+ def surname(
347
+ surname: str,
348
+ limit: int,
349
+ as_json: bool,
350
+ refresh: bool,
351
+ cache_ttl_hours: float | None,
352
+ ) -> None:
205
353
  """Search PERSI by surname, e.g. persi surname Lincoln."""
206
- page = fetch(SURNAME_URL, {"surname": surname, "sort": "title", "submit": "Search"}, BASE + "/search_persisurname.php")
207
- emit(parse_articles(page), as_json, limit)
354
+ ttl = resolve_ttl_hours(cache_ttl_hours)
355
+
356
+ def _fetch() -> dict:
357
+ page = fetch(
358
+ SURNAME_URL,
359
+ {"surname": surname, "sort": "title", "submit": "Search"},
360
+ BASE + "/search_persisurname.php",
361
+ )
362
+ return {"articles": parse_articles(page)}
363
+
364
+ data, hit = cached_call(
365
+ "surname",
366
+ {"surname": surname.strip().lower()},
367
+ _fetch,
368
+ refresh=refresh,
369
+ ttl_hours=ttl,
370
+ cacheable=lambda r: bool(r.get("articles")),
371
+ )
372
+ emit(data.get("articles") or [], as_json, limit, cache_hit=hit)
208
373
 
209
374
 
210
375
  @cli.command()
211
376
  @click.argument("keyword")
212
377
  @click.option("--limit", default=25, show_default=True, help="Max results to show.")
213
378
  @click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
214
- def title(keyword: str, limit: int, as_json: bool) -> None:
379
+ @cache_options
380
+ def title(
381
+ keyword: str,
382
+ limit: int,
383
+ as_json: bool,
384
+ refresh: bool,
385
+ cache_ttl_hours: float | None,
386
+ ) -> None:
215
387
  """Search PERSI by article-title keyword, e.g. persi title Lincoln."""
216
- page = fetch(TITLE_URL, {"keyword": keyword, "sort": "title", "submit": "Search"}, BASE + "/search_persiarttitle.php")
217
- emit(parse_articles(page), as_json, limit)
388
+ ttl = resolve_ttl_hours(cache_ttl_hours)
389
+
390
+ def _fetch() -> dict:
391
+ page = fetch(
392
+ TITLE_URL,
393
+ {"keyword": keyword, "sort": "title", "submit": "Search"},
394
+ BASE + "/search_persiarttitle.php",
395
+ )
396
+ return {"articles": parse_articles(page)}
397
+
398
+ data, hit = cached_call(
399
+ "title",
400
+ {"keyword": keyword.strip().lower()},
401
+ _fetch,
402
+ refresh=refresh,
403
+ ttl_hours=ttl,
404
+ cacheable=lambda r: bool(r.get("articles")),
405
+ )
406
+ emit(data.get("articles") or [], as_json, limit, cache_hit=hit)
218
407
 
219
408
 
220
409
  @cli.command()
221
410
  @click.option("--state", required=True, help="Two-letter state code, e.g. MI. GEN for US general.")
222
411
  @click.option("--county", default="", help="County name (optional; leave blank for statewide).")
223
412
  @click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
224
- def location(state: str, county: str, as_json: bool) -> None:
413
+ @cache_options
414
+ def location(
415
+ state: str,
416
+ county: str,
417
+ as_json: bool,
418
+ refresh: bool,
419
+ cache_ttl_hours: float | None,
420
+ ) -> None:
225
421
  """List PERSI article counts by category for a state/county.
226
422
 
227
423
  Returns category counts, not articles: pick a category on the website
@@ -230,18 +426,31 @@ def location(state: str, county: str, as_json: bool) -> None:
230
426
  state = state.upper()
231
427
  if state not in US_STATES:
232
428
  raise click.ClickException(f"Unknown state code: {state}")
233
- page = fetch(
234
- LOCATION_URL,
235
- {
236
- "subloc": "USA",
237
- "cosearch": "USA",
238
- "usloc": state,
239
- "county": county,
240
- "submit": "Search",
241
- },
242
- BASE + "/search_persilocation.php",
429
+ ttl = resolve_ttl_hours(cache_ttl_hours)
430
+
431
+ def _fetch() -> dict:
432
+ page = fetch(
433
+ LOCATION_URL,
434
+ {
435
+ "subloc": "USA",
436
+ "cosearch": "USA",
437
+ "usloc": state,
438
+ "county": county,
439
+ "submit": "Search",
440
+ },
441
+ BASE + "/search_persilocation.php",
442
+ )
443
+ return {"categories": parse_categories(page)}
444
+
445
+ data, hit = cached_call(
446
+ "location",
447
+ {"state": state, "county": county.strip().lower()},
448
+ _fetch,
449
+ refresh=refresh,
450
+ ttl_hours=ttl,
451
+ cacheable=lambda r: bool(r.get("categories")),
243
452
  )
244
- cats = parse_categories(page)
453
+ cats = data.get("categories") or []
245
454
  if not cats:
246
455
  click.echo(
247
456
  "No category counts returned. The county value may not match "
@@ -249,7 +458,69 @@ def location(state: str, county: str, as_json: bool) -> None:
249
458
  "website form."
250
459
  )
251
460
  sys.exit(1)
252
- emit(cats, as_json, len(cats))
461
+ emit(cats, as_json, len(cats), cache_hit=hit)
462
+
463
+
464
+ @cli.command("search")
465
+ @click.argument("query", required=False, default=None)
466
+ @click.option("--surname", "surname_opt", default=None, help="Search by surname (alias for `persi surname`).")
467
+ @click.option("--title", "title_opt", default=None, help="Search by article-title keyword (alias for `persi title`).")
468
+ @click.option("--state", default=None, help="Two-letter state code for location counts (alias for `persi location`).")
469
+ @click.option("--county", default="", help="County name (used with --state).")
470
+ @click.option("--limit", default=25, show_default=True, help="Max results to show.")
471
+ @click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
472
+ @cache_options
473
+ @click.pass_context
474
+ def search_cmd(
475
+ ctx: click.Context,
476
+ query: str | None,
477
+ surname_opt: str | None,
478
+ title_opt: str | None,
479
+ state: str | None,
480
+ county: str,
481
+ limit: int,
482
+ as_json: bool,
483
+ refresh: bool,
484
+ cache_ttl_hours: float | None,
485
+ ) -> None:
486
+ """Convenience router to `surname`, `title`, or `location` search."""
487
+ if state and (query or surname_opt or title_opt):
488
+ raise click.UsageError(
489
+ "PERSI's surname and title forms do not accept a --state filter. "
490
+ "Use `persi surname <SURNAME>`, `persi title <KEYWORD>`, or `persi location --state <ST>` separately."
491
+ )
492
+ if state:
493
+ ctx.invoke(
494
+ location,
495
+ state=state,
496
+ county=county,
497
+ as_json=as_json,
498
+ refresh=refresh,
499
+ cache_ttl_hours=cache_ttl_hours,
500
+ )
501
+ return
502
+ if title_opt:
503
+ ctx.invoke(
504
+ title,
505
+ keyword=title_opt,
506
+ limit=limit,
507
+ as_json=as_json,
508
+ refresh=refresh,
509
+ cache_ttl_hours=cache_ttl_hours,
510
+ )
511
+ return
512
+ target_surname = surname_opt or query
513
+ if target_surname:
514
+ ctx.invoke(
515
+ surname,
516
+ surname=target_surname,
517
+ limit=limit,
518
+ as_json=as_json,
519
+ refresh=refresh,
520
+ cache_ttl_hours=cache_ttl_hours,
521
+ )
522
+ return
523
+ raise click.UsageError("Pass a surname, --title <KEYWORD>, or --state <ST>.")
253
524
 
254
525
 
255
526
  @cli.command()
@@ -11,14 +11,21 @@ This skill includes a standalone executable Python 3.11+ standard-library CLI at
11
11
 
12
12
  Path: `skills/archive-org/scripts/archive-org`
13
13
 
14
- ### Persistent local disk cache (`grep` & `page`)
14
+ ### Persistent local disk cache (all network commands)
15
15
 
16
- `grep` and `page --printed-page` cache each item atomically at `~/.cache/kinloom-ia/<item_id>/` (overrideable via `KINLOOM_IA_CACHE_DIR`):
16
+ Every network command (`get`, `grep`, `text`, `lookup`, `page`, `download`, `search`, and `fulltext`) writes atomically under `~/.cache/kinloom-ia/` (overrideable via `KINLOOM_IA_CACHE_DIR`) using per-item advisory locks (`fcntl.flock`) so concurrent processes never duplicate downloads and repeat calls make zero HTTP requests. Pass `--refresh` on any command to bypass the local cache and fetch fresh data.
17
17
 
18
- - `metadata.json`: item metadata and file inventory from `/metadata/<item_id>`.
19
- - `scandata.xml`: raw IA leaf/page scan metadata (when present).
20
- - `page_index.json`: pre-parsed bidirectional lookup table mapping `scandata` `leafNum`, BookReader `n<leaf>` index (skipping deleted/non-access leaves), and `printed_page` label so cache hits never re-parse XML.
21
- - `djvu.txt`: form-feed (`\x0c`) page-delimited OCR text (taken verbatim from `_djvu.txt` when form-feed delimited, or reconstructed from `_hocr_searchtext.txt.gz` + `_hocr_pageindex.json.gz` when raw `_djvu.txt` lacks page breaks).
18
+ Cache layout:
19
+
20
+ - `<item_id>/metadata.json`: item metadata and file inventory from `/metadata/<item_id>`, shared by `get`, `grep`, `page`, and `download`.
21
+ - `<item_id>/scandata.xml`: raw IA leaf/page scan metadata (when present).
22
+ - `<item_id>/page_index.json`: pre-parsed bidirectional lookup table mapping `scandata` `leafNum`, BookReader `n<leaf>` index (skipping deleted/non-access leaves), and `printed_page` label so cache hits never re-parse XML.
23
+ - `<item_id>/djvu.txt`: form-feed (`\x0c`) page-delimited OCR text (fetched from `_djvu.txt` first; falls back to `_hocr_searchtext.txt.gz` + `_hocr_pageindex.json.gz` only when `_djvu.txt` is absent, fails, or lacks `\x0c` page breaks).
24
+ - `<item_id>/pages/n<leaf>_<suffix>.jpg`: cached rendered page JPEGs (for example `n127_w2400.jpg` or `n127_s2.jpg`) served directly to `--out` on repeat `page` calls.
25
+ - `<item_id>/files/<relpath>`: cached item files downloaded via `download` (with path-traversal validation; exact raw `scandata.xml` and `_djvu.txt` artifacts are also reused without re-downloading).
26
+ - `_queries/<search|fulltext>/<sha256>.json`: cached JSON responses for `search` and `fulltext` keyed by canonical query parameters with a 168-hour (7-day) default TTL (`--cache-ttl-hours` or `KINLOOM_IA_QUERY_TTL_HOURS`).
27
+
28
+ Transient HTTP `429`, `502`, `503`, and `504` responses retry politely up to 2 times (honoring numeric `Retry-After` capped at 5s), while `403`, `404`, and socket timeouts fail fast with 0 retries.
22
29
 
23
30
  ### Search inside cached digitized books (`grep`)
24
31
 
@@ -47,6 +54,31 @@ skills/archive-org/scripts/archive-org page ourmartyrpreside00banc 0 --width 120
47
54
 
48
55
  Single-page URL patterns: `https://archive.org/download/<identifier>/page/n<leaf>_s<scale>.jpg` and `https://archive.org/download/<identifier>/page/n<leaf>_w<width>.jpg`. Returns HTTP 403 on borrow-only / `inlibrary` items.
49
56
 
57
+ ### Read OCR text for specific pages (`text`) and resolve page numbers (`lookup`)
58
+
59
+ `text` reads the cached `djvu.txt` + `page_index.json` (populating them on a cache miss, same as `grep`), resolves printed page labels to BookReader leaves, and prints that page's OCR text with its leaf / printed-page / scandata-leaf metadata plus `image_url` and `details_url`. It never downloads a JPEG; use `page` only when you need to look at the scan. Pass exactly one of `--printed-page`, `--leaf`, or `--pages <p1-p2>` (inclusive printed-page range, which also covers unnumbered leaves between the endpoints):
60
+
61
+ ```bash
62
+ # OCR text of printed page 12 (cache-hit repeat calls make zero HTTP requests)
63
+ kinloom ia text ourmartyrpreside00banc --printed-page 12
64
+
65
+ # A printed-page range or an explicit BookReader leaf, as JSON
66
+ kinloom ia text ourmartyrpreside00banc --pages 12-14 --json
67
+ kinloom ia text ourmartyrpreside00banc --leaf 7 --json
68
+ ```
69
+
70
+ JSON shape: `{identifier, cached, pages: [{leaf, scandata_leaf, printed_page, text, image_url, details_url}]}`. An unknown printed page, out-of-range leaf, reversed range, or OCR text without page breaks exits nonzero with a clear message.
71
+
72
+ `lookup` resolves printed page <-> BookReader leaf <-> scandata leaf using only `metadata.json` + `page_index.json` (never fetches `djvu.txt` or JPEGs). Pass exactly one of `--printed-page`, `--leaf`, or `--scandata-leaf`:
73
+
74
+ ```bash
75
+ kinloom ia lookup ourmartyrpreside00banc --printed-page 12
76
+ kinloom ia lookup ourmartyrpreside00banc --leaf 20 --json
77
+ kinloom ia lookup ourmartyrpreside00banc --scandata-leaf 21 --json
78
+ ```
79
+
80
+ Both accept `--refresh` to re-fetch cached metadata/scandata (and OCR text for `text`).
81
+
50
82
  ### Search item metadata (`search`) vs full-text OCR (`fulltext`)
51
83
 
52
84
  `search` calls `advancedsearch.php`, which searches **item metadata only** (title, creator, description, subjects), NOT the OCR text inside digitized books. Use `fulltext` to search across books, and `grep` to search inside specific known items:
@@ -126,4 +158,5 @@ skills/archive-org/scripts/archive-org url 'title:(Lincoln)' --mediatype texts
126
158
 
127
159
  ## Environment variables
128
160
 
129
- - `KINLOOM_IA_CACHE_DIR` (optional): overrides the default `~/.cache/kinloom-ia` cache directory used by `grep` and `page`. No API key or login is required.
161
+ - `KINLOOM_IA_CACHE_DIR` (optional): overrides the default `~/.cache/kinloom-ia` cache directory used by all network commands.
162
+ - `KINLOOM_IA_QUERY_TTL_HOURS` (optional): overrides the default `168` hour (7-day) TTL for cached `search` and `fulltext` responses. No API key or login is required.