@kinloom/cli 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/cached-ocr.py +346 -116
- package/dist/assets/ocr.md +25 -1
- package/dist/assets/prep-scan.md +42 -4
- package/dist/assets/prep-scan.py +432 -10
- package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
- package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
- package/dist/bundled-skills/archive-org/SKILL.md +40 -7
- package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
- package/dist/bundled-skills/california-archives/SKILL.md +10 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
- package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
- package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
- package/dist/bundled-skills/findagrave/SKILL.md +18 -5
- package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
- package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
- package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
- package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
- package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
- package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
- package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
- package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
- package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
- package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
- package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
- package/dist/bundled-skills/wikitree/SKILL.md +7 -1
- package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +107 -2
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +30 -5
- package/dist/client.js.map +1 -1
- package/dist/commands/ops/audit.d.ts.map +1 -1
- package/dist/commands/ops/audit.js +5 -0
- package/dist/commands/ops/audit.js.map +1 -1
- package/dist/commands/ops/dates.d.ts +87 -0
- package/dist/commands/ops/dates.d.ts.map +1 -0
- package/dist/commands/ops/dates.js +228 -0
- package/dist/commands/ops/dates.js.map +1 -0
- package/dist/commands/ops/help.d.ts +3 -1
- package/dist/commands/ops/help.d.ts.map +1 -1
- package/dist/commands/ops/help.js +33 -0
- package/dist/commands/ops/help.js.map +1 -1
- package/dist/commands/ops/index.d.ts +3 -1
- package/dist/commands/ops/index.d.ts.map +1 -1
- package/dist/commands/ops/index.js +2 -0
- package/dist/commands/ops/index.js.map +1 -1
- package/dist/commands/ops/integrate.d.ts +5 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -1
- package/dist/commands/ops/integrate.js +217 -26
- package/dist/commands/ops/integrate.js.map +1 -1
- package/dist/commands/ops/sync.d.ts +17 -0
- package/dist/commands/ops/sync.d.ts.map +1 -1
- package/dist/commands/ops/sync.js +173 -0
- package/dist/commands/ops/sync.js.map +1 -1
- package/dist/commands/ops/verify.d.ts +76 -0
- package/dist/commands/ops/verify.d.ts.map +1 -0
- package/dist/commands/ops/verify.js +325 -0
- package/dist/commands/ops/verify.js.map +1 -0
- package/dist/commands/records/index.d.ts +1 -1
- package/dist/commands/records/index.d.ts.map +1 -1
- package/dist/commands/records/index.js +1 -1
- package/dist/commands/records/index.js.map +1 -1
- package/dist/commands/records/runner.d.ts +2 -0
- package/dist/commands/records/runner.d.ts.map +1 -1
- package/dist/commands/records/runner.js +33 -2
- package/dist/commands/records/runner.js.map +1 -1
- package/package.json +2 -2
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
# dependencies = [
|
|
5
5
|
# "click>=8.1",
|
|
6
6
|
# "httpx>=0.27",
|
|
7
|
+
# "pillow>=10",
|
|
7
8
|
# ]
|
|
8
9
|
# ///
|
|
9
10
|
"""CLI for Library of Virginia research: Chancery Records Index, Primo catalog.
|
|
@@ -28,16 +29,39 @@ interface was verified for it; use the `url --chronicle` pointer and search
|
|
|
28
29
|
in the browser. ARVAS (arvasarchive.org) returns an empty 202 to plain HTTP
|
|
29
30
|
and is likewise browser-only. The old Aleph Land Office index host
|
|
30
31
|
(lva1.hosted.exlibrisgroup.com) was unreachable on 2026-11-24.
|
|
32
|
+
|
|
33
|
+
Image and Rosetta routes verified live 2026-11-26:
|
|
34
|
+
|
|
35
|
+
- Land Office patent/grant scans are plain TIFFs on image.lva.virginia.gov,
|
|
36
|
+
e.g. /LONN/LO-3/372/372_0195.tif (image/tiff, CCITT G4 bi-level).
|
|
37
|
+
- Dunmore's War (1774) cards: /cgi-bin/GetDW.pl?dir=<dddd>/W<dddd>&card=<n>
|
|
38
|
+
redirects to a /cgi-bin/drawer page listing neighbouring page TIFFs under
|
|
39
|
+
/Microfilm/DW/<reel>/<nnnnn>.tif; the current card is the link without a
|
|
40
|
+
"Page N" label.
|
|
41
|
+
- Rosetta (rosetta.virginiamemory.com): DeliveryManagerServlet?dps_pid=IE<n>
|
|
42
|
+
embeds an iframe to /view/action/ieViewer.do?...&dps_dvs=<session>&dps_pid=IE<n>;
|
|
43
|
+
the viewer lists file pids (FL<n>, with METS titles such as Original /
|
|
44
|
+
Transcription); DeliveryManagerServlet?dps_pid=FL<n>&dps_func=stream returns
|
|
45
|
+
the delivered file (application/pdf for the sample checked). The session
|
|
46
|
+
cookie jar is kept for the whole resolution.
|
|
47
|
+
|
|
48
|
+
Every network response is cached on disk (see get_cache_root); pass the
|
|
49
|
+
global `--refresh` (or a command's own `--refresh`) to refetch.
|
|
31
50
|
"""
|
|
32
51
|
|
|
33
52
|
from __future__ import annotations
|
|
34
53
|
|
|
54
|
+
import hashlib
|
|
35
55
|
import html as _html
|
|
36
56
|
import json
|
|
57
|
+
import os
|
|
37
58
|
import re
|
|
38
59
|
import sys
|
|
60
|
+
import time
|
|
61
|
+
from contextlib import contextmanager
|
|
39
62
|
from pathlib import Path
|
|
40
|
-
from
|
|
63
|
+
from typing import Any, Iterator
|
|
64
|
+
from urllib.parse import quote, unquote, urlencode, urlsplit
|
|
41
65
|
|
|
42
66
|
import click
|
|
43
67
|
import httpx
|
|
@@ -57,6 +81,364 @@ USER_AGENT = (
|
|
|
57
81
|
)
|
|
58
82
|
MATCH_OPS = ("Exact", "Starts", "Includes")
|
|
59
83
|
CATALOG_FIELDS = ("any", "title", "creator")
|
|
84
|
+
LVA_IMAGE_HOST = "image.lva.virginia.gov"
|
|
85
|
+
LVA_IMAGE_BASE = "https://" + LVA_IMAGE_HOST
|
|
86
|
+
DUNMORE_CGI = LVA_IMAGE_BASE + "/cgi-bin/GetDW.pl"
|
|
87
|
+
IMAGE_SUFFIXES = (".tif", ".tiff", ".jpg", ".jpeg", ".png", ".gif")
|
|
88
|
+
ROSETTA_HOST = "rosetta.virginiamemory.com"
|
|
89
|
+
ROSETTA_BASE = "https://" + ROSETTA_HOST
|
|
90
|
+
ROSETTA_DELIVERY = ROSETTA_BASE + "/delivery/DeliveryManagerServlet"
|
|
91
|
+
ROSETTA_VIEWER = ROSETTA_BASE + "/view/action/ieViewer.do"
|
|
92
|
+
DEFAULT_TTL_HOURS = 168.0
|
|
93
|
+
CACHE_ENV = "KINLOOM_VA_ARCHIVES_CACHE_DIR"
|
|
94
|
+
TTL_ENV = "KINLOOM_VA_ARCHIVES_TTL_HOURS"
|
|
95
|
+
|
|
96
|
+
# Per-invocation state: the group-level --refresh resets it, a command-level
|
|
97
|
+
# --refresh can only turn it on.
|
|
98
|
+
_STATE: dict[str, bool] = {"refresh": False}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
# Disk cache (atomic temp-file + rename writes, fcntl.flock per entry)
|
|
103
|
+
# ---------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
def get_cache_root() -> Path:
|
|
106
|
+
override = os.environ.get(CACHE_ENV)
|
|
107
|
+
if override:
|
|
108
|
+
return Path(override).expanduser()
|
|
109
|
+
xdg = os.environ.get("XDG_CACHE_HOME")
|
|
110
|
+
base = Path(xdg).expanduser() if xdg else Path.home() / ".cache"
|
|
111
|
+
return base / "kinloom-va-archives"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def resolve_ttl_hours() -> float:
|
|
115
|
+
raw = os.environ.get(TTL_ENV)
|
|
116
|
+
if raw is not None and raw.strip():
|
|
117
|
+
try:
|
|
118
|
+
val = float(raw.strip())
|
|
119
|
+
except ValueError as exc:
|
|
120
|
+
raise click.BadParameter(f"Invalid {TTL_ENV} value: {raw!r}.") from exc
|
|
121
|
+
if val < 0 or val != val:
|
|
122
|
+
raise click.BadParameter(f"Invalid {TTL_ENV} value: {raw!r} (must be >= 0).")
|
|
123
|
+
return val
|
|
124
|
+
return DEFAULT_TTL_HOURS
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@contextmanager
|
|
128
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
129
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
130
|
+
try:
|
|
131
|
+
import fcntl
|
|
132
|
+
except ImportError:
|
|
133
|
+
yield
|
|
134
|
+
return
|
|
135
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
with open(lock_path, "a+b") as fh:
|
|
137
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
|
|
138
|
+
try:
|
|
139
|
+
yield
|
|
140
|
+
finally:
|
|
141
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _tmp_sibling(dest: Path) -> Path:
|
|
145
|
+
return dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def atomic_write_bytes(dest: Path, data: bytes) -> None:
|
|
149
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
150
|
+
tmp = _tmp_sibling(dest)
|
|
151
|
+
try:
|
|
152
|
+
tmp.write_bytes(data)
|
|
153
|
+
os.replace(tmp, dest)
|
|
154
|
+
except BaseException:
|
|
155
|
+
tmp.unlink(missing_ok=True)
|
|
156
|
+
raise
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
160
|
+
atomic_write_bytes(dest, json.dumps(payload, ensure_ascii=False, indent=1).encode("utf-8"))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def read_json_if_valid(path: Path) -> dict | None:
|
|
164
|
+
if not path.is_file():
|
|
165
|
+
return None
|
|
166
|
+
try:
|
|
167
|
+
parsed = json.loads(path.read_text(encoding="utf-8"))
|
|
168
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
169
|
+
return None
|
|
170
|
+
return parsed if isinstance(parsed, dict) else None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _meta_path(cache_path: Path) -> Path:
|
|
174
|
+
return cache_path.with_name(cache_path.name + ".meta.json")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _host_ok(url: httpx.URL | str, allowed_hosts: tuple[str, ...] | None) -> bool:
|
|
178
|
+
if not allowed_hosts:
|
|
179
|
+
return True
|
|
180
|
+
u = httpx.URL(str(url))
|
|
181
|
+
return u.scheme == "https" and u.host in allowed_hosts
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _cache_valid(cache_path: Path, ttl_hours: float | None) -> dict | None:
|
|
185
|
+
meta = read_json_if_valid(_meta_path(cache_path))
|
|
186
|
+
if meta is None or not cache_path.is_file():
|
|
187
|
+
return None
|
|
188
|
+
if ttl_hours is not None:
|
|
189
|
+
cached_at = meta.get("cached_at")
|
|
190
|
+
if not isinstance(cached_at, (int, float)) or time.time() - cached_at > ttl_hours * 3600:
|
|
191
|
+
return None
|
|
192
|
+
return meta
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def cached_fetch(
|
|
196
|
+
c: httpx.Client,
|
|
197
|
+
url: str,
|
|
198
|
+
cache_path: Path,
|
|
199
|
+
*,
|
|
200
|
+
method: str = "GET",
|
|
201
|
+
params: dict | None = None,
|
|
202
|
+
data: dict | None = None,
|
|
203
|
+
ttl_hours: float | None = None,
|
|
204
|
+
allowed_hosts: tuple[str, ...] | None = None,
|
|
205
|
+
refresh: bool | None = None,
|
|
206
|
+
) -> tuple[Path, dict]:
|
|
207
|
+
"""Fetch url into cache_path (streamed, atomic) unless a fresh copy exists.
|
|
208
|
+
|
|
209
|
+
ttl_hours=None means the entry never expires (immutable scans/files).
|
|
210
|
+
allowed_hosts pins the final (post-redirect) https host.
|
|
211
|
+
"""
|
|
212
|
+
refresh = _STATE["refresh"] if refresh is None else refresh
|
|
213
|
+
if not refresh:
|
|
214
|
+
meta = _cache_valid(cache_path, ttl_hours)
|
|
215
|
+
if meta is not None:
|
|
216
|
+
return cache_path, meta
|
|
217
|
+
lock = cache_path.parent / f".{cache_path.name}.lock"
|
|
218
|
+
with file_lock(lock):
|
|
219
|
+
if not refresh:
|
|
220
|
+
meta = _cache_valid(cache_path, ttl_hours)
|
|
221
|
+
if meta is not None:
|
|
222
|
+
return cache_path, meta
|
|
223
|
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
224
|
+
tmp = _tmp_sibling(cache_path)
|
|
225
|
+
try:
|
|
226
|
+
with c.stream(method, url, params=params, data=data) as r:
|
|
227
|
+
r.raise_for_status()
|
|
228
|
+
if not _host_ok(r.url, allowed_hosts):
|
|
229
|
+
raise click.ClickException(f"Refusing redirect outside {allowed_hosts}: {r.url}")
|
|
230
|
+
with open(tmp, "wb") as fh:
|
|
231
|
+
for chunk in r.iter_bytes():
|
|
232
|
+
fh.write(chunk)
|
|
233
|
+
meta = {
|
|
234
|
+
"url": str(r.url),
|
|
235
|
+
"content_type": r.headers.get("content-type", ""),
|
|
236
|
+
"cached_at": time.time(),
|
|
237
|
+
"size": tmp.stat().st_size,
|
|
238
|
+
}
|
|
239
|
+
os.replace(tmp, cache_path)
|
|
240
|
+
except BaseException:
|
|
241
|
+
tmp.unlink(missing_ok=True)
|
|
242
|
+
raise
|
|
243
|
+
atomic_write_json(_meta_path(cache_path), meta)
|
|
244
|
+
return cache_path, meta
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _request_key(method: str, url: str, params: dict | None, data: dict | None) -> str:
|
|
248
|
+
canon = json.dumps(
|
|
249
|
+
{"m": method.upper(), "u": url, "p": params or {}, "d": data or {}},
|
|
250
|
+
sort_keys=True, separators=(",", ":"), ensure_ascii=False,
|
|
251
|
+
)
|
|
252
|
+
return hashlib.sha256(canon.encode("utf-8")).hexdigest()
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def fetch_text(c: httpx.Client, url: str, *, method: str = "GET", params: dict | None = None,
|
|
256
|
+
data: dict | None = None) -> str:
|
|
257
|
+
"""Cached HTML/JSON GET/POST (TTL from $KINLOOM_VA_ARCHIVES_TTL_HOURS, default 168h)."""
|
|
258
|
+
key = _request_key(method, url, params, data)
|
|
259
|
+
path, meta = cached_fetch(
|
|
260
|
+
c, url, get_cache_root() / "http" / f"{key}.body",
|
|
261
|
+
method=method, params=params, data=data, ttl_hours=resolve_ttl_hours(),
|
|
262
|
+
)
|
|
263
|
+
return httpx.Response(200, headers={"content-type": meta.get("content_type", "")},
|
|
264
|
+
content=path.read_bytes()).text
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def fetch_file(c: httpx.Client, url: str, *, allowed_hosts: tuple[str, ...] | None = None) -> Path:
|
|
268
|
+
"""Cached immutable binary (PDF/ZIP/TIFF), keyed by URL. Returns cache path."""
|
|
269
|
+
key = hashlib.sha256(url.encode("utf-8")).hexdigest()
|
|
270
|
+
suffix = Path(urlsplit(url).path).suffix.lower()
|
|
271
|
+
if not re.fullmatch(r"\.[a-z0-9]{1,5}", suffix):
|
|
272
|
+
suffix = ".bin"
|
|
273
|
+
path, _ = cached_fetch(c, url, get_cache_root() / "files" / f"{key}{suffix}",
|
|
274
|
+
allowed_hosts=allowed_hosts)
|
|
275
|
+
return path
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def copy_atomic(src: Path, dest: Path) -> None:
|
|
279
|
+
atomic_write_bytes(dest, src.read_bytes())
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _refresh_callback(ctx: click.Context, _param: click.Parameter, value: bool) -> bool:
|
|
283
|
+
if value:
|
|
284
|
+
_STATE["refresh"] = True
|
|
285
|
+
return value
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
refresh_option = click.option(
|
|
289
|
+
"--refresh", is_flag=True, expose_value=False, callback=_refresh_callback,
|
|
290
|
+
help="Bypass the disk cache for this command and refetch.",
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
# ---------------------------------------------------------------------------
|
|
295
|
+
# Library of Virginia image server + Rosetta validation helpers
|
|
296
|
+
# ---------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
_SAFE_PATH = re.compile(r"/[A-Za-z0-9._~+\-/]+")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def normalize_lva_image_url(raw: str) -> str:
|
|
302
|
+
"""Validate an image.lva.virginia.gov image path or https URL; return the https URL.
|
|
303
|
+
|
|
304
|
+
Accepts 'https://image.lva.virginia.gov/<path>', '/<path>' or '<path>'.
|
|
305
|
+
Rejects other schemes/hosts, credentials, ports, queries, fragments,
|
|
306
|
+
'.'/'..' segments (raw or percent-encoded), backslashes, and non-image suffixes.
|
|
307
|
+
"""
|
|
308
|
+
if not isinstance(raw, str):
|
|
309
|
+
raise ValueError("image path must be a string")
|
|
310
|
+
text = raw.strip()
|
|
311
|
+
if not text or any(ch in text for ch in ("\x00", "\\", "\r", "\n", "\t", " ")):
|
|
312
|
+
raise ValueError(f"Invalid LVA image path: {raw!r}")
|
|
313
|
+
if "?" in text or "#" in text:
|
|
314
|
+
raise ValueError(f"Query strings/fragments are not allowed: {raw!r}")
|
|
315
|
+
if text.startswith("//"):
|
|
316
|
+
raise ValueError(f"Scheme-relative URLs are not allowed: {raw!r}")
|
|
317
|
+
if re.match(r"^[A-Za-z][A-Za-z0-9+.\-]*:", text):
|
|
318
|
+
parts = urlsplit(text)
|
|
319
|
+
if parts.scheme.lower() != "https":
|
|
320
|
+
raise ValueError(f"Only https URLs are allowed (got {parts.scheme!r}): {raw!r}")
|
|
321
|
+
if parts.username or parts.password or parts.port not in (None, 443):
|
|
322
|
+
raise ValueError(f"Credentials/ports are not allowed: {raw!r}")
|
|
323
|
+
if (parts.hostname or "").lower() != LVA_IMAGE_HOST:
|
|
324
|
+
raise ValueError(f"Only {LVA_IMAGE_HOST} is allowed: {raw!r}")
|
|
325
|
+
path = parts.path
|
|
326
|
+
else:
|
|
327
|
+
path = text if text.startswith("/") else "/" + text
|
|
328
|
+
decoded = unquote(path)
|
|
329
|
+
if "%" in decoded or decoded != unquote(decoded):
|
|
330
|
+
raise ValueError(f"Double/odd percent-encoding is not allowed: {raw!r}")
|
|
331
|
+
if not _SAFE_PATH.fullmatch(decoded):
|
|
332
|
+
raise ValueError(f"Unsafe characters in LVA image path: {raw!r}")
|
|
333
|
+
segments = decoded.split("/")[1:]
|
|
334
|
+
if any(seg in ("", ".", "..") for seg in segments):
|
|
335
|
+
raise ValueError(f"Empty, '.' or '..' path segments are not allowed: {raw!r}")
|
|
336
|
+
if not decoded.lower().endswith(IMAGE_SUFFIXES):
|
|
337
|
+
raise ValueError(f"Not an image path (expected {', '.join(IMAGE_SUFFIXES)}): {raw!r}")
|
|
338
|
+
return LVA_IMAGE_BASE + decoded
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def validate_ie_id(raw: str) -> str:
|
|
342
|
+
text = (raw or "").strip()
|
|
343
|
+
if not re.fullmatch(r"IE\d{1,12}", text):
|
|
344
|
+
raise click.BadParameter(f"Invalid Rosetta IE id (expected IE<digits>): {raw!r}")
|
|
345
|
+
return text
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def validate_fl_id(raw: str) -> str:
|
|
349
|
+
text = (raw or "").strip()
|
|
350
|
+
if not re.fullmatch(r"FL\d{1,12}", text):
|
|
351
|
+
raise click.BadParameter(f"Invalid Rosetta file id (expected FL<digits>): {raw!r}")
|
|
352
|
+
return text
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def save_image(src: Path, out: Path) -> str:
|
|
356
|
+
"""Write cached image bytes to out. TIFF->JPEG when out is .jpg/.jpeg and Pillow exists.
|
|
357
|
+
|
|
358
|
+
Returns 'jpeg' or 'raw'. Without Pillow a .jpg request writes the raw bytes
|
|
359
|
+
next to it with a .tif suffix instead of mislabelling TIFF data as JPEG.
|
|
360
|
+
"""
|
|
361
|
+
if out.suffix.lower() in (".jpg", ".jpeg"):
|
|
362
|
+
try:
|
|
363
|
+
from PIL import Image # type: ignore[import-not-found]
|
|
364
|
+
except ImportError:
|
|
365
|
+
alt = out.with_suffix(".tif")
|
|
366
|
+
click.echo(f"Pillow not installed; saving raw TIFF to {alt} instead of {out}", err=True)
|
|
367
|
+
copy_atomic(src, alt)
|
|
368
|
+
return "raw:" + str(alt)
|
|
369
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
370
|
+
tmp = _tmp_sibling(out)
|
|
371
|
+
try:
|
|
372
|
+
with Image.open(src) as im:
|
|
373
|
+
mode = "L" if im.mode in ("1", "L", "I;16", "I") else "RGB"
|
|
374
|
+
im.convert(mode).save(tmp, format="JPEG", quality=90)
|
|
375
|
+
os.replace(tmp, out)
|
|
376
|
+
except BaseException:
|
|
377
|
+
tmp.unlink(missing_ok=True)
|
|
378
|
+
raise
|
|
379
|
+
return "jpeg"
|
|
380
|
+
copy_atomic(src, out)
|
|
381
|
+
return "raw"
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def parse_dunmore_drawer(page: str) -> dict:
|
|
385
|
+
"""Parse a Dunmore's War /cgi-bin/drawer page into page TIFF links."""
|
|
386
|
+
title_m = re.search(r"Dunmore's War\s*-\s*Page\s*(\d+)", page, re.I)
|
|
387
|
+
current = int(title_m.group(1)) if title_m else None
|
|
388
|
+
images = []
|
|
389
|
+
for m in re.finditer(r'<a href="(/Microfilm/[^"]+)"\s*>(.*?)</a>', page, re.S | re.I):
|
|
390
|
+
try:
|
|
391
|
+
url = normalize_lva_image_url(_html.unescape(m.group(1)))
|
|
392
|
+
except ValueError:
|
|
393
|
+
continue
|
|
394
|
+
label_m = re.search(r"Page\s*(\d+)", _clean(m.group(2)))
|
|
395
|
+
is_current = label_m is None
|
|
396
|
+
num = int(label_m.group(1)) if label_m else current
|
|
397
|
+
images.append({"page": num, "url": url, "current": is_current})
|
|
398
|
+
return {"current_page": current, "images": images}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def parse_rosetta_delivery(page: str) -> dict:
|
|
402
|
+
"""Find the ieViewer iframe URL and dps_dvs session token on a delivery page."""
|
|
403
|
+
viewer = None
|
|
404
|
+
for m in re.finditer(r'src="([^"]*ieViewer\.do[^"]*)"', page, re.I):
|
|
405
|
+
viewer = _html.unescape(m.group(1))
|
|
406
|
+
break
|
|
407
|
+
dvs_m = re.search(r"dps_dvs=([0-9]+~[0-9]+)", page)
|
|
408
|
+
return {"viewer_url": viewer, "dps_dvs": dvs_m.group(1) if dvs_m else None}
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def parse_rosetta_viewer(page: str) -> dict:
|
|
412
|
+
"""List FL file pids (with METS titles) and the initially selected one."""
|
|
413
|
+
files: list[dict] = []
|
|
414
|
+
seen: set[str] = set()
|
|
415
|
+
for m in re.finditer(r"<item id='(FL\d+)' title='([^']*)'", page):
|
|
416
|
+
if m.group(1) not in seen:
|
|
417
|
+
seen.add(m.group(1))
|
|
418
|
+
files.append({"fl": m.group(1), "title": _html.unescape(m.group(2))})
|
|
419
|
+
for m in re.finditer(r"JSONObject\s*=\s*'(\{[^']*\})'", page):
|
|
420
|
+
try:
|
|
421
|
+
obj = json.loads(m.group(1))
|
|
422
|
+
except json.JSONDecodeError:
|
|
423
|
+
continue
|
|
424
|
+
for val in obj.values():
|
|
425
|
+
for fl in re.findall(r"FL\d+", str(val)):
|
|
426
|
+
if fl not in seen:
|
|
427
|
+
seen.add(fl)
|
|
428
|
+
files.append({"fl": fl, "title": ""})
|
|
429
|
+
init_m = re.search(r'initialSelect\s*=\s*"(FL\d+)"', page)
|
|
430
|
+
initial = init_m.group(1) if init_m else (files[0]["fl"] if files else None)
|
|
431
|
+
return {"files": files, "initial": initial}
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
_CT_EXT = {
|
|
435
|
+
"application/pdf": ".pdf", "image/jpeg": ".jpg", "image/jp2": ".jp2", "image/tiff": ".tif",
|
|
436
|
+
"image/png": ".png", "image/gif": ".gif", "text/plain": ".txt", "application/zip": ".zip",
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _ext_for(content_type: str) -> str:
|
|
441
|
+
return _CT_EXT.get(content_type.split(";")[0].strip().lower(), ".bin")
|
|
60
442
|
|
|
61
443
|
|
|
62
444
|
def _client() -> httpx.Client:
|
|
@@ -210,8 +592,14 @@ def _fmt_record_text(rec: dict) -> str:
|
|
|
210
592
|
|
|
211
593
|
|
|
212
594
|
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
213
|
-
|
|
214
|
-
|
|
595
|
+
@click.option("--refresh", is_flag=True, help="Bypass the disk cache for every request in this run.")
|
|
596
|
+
def cli(refresh: bool) -> None:
|
|
597
|
+
"""Search the Library of Virginia: Chancery Records Index, Primo catalog, image server, Rosetta.
|
|
598
|
+
|
|
599
|
+
Responses are cached under $KINLOOM_VA_ARCHIVES_CACHE_DIR
|
|
600
|
+
(default $XDG_CACHE_HOME/kinloom-va-archives or ~/.cache/kinloom-va-archives).
|
|
601
|
+
"""
|
|
602
|
+
_STATE["refresh"] = refresh
|
|
215
603
|
|
|
216
604
|
|
|
217
605
|
@cli.group("chancery")
|
|
@@ -239,6 +627,7 @@ def chancery() -> None:
|
|
|
239
627
|
@click.option("--plats", is_flag=True, help="Only cases with plats available.")
|
|
240
628
|
@click.option("--pages", default="1", show_default=True, help="Result pages to fetch: '1', '1-3', '1,3', or 'all' (20 records per page).")
|
|
241
629
|
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
630
|
+
@refresh_option
|
|
242
631
|
def cmd_chancery_search(surnames, locality, match, surname2, plaintiff_last, plaintiff_first,
|
|
243
632
|
defendant_last, defendant_first, year_from, year_to, index_number,
|
|
244
633
|
local_case_number, enslaved, free, plats, pages, as_json):
|
|
@@ -269,9 +658,7 @@ def cmd_chancery_search(surnames, locality, match, surname2, plaintiff_last, pla
|
|
|
269
658
|
form["chkPlat"] = "on"
|
|
270
659
|
first_page = 1
|
|
271
660
|
form["LOC"] = locality
|
|
272
|
-
|
|
273
|
-
resp.raise_for_status()
|
|
274
|
-
parsed = parse_search_page(resp.text)
|
|
661
|
+
parsed = parse_search_page(fetch_text(c, CHANCERY_SEARCH, method="POST", data=form))
|
|
275
662
|
total += parsed["total"]
|
|
276
663
|
if pages.strip().lower() == "all":
|
|
277
664
|
wanted = list(range(1, (total + 19) // 20 + 1)) or [1]
|
|
@@ -283,9 +670,8 @@ def cmd_chancery_search(surnames, locality, match, surname2, plaintiff_last, pla
|
|
|
283
670
|
continue
|
|
284
671
|
form2 = dict(form)
|
|
285
672
|
form2["intPage"] = str(pn)
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
all_records.extend(parse_search_page(r2.text)["records"])
|
|
673
|
+
all_records.extend(parse_search_page(
|
|
674
|
+
fetch_text(c, CHANCERY_SEARCH, method="POST", data=form2))["records"])
|
|
289
675
|
if as_json:
|
|
290
676
|
click.echo(json.dumps({"total": total, "returned": len(all_records), "records": all_records}, indent=1))
|
|
291
677
|
return
|
|
@@ -299,19 +685,15 @@ def cmd_chancery_search(surnames, locality, match, surname2, plaintiff_last, pla
|
|
|
299
685
|
@click.argument("cfn")
|
|
300
686
|
@click.option("--images", is_flag=True, help="Also list the scanned page PDFs and ZIP URL.")
|
|
301
687
|
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
688
|
+
@refresh_option
|
|
302
689
|
def cmd_chancery_case(cfn: str, images: bool, as_json: bool) -> None:
|
|
303
690
|
"""Show one chancery cause by CFN (locality-year-number)."""
|
|
304
691
|
with _client() as c:
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
detail =
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
if images:
|
|
311
|
-
with _client() as c:
|
|
312
|
-
resp = c.get(CHANCERY_IMAGES, params={"CFN": cfn})
|
|
313
|
-
resp.raise_for_status()
|
|
314
|
-
detail["images"] = parse_images_page(resp.text)
|
|
692
|
+
detail = parse_case_page(fetch_text(c, CHANCERY_DETAIL, params={"CFN": cfn}))
|
|
693
|
+
detail["cfn"] = cfn
|
|
694
|
+
detail["case_url"] = CHANCERY_DETAIL + "?CFN=" + cfn
|
|
695
|
+
if images:
|
|
696
|
+
detail["images"] = parse_images_page(fetch_text(c, CHANCERY_IMAGES, params={"CFN": cfn}))
|
|
315
697
|
if as_json:
|
|
316
698
|
click.echo(json.dumps(detail, indent=1))
|
|
317
699
|
return
|
|
@@ -336,21 +718,20 @@ def cmd_chancery_case(cfn: str, images: bool, as_json: bool) -> None:
|
|
|
336
718
|
@click.option("--pages", default="all", show_default=True, help="1-based page selection, e.g. '1-5' or 'all'.")
|
|
337
719
|
@click.option("--zip", "as_zip", is_flag=True, help="Download the whole-case ZIP instead of page PDFs.")
|
|
338
720
|
@click.option("--overwrite", is_flag=True, help="Overwrite existing files.")
|
|
721
|
+
@refresh_option
|
|
339
722
|
def cmd_chancery_download(cfn: str, out_dir: Path | None, pages: str, as_zip: bool, overwrite: bool) -> None:
|
|
340
|
-
"""Download the scanned pages (or whole-case ZIP) for one chancery cause."""
|
|
723
|
+
"""Download the scanned pages (or whole-case ZIP) for one chancery cause (disk-cached)."""
|
|
724
|
+
if not re.fullmatch(r"[0-9]+(?:-[0-9]+)*", cfn):
|
|
725
|
+
raise click.BadParameter(f"Invalid CFN (expected locality-year-number digits): {cfn!r}")
|
|
341
726
|
out_dir = out_dir or Path(f"va-chancery-{cfn}")
|
|
342
727
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
343
728
|
with _client() as c:
|
|
344
|
-
|
|
345
|
-
resp.raise_for_status()
|
|
346
|
-
detail = parse_case_page(resp.text)
|
|
729
|
+
detail = parse_case_page(fetch_text(c, CHANCERY_DETAIL, params={"CFN": cfn}))
|
|
347
730
|
detail["cfn"] = cfn
|
|
348
731
|
detail["case_url"] = CHANCERY_DETAIL + "?CFN=" + cfn
|
|
349
732
|
imgs = None
|
|
350
733
|
if not as_zip:
|
|
351
|
-
|
|
352
|
-
r2.raise_for_status()
|
|
353
|
-
imgs = parse_images_page(r2.text)
|
|
734
|
+
imgs = parse_images_page(fetch_text(c, CHANCERY_IMAGES, params={"CFN": cfn}))
|
|
354
735
|
detail["images"] = imgs
|
|
355
736
|
(out_dir / "metadata.json").write_text(json.dumps(detail, indent=1), encoding="utf-8")
|
|
356
737
|
if as_zip:
|
|
@@ -359,26 +740,19 @@ def cmd_chancery_download(cfn: str, out_dir: Path | None, pages: str, as_zip: bo
|
|
|
359
740
|
if dest.exists() and not overwrite:
|
|
360
741
|
click.echo(f"exists, skipping: {dest}")
|
|
361
742
|
return
|
|
362
|
-
|
|
363
|
-
r.raise_for_status()
|
|
364
|
-
with open(dest, "wb") as f:
|
|
365
|
-
for chunk in r.iter_bytes():
|
|
366
|
-
f.write(chunk)
|
|
743
|
+
copy_atomic(fetch_file(c, zip_url), dest)
|
|
367
744
|
click.echo(f"saved {dest} ({dest.stat().st_size} bytes)")
|
|
368
745
|
return
|
|
369
746
|
assert imgs is not None
|
|
370
747
|
wanted = parse_page_spec(pages, imgs["total_pages"])
|
|
371
748
|
for n in wanted:
|
|
372
749
|
url = imgs["page_pdfs"][n - 1]
|
|
373
|
-
|
|
750
|
+
name = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(urlsplit(url).path).name).lstrip(".") or f"{n:04d}.pdf"
|
|
751
|
+
dest = out_dir / name
|
|
374
752
|
if dest.exists() and not overwrite:
|
|
375
753
|
click.echo(f"exists, skipping: {dest.name}")
|
|
376
754
|
continue
|
|
377
|
-
|
|
378
|
-
r.raise_for_status()
|
|
379
|
-
with open(dest, "wb") as f:
|
|
380
|
-
for chunk in r.iter_bytes():
|
|
381
|
-
f.write(chunk)
|
|
755
|
+
copy_atomic(fetch_file(c, url), dest)
|
|
382
756
|
click.echo(f"saved {dest} ({dest.stat().st_size} bytes)")
|
|
383
757
|
click.echo(f"metadata: {out_dir / 'metadata.json'}")
|
|
384
758
|
|
|
@@ -386,12 +760,11 @@ def cmd_chancery_download(cfn: str, out_dir: Path | None, pages: str, as_zip: bo
|
|
|
386
760
|
@chancery.command("localities")
|
|
387
761
|
@click.option("--status", default=None, help="Filter by viewing status substring, e.g. Scanned.")
|
|
388
762
|
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
763
|
+
@refresh_option
|
|
389
764
|
def cmd_chancery_localities(status: str | None, as_json: bool) -> None:
|
|
390
765
|
"""List per-locality chancery coverage from available.asp."""
|
|
391
766
|
with _client() as c:
|
|
392
|
-
|
|
393
|
-
resp.raise_for_status()
|
|
394
|
-
rows = parse_localities_page(resp.text)
|
|
767
|
+
rows = parse_localities_page(fetch_text(c, CHANCERY_AVAILABLE))
|
|
395
768
|
if status:
|
|
396
769
|
rows = [r for r in rows if status.lower() in r["viewing_status"].lower()]
|
|
397
770
|
if as_json:
|
|
@@ -409,6 +782,7 @@ def cmd_chancery_localities(status: str | None, as_json: bool) -> None:
|
|
|
409
782
|
@click.option("--limit", default=10, show_default=True, type=int, help="Results per page (PNXS limit).")
|
|
410
783
|
@click.option("--offset", default=0, show_default=True, type=int, help="Result offset (PNXS offset).")
|
|
411
784
|
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
785
|
+
@refresh_option
|
|
412
786
|
def cmd_catalog(query: str, field: str, limit: int, offset: int, as_json: bool) -> None:
|
|
413
787
|
"""Search the Library of Virginia catalog via the public Primo PNXS API."""
|
|
414
788
|
params = {
|
|
@@ -417,9 +791,7 @@ def cmd_catalog(query: str, field: str, limit: int, offset: int, as_json: bool)
|
|
|
417
791
|
"limit": str(limit), "offset": str(offset),
|
|
418
792
|
}
|
|
419
793
|
with _client() as c:
|
|
420
|
-
|
|
421
|
-
resp.raise_for_status()
|
|
422
|
-
data = resp.json()
|
|
794
|
+
data = json.loads(fetch_text(c, PRIMO_PNXS, params=params))
|
|
423
795
|
info = data.get("info", {})
|
|
424
796
|
records = [_pnxs_record(d) for d in data.get("docs", [])]
|
|
425
797
|
if as_json:
|
|
@@ -462,5 +834,206 @@ def cmd_url(chancery_case, catalog_query, chronicle, land, arvas, chancery) -> N
|
|
|
462
834
|
click.echo("https://www.lva.virginia.gov/collections/digital-collections")
|
|
463
835
|
|
|
464
836
|
|
|
837
|
+
def _grant_tif(path_or_url: str, out: Path | None, as_json: bool) -> None:
|
|
838
|
+
try:
|
|
839
|
+
url = normalize_lva_image_url(path_or_url)
|
|
840
|
+
except ValueError as exc:
|
|
841
|
+
raise click.BadParameter(str(exc)) from exc
|
|
842
|
+
with _client() as c:
|
|
843
|
+
cached = fetch_file(c, url, allowed_hosts=(LVA_IMAGE_HOST,))
|
|
844
|
+
result: dict = {"url": url, "cache_path": str(cached), "bytes": cached.stat().st_size}
|
|
845
|
+
if out is not None:
|
|
846
|
+
mode = save_image(cached, out)
|
|
847
|
+
if mode.startswith("raw:"):
|
|
848
|
+
result.update(out=mode[4:], mode="raw")
|
|
849
|
+
else:
|
|
850
|
+
result.update(out=str(out), mode=mode)
|
|
851
|
+
if as_json:
|
|
852
|
+
click.echo(json.dumps(result, indent=1))
|
|
853
|
+
return
|
|
854
|
+
if out is not None:
|
|
855
|
+
click.echo(f"saved {result['out']} ({result['mode']}) from {url}")
|
|
856
|
+
else:
|
|
857
|
+
click.echo(f"cached {url} -> {cached} ({result['bytes']} bytes); pass --out FILE to save it")
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
_GRANT_TIF_HELP = (
|
|
861
|
+
"Fetch (and cache) one Library of Virginia image-server scan, e.g. a Land Office patent "
|
|
862
|
+
"/LONN/LO-3/372/372_0195.tif or a Dunmore's War /Microfilm/DW/... page. Accepts "
|
|
863
|
+
"https://image.lva.virginia.gov/<path> or a path on that host only. --out x.jpg converts "
|
|
864
|
+
"TIFF to JPEG when Pillow is available; any other suffix gets the raw bytes."
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
@cli.command("grant-tif", help=_GRANT_TIF_HELP)
|
|
869
|
+
@click.argument("path_or_url")
|
|
870
|
+
@click.option("--out", type=click.Path(path_type=Path), default=None, help="Output file (.jpg/.jpeg converts; else raw).")
|
|
871
|
+
@click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
|
|
872
|
+
@refresh_option
|
|
873
|
+
def cmd_grant_tif(path_or_url: str, out: Path | None, as_json: bool) -> None:
|
|
874
|
+
_grant_tif(path_or_url, out, as_json)
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
@cli.command("lva-tif", help="Alias of grant-tif. " + _GRANT_TIF_HELP)
|
|
878
|
+
@click.argument("path_or_url")
|
|
879
|
+
@click.option("--out", type=click.Path(path_type=Path), default=None, help="Output file (.jpg/.jpeg converts; else raw).")
|
|
880
|
+
@click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
|
|
881
|
+
@refresh_option
|
|
882
|
+
def cmd_lva_tif(path_or_url: str, out: Path | None, as_json: bool) -> None:
|
|
883
|
+
_grant_tif(path_or_url, out, as_json)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
@cli.command("dunmore")
|
|
887
|
+
@click.argument("drawer")
|
|
888
|
+
@click.argument("card")
|
|
889
|
+
@click.option("--page", "page_no", type=int, default=None, help="Page number to save (default: the card's own page).")
|
|
890
|
+
@click.option("--out", type=click.Path(path_type=Path), default=None, help="Save the selected page image (.jpg converts; else raw TIFF).")
|
|
891
|
+
@click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
|
|
892
|
+
@refresh_option
|
|
893
|
+
def cmd_dunmore(drawer: str, card: str, page_no: int | None, out: Path | None, as_json: bool) -> None:
|
|
894
|
+
"""Resolve a Dunmore's War (1774) index card to its page TIFFs on image.lva.virginia.gov.
|
|
895
|
+
|
|
896
|
+
DRAWER and CARD come from the catalog's GetDW.pl links
|
|
897
|
+
(GetDW.pl?dir=<DRAWER>&card=<CARD> -> `dunmore <DRAWER> <CARD>`). Lists the
|
|
898
|
+
neighbouring page images; --out saves the card's page (or --page N).
|
|
899
|
+
"""
|
|
900
|
+
if not re.fullmatch(r"\d{1,5}/W\d{1,6}", drawer):
|
|
901
|
+
raise click.BadParameter(f"Invalid drawer (expected e.g. 0001/W0001): {drawer!r}")
|
|
902
|
+
if not re.fullmatch(r"\d{1,6}", card):
|
|
903
|
+
raise click.BadParameter(f"Invalid card number: {card!r}")
|
|
904
|
+
with _client() as c:
|
|
905
|
+
parsed = parse_dunmore_drawer(fetch_text(c, DUNMORE_CGI, params={"dir": drawer, "card": card}))
|
|
906
|
+
parsed.update(drawer=drawer, card=card, source_url=f"{DUNMORE_CGI}?dir={drawer}&card={card}")
|
|
907
|
+
if not parsed["images"]:
|
|
908
|
+
raise click.ClickException("No page images found on the Dunmore's War drawer page.")
|
|
909
|
+
chosen = None
|
|
910
|
+
if page_no is not None:
|
|
911
|
+
chosen = next((im for im in parsed["images"] if im["page"] == page_no), None)
|
|
912
|
+
if chosen is None:
|
|
913
|
+
raise click.ClickException(f"Page {page_no} is not listed for this card.")
|
|
914
|
+
else:
|
|
915
|
+
chosen = next((im for im in parsed["images"] if im["current"]), parsed["images"][0])
|
|
916
|
+
parsed["selected"] = chosen
|
|
917
|
+
if out is not None:
|
|
918
|
+
with _client() as c:
|
|
919
|
+
cached = fetch_file(c, chosen["url"], allowed_hosts=(LVA_IMAGE_HOST,))
|
|
920
|
+
mode = save_image(cached, out)
|
|
921
|
+
parsed["out"] = mode[4:] if mode.startswith("raw:") else str(out)
|
|
922
|
+
parsed["mode"] = "raw" if mode.startswith("raw") else mode
|
|
923
|
+
if as_json:
|
|
924
|
+
click.echo(json.dumps(parsed, indent=1))
|
|
925
|
+
return
|
|
926
|
+
click.echo(f"Dunmore's War drawer {drawer} card {card}: page {parsed['current_page']}")
|
|
927
|
+
for im in parsed["images"]:
|
|
928
|
+
mark = "*" if im is chosen else " "
|
|
929
|
+
click.echo(f" {mark} page {im['page']}: {im['url']}")
|
|
930
|
+
if out is not None:
|
|
931
|
+
click.echo(f"saved {parsed['out']} ({parsed['mode']})")
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
def resolve_rosetta(c: httpx.Client, ie: str) -> dict:
|
|
935
|
+
"""Resolve an IE to its FL file list via the delivery page + ieViewer (one cookie session)."""
|
|
936
|
+
cache_dir = get_cache_root() / "rosetta" / ie
|
|
937
|
+
files_path = cache_dir / "files.json"
|
|
938
|
+
if not _STATE["refresh"]:
|
|
939
|
+
cached = read_json_if_valid(files_path)
|
|
940
|
+
if cached and cached.get("files"):
|
|
941
|
+
return {**cached, "session": False}
|
|
942
|
+
r = c.get(ROSETTA_DELIVERY, params={"dps_pid": ie})
|
|
943
|
+
r.raise_for_status()
|
|
944
|
+
if not _host_ok(r.url, (ROSETTA_HOST,)):
|
|
945
|
+
raise click.ClickException(f"Unexpected Rosetta redirect: {r.url}")
|
|
946
|
+
info = parse_rosetta_delivery(r.text)
|
|
947
|
+
viewer_url = info["viewer_url"]
|
|
948
|
+
if viewer_url:
|
|
949
|
+
vu = httpx.URL(viewer_url)
|
|
950
|
+
if vu.scheme != "https" or vu.host != ROSETTA_HOST or not vu.path.endswith("/ieViewer.do") or vu.params.get("dps_pid") != ie:
|
|
951
|
+
viewer_url = None
|
|
952
|
+
if not viewer_url:
|
|
953
|
+
params = {"search": "hide", "dps_pid": ie}
|
|
954
|
+
if info["dps_dvs"]:
|
|
955
|
+
params["dps_dvs"] = info["dps_dvs"]
|
|
956
|
+
viewer_url = str(httpx.URL(ROSETTA_VIEWER, params=params))
|
|
957
|
+
v = c.get(viewer_url)
|
|
958
|
+
v.raise_for_status()
|
|
959
|
+
if not _host_ok(v.url, (ROSETTA_HOST,)):
|
|
960
|
+
raise click.ClickException(f"Unexpected Rosetta redirect: {v.url}")
|
|
961
|
+
listing = parse_rosetta_viewer(v.text)
|
|
962
|
+
if not listing["files"]:
|
|
963
|
+
raise click.ClickException(f"No delivered files found for {ie} (restricted or not a viewable IE).")
|
|
964
|
+
result = {"ie": ie, "delivery_url": f"{ROSETTA_DELIVERY}?dps_pid={ie}",
|
|
965
|
+
"files": listing["files"], "initial": listing["initial"], "cached_at": time.time()}
|
|
966
|
+
atomic_write_json(files_path, result)
|
|
967
|
+
return {**result, "session": True}
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def download_rosetta_file(c: httpx.Client, ie: str, fl: str) -> tuple[Path, dict]:
|
|
971
|
+
cache_dir = get_cache_root() / "rosetta" / ie
|
|
972
|
+
path, meta = cached_fetch(
|
|
973
|
+
c, ROSETTA_DELIVERY, cache_dir / f"{fl}.bin",
|
|
974
|
+
params={"dps_pid": fl, "dps_func": "stream"}, allowed_hosts=(ROSETTA_HOST,),
|
|
975
|
+
)
|
|
976
|
+
if meta.get("content_type", "").lower().startswith("text/html"):
|
|
977
|
+
path.unlink(missing_ok=True)
|
|
978
|
+
_meta_path(path).unlink(missing_ok=True)
|
|
979
|
+
raise click.ClickException(f"Rosetta returned HTML instead of a file for {ie}/{fl} (access restricted?).")
|
|
980
|
+
return path, meta
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
@cli.command("download-rosetta")
|
|
984
|
+
@click.argument("ie_id")
|
|
985
|
+
@click.option("--file", "file_index", type=int, default=None, help="1-based file number from --list (default: viewer's initial file).")
|
|
986
|
+
@click.option("--fl", "fl_id", default=None, help="Explicit Rosetta file pid (FL<digits>) belonging to this IE.")
|
|
987
|
+
@click.option("--list", "list_only", is_flag=True, help="Only list the IE's delivered files.")
|
|
988
|
+
@click.option("--out", type=click.Path(path_type=Path), default=None, help="Output file (default ./<IE>_<FL>.<ext>).")
|
|
989
|
+
@click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
|
|
990
|
+
@refresh_option
|
|
991
|
+
def cmd_download_rosetta(ie_id: str, file_index: int | None, fl_id: str | None, list_only: bool,
|
|
992
|
+
out: Path | None, as_json: bool) -> None:
|
|
993
|
+
"""Download a delivered file (PDF/image) for a Library of Virginia Rosetta IE id.
|
|
994
|
+
|
|
995
|
+
Resolves rosetta.virginiamemory.com DeliveryManagerServlet?dps_pid=IE... ->
|
|
996
|
+
ieViewer.do (same cookie session) -> FL file pid -> dps_func=stream. The
|
|
997
|
+
file list and bytes are cached per IE id.
|
|
998
|
+
"""
|
|
999
|
+
ie = validate_ie_id(ie_id)
|
|
1000
|
+
if fl_id is not None:
|
|
1001
|
+
fl_id = validate_fl_id(fl_id)
|
|
1002
|
+
with _client() as c:
|
|
1003
|
+
info = resolve_rosetta(c, ie)
|
|
1004
|
+
files = info["files"]
|
|
1005
|
+
if list_only:
|
|
1006
|
+
if as_json:
|
|
1007
|
+
click.echo(json.dumps({k: v for k, v in info.items() if k != "session"}, indent=1))
|
|
1008
|
+
else:
|
|
1009
|
+
for i, f in enumerate(files, 1):
|
|
1010
|
+
star = "*" if f["fl"] == info.get("initial") else " "
|
|
1011
|
+
click.echo(f" {star} {i}. {f['fl']} {f['title']}")
|
|
1012
|
+
return
|
|
1013
|
+
if fl_id is not None:
|
|
1014
|
+
if fl_id not in {f["fl"] for f in files}:
|
|
1015
|
+
raise click.ClickException(f"{fl_id} is not a file of {ie}; see --list.")
|
|
1016
|
+
fl = fl_id
|
|
1017
|
+
elif file_index is not None:
|
|
1018
|
+
if not 1 <= file_index <= len(files):
|
|
1019
|
+
raise click.BadParameter(f"--file must be 1..{len(files)}")
|
|
1020
|
+
fl = files[file_index - 1]["fl"]
|
|
1021
|
+
else:
|
|
1022
|
+
fl = info.get("initial") or files[0]["fl"]
|
|
1023
|
+
if not info.get("session") and (_STATE["refresh"] or _cache_valid(get_cache_root() / "rosetta" / ie / f"{fl}.bin", None) is None):
|
|
1024
|
+
# Listing came from cache: open a delivery session (cookies) before streaming.
|
|
1025
|
+
warm = c.get(ROSETTA_DELIVERY, params={"dps_pid": ie})
|
|
1026
|
+
warm.raise_for_status()
|
|
1027
|
+
path, meta = download_rosetta_file(c, ie, fl)
|
|
1028
|
+
dest = out or Path(f"{ie}_{fl}{_ext_for(meta.get('content_type', ''))}")
|
|
1029
|
+
copy_atomic(path, dest)
|
|
1030
|
+
result = {"ie": ie, "fl": fl, "content_type": meta.get("content_type", ""), "out": str(dest),
|
|
1031
|
+
"bytes": dest.stat().st_size, "cache_path": str(path)}
|
|
1032
|
+
if as_json:
|
|
1033
|
+
click.echo(json.dumps(result, indent=1))
|
|
1034
|
+
else:
|
|
1035
|
+
click.echo(f"saved {dest} ({result['bytes']} bytes, {result['content_type']}) from {ie}/{fl}")
|
|
1036
|
+
|
|
1037
|
+
|
|
465
1038
|
if __name__ == "__main__":
|
|
466
1039
|
cli()
|