@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,624 @@
|
|
|
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
|
+
"""Search and inspect Dutch and Belgian genealogical records via OpenArchieven.
|
|
10
|
+
|
|
11
|
+
Uses the public OpenArchieven 1.0 JSON API (https://api.openarch.nl/1.0/records/):
|
|
12
|
+
no API key or login is required for read access. Requests are spaced to respect
|
|
13
|
+
the 4 requests/second IP rate limit.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import time
|
|
24
|
+
from contextlib import contextmanager
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, Callable, Iterator
|
|
27
|
+
from urllib.parse import urlencode
|
|
28
|
+
|
|
29
|
+
import click
|
|
30
|
+
import httpx
|
|
31
|
+
|
|
32
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
33
|
+
CACHE_SCHEMA = 1
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def cache_dir() -> Path:
|
|
37
|
+
override = os.environ.get("KINLOOM_OPENARCHIEVEN_CACHE_DIR")
|
|
38
|
+
if override:
|
|
39
|
+
return Path(override).expanduser()
|
|
40
|
+
return Path.home() / ".cache" / "kinloom-openarchieven"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
44
|
+
if cli_ttl is not None:
|
|
45
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
46
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
47
|
+
return float(cli_ttl)
|
|
48
|
+
raw = os.environ.get("KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS")
|
|
49
|
+
if raw is not None and raw.strip():
|
|
50
|
+
try:
|
|
51
|
+
parsed = float(raw.strip())
|
|
52
|
+
except ValueError as exc:
|
|
53
|
+
raise click.BadParameter(f"Invalid KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
54
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
55
|
+
raise click.BadParameter(
|
|
56
|
+
f"Invalid KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS value: {raw!r} (must be >= 0).")
|
|
57
|
+
return parsed
|
|
58
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@contextmanager
|
|
62
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
63
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
64
|
+
try:
|
|
65
|
+
import fcntl
|
|
66
|
+
except ImportError:
|
|
67
|
+
yield
|
|
68
|
+
return
|
|
69
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
with open(lock_path, "a+b") as lock_file:
|
|
71
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
72
|
+
try:
|
|
73
|
+
yield
|
|
74
|
+
finally:
|
|
75
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
79
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
81
|
+
try:
|
|
82
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
83
|
+
os.replace(tmp, dest)
|
|
84
|
+
except Exception:
|
|
85
|
+
tmp.unlink(missing_ok=True)
|
|
86
|
+
raise
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
90
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
91
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
95
|
+
if not path.is_file():
|
|
96
|
+
return None
|
|
97
|
+
try:
|
|
98
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
99
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
100
|
+
return None
|
|
101
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
102
|
+
return None
|
|
103
|
+
fetched = entry.get("fetched_at")
|
|
104
|
+
if not isinstance(fetched, (int, float)):
|
|
105
|
+
return None
|
|
106
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
107
|
+
return None
|
|
108
|
+
result = entry.get("result")
|
|
109
|
+
return result if isinstance(result, dict) else None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def cached_call(kind: str, payload: dict, fetch: Callable[[], dict], *,
|
|
113
|
+
refresh: bool, ttl_hours: float,
|
|
114
|
+
cacheable: Callable[[dict], bool] = lambda _r: True) -> tuple[dict, bool]:
|
|
115
|
+
"""Return (result, cache_hit). Concurrent callers of one query serialize
|
|
116
|
+
on a per-key flock, so the second caller reads the first caller's file.
|
|
117
|
+
Failures raise out of fetch() and are never written; results rejected by
|
|
118
|
+
`cacheable` are returned but not stored."""
|
|
119
|
+
key = cache_key(kind, payload)
|
|
120
|
+
root = cache_dir()
|
|
121
|
+
path = root / f"{key}.json"
|
|
122
|
+
if not refresh:
|
|
123
|
+
hit = read_cache(path, ttl_hours)
|
|
124
|
+
if hit is not None:
|
|
125
|
+
return hit, True
|
|
126
|
+
with file_lock(root / f"{key}.lock"):
|
|
127
|
+
if not refresh:
|
|
128
|
+
hit = read_cache(path, ttl_hours)
|
|
129
|
+
if hit is not None:
|
|
130
|
+
return hit, True
|
|
131
|
+
result = fetch()
|
|
132
|
+
if cacheable(result):
|
|
133
|
+
atomic_write_json(path, {"schema": CACHE_SCHEMA, "fetched_at": time.time(),
|
|
134
|
+
"kind": kind, "query": payload, "result": result})
|
|
135
|
+
return result, False
|
|
136
|
+
|
|
137
|
+
API_BASE = "https://api.openarch.nl/1.0/records"
|
|
138
|
+
WEB_BASE = "https://www.openarchieven.nl"
|
|
139
|
+
USER_AGENT = "kinloom/1.0 (genealogy research; https://github.com/tiberriver256/kinloom)"
|
|
140
|
+
MIN_INTERVAL_S = 0.25
|
|
141
|
+
TIMEOUT = 30.0
|
|
142
|
+
|
|
143
|
+
KNOWN_SOURCE_TYPES = {
|
|
144
|
+
"bevolkingsregister",
|
|
145
|
+
"passagiersregisters",
|
|
146
|
+
"notariële archieven",
|
|
147
|
+
"militieregisters",
|
|
148
|
+
"bidprentjes",
|
|
149
|
+
"familienamen",
|
|
150
|
+
"gezinskaarten",
|
|
151
|
+
"persoonskaarten",
|
|
152
|
+
"woningkaarten",
|
|
153
|
+
"memorie van successie",
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _fail(message: str) -> None:
|
|
158
|
+
click.echo(message, err=True)
|
|
159
|
+
raise SystemExit(1)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def cache_options(func: Callable) -> Callable:
|
|
163
|
+
func = click.option(
|
|
164
|
+
"--cache-ttl-hours",
|
|
165
|
+
type=float,
|
|
166
|
+
default=None,
|
|
167
|
+
help="Cache TTL in hours (default 168, env KINLOOM_OPENARCHIEVEN_CACHE_TTL_HOURS; 0 disables reads).",
|
|
168
|
+
)(func)
|
|
169
|
+
func = click.option(
|
|
170
|
+
"--refresh",
|
|
171
|
+
is_flag=True,
|
|
172
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).",
|
|
173
|
+
)(func)
|
|
174
|
+
return func
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _client() -> httpx.Client:
|
|
178
|
+
return httpx.Client(
|
|
179
|
+
timeout=TIMEOUT,
|
|
180
|
+
follow_redirects=True,
|
|
181
|
+
headers={"User-Agent": USER_AGENT, "Accept": "application/json"},
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _get_json(endpoint: str, params: dict[str, Any]) -> Any:
|
|
186
|
+
"""Fetch one JSON response from api.openarch.nl with boundary validation."""
|
|
187
|
+
if MIN_INTERVAL_S > 0:
|
|
188
|
+
time.sleep(MIN_INTERVAL_S)
|
|
189
|
+
url = f"{API_BASE}/{endpoint}"
|
|
190
|
+
try:
|
|
191
|
+
with _client() as client:
|
|
192
|
+
resp = client.get(url, params=params)
|
|
193
|
+
except httpx.HTTPError as exc:
|
|
194
|
+
_fail(f"OpenArchieven request failed: {exc}")
|
|
195
|
+
if resp.status_code != 200:
|
|
196
|
+
_fail(f"HTTP {resp.status_code} from {url}")
|
|
197
|
+
try:
|
|
198
|
+
data = resp.json()
|
|
199
|
+
except ValueError as exc:
|
|
200
|
+
_fail(f"Invalid JSON from {url}: {exc}")
|
|
201
|
+
if isinstance(data, dict) and data.get("error_code") is not None:
|
|
202
|
+
desc = data.get("error_description") or data.get("error") or "Unknown API error"
|
|
203
|
+
_fail(f"OpenArchieven API error {data['error_code']}: {desc}")
|
|
204
|
+
return data
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _search_cacheable(result: dict[str, Any]) -> bool:
|
|
208
|
+
resp = result.get("response")
|
|
209
|
+
if not isinstance(resp, dict):
|
|
210
|
+
return False
|
|
211
|
+
docs = resp.get("docs")
|
|
212
|
+
found = resp.get("number_found")
|
|
213
|
+
return isinstance(docs, list) and isinstance(found, int) and found >= 0 and (bool(docs) or found == 0)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _show_cacheable(result: dict[str, Any]) -> bool:
|
|
217
|
+
data = result.get("data")
|
|
218
|
+
if isinstance(data, dict):
|
|
219
|
+
return bool(data)
|
|
220
|
+
if isinstance(data, list):
|
|
221
|
+
return len(data) > 0
|
|
222
|
+
return False
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _is_source_type(value: str) -> bool:
|
|
226
|
+
low = value.strip().lower()
|
|
227
|
+
return low.startswith("bs ") or low.startswith("dtb ") or low in KNOWN_SOURCE_TYPES
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _fmt_eventdate(date_obj: Any) -> str:
|
|
231
|
+
if not isinstance(date_obj, dict):
|
|
232
|
+
return ""
|
|
233
|
+
year = date_obj.get("year")
|
|
234
|
+
month = date_obj.get("month")
|
|
235
|
+
day = date_obj.get("day")
|
|
236
|
+
if year is None:
|
|
237
|
+
return ""
|
|
238
|
+
if month and day:
|
|
239
|
+
return f"{int(year):04d}-{int(month):02d}-{int(day):02d}"
|
|
240
|
+
if month:
|
|
241
|
+
return f"{int(year):04d}-{int(month):02d}"
|
|
242
|
+
return f"{int(year):04d}"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _a2a_text(node: Any) -> str:
|
|
246
|
+
"""Unwrap OpenArchieven's nested A2A JSON single-key string wrappers."""
|
|
247
|
+
if node is None:
|
|
248
|
+
return ""
|
|
249
|
+
if isinstance(node, str):
|
|
250
|
+
return node.strip()
|
|
251
|
+
if isinstance(node, (int, float)):
|
|
252
|
+
return str(node)
|
|
253
|
+
if isinstance(node, dict):
|
|
254
|
+
for key, val in node.items():
|
|
255
|
+
if isinstance(val, (str, int, float)):
|
|
256
|
+
return str(val).strip()
|
|
257
|
+
if isinstance(val, dict) and key in val:
|
|
258
|
+
return _a2a_text(val[key])
|
|
259
|
+
for val in node.values():
|
|
260
|
+
found = _a2a_text(val)
|
|
261
|
+
if found:
|
|
262
|
+
return found
|
|
263
|
+
return ""
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _as_list(val: Any) -> list[Any]:
|
|
267
|
+
if val is None:
|
|
268
|
+
return []
|
|
269
|
+
return val if isinstance(val, list) else [val]
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _fmt_a2a_date(date_node: Any) -> str:
|
|
273
|
+
if not isinstance(date_node, dict):
|
|
274
|
+
return _a2a_text(date_node)
|
|
275
|
+
year = _a2a_text(date_node.get("a2a_Year"))
|
|
276
|
+
month = _a2a_text(date_node.get("a2a_Month"))
|
|
277
|
+
day = _a2a_text(date_node.get("a2a_Day"))
|
|
278
|
+
if year and month and day:
|
|
279
|
+
try:
|
|
280
|
+
return f"{int(year):04d}-{int(month):02d}-{int(day):02d}"
|
|
281
|
+
except ValueError:
|
|
282
|
+
pass
|
|
283
|
+
if year and month:
|
|
284
|
+
try:
|
|
285
|
+
return f"{int(year):04d}-{int(month):02d}"
|
|
286
|
+
except ValueError:
|
|
287
|
+
pass
|
|
288
|
+
if year:
|
|
289
|
+
return year
|
|
290
|
+
return _a2a_text(date_node.get("a2a_LiteralDate"))
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _fmt_a2a_person_name(name_node: Any) -> str:
|
|
294
|
+
if not isinstance(name_node, dict):
|
|
295
|
+
return _a2a_text(name_node)
|
|
296
|
+
parts = [
|
|
297
|
+
_a2a_text(name_node.get("a2a_PersonNameFirstName")),
|
|
298
|
+
_a2a_text(name_node.get("a2a_PersonNamePatronym")),
|
|
299
|
+
_a2a_text(name_node.get("a2a_PersonNamePrefixLastName")),
|
|
300
|
+
_a2a_text(name_node.get("a2a_PersonNameLastName")),
|
|
301
|
+
]
|
|
302
|
+
return " ".join(p for p in parts if p)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _parse_record_ref(archive: str, identifier: str | None) -> tuple[str, str]:
|
|
306
|
+
"""Accept either (archive, identifier), 'archive:identifier', or an openarchieven.nl URL."""
|
|
307
|
+
if identifier:
|
|
308
|
+
return archive.strip(), identifier.strip()
|
|
309
|
+
match = re.search(r"openarchieven\.nl/([a-z0-9_-]+):([A-Za-z0-9-]+)", archive, re.I)
|
|
310
|
+
if match:
|
|
311
|
+
return match.group(1), match.group(2)
|
|
312
|
+
if ":" in archive:
|
|
313
|
+
code, ident = archive.split(":", 1)
|
|
314
|
+
if code.strip() and ident.strip():
|
|
315
|
+
return code.strip(), ident.strip()
|
|
316
|
+
raise click.UsageError(
|
|
317
|
+
"Pass ARCHIVE and IDENTIFIER, an 'archive:uuid' token, or an openarchieven.nl record URL."
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _format_a2a_record(archive: str, identifier: str, record: dict[str, Any]) -> str:
|
|
322
|
+
lines = [
|
|
323
|
+
f"Record: {archive}:{identifier}",
|
|
324
|
+
f" URL: {WEB_BASE}/{archive}:{identifier}",
|
|
325
|
+
]
|
|
326
|
+
source = record.get("a2a_Source") or {}
|
|
327
|
+
source_type = _a2a_text(source.get("a2a_SourceType"))
|
|
328
|
+
source_place = _a2a_text((source.get("a2a_SourcePlace") or {}).get("a2a_Place"))
|
|
329
|
+
ref = source.get("a2a_SourceReference") or {}
|
|
330
|
+
inst = _a2a_text(ref.get("a2a_InstitutionName"))
|
|
331
|
+
book = _a2a_text(ref.get("a2a_Book"))
|
|
332
|
+
collection = _a2a_text(ref.get("a2a_Collection"))
|
|
333
|
+
doc_num = _a2a_text(ref.get("a2a_DocumentNumber"))
|
|
334
|
+
archive_num = _a2a_text(ref.get("a2a_Archive"))
|
|
335
|
+
reg_num = _a2a_text(ref.get("a2a_RegistryNumber"))
|
|
336
|
+
|
|
337
|
+
if source_type:
|
|
338
|
+
lines.append(f" Source type: {source_type}")
|
|
339
|
+
if inst:
|
|
340
|
+
lines.append(f" Institution: {inst}")
|
|
341
|
+
if source_place:
|
|
342
|
+
lines.append(f" Source place: {source_place}")
|
|
343
|
+
ref_parts = [
|
|
344
|
+
f"Archive {archive_num}" if archive_num else "",
|
|
345
|
+
f"Registry {reg_num}" if reg_num else "",
|
|
346
|
+
book,
|
|
347
|
+
collection,
|
|
348
|
+
f"Document {doc_num}" if doc_num else "",
|
|
349
|
+
]
|
|
350
|
+
ref_line = " | ".join(p for p in ref_parts if p)
|
|
351
|
+
if ref_line:
|
|
352
|
+
lines.append(f" Reference: {ref_line}")
|
|
353
|
+
|
|
354
|
+
events = _as_list(record.get("a2a_Event"))
|
|
355
|
+
for ev in events:
|
|
356
|
+
if not isinstance(ev, dict):
|
|
357
|
+
continue
|
|
358
|
+
ev_type = _a2a_text(ev.get("a2a_EventType"))
|
|
359
|
+
ev_date = _fmt_a2a_date(ev.get("a2a_EventDate"))
|
|
360
|
+
ev_place = _a2a_text((ev.get("a2a_EventPlace") or {}).get("a2a_Place"))
|
|
361
|
+
summary = " | ".join(p for p in (ev_type, ev_date, ev_place) if p)
|
|
362
|
+
if summary:
|
|
363
|
+
lines.append(f" Event: {summary}")
|
|
364
|
+
|
|
365
|
+
roles_by_pid: dict[str, list[str]] = {}
|
|
366
|
+
for rel in _as_list(record.get("a2a_RelationEP")):
|
|
367
|
+
if not isinstance(rel, dict):
|
|
368
|
+
continue
|
|
369
|
+
pid = _a2a_text(rel.get("a2a_PersonKeyRef"))
|
|
370
|
+
role = _a2a_text(rel.get("a2a_RelationType"))
|
|
371
|
+
if pid and role:
|
|
372
|
+
roles_by_pid.setdefault(pid, []).append(role)
|
|
373
|
+
|
|
374
|
+
persons = _as_list(record.get("a2a_Person"))
|
|
375
|
+
if persons:
|
|
376
|
+
lines.append(" Persons:")
|
|
377
|
+
for person in persons:
|
|
378
|
+
if not isinstance(person, dict):
|
|
379
|
+
continue
|
|
380
|
+
pid = str(person.get("pid") or "")
|
|
381
|
+
name = _fmt_a2a_person_name(person.get("a2a_PersonName")) or "(unnamed)"
|
|
382
|
+
role_str = ", ".join(roles_by_pid.get(pid, []))
|
|
383
|
+
bdate = _fmt_a2a_date(person.get("a2a_BirthDate"))
|
|
384
|
+
bplace = _a2a_text((person.get("a2a_BirthPlace") or {}).get("a2a_Place"))
|
|
385
|
+
res = _a2a_text((person.get("a2a_Residence") or {}).get("a2a_Place"))
|
|
386
|
+
occ = _a2a_text(person.get("a2a_Profession"))
|
|
387
|
+
details = []
|
|
388
|
+
if role_str:
|
|
389
|
+
details.append(role_str)
|
|
390
|
+
if bdate or bplace:
|
|
391
|
+
details.append("b. " + ", ".join(p for p in (bdate, bplace) if p))
|
|
392
|
+
if res:
|
|
393
|
+
details.append(f"res. {res}")
|
|
394
|
+
if occ:
|
|
395
|
+
details.append(f"occ. {occ}")
|
|
396
|
+
suffix = f" ({'; '.join(details)})" if details else ""
|
|
397
|
+
lines.append(f" - {name}{suffix}")
|
|
398
|
+
|
|
399
|
+
scans_block = source.get("a2a_SourceAvailableScans") or {}
|
|
400
|
+
scans = _as_list(scans_block.get("a2a_Scan")) if isinstance(scans_block, dict) else []
|
|
401
|
+
scan_uris = [_a2a_text(s.get("a2a_Uri")) for s in scans if isinstance(s, dict)]
|
|
402
|
+
scan_uris = [u for u in scan_uris if u]
|
|
403
|
+
if scan_uris:
|
|
404
|
+
lines.append(" Scans:")
|
|
405
|
+
for uri in scan_uris[:5]:
|
|
406
|
+
lines.append(f" - {uri}")
|
|
407
|
+
if len(scan_uris) > 5:
|
|
408
|
+
lines.append(f" - (+{len(scan_uris) - 5} more)")
|
|
409
|
+
|
|
410
|
+
orig = _a2a_text(source.get("a2a_SourceDigitalOriginal"))
|
|
411
|
+
if orig:
|
|
412
|
+
lines.append(f" Original: {orig}")
|
|
413
|
+
|
|
414
|
+
return "\n".join(lines)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
418
|
+
def cli() -> None:
|
|
419
|
+
"""Search and inspect Dutch and Belgian archive records on OpenArchieven."""
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
@cli.command()
|
|
423
|
+
@click.argument("name_arg", required=False, default=None)
|
|
424
|
+
@click.option("--name", "name_opt", default=None, help="Person name query (may include '&' for two names).")
|
|
425
|
+
@click.option("--place", default=None, help="Filter by event place (eventplace), e.g. Zundert or Rotterdam.")
|
|
426
|
+
@click.option("--birth-place", default=None, help="Filter by person birth place (birthplace).")
|
|
427
|
+
@click.option(
|
|
428
|
+
"--event-type",
|
|
429
|
+
default=None,
|
|
430
|
+
help="Event type (e.g. Geboorte, Huwelijk, Overlijden) or source type (e.g. 'BS Geboorte', Bevolkingsregister).",
|
|
431
|
+
)
|
|
432
|
+
@click.option(
|
|
433
|
+
"--source-type",
|
|
434
|
+
default=None,
|
|
435
|
+
help="Explicit OpenArchieven source type (e.g. 'BS Geboorte', 'BS Huwelijk', 'BS Overlijden', Bevolkingsregister, Passagiersregisters).",
|
|
436
|
+
)
|
|
437
|
+
@click.option(
|
|
438
|
+
"--year",
|
|
439
|
+
default=None,
|
|
440
|
+
help="Year or year range (e.g. 1853 or 1850-1860), appended to the name query as required by the API.",
|
|
441
|
+
)
|
|
442
|
+
@click.option("--archive", default=None, help="Archive code filter, e.g. bhi, wba, srt, saa, zal.")
|
|
443
|
+
@click.option("--relation", default=None, help="Relation/role filter, e.g. Kind, Vader, Bruid, Geregistreerde.")
|
|
444
|
+
@click.option("--country", default=None, help="Country code filter, e.g. nl, be, fr.")
|
|
445
|
+
@click.option(
|
|
446
|
+
"--lang",
|
|
447
|
+
default="nl",
|
|
448
|
+
show_default=True,
|
|
449
|
+
type=click.Choice(["nl", "en", "de", "fr"]),
|
|
450
|
+
help="Language for returned archive and type labels.",
|
|
451
|
+
)
|
|
452
|
+
@click.option("--limit", "-n", type=int, default=10, show_default=True, help="Results to return (max 100).")
|
|
453
|
+
@click.option("--start", type=int, default=0, show_default=True, help="Offset for paging (max 10000).")
|
|
454
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit raw API JSON output.")
|
|
455
|
+
@cache_options
|
|
456
|
+
def search(
|
|
457
|
+
name_arg: str | None,
|
|
458
|
+
name_opt: str | None,
|
|
459
|
+
place: str | None,
|
|
460
|
+
birth_place: str | None,
|
|
461
|
+
event_type: str | None,
|
|
462
|
+
source_type: str | None,
|
|
463
|
+
year: str | None,
|
|
464
|
+
archive: str | None,
|
|
465
|
+
relation: str | None,
|
|
466
|
+
country: str | None,
|
|
467
|
+
lang: str,
|
|
468
|
+
limit: int,
|
|
469
|
+
start: int,
|
|
470
|
+
as_json: bool,
|
|
471
|
+
refresh: bool,
|
|
472
|
+
cache_ttl_hours: float | None,
|
|
473
|
+
) -> None:
|
|
474
|
+
"""Search OpenArchieven records.
|
|
475
|
+
|
|
476
|
+
Example: openarchieven search --name "Vincent van Gogh" --place Zundert --year 1853
|
|
477
|
+
"""
|
|
478
|
+
raw_name = (name_opt or name_arg or "").strip()
|
|
479
|
+
if not raw_name:
|
|
480
|
+
raise click.UsageError("Provide a name via --name or a positional argument.")
|
|
481
|
+
if year:
|
|
482
|
+
raw_name = f"{raw_name} {year.strip()}"
|
|
483
|
+
|
|
484
|
+
params: dict[str, Any] = {
|
|
485
|
+
"name": raw_name,
|
|
486
|
+
"number_show": max(1, min(limit, 100)),
|
|
487
|
+
"start": max(0, min(start, 10000)),
|
|
488
|
+
"lang": lang,
|
|
489
|
+
}
|
|
490
|
+
if place:
|
|
491
|
+
params["eventplace"] = place
|
|
492
|
+
if birth_place:
|
|
493
|
+
params["birthplace"] = birth_place
|
|
494
|
+
if source_type:
|
|
495
|
+
params["sourcetype"] = source_type
|
|
496
|
+
if event_type:
|
|
497
|
+
if _is_source_type(event_type) and "sourcetype" not in params:
|
|
498
|
+
params["sourcetype"] = event_type
|
|
499
|
+
else:
|
|
500
|
+
params["eventtype"] = event_type
|
|
501
|
+
if archive:
|
|
502
|
+
params["archive"] = archive
|
|
503
|
+
if relation:
|
|
504
|
+
params["relationtype"] = relation
|
|
505
|
+
if country:
|
|
506
|
+
params["country_code"] = country
|
|
507
|
+
|
|
508
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
509
|
+
|
|
510
|
+
def _fetch() -> dict[str, Any]:
|
|
511
|
+
fetched = _get_json("search.json", params)
|
|
512
|
+
if not isinstance(fetched, dict):
|
|
513
|
+
_fail(f"Unexpected non-object search response from {API_BASE}/search.json")
|
|
514
|
+
return fetched
|
|
515
|
+
|
|
516
|
+
data, hit = cached_call(
|
|
517
|
+
"search",
|
|
518
|
+
params,
|
|
519
|
+
_fetch,
|
|
520
|
+
refresh=refresh,
|
|
521
|
+
ttl_hours=ttl,
|
|
522
|
+
cacheable=_search_cacheable,
|
|
523
|
+
)
|
|
524
|
+
if as_json:
|
|
525
|
+
click.echo(json.dumps({**data, "cache_hit": hit}, indent=2, ensure_ascii=False))
|
|
526
|
+
return
|
|
527
|
+
|
|
528
|
+
resp = data.get("response") or {}
|
|
529
|
+
total = resp.get("number_found", 0)
|
|
530
|
+
docs = resp.get("docs") or []
|
|
531
|
+
marker = " [cache]" if hit else ""
|
|
532
|
+
click.echo(f"Found {total} records (showing {len(docs)} from offset {start}){marker}")
|
|
533
|
+
for doc in docs:
|
|
534
|
+
code = doc.get("archive_code") or ""
|
|
535
|
+
ident = doc.get("identifier") or ""
|
|
536
|
+
person = doc.get("personname") or "(unnamed)"
|
|
537
|
+
role = doc.get("relationtype") or ""
|
|
538
|
+
stype = doc.get("sourcetype") or doc.get("eventtype") or ""
|
|
539
|
+
date_str = _fmt_eventdate(doc.get("eventdate"))
|
|
540
|
+
places = doc.get("eventplace") or []
|
|
541
|
+
place_str = ", ".join(places) if isinstance(places, list) else str(places)
|
|
542
|
+
url = doc.get("url") or f"{WEB_BASE}/{code}:{ident}"
|
|
543
|
+
click.echo(
|
|
544
|
+
f"- {code}:{ident} | {person} ({role}) | {stype} | {date_str} | {place_str}\n"
|
|
545
|
+
f" {url}"
|
|
546
|
+
)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
@cli.command()
|
|
550
|
+
@click.argument("archive")
|
|
551
|
+
@click.argument("identifier", required=False, default=None)
|
|
552
|
+
@click.option(
|
|
553
|
+
"--lang",
|
|
554
|
+
default="nl",
|
|
555
|
+
show_default=True,
|
|
556
|
+
type=click.Choice(["nl", "en", "de", "fr"]),
|
|
557
|
+
help="Language for returned labels.",
|
|
558
|
+
)
|
|
559
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit raw A2A JSON output.")
|
|
560
|
+
@cache_options
|
|
561
|
+
def show(
|
|
562
|
+
archive: str,
|
|
563
|
+
identifier: str | None,
|
|
564
|
+
lang: str,
|
|
565
|
+
as_json: bool,
|
|
566
|
+
refresh: bool,
|
|
567
|
+
cache_ttl_hours: float | None,
|
|
568
|
+
) -> None:
|
|
569
|
+
"""Fetch full A2A details for one record by ARCHIVE IDENTIFIER, archive:uuid, or URL."""
|
|
570
|
+
code, ident = _parse_record_ref(archive, identifier)
|
|
571
|
+
params = {"archive": code, "identifier": ident, "lang": lang}
|
|
572
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
573
|
+
wrapped, hit = cached_call(
|
|
574
|
+
"show",
|
|
575
|
+
params,
|
|
576
|
+
lambda: {"data": _get_json("show.json", params)},
|
|
577
|
+
refresh=refresh,
|
|
578
|
+
ttl_hours=ttl,
|
|
579
|
+
cacheable=_show_cacheable,
|
|
580
|
+
)
|
|
581
|
+
data = wrapped.get("data")
|
|
582
|
+
if as_json:
|
|
583
|
+
if isinstance(data, dict):
|
|
584
|
+
click.echo(json.dumps({**data, "cache_hit": hit}, indent=2, ensure_ascii=False))
|
|
585
|
+
else:
|
|
586
|
+
click.echo(json.dumps({"records": data, "cache_hit": hit}, indent=2, ensure_ascii=False))
|
|
587
|
+
return
|
|
588
|
+
records = data if isinstance(data, list) else [data]
|
|
589
|
+
if not records:
|
|
590
|
+
click.echo("No record data returned.")
|
|
591
|
+
return
|
|
592
|
+
for idx, rec in enumerate(records):
|
|
593
|
+
if idx > 0:
|
|
594
|
+
click.echo("")
|
|
595
|
+
if isinstance(rec, dict):
|
|
596
|
+
formatted = _format_a2a_record(code, ident, rec)
|
|
597
|
+
if idx == 0 and hit:
|
|
598
|
+
first_line, sep, rest = formatted.partition("\n")
|
|
599
|
+
formatted = f"{first_line} [cache]{sep}{rest}"
|
|
600
|
+
click.echo(formatted)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
@cli.command()
|
|
604
|
+
@click.option("--name", default=None, help="Person name query.")
|
|
605
|
+
@click.option("--place", default=None, help="Event place.")
|
|
606
|
+
@click.option("--year", default=None, help="Year or year range (e.g. 1853 or 1850-1860).")
|
|
607
|
+
@click.option("--record", default=None, help="Record token 'archive:uuid' to build a direct record URL.")
|
|
608
|
+
def url(name: str | None, place: str | None, year: str | None, record: str | None) -> None:
|
|
609
|
+
"""Print a shareable OpenArchieven website URL offline."""
|
|
610
|
+
if record:
|
|
611
|
+
code, ident = _parse_record_ref(record, None)
|
|
612
|
+
click.echo(f"{WEB_BASE}/{code}:{ident}")
|
|
613
|
+
return
|
|
614
|
+
if not name:
|
|
615
|
+
raise click.UsageError("Pass --name or --record.")
|
|
616
|
+
q = f"{name.strip()} {year.strip()}" if year else name.strip()
|
|
617
|
+
params = [("name", q)]
|
|
618
|
+
if place:
|
|
619
|
+
params.append(("eventplace", place.strip()))
|
|
620
|
+
click.echo(f"{WEB_BASE}/search.php?{urlencode(params)}")
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
if __name__ == "__main__":
|
|
624
|
+
cli()
|