@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.
- package/dist/assets/cached-ocr.py +346 -116
- package/dist/assets/ocr.md +25 -1
- package/dist/assets/prep-scan.md +42 -4
- package/dist/assets/prep-scan.py +432 -10
- package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
- package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
- package/dist/bundled-skills/archive-org/SKILL.md +40 -7
- package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
- package/dist/bundled-skills/california-archives/SKILL.md +10 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
- package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
- package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
- package/dist/bundled-skills/findagrave/SKILL.md +18 -5
- package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
- package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
- package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
- package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
- package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
- package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
- package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
- package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
- package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
- package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
- package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
- package/dist/bundled-skills/wikitree/SKILL.md +7 -1
- package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +107 -2
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +30 -5
- package/dist/client.js.map +1 -1
- package/dist/commands/ops/audit.d.ts.map +1 -1
- package/dist/commands/ops/audit.js +5 -0
- package/dist/commands/ops/audit.js.map +1 -1
- package/dist/commands/ops/dates.d.ts +87 -0
- package/dist/commands/ops/dates.d.ts.map +1 -0
- package/dist/commands/ops/dates.js +228 -0
- package/dist/commands/ops/dates.js.map +1 -0
- package/dist/commands/ops/help.d.ts +3 -1
- package/dist/commands/ops/help.d.ts.map +1 -1
- package/dist/commands/ops/help.js +33 -0
- package/dist/commands/ops/help.js.map +1 -1
- package/dist/commands/ops/index.d.ts +3 -1
- package/dist/commands/ops/index.d.ts.map +1 -1
- package/dist/commands/ops/index.js +2 -0
- package/dist/commands/ops/index.js.map +1 -1
- package/dist/commands/ops/integrate.d.ts +5 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -1
- package/dist/commands/ops/integrate.js +217 -26
- package/dist/commands/ops/integrate.js.map +1 -1
- package/dist/commands/ops/sync.d.ts +17 -0
- package/dist/commands/ops/sync.d.ts.map +1 -1
- package/dist/commands/ops/sync.js +173 -0
- package/dist/commands/ops/sync.js.map +1 -1
- package/dist/commands/ops/verify.d.ts +76 -0
- package/dist/commands/ops/verify.d.ts.map +1 -0
- package/dist/commands/ops/verify.js +325 -0
- package/dist/commands/ops/verify.js.map +1 -0
- package/dist/commands/records/index.d.ts +1 -1
- package/dist/commands/records/index.d.ts.map +1 -1
- package/dist/commands/records/index.js +1 -1
- package/dist/commands/records/index.js.map +1 -1
- package/dist/commands/records/runner.d.ts +2 -0
- package/dist/commands/records/runner.d.ts.map +1 -1
- package/dist/commands/records/runner.js +33 -2
- package/dist/commands/records/runner.js.map +1 -1
- package/package.json +2 -2
|
@@ -34,6 +34,16 @@ skills/california-archives/scripts/ca-archives get --portal <portal-id>
|
|
|
34
34
|
skills/california-archives/scripts/ca-archives get --exhibits <exhibits-id>
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
+
### Disk cache and environment variables
|
|
38
|
+
|
|
39
|
+
`search` (per source) and `get` cache successful responses on disk under `~/.cache/kinloom-ca-archives/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors and blocked/empty pages without a parsed total are never cached.
|
|
40
|
+
|
|
41
|
+
- `--refresh`: bypass cached reads and write the fresh response to disk.
|
|
42
|
+
- `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
|
|
43
|
+
- `KINLOOM_CA_ARCHIVES_CACHE_DIR`: override the cache directory path.
|
|
44
|
+
- `KINLOOM_CA_ARCHIVES_CACHE_TTL_HOURS`: override the default TTL in hours.
|
|
45
|
+
- `CA_ARCHIVES_BROWSER`: override the Chromium/Chrome executable path for `oac` and `calisphere`.
|
|
46
|
+
|
|
37
47
|
## Verification log (verified live 2026-11-24)
|
|
38
48
|
|
|
39
49
|
- OAC home page `oac.cdlib.org/` returns 200. Its search page `https://oac.cdlib.org/search?q=<query>` returns an AWS WAF JavaScript challenge (HTTP 202, empty body) to plain curl, but loads and returns real results in headless Chromium. The `q` parameter is the search form's own field (verified in the home-page form markup).
|
|
@@ -23,18 +23,187 @@ two are URL builders only (see the `url` command).
|
|
|
23
23
|
|
|
24
24
|
from __future__ import annotations
|
|
25
25
|
|
|
26
|
+
import hashlib
|
|
26
27
|
import json
|
|
28
|
+
import math
|
|
27
29
|
import os
|
|
28
30
|
import re
|
|
29
31
|
import shutil
|
|
30
32
|
import sys
|
|
33
|
+
import time
|
|
34
|
+
from contextlib import contextmanager
|
|
31
35
|
from html.parser import HTMLParser
|
|
32
36
|
from pathlib import Path
|
|
37
|
+
from typing import Any, Callable, Iterator
|
|
33
38
|
from urllib.parse import quote, urlencode
|
|
34
39
|
|
|
35
40
|
import click
|
|
36
41
|
import httpx
|
|
37
42
|
|
|
43
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
44
|
+
CACHE_SCHEMA = 1
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def cache_dir() -> Path:
|
|
48
|
+
override = os.environ.get("KINLOOM_CA_ARCHIVES_CACHE_DIR")
|
|
49
|
+
if override:
|
|
50
|
+
return Path(override).expanduser()
|
|
51
|
+
return Path.home() / ".cache" / "kinloom-ca-archives"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
55
|
+
if cli_ttl is not None:
|
|
56
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
57
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
58
|
+
return float(cli_ttl)
|
|
59
|
+
raw = os.environ.get("KINLOOM_CA_ARCHIVES_CACHE_TTL_HOURS")
|
|
60
|
+
if raw is not None and raw.strip():
|
|
61
|
+
try:
|
|
62
|
+
parsed = float(raw.strip())
|
|
63
|
+
except ValueError as exc:
|
|
64
|
+
raise click.BadParameter(f"Invalid KINLOOM_CA_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
65
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
66
|
+
raise click.BadParameter(
|
|
67
|
+
f"Invalid KINLOOM_CA_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
|
|
68
|
+
)
|
|
69
|
+
return parsed
|
|
70
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@contextmanager
|
|
74
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
75
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
76
|
+
try:
|
|
77
|
+
import fcntl
|
|
78
|
+
except ImportError:
|
|
79
|
+
yield
|
|
80
|
+
return
|
|
81
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
with open(lock_path, "a+b") as lock_file:
|
|
83
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
84
|
+
try:
|
|
85
|
+
yield
|
|
86
|
+
finally:
|
|
87
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
91
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
93
|
+
try:
|
|
94
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
95
|
+
os.replace(tmp, dest)
|
|
96
|
+
except Exception:
|
|
97
|
+
tmp.unlink(missing_ok=True)
|
|
98
|
+
raise
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
102
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
103
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
107
|
+
if not path.is_file():
|
|
108
|
+
return None
|
|
109
|
+
try:
|
|
110
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
111
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
112
|
+
return None
|
|
113
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
114
|
+
return None
|
|
115
|
+
fetched = entry.get("fetched_at")
|
|
116
|
+
if not isinstance(fetched, (int, float)):
|
|
117
|
+
return None
|
|
118
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
119
|
+
return None
|
|
120
|
+
result = entry.get("result")
|
|
121
|
+
return result if isinstance(result, dict) else None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cached_call(
|
|
125
|
+
kind: str,
|
|
126
|
+
payload: dict,
|
|
127
|
+
fetch: Callable[[], dict],
|
|
128
|
+
*,
|
|
129
|
+
refresh: bool,
|
|
130
|
+
ttl_hours: float,
|
|
131
|
+
cacheable: Callable[[dict], bool] = lambda _r: True,
|
|
132
|
+
) -> tuple[dict, bool]:
|
|
133
|
+
"""Return (result, cache_hit) with per-key flock and atomic JSON writes."""
|
|
134
|
+
key = cache_key(kind, payload)
|
|
135
|
+
root = cache_dir()
|
|
136
|
+
path = root / f"{key}.json"
|
|
137
|
+
if not refresh:
|
|
138
|
+
hit = read_cache(path, ttl_hours)
|
|
139
|
+
if hit is not None:
|
|
140
|
+
return hit, True
|
|
141
|
+
with file_lock(root / f"{key}.lock"):
|
|
142
|
+
if not refresh:
|
|
143
|
+
hit = read_cache(path, ttl_hours)
|
|
144
|
+
if hit is not None:
|
|
145
|
+
return hit, True
|
|
146
|
+
result = fetch()
|
|
147
|
+
if cacheable(result):
|
|
148
|
+
atomic_write_json(
|
|
149
|
+
path,
|
|
150
|
+
{
|
|
151
|
+
"schema": CACHE_SCHEMA,
|
|
152
|
+
"fetched_at": time.time(),
|
|
153
|
+
"kind": kind,
|
|
154
|
+
"query": payload,
|
|
155
|
+
"result": result,
|
|
156
|
+
},
|
|
157
|
+
)
|
|
158
|
+
return result, False
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def write_cache_entry(kind: str, payload: dict, result: dict) -> None:
|
|
162
|
+
key = cache_key(kind, payload)
|
|
163
|
+
root = cache_dir()
|
|
164
|
+
path = root / f"{key}.json"
|
|
165
|
+
with file_lock(root / f"{key}.lock"):
|
|
166
|
+
atomic_write_json(
|
|
167
|
+
path,
|
|
168
|
+
{
|
|
169
|
+
"schema": CACHE_SCHEMA,
|
|
170
|
+
"fetched_at": time.time(),
|
|
171
|
+
"kind": kind,
|
|
172
|
+
"query": payload,
|
|
173
|
+
"result": result,
|
|
174
|
+
},
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def cache_options(func: Callable) -> Callable:
|
|
179
|
+
func = click.option(
|
|
180
|
+
"--cache-ttl-hours",
|
|
181
|
+
type=float,
|
|
182
|
+
default=None,
|
|
183
|
+
help="Cache TTL in hours (default 168, env KINLOOM_CA_ARCHIVES_CACHE_TTL_HOURS; 0 disables reads).",
|
|
184
|
+
)(func)
|
|
185
|
+
func = click.option(
|
|
186
|
+
"--refresh",
|
|
187
|
+
is_flag=True,
|
|
188
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).",
|
|
189
|
+
)(func)
|
|
190
|
+
return func
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _client() -> httpx.Client:
|
|
194
|
+
return httpx.Client(timeout=30.0, follow_redirects=True, headers={"User-Agent": USER_AGENT})
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _http_get(url: str, headers: dict[str, str] | None = None) -> httpx.Response:
|
|
198
|
+
try:
|
|
199
|
+
with _client() as client:
|
|
200
|
+
resp = client.get(url, headers=headers)
|
|
201
|
+
except httpx.HTTPError as exc:
|
|
202
|
+
raise click.ClickException(f"California Archives request failed: {exc}") from exc
|
|
203
|
+
if resp.status_code != 200:
|
|
204
|
+
raise click.ClickException(f"California Archives returned HTTP {resp.status_code} for {url}")
|
|
205
|
+
return resp
|
|
206
|
+
|
|
38
207
|
OAC_BASE = "https://oac.cdlib.org"
|
|
39
208
|
CALISPHERE_BASE = "https://calisphere.org"
|
|
40
209
|
PORTAL_BASE = "https://archives.sos.ca.gov"
|
|
@@ -133,10 +302,8 @@ class PortalLinkParser(HTMLParser):
|
|
|
133
302
|
|
|
134
303
|
def search_portal(query, limit=10):
|
|
135
304
|
url = portal_url(query)
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
resp.raise_for_status()
|
|
139
|
-
html = resp.text
|
|
305
|
+
resp = _http_get(url)
|
|
306
|
+
html = resp.text
|
|
140
307
|
total = None
|
|
141
308
|
m = re.search(r"Search Results \d+ to \d+ of (\d+)", html)
|
|
142
309
|
if m:
|
|
@@ -158,14 +325,17 @@ def _omeka_title(item):
|
|
|
158
325
|
|
|
159
326
|
def search_exhibits(query, limit=10):
|
|
160
327
|
url = exhibits_url(query, limit)
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
resp.raise_for_status()
|
|
328
|
+
resp = _http_get(url, headers={"Accept": "application/ld+json"})
|
|
329
|
+
try:
|
|
164
330
|
items = resp.json()
|
|
165
|
-
|
|
166
|
-
|
|
331
|
+
except ValueError as exc:
|
|
332
|
+
raise click.ClickException(f"Invalid JSON from {url}: {exc}") from exc
|
|
333
|
+
if not isinstance(items, list):
|
|
334
|
+
raise click.ClickException(f"Unexpected JSON response from {url}")
|
|
335
|
+
hdr = resp.headers.get("Omeka-S-Total-Results")
|
|
336
|
+
total = int(hdr) if hdr else len(items)
|
|
167
337
|
results = []
|
|
168
|
-
for item in items
|
|
338
|
+
for item in items:
|
|
169
339
|
item_id = item.get("o:id")
|
|
170
340
|
types = item.get("@type", [])
|
|
171
341
|
results.append({
|
|
@@ -268,6 +438,8 @@ def _print_source(entry, limit_note=True):
|
|
|
268
438
|
header += ")"
|
|
269
439
|
else:
|
|
270
440
|
header += " (showing %d)" % shown
|
|
441
|
+
if entry.get("cache_hit"):
|
|
442
|
+
header += " [cache]"
|
|
271
443
|
click.echo(header)
|
|
272
444
|
click.echo(" " + entry["url"])
|
|
273
445
|
if not entry["results"]:
|
|
@@ -282,6 +454,42 @@ def _print_source(entry, limit_note=True):
|
|
|
282
454
|
click.echo(" " + r["url"])
|
|
283
455
|
|
|
284
456
|
|
|
457
|
+
def _source_cacheable(entry: dict) -> bool:
|
|
458
|
+
return bool(entry.get("results")) or entry.get("total") is not None
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _fetch_portal_item(portal_id: str) -> dict:
|
|
462
|
+
url = PORTAL_BASE + "/Items/Details/" + portal_id
|
|
463
|
+
resp = _http_get(url)
|
|
464
|
+
m = re.search(r"<title>([^<]+)</title>", resp.text)
|
|
465
|
+
title = (m.group(1).strip() if m else "(no title)").replace(" | California Archives Search", "")
|
|
466
|
+
return {"source": "portal", "id": portal_id, "title": title, "url": url}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _fetch_exhibits_item(exhibits_id: str) -> dict:
|
|
470
|
+
url = EXHIBITS_BASE + "/api/items/" + exhibits_id
|
|
471
|
+
resp = _http_get(url, headers={"Accept": "application/ld+json"})
|
|
472
|
+
try:
|
|
473
|
+
item = resp.json()
|
|
474
|
+
except ValueError as exc:
|
|
475
|
+
raise click.ClickException(f"Invalid JSON from {url}: {exc}") from exc
|
|
476
|
+
if not isinstance(item, dict):
|
|
477
|
+
raise click.ClickException(f"Unexpected JSON response from {url}")
|
|
478
|
+
desc = ""
|
|
479
|
+
for val in item.get("dcterms:description", []) or []:
|
|
480
|
+
if val.get("@value"):
|
|
481
|
+
desc = val["@value"]
|
|
482
|
+
break
|
|
483
|
+
return {
|
|
484
|
+
"source": "exhibits",
|
|
485
|
+
"id": exhibits_id,
|
|
486
|
+
"title": _omeka_title(item),
|
|
487
|
+
"type": ", ".join(t for t in item.get("@type", []) if t != "o:Item"),
|
|
488
|
+
"description": desc[:500],
|
|
489
|
+
"url": EXHIBITS_BASE + "/s/exhibits/item/" + exhibits_id,
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
|
|
285
493
|
@click.group()
|
|
286
494
|
def cli():
|
|
287
495
|
"""Search California archives portals (OAC, Calisphere, State Archives)."""
|
|
@@ -293,21 +501,54 @@ def cli():
|
|
|
293
501
|
help="Only search this source (repeatable). Default: all four.")
|
|
294
502
|
@click.option("--limit", default=10, show_default=True, help="Results per source.")
|
|
295
503
|
@click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of text.")
|
|
296
|
-
|
|
504
|
+
@cache_options
|
|
505
|
+
def search(query, sources, limit, as_json, refresh, cache_ttl_hours):
|
|
297
506
|
"""Search the California archives portals for QUERY."""
|
|
298
507
|
q = " ".join(query)
|
|
299
508
|
wanted = list(sources) if sources else list(SEARCHABLE)
|
|
509
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
510
|
+
payload = {"query": q, "limit": limit}
|
|
300
511
|
browser_sources = [s for s in wanted if s in ("oac", "calisphere")]
|
|
301
512
|
out = {}
|
|
302
|
-
|
|
303
|
-
|
|
513
|
+
uncached_browser: list[str] = []
|
|
514
|
+
for src in browser_sources:
|
|
515
|
+
key = cache_key(f"search:{src}", payload)
|
|
516
|
+
path = cache_dir() / f"{key}.json"
|
|
517
|
+
hit = None if refresh else read_cache(path, ttl)
|
|
518
|
+
if hit is not None:
|
|
519
|
+
out[src] = {**hit, "cache_hit": True}
|
|
520
|
+
else:
|
|
521
|
+
uncached_browser.append(src)
|
|
522
|
+
if uncached_browser:
|
|
523
|
+
fetched = browser_search(uncached_browser, q, limit)
|
|
524
|
+
for src, entry in fetched.items():
|
|
525
|
+
if _source_cacheable(entry):
|
|
526
|
+
write_cache_entry(f"search:{src}", payload, entry)
|
|
527
|
+
out[src] = {**entry, "cache_hit": False}
|
|
304
528
|
if "portal" in wanted:
|
|
305
|
-
|
|
529
|
+
entry, hit = cached_call(
|
|
530
|
+
"search:portal",
|
|
531
|
+
payload,
|
|
532
|
+
lambda: search_portal(q, limit),
|
|
533
|
+
refresh=refresh,
|
|
534
|
+
ttl_hours=ttl,
|
|
535
|
+
cacheable=_source_cacheable,
|
|
536
|
+
)
|
|
537
|
+
out["portal"] = {**entry, "cache_hit": hit}
|
|
306
538
|
if "exhibits" in wanted:
|
|
307
|
-
|
|
539
|
+
entry, hit = cached_call(
|
|
540
|
+
"search:exhibits",
|
|
541
|
+
payload,
|
|
542
|
+
lambda: search_exhibits(q, limit),
|
|
543
|
+
refresh=refresh,
|
|
544
|
+
ttl_hours=ttl,
|
|
545
|
+
cacheable=_source_cacheable,
|
|
546
|
+
)
|
|
547
|
+
out["exhibits"] = {**entry, "cache_hit": hit}
|
|
308
548
|
ordered = [out[s] for s in wanted if s in out]
|
|
309
549
|
if as_json:
|
|
310
|
-
|
|
550
|
+
all_cached = bool(ordered) and all(e.get("cache_hit") for e in ordered)
|
|
551
|
+
click.echo(json.dumps({"query": q, "cache_hit": all_cached, "sources": ordered}, indent=2))
|
|
311
552
|
return
|
|
312
553
|
for entry in ordered:
|
|
313
554
|
_print_source(entry)
|
|
@@ -334,39 +575,39 @@ def url(query, sources):
|
|
|
334
575
|
@click.option("--portal", "portal_id", default=None, help="Portal item ID (from search results).")
|
|
335
576
|
@click.option("--exhibits", "exhibits_id", default=None, help="Exhibits item ID (from search results).")
|
|
336
577
|
@click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of text.")
|
|
337
|
-
|
|
578
|
+
@cache_options
|
|
579
|
+
def get(portal_id, exhibits_id, as_json, refresh, cache_ttl_hours):
|
|
338
580
|
"""Fetch one Portal or exhibits item by ID."""
|
|
339
581
|
if bool(portal_id) == bool(exhibits_id):
|
|
340
582
|
raise click.UsageError("Pass exactly one of --portal ID or --exhibits ID.")
|
|
583
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
341
584
|
if portal_id:
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
585
|
+
data, hit = cached_call(
|
|
586
|
+
"get:portal",
|
|
587
|
+
{"id": portal_id},
|
|
588
|
+
lambda: _fetch_portal_item(portal_id),
|
|
589
|
+
refresh=refresh,
|
|
590
|
+
ttl_hours=ttl,
|
|
591
|
+
cacheable=lambda r: bool(r.get("title") and r.get("title") != "(no title)"),
|
|
592
|
+
)
|
|
349
593
|
else:
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
desc = val["@value"]
|
|
359
|
-
break
|
|
360
|
-
data = {"source": "exhibits", "id": exhibits_id, "title": _omeka_title(item),
|
|
361
|
-
"type": ", ".join(t for t in item.get("@type", []) if t != "o:Item"),
|
|
362
|
-
"description": desc[:500],
|
|
363
|
-
"url": EXHIBITS_BASE + "/s/exhibits/item/" + exhibits_id}
|
|
594
|
+
data, hit = cached_call(
|
|
595
|
+
"get:exhibits",
|
|
596
|
+
{"id": exhibits_id},
|
|
597
|
+
lambda: _fetch_exhibits_item(exhibits_id),
|
|
598
|
+
refresh=refresh,
|
|
599
|
+
ttl_hours=ttl,
|
|
600
|
+
cacheable=lambda r: bool(r.get("id")),
|
|
601
|
+
)
|
|
364
602
|
if as_json:
|
|
365
|
-
click.echo(json.dumps(data, indent=2))
|
|
603
|
+
click.echo(json.dumps({**data, "cache_hit": hit}, indent=2))
|
|
366
604
|
return
|
|
605
|
+
first = True
|
|
367
606
|
for key, val in data.items():
|
|
368
607
|
if val:
|
|
369
|
-
|
|
608
|
+
suffix = " [cache]" if first and hit else ""
|
|
609
|
+
click.echo("%s: %s%s" % (key, val, suffix))
|
|
610
|
+
first = False
|
|
370
611
|
|
|
371
612
|
|
|
372
613
|
if __name__ == "__main__":
|
|
@@ -9,7 +9,10 @@ This skill includes a standalone executable Python CLI at `skills/chronicling-am
|
|
|
9
9
|
|
|
10
10
|
- **Coverage:** millions of digitized U.S. newspaper pages, 1736 through 1963 (per the collection record; the site describes it as "through 1963").
|
|
11
11
|
- **Access:** the public loc.gov JSON API. No key, no account, no sign-in.
|
|
12
|
-
- **
|
|
12
|
+
- **Latency (measured 2026-11-25):** every loc.gov collection search takes **20-45 s** on the server side. Connect + TLS take under 0.1 s, but time-to-first-byte was 19-43 s for every query shape tried (with or without `q`, `dates`, `fa=location_state`, `dl=page`, `at=results` vs `at=search,results`, HTTP/1.1 vs HTTP/2, kinloom vs browser User-Agent). One probe under 6 parallel requests took 70 s. The old 8 s default timeout therefore failed 80%+ of searches. The default `--timeout` is now **120 s**. `/newspapers/?fo=json` returned 0 hits for the same query, and `/search/?fa=partof:chronicling+america` 302-redirects to the collection endpoint, so neither is faster.
|
|
13
|
+
- **Disk cache:** every successful search (and every `get`/`download` item lookup) is cached, so a repeat returns in well under a second with no network call. See [Disk cache](#disk-cache).
|
|
14
|
+
- **Rate limits:** be gentle. LoC asks users to stay within limits; search queries returning more than 100,000 results are too big for the API, so narrow with `--dates`, `--state`, or `--lccn` first. The CLI retries HTTP 429/503 once after the `Retry-After` delay (capped at 30 s) and retries 5xx and dropped connections once.
|
|
15
|
+
- **Unstable hit counts (measured 2026-11-25):** loc.gov can return very different `hits` for byte-identical requests. `Merced` + California + 1900/1920 returned 32, then 34,133, then 35,404. `Abraham Lincoln` returned 0, then 25,392, then 77,301. So a low or zero count is **not** evidence of absence. The CLI never caches a zero-hit answer. To recheck a suspiciously low count, rerun with `--refresh`.
|
|
13
16
|
|
|
14
17
|
## Bundled CLI (`scripts/chronam`)
|
|
15
18
|
|
|
@@ -21,19 +24,34 @@ Path: `skills/chronicling-america/scripts/chronam`
|
|
|
21
24
|
# Full-text search for a surname, page level, 10 results
|
|
22
25
|
skills/chronicling-america/scripts/chronam search Lincoln
|
|
23
26
|
|
|
24
|
-
#
|
|
27
|
+
# Multi-word queries need no quotes; postal codes work for --state
|
|
28
|
+
skills/chronicling-america/scripts/chronam search Abraham Lincoln --state IL --dates 1860/1865
|
|
29
|
+
|
|
30
|
+
# Surname search narrowed to 1860-1865 (or --date-from 1860 --date-to 1865)
|
|
25
31
|
skills/chronicling-america/scripts/chronam search Lincoln --dates 1860/1865
|
|
26
32
|
|
|
27
33
|
# Illinois papers only (server-side state facet), JSON output
|
|
28
34
|
skills/chronicling-america/scripts/chronam search Lincoln --dates 1860/1865 --state Illinois --json
|
|
29
35
|
|
|
30
36
|
# One newspaper title only, by LCCN (Evening Star, Washington, D.C.)
|
|
31
|
-
|
|
37
|
+
# Use one distinctive word with --lccn: measured 2026-11-25, "Clara Barton" + this LCCN
|
|
38
|
+
# returned 0 hits on three tries, while "Barton" + the same LCCN returned 38,628.
|
|
39
|
+
skills/chronicling-america/scripts/chronam search Barton --lccn sn83045462
|
|
32
40
|
|
|
33
|
-
# Second page of results, 25 per page
|
|
41
|
+
# Second page of results, 25 per page (--per-page is an alias for --limit)
|
|
34
42
|
skills/chronicling-america/scripts/chronam search "Frederick Douglass" --dates 1870/1895 --limit 25 --page 2
|
|
35
43
|
```
|
|
36
44
|
|
|
45
|
+
Options: `--dates YYYY/YYYY` or `YYYY` (or `--date-from`/`--from-year`/`--date1`/`--year1` and `--date-to`/`--to-year`/`--date2`/`--year2`), `--state` (name or postal code), `--lccn`, `--level` (`page`/`issue`/`title`/`all`), `--limit` / `--per-page` / `--rows` / `-n`, `--page` / `-p`, `--timeout` (seconds, default `120`), `--terms` / `--query` / `-q` (alias for positional query), `--refresh`, `--cache-ttl-hours`, `--json`. JSON output carries `"cache_hit": true|false`; text output marks hits with `[cache]`.
|
|
46
|
+
|
|
47
|
+
### Disk cache
|
|
48
|
+
|
|
49
|
+
- Location: `~/.cache/kinloom-chronam/` (override with `KINLOOM_CHRONAM_CACHE_DIR`). One JSON file per request, keyed by the SHA-256 of the URL and sorted query parameters.
|
|
50
|
+
- TTL: 168 hours (override with `--cache-ttl-hours` or `KINLOOM_CHRONAM_CACHE_TTL_HOURS`; `0` disables reads).
|
|
51
|
+
- `--refresh` re-queries loc.gov and rewrites the entry.
|
|
52
|
+
- Zero-hit answers are never cached (see unstable hit counts above).
|
|
53
|
+
- Writes are atomic (temp file + rename). A per-query `flock` makes concurrent agents that run the same search wait for the first one and then read its file, so loc.gov sees one request.
|
|
54
|
+
|
|
37
55
|
### Inspect one page
|
|
38
56
|
|
|
39
57
|
```bash
|
|
@@ -85,13 +103,15 @@ skills/chronicling-america/scripts/chronam url "Susan B. Anthony" --dates 1870/1
|
|
|
85
103
|
|
|
86
104
|
## What is dead (verified 2026-11-24)
|
|
87
105
|
|
|
88
|
-
- The old Chronicling America API at `chroniclingamerica.loc.gov/search/pages/results/?...&format=json`
|
|
106
|
+
- The old Chronicling America API at `chroniclingamerica.loc.gov/search/pages/results/?...&format=json` returned **404** on 2026-11-24 and a Cloudflare **308** redirect on 2026-11-25. Third-party API directories (publicapi.dev, publicapis.io) still document it, including claims that an API key is required. Both claims are wrong now: the endpoint is gone, and the loc.gov API never needs a key.
|
|
89
107
|
- `chroniclingamerica.loc.gov/about/api/` returns 403.
|
|
90
108
|
- The loc.gov HTML pages return 403 to plain scripted requests; use the `fo=json` endpoints for machine access.
|
|
91
109
|
|
|
92
110
|
## Environment variables
|
|
93
111
|
|
|
94
|
-
-
|
|
112
|
+
- No key or account is needed.
|
|
113
|
+
- `KINLOOM_CHRONAM_CACHE_DIR` (optional): cache directory (default `~/.cache/kinloom-chronam`).
|
|
114
|
+
- `KINLOOM_CHRONAM_CACHE_TTL_HOURS` (optional): cache TTL in hours (default `168`).
|
|
95
115
|
|
|
96
116
|
## Research workflow notes
|
|
97
117
|
|