@kinloom/cli 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/cached-ocr.py +786 -0
- package/dist/assets/ocr.md +76 -0
- package/dist/assets/prep-scan.md +97 -0
- package/dist/assets/prep-scan.py +1313 -0
- package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
- package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
- package/dist/bundled-skills/archive-org/SKILL.md +162 -0
- package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
- package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
- package/dist/bundled-skills/california-archives/SKILL.md +130 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
- package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
- package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
- package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
- package/dist/bundled-skills/findagrave/SKILL.md +129 -0
- package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
- package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
- package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
- package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
- package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
- package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
- package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
- package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
- package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
- package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
- package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
- package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
- package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
- package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
- package/dist/bundled-skills/wikitree/SKILL.md +154 -0
- package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +488 -26
- 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 +138 -0
- package/dist/commands/ops/audit.d.ts.map +1 -0
- package/dist/commands/ops/audit.js +872 -0
- package/dist/commands/ops/audit.js.map +1 -0
- package/dist/commands/ops/context.d.ts +100 -0
- package/dist/commands/ops/context.d.ts.map +1 -0
- package/dist/commands/ops/context.js +917 -0
- package/dist/commands/ops/context.js.map +1 -0
- 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 +8 -0
- package/dist/commands/ops/help.d.ts.map +1 -0
- package/dist/commands/ops/help.js +107 -0
- package/dist/commands/ops/help.js.map +1 -0
- package/dist/commands/ops/index.d.ts +8 -0
- package/dist/commands/ops/index.d.ts.map +1 -0
- package/dist/commands/ops/index.js +8 -0
- package/dist/commands/ops/index.js.map +1 -0
- package/dist/commands/ops/integrate.d.ts +61 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -0
- package/dist/commands/ops/integrate.js +1063 -0
- package/dist/commands/ops/integrate.js.map +1 -0
- package/dist/commands/ops/sync.d.ts +194 -0
- package/dist/commands/ops/sync.d.ts.map +1 -0
- package/dist/commands/ops/sync.js +1251 -0
- package/dist/commands/ops/sync.js.map +1 -0
- package/dist/commands/ops/telemetry.d.ts +79 -0
- package/dist/commands/ops/telemetry.d.ts.map +1 -0
- package/dist/commands/ops/telemetry.js +249 -0
- package/dist/commands/ops/telemetry.js.map +1 -0
- 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/help.d.ts +18 -0
- package/dist/commands/records/help.d.ts.map +1 -0
- package/dist/commands/records/help.js +174 -0
- package/dist/commands/records/help.js.map +1 -0
- package/dist/commands/records/index.d.ts +5 -0
- package/dist/commands/records/index.d.ts.map +1 -0
- package/dist/commands/records/index.js +5 -0
- package/dist/commands/records/index.js.map +1 -0
- package/dist/commands/records/registry.d.ts +32 -0
- package/dist/commands/records/registry.d.ts.map +1 -0
- package/dist/commands/records/registry.js +227 -0
- package/dist/commands/records/registry.js.map +1 -0
- package/dist/commands/records/resolve.d.ts +14 -0
- package/dist/commands/records/resolve.d.ts.map +1 -0
- package/dist/commands/records/resolve.js +61 -0
- package/dist/commands/records/resolve.js.map +1 -0
- package/dist/commands/records/runner.d.ts +27 -0
- package/dist/commands/records/runner.d.ts.map +1 -0
- package/dist/commands/records/runner.js +255 -0
- package/dist/commands/records/runner.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
#!/usr/bin/env -S uv run --script
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.11"
|
|
4
|
+
# dependencies = [
|
|
5
|
+
# "click>=8.1",
|
|
6
|
+
# "httpx>=0.27",
|
|
7
|
+
# "playwright>=1.49",
|
|
8
|
+
# ]
|
|
9
|
+
# ///
|
|
10
|
+
"""Search California archives portals: OAC, Calisphere, the California
|
|
11
|
+
Archives Search Portal, the Archives exhibits (Omeka S API), plus
|
|
12
|
+
search-URL builders for CDNC and Minerva.
|
|
13
|
+
|
|
14
|
+
Machine interfaces verified live 2026-11-24 (see the
|
|
15
|
+
california-archives SKILL.md). No account or API key is needed for any
|
|
16
|
+
source. OAC and Calisphere sit behind a bot challenge that plain HTTP
|
|
17
|
+
cannot pass, so those two run through headless Chromium; the Portal and
|
|
18
|
+
the exhibits API answer plain HTTPS directly. CDNC is behind a
|
|
19
|
+
Cloudflare challenge even headless Chromium cannot pass, and Minerva
|
|
20
|
+
is a POST/JS catalog with no verified machine search route, so those
|
|
21
|
+
two are URL builders only (see the `url` command).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import hashlib
|
|
27
|
+
import json
|
|
28
|
+
import math
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import shutil
|
|
32
|
+
import sys
|
|
33
|
+
import time
|
|
34
|
+
from contextlib import contextmanager
|
|
35
|
+
from html.parser import HTMLParser
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import Any, Callable, Iterator
|
|
38
|
+
from urllib.parse import quote, urlencode
|
|
39
|
+
|
|
40
|
+
import click
|
|
41
|
+
import httpx
|
|
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
|
+
|
|
207
|
+
OAC_BASE = "https://oac.cdlib.org"
|
|
208
|
+
CALISPHERE_BASE = "https://calisphere.org"
|
|
209
|
+
PORTAL_BASE = "https://archives.sos.ca.gov"
|
|
210
|
+
EXHIBITS_BASE = "https://exhibits.sos.ca.gov"
|
|
211
|
+
CDNC_BASE = "https://cdnc.ucr.edu/cgi-bin/cdnc"
|
|
212
|
+
MINERVA_URL = (
|
|
213
|
+
"https://gencat.sos.ca.gov/webcat/request/DoMenuRequest"
|
|
214
|
+
"?SystemName=California+State+Archives&UserName=csa+public&Password="
|
|
215
|
+
"&TemplateProcessID=6000_3355&bCachable=1&MenuName=Minerva+Online+Catalog"
|
|
216
|
+
)
|
|
217
|
+
USER_AGENT = (
|
|
218
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
|
219
|
+
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
|
220
|
+
)
|
|
221
|
+
SEARCHABLE = ("oac", "calisphere", "portal", "exhibits")
|
|
222
|
+
ALL_SOURCES = SEARCHABLE + ("cdnc", "minerva")
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def find_browser_executable():
|
|
226
|
+
env_exe = os.environ.get("CA_ARCHIVES_BROWSER")
|
|
227
|
+
if env_exe and Path(env_exe).exists():
|
|
228
|
+
return env_exe
|
|
229
|
+
for candidate in ("chromium", "chromium-browser", "google-chrome", "google-chrome-stable"):
|
|
230
|
+
found = shutil.which(candidate)
|
|
231
|
+
if found:
|
|
232
|
+
return found
|
|
233
|
+
return None
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def oac_url(query):
|
|
237
|
+
return OAC_BASE + "/search?" + urlencode({"q": query}, quote_via=quote)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def calisphere_url(query):
|
|
241
|
+
return CALISPHERE_BASE + "/search/?" + urlencode({"q": query}, quote_via=quote)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def portal_url(query):
|
|
245
|
+
return PORTAL_BASE + "/Items?" + urlencode({"SearchText": query}, quote_via=quote)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def exhibits_url(query, limit=10):
|
|
249
|
+
return EXHIBITS_BASE + "/api/items?" + urlencode(
|
|
250
|
+
{"search": query, "per_page": str(limit)}, quote_via=quote
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def cdnc_url(query):
|
|
255
|
+
# Veridian search URL; pattern corroborated by published CDNC result
|
|
256
|
+
# URLs. The e= value selects all years, English, 20 results per page.
|
|
257
|
+
return CDNC_BASE + "?a=q&r=1&results=1&txq=" + quote(query) + "&e=-------en--20--1--txt-txIN-------"
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def build_url(source, query, limit=10):
|
|
261
|
+
builders = {
|
|
262
|
+
"oac": lambda: oac_url(query),
|
|
263
|
+
"calisphere": lambda: calisphere_url(query),
|
|
264
|
+
"portal": lambda: portal_url(query),
|
|
265
|
+
"exhibits": lambda: exhibits_url(query, limit),
|
|
266
|
+
"cdnc": lambda: cdnc_url(query),
|
|
267
|
+
"minerva": lambda: MINERVA_URL,
|
|
268
|
+
}
|
|
269
|
+
return builders[source]()
|
|
270
|
+
|
|
271
|
+
class PortalLinkParser(HTMLParser):
|
|
272
|
+
"""Collect titled links to /Items/Details/<id> from a Portal results page."""
|
|
273
|
+
|
|
274
|
+
def __init__(self):
|
|
275
|
+
super().__init__(convert_charrefs=True)
|
|
276
|
+
self.results = []
|
|
277
|
+
self._href = None
|
|
278
|
+
self._text = []
|
|
279
|
+
|
|
280
|
+
def handle_starttag(self, tag, attrs):
|
|
281
|
+
if tag == "a":
|
|
282
|
+
href = dict(attrs).get("href", "")
|
|
283
|
+
m = re.match(r"/Items/Details/(\d+)$", href)
|
|
284
|
+
if m:
|
|
285
|
+
self._href = (m.group(1), href)
|
|
286
|
+
self._text = []
|
|
287
|
+
|
|
288
|
+
def handle_data(self, data):
|
|
289
|
+
if self._href is not None:
|
|
290
|
+
self._text.append(data)
|
|
291
|
+
|
|
292
|
+
def handle_endtag(self, tag):
|
|
293
|
+
if tag == "a" and self._href is not None:
|
|
294
|
+
title = " ".join("".join(self._text).split())
|
|
295
|
+
if title:
|
|
296
|
+
item_id, href = self._href
|
|
297
|
+
if not any(r["id"] == item_id for r in self.results):
|
|
298
|
+
self.results.append({"id": item_id, "title": title, "url": PORTAL_BASE + href})
|
|
299
|
+
self._href = None
|
|
300
|
+
self._text = []
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def search_portal(query, limit=10):
|
|
304
|
+
url = portal_url(query)
|
|
305
|
+
resp = _http_get(url)
|
|
306
|
+
html = resp.text
|
|
307
|
+
total = None
|
|
308
|
+
m = re.search(r"Search Results \d+ to \d+ of (\d+)", html)
|
|
309
|
+
if m:
|
|
310
|
+
total = int(m.group(1))
|
|
311
|
+
parser = PortalLinkParser()
|
|
312
|
+
parser.feed(html)
|
|
313
|
+
return {"source": "portal", "url": url, "total": total, "results": parser.results[:limit]}
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _omeka_title(item):
|
|
317
|
+
title = item.get("o:title")
|
|
318
|
+
if title:
|
|
319
|
+
return title
|
|
320
|
+
vals = item.get("dcterms:title", [])
|
|
321
|
+
if vals and isinstance(vals, list) and vals[0].get("@value"):
|
|
322
|
+
return vals[0]["@value"]
|
|
323
|
+
return "(untitled)"
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def search_exhibits(query, limit=10):
|
|
327
|
+
url = exhibits_url(query, limit)
|
|
328
|
+
resp = _http_get(url, headers={"Accept": "application/ld+json"})
|
|
329
|
+
try:
|
|
330
|
+
items = resp.json()
|
|
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)
|
|
337
|
+
results = []
|
|
338
|
+
for item in items:
|
|
339
|
+
item_id = item.get("o:id")
|
|
340
|
+
types = item.get("@type", [])
|
|
341
|
+
results.append({
|
|
342
|
+
"id": str(item_id),
|
|
343
|
+
"title": _omeka_title(item),
|
|
344
|
+
"type": ", ".join(t for t in types if t != "o:Item"),
|
|
345
|
+
"url": EXHIBITS_BASE + "/s/exhibits/item/" + str(item_id),
|
|
346
|
+
})
|
|
347
|
+
return {"source": "exhibits", "url": url, "total": total, "results": results}
|
|
348
|
+
|
|
349
|
+
OAC_LINKS_JS = """() => Array.from(document.querySelectorAll('a[href*="/findaid/"]')).map(a => ({href: a.getAttribute('href'), text: a.textContent.trim().replace(/\\s+/g, ' ').slice(0, 160)}))"""
|
|
350
|
+
CAL_LINKS_JS = """() => Array.from(document.querySelectorAll('a[href*="/item/"]')).map(a => ({href: a.getAttribute('href'), text: a.textContent.trim().replace(/\\s+/g, ' ').slice(0, 160)}))"""
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _dedupe_links(links, base, limit):
|
|
354
|
+
seen = set()
|
|
355
|
+
results = []
|
|
356
|
+
for link in links:
|
|
357
|
+
href = link.get("href", "")
|
|
358
|
+
text = (link.get("text") or "").strip()
|
|
359
|
+
if not href or not text or href in seen:
|
|
360
|
+
continue
|
|
361
|
+
seen.add(href)
|
|
362
|
+
kind = "component" if "_aspace_" in href else "collection"
|
|
363
|
+
results.append({"title": text, "url": base + href, "kind": kind})
|
|
364
|
+
if len(results) >= limit:
|
|
365
|
+
break
|
|
366
|
+
return results
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def browser_search(sources, query, limit=10, timeout_ms=60000):
|
|
370
|
+
"""Search OAC and/or Calisphere sharing one headless Chromium session."""
|
|
371
|
+
from playwright.sync_api import sync_playwright
|
|
372
|
+
|
|
373
|
+
exe = find_browser_executable()
|
|
374
|
+
if exe is None:
|
|
375
|
+
raise click.ClickException("No Chromium/Chrome executable found; set CA_ARCHIVES_BROWSER.")
|
|
376
|
+
out = {}
|
|
377
|
+
with sync_playwright() as pw:
|
|
378
|
+
browser = pw.chromium.launch(headless=True, executable_path=exe, args=["--no-sandbox"])
|
|
379
|
+
page = browser.new_page(user_agent=USER_AGENT)
|
|
380
|
+
try:
|
|
381
|
+
if "oac" in sources:
|
|
382
|
+
url = oac_url(query)
|
|
383
|
+
page.goto(url, wait_until="domcontentloaded", timeout=timeout_ms)
|
|
384
|
+
try:
|
|
385
|
+
page.wait_for_function(
|
|
386
|
+
"() => /of \\d+ entries|No results/i.test(document.body.innerText)",
|
|
387
|
+
timeout=20000,
|
|
388
|
+
)
|
|
389
|
+
except Exception:
|
|
390
|
+
pass
|
|
391
|
+
page.wait_for_timeout(500)
|
|
392
|
+
text = page.evaluate("document.body.innerText")
|
|
393
|
+
m = re.search(r"of (\d+) entries", text)
|
|
394
|
+
total = int(m.group(1)) if m else None
|
|
395
|
+
links = page.evaluate(OAC_LINKS_JS)
|
|
396
|
+
out["oac"] = {"source": "oac", "url": url, "total": total,
|
|
397
|
+
"results": _dedupe_links(links, OAC_BASE, limit)}
|
|
398
|
+
if "calisphere" in sources:
|
|
399
|
+
url = calisphere_url(query)
|
|
400
|
+
page.goto(url, wait_until="domcontentloaded", timeout=timeout_ms)
|
|
401
|
+
try:
|
|
402
|
+
page.wait_for_function(
|
|
403
|
+
"() => /\\d+ items? found|No results/i.test(document.body.innerText)",
|
|
404
|
+
timeout=20000,
|
|
405
|
+
)
|
|
406
|
+
except Exception:
|
|
407
|
+
pass
|
|
408
|
+
page.wait_for_timeout(500)
|
|
409
|
+
text = page.evaluate("document.body.innerText")
|
|
410
|
+
m = re.search(r"(\d+) items? found", text)
|
|
411
|
+
total = int(m.group(1)) if m else None
|
|
412
|
+
links = page.evaluate(CAL_LINKS_JS)
|
|
413
|
+
results = []
|
|
414
|
+
for link in links:
|
|
415
|
+
href = link.get("href", "")
|
|
416
|
+
title = (link.get("text") or "").strip()
|
|
417
|
+
if not href.startswith("/item/") or not title:
|
|
418
|
+
continue
|
|
419
|
+
if any(r["url"] == CALISPHERE_BASE + href for r in results):
|
|
420
|
+
continue
|
|
421
|
+
results.append({"title": title, "url": CALISPHERE_BASE + href})
|
|
422
|
+
if len(results) >= limit:
|
|
423
|
+
break
|
|
424
|
+
out["calisphere"] = {"source": "calisphere", "url": url, "total": total, "results": results}
|
|
425
|
+
finally:
|
|
426
|
+
browser.close()
|
|
427
|
+
return out
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _print_source(entry, limit_note=True):
|
|
431
|
+
total = entry.get("total")
|
|
432
|
+
shown = len(entry["results"])
|
|
433
|
+
header = entry["source"]
|
|
434
|
+
if total is not None:
|
|
435
|
+
header += " (%d total" % total
|
|
436
|
+
header += ", showing %d" % shown if shown != total else ")"
|
|
437
|
+
if shown != total:
|
|
438
|
+
header += ")"
|
|
439
|
+
else:
|
|
440
|
+
header += " (showing %d)" % shown
|
|
441
|
+
if entry.get("cache_hit"):
|
|
442
|
+
header += " [cache]"
|
|
443
|
+
click.echo(header)
|
|
444
|
+
click.echo(" " + entry["url"])
|
|
445
|
+
if not entry["results"]:
|
|
446
|
+
click.echo(" No results.")
|
|
447
|
+
for i, r in enumerate(entry["results"], 1):
|
|
448
|
+
line = " %d. %s" % (i, r["title"])
|
|
449
|
+
if r.get("kind"):
|
|
450
|
+
line += " [%s]" % r["kind"]
|
|
451
|
+
if r.get("type"):
|
|
452
|
+
line += " (%s)" % r["type"]
|
|
453
|
+
click.echo(line)
|
|
454
|
+
click.echo(" " + r["url"])
|
|
455
|
+
|
|
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
|
+
|
|
493
|
+
@click.group()
|
|
494
|
+
def cli():
|
|
495
|
+
"""Search California archives portals (OAC, Calisphere, State Archives)."""
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
@cli.command()
|
|
499
|
+
@click.argument("query", nargs=-1, required=True)
|
|
500
|
+
@click.option("--source", "sources", multiple=True, type=click.Choice(SEARCHABLE),
|
|
501
|
+
help="Only search this source (repeatable). Default: all four.")
|
|
502
|
+
@click.option("--limit", default=10, show_default=True, help="Results per source.")
|
|
503
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of text.")
|
|
504
|
+
@cache_options
|
|
505
|
+
def search(query, sources, limit, as_json, refresh, cache_ttl_hours):
|
|
506
|
+
"""Search the California archives portals for QUERY."""
|
|
507
|
+
q = " ".join(query)
|
|
508
|
+
wanted = list(sources) if sources else list(SEARCHABLE)
|
|
509
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
510
|
+
payload = {"query": q, "limit": limit}
|
|
511
|
+
browser_sources = [s for s in wanted if s in ("oac", "calisphere")]
|
|
512
|
+
out = {}
|
|
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}
|
|
528
|
+
if "portal" in wanted:
|
|
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}
|
|
538
|
+
if "exhibits" in wanted:
|
|
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}
|
|
548
|
+
ordered = [out[s] for s in wanted if s in out]
|
|
549
|
+
if as_json:
|
|
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))
|
|
552
|
+
return
|
|
553
|
+
for entry in ordered:
|
|
554
|
+
_print_source(entry)
|
|
555
|
+
click.echo("")
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
@cli.command()
|
|
559
|
+
@click.argument("query", nargs=-1, required=True)
|
|
560
|
+
@click.option("--source", "sources", multiple=True, type=click.Choice(ALL_SOURCES),
|
|
561
|
+
help="Only print URLs for this source (repeatable). Default: all six.")
|
|
562
|
+
def url(query, sources):
|
|
563
|
+
"""Print verified search URLs for QUERY without running any search."""
|
|
564
|
+
q = " ".join(query)
|
|
565
|
+
wanted = list(sources) if sources else list(ALL_SOURCES)
|
|
566
|
+
for s in wanted:
|
|
567
|
+
click.echo("%s: %s" % (s, build_url(s, q)))
|
|
568
|
+
if "cdnc" in wanted:
|
|
569
|
+
click.echo("note: CDNC is behind a Cloudflare challenge; open the URL in a browser.")
|
|
570
|
+
if "minerva" in wanted:
|
|
571
|
+
click.echo("note: Minerva is a catalog you search in the browser; this is its launch URL.")
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
@cli.command()
|
|
575
|
+
@click.option("--portal", "portal_id", default=None, help="Portal item ID (from search results).")
|
|
576
|
+
@click.option("--exhibits", "exhibits_id", default=None, help="Exhibits item ID (from search results).")
|
|
577
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of text.")
|
|
578
|
+
@cache_options
|
|
579
|
+
def get(portal_id, exhibits_id, as_json, refresh, cache_ttl_hours):
|
|
580
|
+
"""Fetch one Portal or exhibits item by ID."""
|
|
581
|
+
if bool(portal_id) == bool(exhibits_id):
|
|
582
|
+
raise click.UsageError("Pass exactly one of --portal ID or --exhibits ID.")
|
|
583
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
584
|
+
if portal_id:
|
|
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
|
+
)
|
|
593
|
+
else:
|
|
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
|
+
)
|
|
602
|
+
if as_json:
|
|
603
|
+
click.echo(json.dumps({**data, "cache_hit": hit}, indent=2))
|
|
604
|
+
return
|
|
605
|
+
first = True
|
|
606
|
+
for key, val in data.items():
|
|
607
|
+
if val:
|
|
608
|
+
suffix = " [cache]" if first and hit else ""
|
|
609
|
+
click.echo("%s: %s%s" % (key, val, suffix))
|
|
610
|
+
first = False
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
if __name__ == "__main__":
|
|
614
|
+
cli()
|