@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,646 @@
|
|
|
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
|
+
# ]
|
|
8
|
+
# ///
|
|
9
|
+
"""ky-archives: search Kentucky archives from the command line.
|
|
10
|
+
|
|
11
|
+
Verified live 2026-11-24. No account or API key is needed
|
|
12
|
+
for any command. Three real machine interfaces:
|
|
13
|
+
|
|
14
|
+
- KHS Digital Collections (CONTENTdm dmwebservices API, key-free):
|
|
15
|
+
``cdm`` and ``cdm-item`` hit https://www.kyhistory.com/digital/api/...
|
|
16
|
+
- KY Secretary of State Land Office, County Court Orders patents
|
|
17
|
+
(ASP.NET form POST with VIEWSTATE): ``land`` and ``land-patent``.
|
|
18
|
+
- KDLA Preservica e-archives (WordPress search RSS feed):
|
|
19
|
+
``preservica`` fetches https://kdla.access.preservica.com/search/<term>/feed/rss2/
|
|
20
|
+
and lists the matching record pages. Viewing a packet itself needs the browser.
|
|
21
|
+
|
|
22
|
+
What has NO machine interface (browser only, use the ``urls`` command
|
|
23
|
+
to get the links): the Virginia / Old Kentucky Patent Series browser
|
|
24
|
+
(series + patent dropdowns, no name search), Pass the Word oral
|
|
25
|
+
histories, and the UK Kentucky Vital Records Index (its old
|
|
26
|
+
ukcc.uky.edu/vitalrec URL did not resolve live 2026-11-24).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import hashlib
|
|
32
|
+
import html as htmlmod
|
|
33
|
+
import json
|
|
34
|
+
import math
|
|
35
|
+
import os
|
|
36
|
+
import re
|
|
37
|
+
import time
|
|
38
|
+
from contextlib import contextmanager
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
from typing import Any, Callable, Iterator
|
|
41
|
+
from urllib.parse import quote
|
|
42
|
+
|
|
43
|
+
import click
|
|
44
|
+
import httpx
|
|
45
|
+
|
|
46
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
47
|
+
CACHE_SCHEMA = 1
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cache_dir() -> Path:
|
|
51
|
+
override = os.environ.get("KINLOOM_KY_ARCHIVES_CACHE_DIR")
|
|
52
|
+
if override:
|
|
53
|
+
return Path(override).expanduser()
|
|
54
|
+
return Path.home() / ".cache" / "kinloom-ky-archives"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
58
|
+
if cli_ttl is not None:
|
|
59
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
60
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
61
|
+
return float(cli_ttl)
|
|
62
|
+
raw = os.environ.get("KINLOOM_KY_ARCHIVES_CACHE_TTL_HOURS")
|
|
63
|
+
if raw is not None and raw.strip():
|
|
64
|
+
try:
|
|
65
|
+
parsed = float(raw.strip())
|
|
66
|
+
except ValueError as exc:
|
|
67
|
+
raise click.BadParameter(f"Invalid KINLOOM_KY_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
68
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
69
|
+
raise click.BadParameter(
|
|
70
|
+
f"Invalid KINLOOM_KY_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
|
|
71
|
+
)
|
|
72
|
+
return parsed
|
|
73
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@contextmanager
|
|
77
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
78
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
79
|
+
try:
|
|
80
|
+
import fcntl
|
|
81
|
+
except ImportError:
|
|
82
|
+
yield
|
|
83
|
+
return
|
|
84
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
with open(lock_path, "a+b") as lock_file:
|
|
86
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
87
|
+
try:
|
|
88
|
+
yield
|
|
89
|
+
finally:
|
|
90
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
94
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
96
|
+
try:
|
|
97
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
98
|
+
os.replace(tmp, dest)
|
|
99
|
+
except Exception:
|
|
100
|
+
tmp.unlink(missing_ok=True)
|
|
101
|
+
raise
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
105
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
106
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
110
|
+
if not path.is_file():
|
|
111
|
+
return None
|
|
112
|
+
try:
|
|
113
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
114
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
115
|
+
return None
|
|
116
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
117
|
+
return None
|
|
118
|
+
fetched = entry.get("fetched_at")
|
|
119
|
+
if not isinstance(fetched, (int, float)):
|
|
120
|
+
return None
|
|
121
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
122
|
+
return None
|
|
123
|
+
result = entry.get("result")
|
|
124
|
+
return result if isinstance(result, dict) else None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def cached_call(
|
|
128
|
+
kind: str,
|
|
129
|
+
payload: dict,
|
|
130
|
+
fetch: Callable[[], dict],
|
|
131
|
+
*,
|
|
132
|
+
refresh: bool,
|
|
133
|
+
ttl_hours: float,
|
|
134
|
+
cacheable: Callable[[dict], bool] = lambda _r: True,
|
|
135
|
+
) -> tuple[dict, bool]:
|
|
136
|
+
"""Return (result, cache_hit) with per-key flock and atomic JSON writes."""
|
|
137
|
+
key = cache_key(kind, payload)
|
|
138
|
+
root = cache_dir()
|
|
139
|
+
path = root / f"{key}.json"
|
|
140
|
+
if not refresh:
|
|
141
|
+
hit = read_cache(path, ttl_hours)
|
|
142
|
+
if hit is not None:
|
|
143
|
+
return hit, True
|
|
144
|
+
with file_lock(root / f"{key}.lock"):
|
|
145
|
+
if not refresh:
|
|
146
|
+
hit = read_cache(path, ttl_hours)
|
|
147
|
+
if hit is not None:
|
|
148
|
+
return hit, True
|
|
149
|
+
result = fetch()
|
|
150
|
+
if cacheable(result):
|
|
151
|
+
atomic_write_json(
|
|
152
|
+
path,
|
|
153
|
+
{
|
|
154
|
+
"schema": CACHE_SCHEMA,
|
|
155
|
+
"fetched_at": time.time(),
|
|
156
|
+
"kind": kind,
|
|
157
|
+
"query": payload,
|
|
158
|
+
"result": result,
|
|
159
|
+
},
|
|
160
|
+
)
|
|
161
|
+
return result, False
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def cache_options(func: Callable) -> Callable:
|
|
165
|
+
func = click.option(
|
|
166
|
+
"--cache-ttl-hours",
|
|
167
|
+
type=float,
|
|
168
|
+
default=None,
|
|
169
|
+
help="Cache TTL in hours (default 168, env KINLOOM_KY_ARCHIVES_CACHE_TTL_HOURS; 0 disables reads).",
|
|
170
|
+
)(func)
|
|
171
|
+
func = click.option(
|
|
172
|
+
"--refresh",
|
|
173
|
+
is_flag=True,
|
|
174
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).",
|
|
175
|
+
)(func)
|
|
176
|
+
return func
|
|
177
|
+
|
|
178
|
+
CDM_BASE = "https://www.kyhistory.com"
|
|
179
|
+
CDM_API = CDM_BASE + "/digital/api"
|
|
180
|
+
LAND_URL = "https://web.sos.ky.gov/land/ccorders.aspx"
|
|
181
|
+
PRESERVICA_BASE = "https://kdla.access.preservica.com"
|
|
182
|
+
# The KHS web UI returns 403 to a bare Linux-Chrome UA; a Windows Chrome
|
|
183
|
+
# UA returns 200. The CONTENTdm API accepts either; use one UA everywhere.
|
|
184
|
+
UA = (
|
|
185
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
186
|
+
"(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
|
|
187
|
+
)
|
|
188
|
+
TIMEOUT = 30.0
|
|
189
|
+
|
|
190
|
+
LAND_BY = {
|
|
191
|
+
"grantee": "GrantHR",
|
|
192
|
+
"patent": "Patent",
|
|
193
|
+
"grant-book": "GRNTBKPG",
|
|
194
|
+
"county": "County",
|
|
195
|
+
"watercourse": "Water",
|
|
196
|
+
"survey-name": "SurName",
|
|
197
|
+
"survey-year": "Sur_Date",
|
|
198
|
+
"grant-year": "GrantDte",
|
|
199
|
+
"warrant": "Warrant",
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _client() -> httpx.Client:
|
|
204
|
+
return httpx.Client(headers={"User-Agent": UA}, timeout=TIMEOUT, follow_redirects=True)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _get(client: httpx.Client, url: str) -> httpx.Response:
|
|
208
|
+
try:
|
|
209
|
+
resp = client.get(url)
|
|
210
|
+
except httpx.HTTPError as exc:
|
|
211
|
+
raise click.ClickException(f"request failed: {exc}")
|
|
212
|
+
if resp.status_code != 200:
|
|
213
|
+
raise click.ClickException(f"{url} returned HTTP {resp.status_code}")
|
|
214
|
+
return resp
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _clean(text: str) -> str:
|
|
218
|
+
text = re.sub(r"<script.*?</script>", " ", text, flags=re.S | re.I)
|
|
219
|
+
text = re.sub(r"<style.*?</style>", " ", text, flags=re.S | re.I)
|
|
220
|
+
text = re.sub(r"<[^>]+>", " ", text)
|
|
221
|
+
text = htmlmod.unescape(text)
|
|
222
|
+
return re.sub(r"\s+", " ", text).strip()
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _get_json(client: httpx.Client, url: str) -> dict[str, Any]:
|
|
226
|
+
resp = _get(client, url)
|
|
227
|
+
try:
|
|
228
|
+
data = resp.json()
|
|
229
|
+
except ValueError as exc:
|
|
230
|
+
raise click.ClickException(f"Invalid JSON from {url}: {exc}") from exc
|
|
231
|
+
if not isinstance(data, dict):
|
|
232
|
+
raise click.ClickException(f"Unexpected JSON response from {url}")
|
|
233
|
+
return data
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _fetch_cdm(query: str, alias: str, field: str, limit: int) -> dict[str, Any]:
|
|
237
|
+
url = (
|
|
238
|
+
f"{CDM_API}/search/collection/{alias}/searchterm/{quote(query)}/"
|
|
239
|
+
f"field/{field}/maxRecords/{limit}"
|
|
240
|
+
)
|
|
241
|
+
with _client() as client:
|
|
242
|
+
data = _get_json(client, url)
|
|
243
|
+
total = data.get("totalResults", 0)
|
|
244
|
+
items = data.get("items", [])
|
|
245
|
+
trimmed = [
|
|
246
|
+
{k: it.get(k) for k in ("collectionAlias", "itemId", "title", "filetype", "itemLink")}
|
|
247
|
+
| {"fields": {f["field"]: f["value"] for f in it.get("metadataFields", [])}}
|
|
248
|
+
for it in items
|
|
249
|
+
]
|
|
250
|
+
verified = isinstance(data.get("items"), list) and isinstance(data.get("totalResults"), int)
|
|
251
|
+
return {"totalResults": total, "items": trimmed, "verified": verified}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
# ---------------------------------------------------------------- CONTENTdm
|
|
255
|
+
@click.command("cdm")
|
|
256
|
+
@click.argument("query")
|
|
257
|
+
@click.option("--collection", "alias", default="all",
|
|
258
|
+
help="CONTENTdm collection alias (default: all). See `collections`.")
|
|
259
|
+
@click.option("--field", default="all",
|
|
260
|
+
help="Search field: all, title, descri, date, subjec, publis, source (default: all).")
|
|
261
|
+
@click.option("--limit", default=10, type=int, show_default=True)
|
|
262
|
+
@click.option("--json", "as_json", is_flag=True, help="Print raw trimmed JSON.")
|
|
263
|
+
@cache_options
|
|
264
|
+
def cdm_cmd(
|
|
265
|
+
query: str,
|
|
266
|
+
alias: str,
|
|
267
|
+
field: str,
|
|
268
|
+
limit: int,
|
|
269
|
+
as_json: bool,
|
|
270
|
+
refresh: bool,
|
|
271
|
+
cache_ttl_hours: float | None,
|
|
272
|
+
) -> None:
|
|
273
|
+
"""Search KHS Digital Collections (CONTENTdm API)."""
|
|
274
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
275
|
+
data, hit = cached_call(
|
|
276
|
+
"cdm",
|
|
277
|
+
{"query": query, "alias": alias, "field": field, "limit": limit},
|
|
278
|
+
lambda: _fetch_cdm(query, alias, field, limit),
|
|
279
|
+
refresh=refresh,
|
|
280
|
+
ttl_hours=ttl,
|
|
281
|
+
cacheable=lambda r: bool(r.get("verified")),
|
|
282
|
+
)
|
|
283
|
+
total = data.get("totalResults", 0)
|
|
284
|
+
items = data.get("items", [])
|
|
285
|
+
if as_json:
|
|
286
|
+
click.echo(json.dumps({"totalResults": total, "items": items, "cache_hit": hit}, indent=2))
|
|
287
|
+
return
|
|
288
|
+
marker = " [cache]" if hit else ""
|
|
289
|
+
click.echo(f"{total} result(s) for {query!r} in KHS Digital Collections{marker}")
|
|
290
|
+
for it in items:
|
|
291
|
+
fields = it.get("fields") or {}
|
|
292
|
+
date = fields.get("date", "")
|
|
293
|
+
click.echo(f"- [{it.get('collectionAlias')}:{it.get('itemId')}] "
|
|
294
|
+
f"{it.get('title')}" + (f" ({date})" if date else ""))
|
|
295
|
+
click.echo(f" {CDM_BASE}/digital{it.get('itemLink', '')}")
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _fetch_cdm_item(alias: str, item_id: str) -> dict[str, Any]:
|
|
299
|
+
url = f"{CDM_API}/singleitem/collection/{alias}/id/{item_id}"
|
|
300
|
+
with _client() as client:
|
|
301
|
+
return _get_json(client, url)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
@click.command("cdm-item")
|
|
305
|
+
@click.argument("alias")
|
|
306
|
+
@click.argument("item_id")
|
|
307
|
+
@click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
|
|
308
|
+
@cache_options
|
|
309
|
+
def cdm_item_cmd(
|
|
310
|
+
alias: str,
|
|
311
|
+
item_id: str,
|
|
312
|
+
as_json: bool,
|
|
313
|
+
refresh: bool,
|
|
314
|
+
cache_ttl_hours: float | None,
|
|
315
|
+
) -> None:
|
|
316
|
+
"""Show full metadata for one CONTENTdm item: ALIAS ITEM_ID."""
|
|
317
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
318
|
+
data, hit = cached_call(
|
|
319
|
+
"cdm-item",
|
|
320
|
+
{"alias": alias, "item_id": item_id},
|
|
321
|
+
lambda: _fetch_cdm_item(alias, item_id),
|
|
322
|
+
refresh=refresh,
|
|
323
|
+
ttl_hours=ttl,
|
|
324
|
+
cacheable=lambda r: bool(r.get("fields") or r.get("title") or r.get("contentType")),
|
|
325
|
+
)
|
|
326
|
+
if as_json:
|
|
327
|
+
click.echo(json.dumps({**data, "cache_hit": hit}, indent=2))
|
|
328
|
+
return
|
|
329
|
+
marker = " [cache]" if hit else ""
|
|
330
|
+
click.echo(f"{CDM_BASE}/digital/singleitem/collection/{alias}/id/{item_id}{marker}")
|
|
331
|
+
for f in data.get("fields", []):
|
|
332
|
+
click.echo(f"{f.get('label', f.get('key'))}: {f.get('value')}")
|
|
333
|
+
if data.get("contentType"):
|
|
334
|
+
click.echo(f"Content-Type: {data['contentType']}")
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _fetch_collections() -> dict[str, Any]:
|
|
338
|
+
with _client() as client:
|
|
339
|
+
return _get_json(client, f"{CDM_API}/collections")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
@click.command("collections")
|
|
343
|
+
@click.option("--json", "as_json", is_flag=True, help="Print raw JSON.")
|
|
344
|
+
@cache_options
|
|
345
|
+
def collections_cmd(as_json: bool, refresh: bool, cache_ttl_hours: float | None) -> None:
|
|
346
|
+
"""List the KHS Digital Collections (CONTENTdm aliases)."""
|
|
347
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
348
|
+
data, hit = cached_call(
|
|
349
|
+
"collections",
|
|
350
|
+
{},
|
|
351
|
+
_fetch_collections,
|
|
352
|
+
refresh=refresh,
|
|
353
|
+
ttl_hours=ttl,
|
|
354
|
+
cacheable=lambda r: bool(r.get("cards")),
|
|
355
|
+
)
|
|
356
|
+
cards = data.get("cards", [])
|
|
357
|
+
if as_json:
|
|
358
|
+
click.echo(
|
|
359
|
+
json.dumps(
|
|
360
|
+
{
|
|
361
|
+
"totalCollections": data.get("totalCollections", len(cards)),
|
|
362
|
+
"cards": cards,
|
|
363
|
+
"cache_hit": hit,
|
|
364
|
+
},
|
|
365
|
+
indent=2,
|
|
366
|
+
)
|
|
367
|
+
)
|
|
368
|
+
return
|
|
369
|
+
marker = " [cache]" if hit else ""
|
|
370
|
+
click.echo(f"{data.get('totalCollections', len(cards))} collections{marker}")
|
|
371
|
+
for c in cards:
|
|
372
|
+
click.echo(f"- {c.get('alias')}: {c.get('title')}")
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
@click.command("cdm-url")
|
|
376
|
+
@click.argument("query")
|
|
377
|
+
def cdm_url_cmd(query: str) -> None:
|
|
378
|
+
"""Print the verified KHS catalog web search URL for QUERY."""
|
|
379
|
+
click.echo(f"{CDM_BASE}/cdm/search/searchterm/{quote(query)}/mode/exact")
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# ---------------------------------------------------------------- Land Office
|
|
383
|
+
def _asp_state(html_text: str) -> dict[str, str]:
|
|
384
|
+
def grab(name: str) -> str:
|
|
385
|
+
m = re.search(r'name="' + re.escape(name) + r'"[^>]*value="([^"]*)"', html_text)
|
|
386
|
+
return m.group(1) if m else ""
|
|
387
|
+
return {
|
|
388
|
+
"__VIEWSTATE": grab("__VIEWSTATE"),
|
|
389
|
+
"__VIEWSTATEGENERATOR": grab("__VIEWSTATEGENERATOR"),
|
|
390
|
+
"__EVENTVALIDATION": grab("__EVENTVALIDATION"),
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _land_post(client: httpx.Client, data: dict[str, str]) -> str:
|
|
395
|
+
try:
|
|
396
|
+
resp = client.post(LAND_URL, data=data)
|
|
397
|
+
except httpx.HTTPError as exc:
|
|
398
|
+
raise click.ClickException(f"Land Office request failed: {exc}")
|
|
399
|
+
if resp.status_code != 200:
|
|
400
|
+
raise click.ClickException(f"Land Office returned HTTP {resp.status_code}")
|
|
401
|
+
return resp.text
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _parse_land_results(page_html: str) -> tuple[int, list[dict[str, str]], bool]:
|
|
405
|
+
text = _clean(page_html)
|
|
406
|
+
m = re.search(r"(\d+) Results found", text)
|
|
407
|
+
total = int(m.group(1)) if m else 0
|
|
408
|
+
body = text[m.end():] if m else text
|
|
409
|
+
entries = re.split(r"\d+\) Patent #", body)
|
|
410
|
+
results: list[dict[str, str]] = []
|
|
411
|
+
field_re = re.compile(
|
|
412
|
+
r"\s*([\d.]+)\s+Grantee:\s*(.*?)\s+Grant Book & Pg:\s*(.*?)\s+"
|
|
413
|
+
r"Acreage:\s*(.*?)\s+County:\s*(.*?)\s+WaterCourse:\s*(.*?)\s+"
|
|
414
|
+
r"Survey Name:\s*(.*?)\s+Survey Date:\s*(.*?)\s+Grant Date:\s*(.*?)\s+"
|
|
415
|
+
r"Grant Note:\s*(.*?)\s*$",
|
|
416
|
+
re.S)
|
|
417
|
+
for chunk in entries[1:]:
|
|
418
|
+
fm = field_re.match(chunk)
|
|
419
|
+
if not fm:
|
|
420
|
+
continue
|
|
421
|
+
keys = ("patent", "grantee", "grant_book_page", "acreage", "county",
|
|
422
|
+
"watercourse", "survey_name", "survey_date", "grant_date",
|
|
423
|
+
"grant_note")
|
|
424
|
+
results.append(dict(zip(keys, (g.strip() for g in fm.groups()))))
|
|
425
|
+
verified = bool(results) or (m is not None)
|
|
426
|
+
return total, results, verified
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _print_land(total: int, results: list[dict[str, str]], as_json: bool, cache_hit: bool = False) -> None:
|
|
430
|
+
if as_json:
|
|
431
|
+
click.echo(json.dumps({"totalResults": total, "results": results, "cache_hit": cache_hit}, indent=2))
|
|
432
|
+
return
|
|
433
|
+
marker = " [cache]" if cache_hit else ""
|
|
434
|
+
click.echo(f"{total} patent(s) found{marker}")
|
|
435
|
+
for r in results:
|
|
436
|
+
click.echo(f"- Patent #{r['patent']}: {r['grantee']} "
|
|
437
|
+
f"({r['county']} Co., grant {r['grant_date']}, "
|
|
438
|
+
f"survey {r['survey_date']}, {r['acreage']} acres)")
|
|
439
|
+
click.echo(f" Grant Book & Pg: {r['grant_book_page']}; "
|
|
440
|
+
f"watercourse: {r['watercourse']}; "
|
|
441
|
+
f"survey name: {r['survey_name']}")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _fetch_land(term: str, by: str, limit: str) -> dict[str, Any]:
|
|
445
|
+
with _client() as client:
|
|
446
|
+
page = _get(client, LAND_URL).text
|
|
447
|
+
adv = _land_post(client, _asp_state(page) | {
|
|
448
|
+
"__EVENTTARGET": "ctl00$ContentPlaceHolder1$LbAdvSearch",
|
|
449
|
+
"__EVENTARGUMENT": ""})
|
|
450
|
+
results_html = _land_post(client, _asp_state(adv) | {
|
|
451
|
+
"__EVENTTARGET": "", "__EVENTARGUMENT": "",
|
|
452
|
+
"ctl00$ContentPlaceHolder1$DdlAdvSearchBy": LAND_BY[by],
|
|
453
|
+
"ctl00$ContentPlaceHolder1$TxtAdvSearchFor": term,
|
|
454
|
+
"ctl00$ContentPlaceHolder1$ddlMatch": "All",
|
|
455
|
+
"ctl00$ContentPlaceHolder1$ddlShow": limit,
|
|
456
|
+
"ctl00$ContentPlaceHolder1$ddlSortBy": "",
|
|
457
|
+
"ctl00$ContentPlaceHolder1$ddlSortDir": "ASC",
|
|
458
|
+
"ctl00$ContentPlaceHolder1$BtnAdvSearch": "Search"})
|
|
459
|
+
total, results, verified = _parse_land_results(results_html)
|
|
460
|
+
return {"totalResults": total, "results": results, "verified": verified}
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _fetch_land_patent(number: str, book: str | None, page: str | None) -> dict[str, Any]:
|
|
464
|
+
with _client() as client:
|
|
465
|
+
state = _asp_state(_get(client, LAND_URL).text)
|
|
466
|
+
data = state | {
|
|
467
|
+
"__EVENTTARGET": "", "__EVENTARGUMENT": "",
|
|
468
|
+
"ctl00$ContentPlaceHolder1$TxtSPatent": number,
|
|
469
|
+
"ctl00$ContentPlaceHolder1$TxtSBook": book or "",
|
|
470
|
+
"ctl00$ContentPlaceHolder1$TxtSPage": page or "",
|
|
471
|
+
"ctl00$ContentPlaceHolder1$BtnSearch": "Search"}
|
|
472
|
+
results_html = _land_post(client, data)
|
|
473
|
+
total, results, verified = _parse_land_results(results_html)
|
|
474
|
+
return {"totalResults": total, "results": results, "verified": verified}
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
@click.command("land")
|
|
478
|
+
@click.argument("term")
|
|
479
|
+
@click.option("--by", "by", default="grantee", type=click.Choice(sorted(LAND_BY)),
|
|
480
|
+
show_default=True, help="Advanced-search field.")
|
|
481
|
+
@click.option("--limit", default="10", type=click.Choice(["10", "25", "50", "100"]),
|
|
482
|
+
show_default=True, help="Results per page.")
|
|
483
|
+
@click.option("--json", "as_json", is_flag=True, help="Print JSON.")
|
|
484
|
+
@cache_options
|
|
485
|
+
def land_cmd(
|
|
486
|
+
term: str,
|
|
487
|
+
by: str,
|
|
488
|
+
limit: str,
|
|
489
|
+
as_json: bool,
|
|
490
|
+
refresh: bool,
|
|
491
|
+
cache_ttl_hours: float | None,
|
|
492
|
+
) -> None:
|
|
493
|
+
"""Advanced search of County Court Orders patents (1835-2000).
|
|
494
|
+
|
|
495
|
+
Example: ky-archives land Lincoln --by grantee
|
|
496
|
+
"""
|
|
497
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
498
|
+
data, hit = cached_call(
|
|
499
|
+
"land",
|
|
500
|
+
{"term": term, "by": by, "limit": limit},
|
|
501
|
+
lambda: _fetch_land(term, by, limit),
|
|
502
|
+
refresh=refresh,
|
|
503
|
+
ttl_hours=ttl,
|
|
504
|
+
cacheable=lambda r: bool(r.get("verified")),
|
|
505
|
+
)
|
|
506
|
+
_print_land(data["totalResults"], data["results"], as_json, cache_hit=hit)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
@click.command("land-patent")
|
|
510
|
+
@click.argument("number")
|
|
511
|
+
@click.option("--book", default=None, help="Grant book number (quick search).")
|
|
512
|
+
@click.option("--page", default=None, help="Grant book page (quick search).")
|
|
513
|
+
@click.option("--json", "as_json", is_flag=True, help="Print JSON.")
|
|
514
|
+
@cache_options
|
|
515
|
+
def land_patent_cmd(
|
|
516
|
+
number: str,
|
|
517
|
+
book: str | None,
|
|
518
|
+
page: str | None,
|
|
519
|
+
as_json: bool,
|
|
520
|
+
refresh: bool,
|
|
521
|
+
cache_ttl_hours: float | None,
|
|
522
|
+
) -> None:
|
|
523
|
+
"""Quick search of County Court Orders patents by patent number.
|
|
524
|
+
|
|
525
|
+
Example: ky-archives land-patent <patent-number>
|
|
526
|
+
"""
|
|
527
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
528
|
+
data, hit = cached_call(
|
|
529
|
+
"land-patent",
|
|
530
|
+
{"number": number, "book": book or "", "page": page or ""},
|
|
531
|
+
lambda: _fetch_land_patent(number, book, page),
|
|
532
|
+
refresh=refresh,
|
|
533
|
+
ttl_hours=ttl,
|
|
534
|
+
cacheable=lambda r: bool(r.get("verified")),
|
|
535
|
+
)
|
|
536
|
+
_print_land(data["totalResults"], data["results"], as_json, cache_hit=hit)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _fetch_preservica(query: str, limit: int) -> dict[str, Any]:
|
|
540
|
+
url = f"{PRESERVICA_BASE}/search/{quote(query)}/feed/rss2/"
|
|
541
|
+
with _client() as client:
|
|
542
|
+
feed = _get(client, url).text
|
|
543
|
+
results: list[dict[str, str]] = []
|
|
544
|
+
seen: set[str] = set()
|
|
545
|
+
for block in re.findall(r"<item>(.*?)</item>", feed, re.S):
|
|
546
|
+
title_m = re.search(r"<title>(.*?)</title>", block, re.S)
|
|
547
|
+
link_m = re.search(r"<link>(.*?)</link>", block, re.S)
|
|
548
|
+
if not title_m or not link_m:
|
|
549
|
+
continue
|
|
550
|
+
link = link_m.group(1).strip()
|
|
551
|
+
if link in seen:
|
|
552
|
+
continue
|
|
553
|
+
seen.add(link)
|
|
554
|
+
title = _clean(title_m.group(1))
|
|
555
|
+
if title:
|
|
556
|
+
results.append({"title": title, "url": link})
|
|
557
|
+
if len(results) >= limit:
|
|
558
|
+
break
|
|
559
|
+
is_rss = "<rss" in feed.lower() or "<channel>" in feed.lower()
|
|
560
|
+
return {
|
|
561
|
+
"search_url": f"{PRESERVICA_BASE}/?s={quote(query)}",
|
|
562
|
+
"feed_url": url,
|
|
563
|
+
"results": results,
|
|
564
|
+
"verified": bool(results) or is_rss,
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
# ---------------------------------------------------------------- Preservica
|
|
569
|
+
@click.command("preservica")
|
|
570
|
+
@click.argument("query")
|
|
571
|
+
@click.option("--limit", default=10, type=int, show_default=True)
|
|
572
|
+
@click.option("--json", "as_json", is_flag=True, help="Print JSON.")
|
|
573
|
+
@cache_options
|
|
574
|
+
def preservica_cmd(
|
|
575
|
+
query: str,
|
|
576
|
+
limit: int,
|
|
577
|
+
as_json: bool,
|
|
578
|
+
refresh: bool,
|
|
579
|
+
cache_ttl_hours: float | None,
|
|
580
|
+
) -> None:
|
|
581
|
+
"""Search the KDLA Preservica e-archives (WordPress search RSS feed).
|
|
582
|
+
|
|
583
|
+
Returns the matching record pages (title + URL). The site's search
|
|
584
|
+
is full-text (titles, descriptions, creators, document contents),
|
|
585
|
+
so open a hit to confirm why it matched. Opening a packet and
|
|
586
|
+
viewing its scans needs the browser; there is no public Preservica
|
|
587
|
+
search API on this host (verified 2026-11-24).
|
|
588
|
+
"""
|
|
589
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
590
|
+
data, hit = cached_call(
|
|
591
|
+
"preservica",
|
|
592
|
+
{"query": query, "limit": limit},
|
|
593
|
+
lambda: _fetch_preservica(query, limit),
|
|
594
|
+
refresh=refresh,
|
|
595
|
+
ttl_hours=ttl,
|
|
596
|
+
cacheable=lambda r: bool(r.get("verified")),
|
|
597
|
+
)
|
|
598
|
+
results = data["results"]
|
|
599
|
+
if as_json:
|
|
600
|
+
click.echo(json.dumps(
|
|
601
|
+
{"search_url": data["search_url"],
|
|
602
|
+
"feed_url": data["feed_url"], "results": results, "cache_hit": hit}, indent=2))
|
|
603
|
+
return
|
|
604
|
+
marker = " [cache]" if hit else ""
|
|
605
|
+
click.echo(f"KDLA Preservica search: {data['search_url']}{marker}")
|
|
606
|
+
if not results:
|
|
607
|
+
click.echo("No results in the search feed.")
|
|
608
|
+
return
|
|
609
|
+
for r in results:
|
|
610
|
+
click.echo(f"- {r['title']}")
|
|
611
|
+
click.echo(f" {r['url']}")
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
# ---------------------------------------------------------------- URLs
|
|
615
|
+
@click.command("urls")
|
|
616
|
+
@click.argument("query")
|
|
617
|
+
def urls_cmd(query: str) -> None:
|
|
618
|
+
"""Print every verified Kentucky search URL for QUERY (no requests)."""
|
|
619
|
+
click.echo("KHS Digital Collections (CONTENTdm web search):")
|
|
620
|
+
click.echo(f" {CDM_BASE}/cdm/search/searchterm/{quote(query)}/mode/exact")
|
|
621
|
+
click.echo("KDLA Preservica e-archives (WordPress search):")
|
|
622
|
+
click.echo(f" {PRESERVICA_BASE}/?s={quote(query)}")
|
|
623
|
+
click.echo("Land Office, County Court Orders patents (form search, no GET URL):")
|
|
624
|
+
click.echo(f" {LAND_URL}")
|
|
625
|
+
click.echo("Pass the Word oral histories (browse/search in browser):")
|
|
626
|
+
click.echo(" https://passtheword.ky.gov/")
|
|
627
|
+
click.echo("KHS research starting page:")
|
|
628
|
+
click.echo(" https://history.ky.gov/research-genealogy")
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
@click.group()
|
|
632
|
+
def cli() -> None:
|
|
633
|
+
"""Search Kentucky archives: KHS, KDLA Preservica, Land Office."""
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
cli.add_command(cdm_cmd)
|
|
637
|
+
cli.add_command(cdm_item_cmd)
|
|
638
|
+
cli.add_command(collections_cmd)
|
|
639
|
+
cli.add_command(cdm_url_cmd)
|
|
640
|
+
cli.add_command(land_cmd)
|
|
641
|
+
cli.add_command(land_patent_cmd)
|
|
642
|
+
cli.add_command(preservica_cmd)
|
|
643
|
+
cli.add_command(urls_cmd)
|
|
644
|
+
|
|
645
|
+
if __name__ == "__main__":
|
|
646
|
+
cli()
|