@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,666 @@
|
|
|
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
|
+
"""texas-archives: search Texas genealogy portals from the command line.
|
|
10
|
+
|
|
11
|
+
Verified live 2026-11-24. No account or API key is needed
|
|
12
|
+
for any command.
|
|
13
|
+
|
|
14
|
+
Machine interfaces:
|
|
15
|
+
|
|
16
|
+
- Portal to Texas History (UNT): OpenSearch JSON at
|
|
17
|
+
``GET https://texashistory.unt.edu/search/opensearch/?q=<query>&format=json``
|
|
18
|
+
(100 hits per page, ``pw`` for page). Item metadata via OAI-PMH
|
|
19
|
+
``GetRecord`` with ``identifier=ark:/67531/<id>``.
|
|
20
|
+
The HTML search UI and item/scan views redirect through an ALTCHA
|
|
21
|
+
challenge; plain HTTP cannot open them.
|
|
22
|
+
|
|
23
|
+
- Texas Digital Archive (TSLAC / Preservica): WordPress search RSS feed at
|
|
24
|
+
``GET https://tsl.access.preservica.com/search/<term>/feed/rss2/``
|
|
25
|
+
(fetched with curl; httpx gets HTTP 403 on this host).
|
|
26
|
+
|
|
27
|
+
Browser-only (use the ``url`` command):
|
|
28
|
+
|
|
29
|
+
- Portal item pages, page images, and OCR downloads (ALTCHA).
|
|
30
|
+
- Texas General Land Office Land Grant Search (``s3.glo.texas.gov``):
|
|
31
|
+
Salesforce/SPA shell; POST did not return parseable results live.
|
|
32
|
+
- Texas Ranger muster rolls and some TSLAC indexes (mail or reading room).
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import hashlib
|
|
38
|
+
import html as htmlmod
|
|
39
|
+
import json
|
|
40
|
+
import math
|
|
41
|
+
import os
|
|
42
|
+
import re
|
|
43
|
+
import subprocess
|
|
44
|
+
import time
|
|
45
|
+
import xml.etree.ElementTree as ET
|
|
46
|
+
from contextlib import contextmanager
|
|
47
|
+
from datetime import date
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
from typing import Any, Callable, Iterator
|
|
50
|
+
from urllib.parse import quote, urlencode
|
|
51
|
+
|
|
52
|
+
import click
|
|
53
|
+
import httpx
|
|
54
|
+
|
|
55
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
56
|
+
CACHE_SCHEMA = 1
|
|
57
|
+
|
|
58
|
+
PORTAL_BASE = "https://texashistory.unt.edu"
|
|
59
|
+
PORTAL_OPENSEARCH = PORTAL_BASE + "/search/opensearch/"
|
|
60
|
+
PORTAL_OAI = PORTAL_BASE + "/oai/"
|
|
61
|
+
TDA_BASE = "https://tsl.access.preservica.com"
|
|
62
|
+
GLO_LAND = "https://s3.glo.texas.gov/lookup/index.php"
|
|
63
|
+
TSLAC_HOME = "https://www.tsl.texas.gov/"
|
|
64
|
+
TSLAC_RANGERS = "https://www.tsl.texas.gov/agency/items/texas-rangers"
|
|
65
|
+
UA = (
|
|
66
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
|
67
|
+
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
|
68
|
+
)
|
|
69
|
+
TIMEOUT = 60.0
|
|
70
|
+
OAI_NS = {"oai": "http://www.openarchives.org/OAI/2.0/", "dc": "http://purl.org/dc/elements/1.1/"}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def cache_dir() -> Path:
|
|
74
|
+
override = os.environ.get("KINLOOM_TEXAS_ARCHIVES_CACHE_DIR")
|
|
75
|
+
if override:
|
|
76
|
+
return Path(override).expanduser()
|
|
77
|
+
return Path.home() / ".cache" / "kinloom-texas-archives"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
81
|
+
if cli_ttl is not None:
|
|
82
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
83
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
84
|
+
return float(cli_ttl)
|
|
85
|
+
raw = os.environ.get("KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS")
|
|
86
|
+
if raw is not None and raw.strip():
|
|
87
|
+
try:
|
|
88
|
+
parsed = float(raw.strip())
|
|
89
|
+
except ValueError as exc:
|
|
90
|
+
raise click.BadParameter(
|
|
91
|
+
f"Invalid KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}."
|
|
92
|
+
) from exc
|
|
93
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
94
|
+
raise click.BadParameter(
|
|
95
|
+
f"Invalid KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
|
|
96
|
+
)
|
|
97
|
+
return parsed
|
|
98
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@contextmanager
|
|
102
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
103
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
104
|
+
try:
|
|
105
|
+
import fcntl
|
|
106
|
+
except ImportError:
|
|
107
|
+
yield
|
|
108
|
+
return
|
|
109
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
with open(lock_path, "a+b") as lock_file:
|
|
111
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
112
|
+
try:
|
|
113
|
+
yield
|
|
114
|
+
finally:
|
|
115
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
119
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
120
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
121
|
+
try:
|
|
122
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
123
|
+
os.replace(tmp, dest)
|
|
124
|
+
except Exception:
|
|
125
|
+
tmp.unlink(missing_ok=True)
|
|
126
|
+
raise
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
130
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
131
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
135
|
+
if not path.is_file():
|
|
136
|
+
return None
|
|
137
|
+
try:
|
|
138
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
139
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
140
|
+
return None
|
|
141
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
142
|
+
return None
|
|
143
|
+
fetched = entry.get("fetched_at")
|
|
144
|
+
if not isinstance(fetched, (int, float)):
|
|
145
|
+
return None
|
|
146
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
147
|
+
return None
|
|
148
|
+
result = entry.get("result")
|
|
149
|
+
return result if isinstance(result, dict) else None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def cached_call(
|
|
153
|
+
kind: str,
|
|
154
|
+
payload: dict,
|
|
155
|
+
fetch: Callable[[], dict],
|
|
156
|
+
*,
|
|
157
|
+
refresh: bool,
|
|
158
|
+
ttl_hours: float,
|
|
159
|
+
cacheable: Callable[[dict], bool] = lambda _r: True,
|
|
160
|
+
) -> tuple[dict, bool]:
|
|
161
|
+
"""Return (result, cache_hit) with per-key flock and atomic JSON writes."""
|
|
162
|
+
key = cache_key(kind, payload)
|
|
163
|
+
root = cache_dir()
|
|
164
|
+
path = root / f"{key}.json"
|
|
165
|
+
if not refresh:
|
|
166
|
+
hit = read_cache(path, ttl_hours)
|
|
167
|
+
if hit is not None:
|
|
168
|
+
return hit, True
|
|
169
|
+
with file_lock(root / f"{key}.lock"):
|
|
170
|
+
if not refresh:
|
|
171
|
+
hit = read_cache(path, ttl_hours)
|
|
172
|
+
if hit is not None:
|
|
173
|
+
return hit, True
|
|
174
|
+
result = fetch()
|
|
175
|
+
if cacheable(result):
|
|
176
|
+
atomic_write_json(
|
|
177
|
+
path,
|
|
178
|
+
{
|
|
179
|
+
"schema": CACHE_SCHEMA,
|
|
180
|
+
"fetched_at": time.time(),
|
|
181
|
+
"kind": kind,
|
|
182
|
+
"query": payload,
|
|
183
|
+
"result": result,
|
|
184
|
+
},
|
|
185
|
+
)
|
|
186
|
+
return result, False
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def cache_options(func: Callable) -> Callable:
|
|
190
|
+
func = click.option(
|
|
191
|
+
"--cache-ttl-hours",
|
|
192
|
+
type=float,
|
|
193
|
+
default=None,
|
|
194
|
+
help="Cache TTL in hours (default 168, env KINLOOM_TEXAS_ARCHIVES_CACHE_TTL_HOURS; 0 disables reads).",
|
|
195
|
+
)(func)
|
|
196
|
+
func = click.option(
|
|
197
|
+
"--refresh",
|
|
198
|
+
is_flag=True,
|
|
199
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).",
|
|
200
|
+
)(func)
|
|
201
|
+
return func
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _client() -> httpx.Client:
|
|
205
|
+
return httpx.Client(headers={"User-Agent": UA}, timeout=TIMEOUT, follow_redirects=True)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _clean(text: str) -> str:
|
|
209
|
+
text = re.sub(r"<[^>]+>", " ", text)
|
|
210
|
+
return htmlmod.unescape(re.sub(r"\s+", " ", text)).strip()
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _ark_id(raw: str) -> str:
|
|
214
|
+
raw = raw.strip()
|
|
215
|
+
if raw.startswith("ark:/"):
|
|
216
|
+
m = re.search(r"metap?th\d+|metadc\d+", raw)
|
|
217
|
+
if m:
|
|
218
|
+
return m.group(0)
|
|
219
|
+
parts = raw.rstrip("/").split("/")
|
|
220
|
+
return parts[-1] if parts else raw
|
|
221
|
+
return raw
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _normalize_ark(ark_token: str) -> str:
|
|
225
|
+
token = _ark_id(ark_token)
|
|
226
|
+
return f"ark:/67531/{token}"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _parse_item_date(value: str | None) -> tuple[date | None, date | None]:
|
|
230
|
+
if not value:
|
|
231
|
+
return None, None
|
|
232
|
+
value = value.strip()
|
|
233
|
+
m = re.match(r"^(\d{4})-(\d{2})-(\d{2})", value)
|
|
234
|
+
if m:
|
|
235
|
+
d = date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
|
236
|
+
return d, d
|
|
237
|
+
m = re.match(r"^(\d{4})/(\d{4})$", value)
|
|
238
|
+
if m:
|
|
239
|
+
return date(int(m.group(1)), 1, 1), date(int(m.group(2)), 12, 31)
|
|
240
|
+
m = re.match(r"^(\d{4})$", value)
|
|
241
|
+
if m:
|
|
242
|
+
y = int(m.group(1))
|
|
243
|
+
return date(y, 1, 1), date(y, 12, 31)
|
|
244
|
+
return None, None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _entry_matches_filters(
|
|
248
|
+
entry: dict,
|
|
249
|
+
county: str | None,
|
|
250
|
+
type_filter: str | None,
|
|
251
|
+
date_from: date | None,
|
|
252
|
+
date_to: date | None,
|
|
253
|
+
) -> bool:
|
|
254
|
+
if type_filter:
|
|
255
|
+
if (entry.get("type") or "").lower() != type_filter.lower():
|
|
256
|
+
return False
|
|
257
|
+
if county:
|
|
258
|
+
blob = " ".join(
|
|
259
|
+
filter(
|
|
260
|
+
None,
|
|
261
|
+
[
|
|
262
|
+
entry.get("title"),
|
|
263
|
+
entry.get("description"),
|
|
264
|
+
" ".join(entry.get("subjects") or []),
|
|
265
|
+
],
|
|
266
|
+
)
|
|
267
|
+
).lower()
|
|
268
|
+
if county.lower() not in blob:
|
|
269
|
+
return False
|
|
270
|
+
if date_from or date_to:
|
|
271
|
+
start, end = _parse_item_date(entry.get("date"))
|
|
272
|
+
if start is None and end is None:
|
|
273
|
+
return False
|
|
274
|
+
lo = start or end
|
|
275
|
+
hi = end or start
|
|
276
|
+
assert lo is not None and hi is not None
|
|
277
|
+
if date_from and hi < date_from:
|
|
278
|
+
return False
|
|
279
|
+
if date_to and lo > date_to:
|
|
280
|
+
return False
|
|
281
|
+
return True
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _opensearch_entry(raw: dict) -> dict:
|
|
285
|
+
return {
|
|
286
|
+
"ark": raw.get("id", ""),
|
|
287
|
+
"title": raw.get("title", ""),
|
|
288
|
+
"creator": raw.get("dc:creator", ""),
|
|
289
|
+
"date": raw.get("dc:date", ""),
|
|
290
|
+
"description": raw.get("dc:description", ""),
|
|
291
|
+
"type": raw.get("dc:type", ""),
|
|
292
|
+
"url": raw.get("link", ""),
|
|
293
|
+
"thumbnail": raw.get("thumbnail") or "",
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _fetch_opensearch_page(client: httpx.Client, query: str, page: int) -> dict:
|
|
298
|
+
params = {"q": query, "format": "json", "pw": str(page)}
|
|
299
|
+
try:
|
|
300
|
+
resp = client.get(PORTAL_OPENSEARCH, params=params)
|
|
301
|
+
except httpx.HTTPError as exc:
|
|
302
|
+
raise click.ClickException(f"OpenSearch request failed: {exc}") from exc
|
|
303
|
+
if resp.status_code != 200:
|
|
304
|
+
raise click.ClickException(f"OpenSearch returned HTTP {resp.status_code}")
|
|
305
|
+
try:
|
|
306
|
+
data = resp.json()
|
|
307
|
+
except ValueError as exc:
|
|
308
|
+
raise click.ClickException(f"OpenSearch returned non-JSON: {exc}") from exc
|
|
309
|
+
if not isinstance(data, dict):
|
|
310
|
+
raise click.ClickException("OpenSearch returned unexpected JSON shape")
|
|
311
|
+
feed = data.get("feed") or {}
|
|
312
|
+
if not isinstance(feed, dict):
|
|
313
|
+
raise click.ClickException("OpenSearch returned malformed feed")
|
|
314
|
+
total_s = feed.get("opensearch:totalResults", "0")
|
|
315
|
+
try:
|
|
316
|
+
total = int(total_s)
|
|
317
|
+
except (ValueError, TypeError):
|
|
318
|
+
total = 0
|
|
319
|
+
entries = [_opensearch_entry(e) for e in feed.get("entry") or []]
|
|
320
|
+
return {"total": total, "page": page, "entries": entries}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _build_portal_query(query: str, county: str | None) -> str:
|
|
324
|
+
parts = [query.strip()]
|
|
325
|
+
if county:
|
|
326
|
+
parts.append(county.strip())
|
|
327
|
+
return " ".join(p for p in parts if p)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _parse_oai_record(xml_text: str) -> dict:
|
|
331
|
+
try:
|
|
332
|
+
root = ET.fromstring(xml_text)
|
|
333
|
+
except ET.ParseError as exc:
|
|
334
|
+
raise click.ClickException(f"OAI response was not valid XML: {exc}") from exc
|
|
335
|
+
err = root.find("oai:error", OAI_NS)
|
|
336
|
+
if err is not None:
|
|
337
|
+
code = err.get("code", "error")
|
|
338
|
+
raise click.ClickException(f"OAI error {code}: {(err.text or '').strip()}")
|
|
339
|
+
rec = root.find(".//oai:record", OAI_NS)
|
|
340
|
+
if rec is None:
|
|
341
|
+
raise click.ClickException("OAI response had no record")
|
|
342
|
+
header = rec.find("oai:header", OAI_NS)
|
|
343
|
+
identifier = ""
|
|
344
|
+
sets: list[str] = []
|
|
345
|
+
if header is not None:
|
|
346
|
+
id_el = header.find("oai:identifier", OAI_NS)
|
|
347
|
+
if id_el is not None and id_el.text:
|
|
348
|
+
identifier = id_el.text.strip()
|
|
349
|
+
for s in header.findall("oai:setSpec", OAI_NS):
|
|
350
|
+
if s.text:
|
|
351
|
+
sets.append(s.text.strip())
|
|
352
|
+
titles = [el.text.strip() for el in rec.findall(".//dc:title", OAI_NS) if el.text]
|
|
353
|
+
creators = [el.text.strip() for el in rec.findall(".//dc:creator", OAI_NS) if el.text]
|
|
354
|
+
subjects = [el.text.strip() for el in rec.findall(".//dc:subject", OAI_NS) if el.text]
|
|
355
|
+
dates = [el.text.strip() for el in rec.findall(".//dc:date", OAI_NS) if el.text]
|
|
356
|
+
types = [el.text.strip() for el in rec.findall(".//dc:type", OAI_NS) if el.text]
|
|
357
|
+
desc = [el.text.strip() for el in rec.findall(".//dc:description", OAI_NS) if el.text]
|
|
358
|
+
ark = ""
|
|
359
|
+
m = re.search(r"metap?th\d+|metadc\d+", identifier)
|
|
360
|
+
if m:
|
|
361
|
+
ark = f"ark:/67531/{m.group(0)}"
|
|
362
|
+
return {
|
|
363
|
+
"oai_identifier": identifier,
|
|
364
|
+
"ark": ark,
|
|
365
|
+
"titles": titles,
|
|
366
|
+
"creators": creators,
|
|
367
|
+
"subjects": subjects,
|
|
368
|
+
"dates": dates,
|
|
369
|
+
"types": types,
|
|
370
|
+
"descriptions": desc,
|
|
371
|
+
"set_specs": sets,
|
|
372
|
+
"url": (PORTAL_BASE + "/" + ark + "/") if ark else "",
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _fetch_portal_item(client: httpx.Client, ark_token: str) -> dict:
|
|
377
|
+
ark = _normalize_ark(ark_token)
|
|
378
|
+
params = {"verb": "GetRecord", "identifier": ark, "metadataPrefix": "oai_dc"}
|
|
379
|
+
try:
|
|
380
|
+
resp = client.get(PORTAL_OAI, params=params)
|
|
381
|
+
except httpx.HTTPError as exc:
|
|
382
|
+
raise click.ClickException(f"OAI GetRecord request failed: {exc}") from exc
|
|
383
|
+
if resp.status_code != 200:
|
|
384
|
+
raise click.ClickException(f"OAI GetRecord returned HTTP {resp.status_code}")
|
|
385
|
+
data = _parse_oai_record(resp.text)
|
|
386
|
+
data["ark"] = ark
|
|
387
|
+
data["url"] = PORTAL_BASE + "/" + ark + "/"
|
|
388
|
+
data["browser_note"] = (
|
|
389
|
+
"Item pages and scans need a browser (ALTCHA challenge on texashistory.unt.edu)."
|
|
390
|
+
)
|
|
391
|
+
return data
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _curl_text(url: str) -> str:
|
|
395
|
+
"""Fetch a URL with curl when Python TLS is blocked (TSLAC Preservica host)."""
|
|
396
|
+
try:
|
|
397
|
+
proc = subprocess.run(
|
|
398
|
+
["curl", "-sS", "-L", "-A", UA, url],
|
|
399
|
+
capture_output=True,
|
|
400
|
+
text=True,
|
|
401
|
+
timeout=int(TIMEOUT),
|
|
402
|
+
check=False,
|
|
403
|
+
)
|
|
404
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
405
|
+
raise click.ClickException(f"curl failed: {exc}") from exc
|
|
406
|
+
if proc.returncode != 0:
|
|
407
|
+
err = (proc.stderr or "").strip() or f"exit {proc.returncode}"
|
|
408
|
+
raise click.ClickException(f"curl error: {err}")
|
|
409
|
+
if "403 Forbidden" in proc.stdout[:500] and "<rss" not in proc.stdout:
|
|
410
|
+
raise click.ClickException("TDA RSS returned a 403 page to curl")
|
|
411
|
+
return proc.stdout
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _fetch_tda_rss(query: str, limit: int | None = None) -> list[dict[str, str]]:
|
|
415
|
+
url = f"{TDA_BASE}/search/{quote(query)}/feed/rss2/"
|
|
416
|
+
feed = _curl_text(url)
|
|
417
|
+
results: list[dict[str, str]] = []
|
|
418
|
+
seen: set[str] = set()
|
|
419
|
+
for block in re.findall(r"<item>(.*?)</item>", feed, re.S):
|
|
420
|
+
title_m = re.search(r"<title>(.*?)</title>", block, re.S)
|
|
421
|
+
link_m = re.search(r"<link>(.*?)</link>", block, re.S)
|
|
422
|
+
if not title_m or not link_m:
|
|
423
|
+
continue
|
|
424
|
+
link = link_m.group(1).strip()
|
|
425
|
+
if link in seen:
|
|
426
|
+
continue
|
|
427
|
+
seen.add(link)
|
|
428
|
+
title = _clean(title_m.group(1))
|
|
429
|
+
if title.lower().startswith("search results for"):
|
|
430
|
+
continue
|
|
431
|
+
if title:
|
|
432
|
+
results.append({"title": title, "url": link})
|
|
433
|
+
if limit is not None and len(results) >= limit:
|
|
434
|
+
break
|
|
435
|
+
return results
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _print_portal_hit(rec: dict) -> None:
|
|
439
|
+
click.echo(rec.get("title") or "(no title)")
|
|
440
|
+
line = f" {rec.get('date') or ''} [{rec.get('type') or ''}] {rec.get('creator') or ''}".rstrip()
|
|
441
|
+
click.echo(line)
|
|
442
|
+
click.echo(f" {rec.get('ark')} {rec.get('url')}")
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
446
|
+
def cli() -> None:
|
|
447
|
+
"""Search Texas archives: Portal to Texas History, Texas Digital Archive, URL builders."""
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
@cli.group("portal")
|
|
451
|
+
def portal() -> None:
|
|
452
|
+
"""The Portal to Texas History (University of North Texas)."""
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
@portal.command("search")
|
|
456
|
+
@click.argument("query", nargs=-1, required=True)
|
|
457
|
+
@click.option("--county", default=None, help="Add a county term to the query and filter hits that mention it.")
|
|
458
|
+
@click.option("--date-from", default=None, help="Keep hits on or after this date (YYYY-MM-DD).")
|
|
459
|
+
@click.option("--date-to", default=None, help="Keep hits on or before this date (YYYY-MM-DD).")
|
|
460
|
+
@click.option("--type", "type_filter", default=None, help="Keep hits whose dc:type matches, e.g. text_newspaper.")
|
|
461
|
+
@click.option("--limit", default=10, show_default=True, type=int, help="Maximum hits to print after filters.")
|
|
462
|
+
@click.option("--pages", default=3, show_default=True, type=int, help="OpenSearch pages to scan (100 hits each).")
|
|
463
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
464
|
+
@cache_options
|
|
465
|
+
def cmd_portal_search(
|
|
466
|
+
query: tuple[str, ...],
|
|
467
|
+
county: str | None,
|
|
468
|
+
date_from: str | None,
|
|
469
|
+
date_to: str | None,
|
|
470
|
+
type_filter: str | None,
|
|
471
|
+
limit: int,
|
|
472
|
+
pages: int,
|
|
473
|
+
as_json: bool,
|
|
474
|
+
refresh: bool,
|
|
475
|
+
cache_ttl_hours: float | None,
|
|
476
|
+
) -> None:
|
|
477
|
+
"""Search the Portal via its public OpenSearch JSON API."""
|
|
478
|
+
d_from = date.fromisoformat(date_from) if date_from else None
|
|
479
|
+
d_to = date.fromisoformat(date_to) if date_to else None
|
|
480
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
481
|
+
q = _build_portal_query(" ".join(query), county)
|
|
482
|
+
matched: list[dict] = []
|
|
483
|
+
total_reported = 0
|
|
484
|
+
page_hits: list[bool] = []
|
|
485
|
+
client: httpx.Client | None = None
|
|
486
|
+
try:
|
|
487
|
+
for page in range(1, pages + 1):
|
|
488
|
+
if len(matched) >= limit:
|
|
489
|
+
break
|
|
490
|
+
|
|
491
|
+
def _fetch_page(p: int = page) -> dict:
|
|
492
|
+
nonlocal client
|
|
493
|
+
if client is None:
|
|
494
|
+
client = _client()
|
|
495
|
+
return _fetch_opensearch_page(client, q, p)
|
|
496
|
+
|
|
497
|
+
batch, hit = cached_call(
|
|
498
|
+
"portal_opensearch",
|
|
499
|
+
{"q": q, "page": page},
|
|
500
|
+
_fetch_page,
|
|
501
|
+
refresh=refresh,
|
|
502
|
+
ttl_hours=ttl,
|
|
503
|
+
cacheable=lambda r: bool(r.get("entries")) or int(r.get("total") or 0) > 0,
|
|
504
|
+
)
|
|
505
|
+
page_hits.append(hit)
|
|
506
|
+
total_reported = batch["total"]
|
|
507
|
+
if not batch["entries"] and page > 1:
|
|
508
|
+
break
|
|
509
|
+
for entry in batch["entries"]:
|
|
510
|
+
full = dict(entry)
|
|
511
|
+
full["subjects"] = []
|
|
512
|
+
if _entry_matches_filters(full, county, type_filter, d_from, d_to):
|
|
513
|
+
matched.append(entry)
|
|
514
|
+
if len(matched) >= limit:
|
|
515
|
+
break
|
|
516
|
+
finally:
|
|
517
|
+
if client is not None:
|
|
518
|
+
client.close()
|
|
519
|
+
all_cached = bool(page_hits) and all(page_hits)
|
|
520
|
+
payload = {
|
|
521
|
+
"query": q,
|
|
522
|
+
"opensearch_total": total_reported,
|
|
523
|
+
"returned": len(matched),
|
|
524
|
+
"records": matched,
|
|
525
|
+
"search_url": PORTAL_BASE + "/search/?" + urlencode({"q": q, "t": "fulltext"}),
|
|
526
|
+
"note": "HTML search requires a browser (ALTCHA). Filters apply to OpenSearch fields only.",
|
|
527
|
+
"cache_hit": all_cached,
|
|
528
|
+
}
|
|
529
|
+
if as_json:
|
|
530
|
+
click.echo(json.dumps(payload, indent=1))
|
|
531
|
+
return
|
|
532
|
+
marker = " [cache]" if all_cached else ""
|
|
533
|
+
click.echo(f"{total_reported} OpenSearch hit(s) for {q!r}; showing {len(matched)} after filters:{marker}")
|
|
534
|
+
click.echo(payload["search_url"] + " (browser)")
|
|
535
|
+
for rec in matched:
|
|
536
|
+
_print_portal_hit(rec)
|
|
537
|
+
click.echo()
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
@portal.command("item")
|
|
541
|
+
@click.argument("ark_id")
|
|
542
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
543
|
+
@cache_options
|
|
544
|
+
def cmd_portal_item(
|
|
545
|
+
ark_id: str,
|
|
546
|
+
as_json: bool,
|
|
547
|
+
refresh: bool,
|
|
548
|
+
cache_ttl_hours: float | None,
|
|
549
|
+
) -> None:
|
|
550
|
+
"""Fetch Dublin Core metadata for one Portal item (OAI-PMH GetRecord)."""
|
|
551
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
552
|
+
ark = _normalize_ark(ark_id)
|
|
553
|
+
|
|
554
|
+
def _fetch() -> dict:
|
|
555
|
+
with _client() as client:
|
|
556
|
+
return _fetch_portal_item(client, ark)
|
|
557
|
+
|
|
558
|
+
data, hit = cached_call(
|
|
559
|
+
"portal_item",
|
|
560
|
+
{"ark": ark},
|
|
561
|
+
_fetch,
|
|
562
|
+
refresh=refresh,
|
|
563
|
+
ttl_hours=ttl,
|
|
564
|
+
cacheable=lambda r: bool(r.get("titles") or r.get("oai_identifier")),
|
|
565
|
+
)
|
|
566
|
+
if as_json:
|
|
567
|
+
click.echo(json.dumps({**data, "cache_hit": hit}, indent=1))
|
|
568
|
+
return
|
|
569
|
+
title = (data.get("titles") or ["(no title)"])[0]
|
|
570
|
+
marker = " [cache]" if hit else ""
|
|
571
|
+
click.echo(f"{title}{marker}")
|
|
572
|
+
click.echo(f" {data['ark']}")
|
|
573
|
+
if data.get("creators"):
|
|
574
|
+
click.echo(" Creator(s): " + "; ".join(data["creators"][:6]))
|
|
575
|
+
if data.get("dates"):
|
|
576
|
+
click.echo(" Date(s): " + "; ".join(data["dates"][:6]))
|
|
577
|
+
if data.get("types"):
|
|
578
|
+
click.echo(" Type(s): " + ", ".join(data["types"]))
|
|
579
|
+
if data.get("subjects"):
|
|
580
|
+
click.echo(" Subject(s): " + "; ".join(data["subjects"][:8]))
|
|
581
|
+
click.echo(f" {data['url']}")
|
|
582
|
+
click.echo(f" {data['browser_note']}")
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
@cli.command("tda")
|
|
586
|
+
@click.argument("query")
|
|
587
|
+
@click.option("--limit", default=10, show_default=True, type=int)
|
|
588
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
589
|
+
@cache_options
|
|
590
|
+
def cmd_tda(
|
|
591
|
+
query: str,
|
|
592
|
+
limit: int,
|
|
593
|
+
as_json: bool,
|
|
594
|
+
refresh: bool,
|
|
595
|
+
cache_ttl_hours: float | None,
|
|
596
|
+
) -> None:
|
|
597
|
+
"""Search the Texas Digital Archive (TSLAC Preservica RSS feed)."""
|
|
598
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
599
|
+
|
|
600
|
+
def _fetch() -> dict:
|
|
601
|
+
return {"results": _fetch_tda_rss(query, limit=None)}
|
|
602
|
+
|
|
603
|
+
data, hit = cached_call(
|
|
604
|
+
"tda_rss",
|
|
605
|
+
{"query": query.strip()},
|
|
606
|
+
_fetch,
|
|
607
|
+
refresh=refresh,
|
|
608
|
+
ttl_hours=ttl,
|
|
609
|
+
cacheable=lambda r: bool(r.get("results")),
|
|
610
|
+
)
|
|
611
|
+
results = (data.get("results") or [])[:limit]
|
|
612
|
+
payload = {
|
|
613
|
+
"search_url": f"{TDA_BASE}/?s={quote(query)}",
|
|
614
|
+
"feed_url": f"{TDA_BASE}/search/{quote(query)}/feed/rss2/",
|
|
615
|
+
"returned": len(results),
|
|
616
|
+
"results": results,
|
|
617
|
+
"cache_hit": hit,
|
|
618
|
+
}
|
|
619
|
+
if as_json:
|
|
620
|
+
click.echo(json.dumps(payload, indent=1))
|
|
621
|
+
return
|
|
622
|
+
marker = " [cache]" if hit else ""
|
|
623
|
+
click.echo(f"TDA search: {payload['search_url']}{marker}")
|
|
624
|
+
if not results:
|
|
625
|
+
click.echo("No results in the RSS feed (feed returns at most ~25 items per query).")
|
|
626
|
+
return
|
|
627
|
+
for r in results:
|
|
628
|
+
click.echo(f"- {r['title']}")
|
|
629
|
+
click.echo(f" {r['url']}")
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
@cli.command("url")
|
|
633
|
+
@click.argument("query", required=False, default="")
|
|
634
|
+
@click.option("--portal", is_flag=True, help="Portal to Texas History full-text search URL.")
|
|
635
|
+
@click.option("--tda", is_flag=True, help="Texas Digital Archive search URL.")
|
|
636
|
+
@click.option("--glo", is_flag=True, help="Texas GLO land grant lookup (browser-only).")
|
|
637
|
+
@click.option("--rangers", is_flag=True, help="TSLAC Texas Rangers collection pointer.")
|
|
638
|
+
@click.option("--tslac", is_flag=True, help="Texas State Library and Archives Commission home.")
|
|
639
|
+
def cmd_url(query: str, portal: bool, tda: bool, glo: bool, rangers: bool, tslac: bool) -> None:
|
|
640
|
+
"""Print verified portal URLs (no search is run)."""
|
|
641
|
+
any_flag = portal or tda or glo or rangers or tslac
|
|
642
|
+
show_all = not any_flag
|
|
643
|
+
q = query or "Houston"
|
|
644
|
+
if portal or show_all:
|
|
645
|
+
click.echo("Portal to Texas History (browser; ALTCHA on HTML):")
|
|
646
|
+
click.echo(" " + PORTAL_BASE + "/search/?" + urlencode({"q": q, "t": "fulltext"}))
|
|
647
|
+
click.echo("Portal OpenSearch JSON (CLI uses this):")
|
|
648
|
+
click.echo(" " + PORTAL_OPENSEARCH + "?" + urlencode({"q": q, "format": "json"}))
|
|
649
|
+
if tda or show_all:
|
|
650
|
+
click.echo("Texas Digital Archive:")
|
|
651
|
+
click.echo(f" {TDA_BASE}/?s={quote(q)}")
|
|
652
|
+
if glo or show_all:
|
|
653
|
+
click.echo("Texas General Land Office Land Grant Search (browser-only; SPA):")
|
|
654
|
+
click.echo(f" {GLO_LAND}")
|
|
655
|
+
click.echo(" Texas was not a public-land state; state grants are indexed here, not BLM GLO patents.")
|
|
656
|
+
if rangers or show_all:
|
|
657
|
+
click.echo("TSLAC Texas Rangers:")
|
|
658
|
+
click.echo(f" {TSLAC_RANGERS}")
|
|
659
|
+
click.echo(" Ranger muster rolls: open records request or in-person at TSLAC.")
|
|
660
|
+
if tslac or show_all:
|
|
661
|
+
click.echo("Texas State Library and Archives Commission:")
|
|
662
|
+
click.echo(f" {TSLAC_HOME}")
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
if __name__ == "__main__":
|
|
666
|
+
cli()
|