@kinloom/cli 0.2.0 → 0.3.1
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 +272 -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
|
@@ -16,10 +16,17 @@ login is needed, but it can change without notice. Requests are spaced
|
|
|
16
16
|
|
|
17
17
|
from __future__ import annotations
|
|
18
18
|
|
|
19
|
+
from contextlib import contextmanager
|
|
20
|
+
import hashlib
|
|
19
21
|
import json
|
|
22
|
+
import math
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
20
26
|
import sys
|
|
21
27
|
import time
|
|
22
28
|
from pathlib import Path
|
|
29
|
+
from typing import Any, Iterator
|
|
23
30
|
from urllib.parse import urlencode
|
|
24
31
|
|
|
25
32
|
import click
|
|
@@ -32,11 +39,280 @@ USER_AGENT = (
|
|
|
32
39
|
"Chrome/131.0 Safari/537.36"
|
|
33
40
|
)
|
|
34
41
|
MIN_INTERVAL_S = 0.3
|
|
42
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
43
|
+
SAFE_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")
|
|
44
|
+
SAFE_EXT_RE = re.compile(r"^\.[A-Za-z0-9]{1,8}$")
|
|
35
45
|
MONTHS = [
|
|
36
46
|
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
37
47
|
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
|
|
38
48
|
]
|
|
39
49
|
|
|
50
|
+
|
|
51
|
+
def get_cache_root() -> Path:
|
|
52
|
+
override = os.environ.get("KINLOOM_FINDAGRAVE_CACHE_DIR")
|
|
53
|
+
if override:
|
|
54
|
+
return Path(override).expanduser()
|
|
55
|
+
return Path.home() / ".cache" / "kinloom-findagrave"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def resolve_cache_ttl_hours(cli_ttl: float | None) -> float:
|
|
59
|
+
if cli_ttl is not None:
|
|
60
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
61
|
+
raise click.BadParameter(
|
|
62
|
+
f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0)."
|
|
63
|
+
)
|
|
64
|
+
return float(cli_ttl)
|
|
65
|
+
raw = os.environ.get("KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS")
|
|
66
|
+
if raw is not None and raw.strip():
|
|
67
|
+
try:
|
|
68
|
+
parsed = float(raw.strip())
|
|
69
|
+
except ValueError as exc:
|
|
70
|
+
raise click.BadParameter(
|
|
71
|
+
f"Invalid KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS value: {raw!r}."
|
|
72
|
+
) from exc
|
|
73
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
74
|
+
raise click.BadParameter(
|
|
75
|
+
f"Invalid KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
|
|
76
|
+
)
|
|
77
|
+
return parsed
|
|
78
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def validate_entity_id(raw_id: str, label: str = "id") -> str:
|
|
82
|
+
cleaned = str(raw_id).strip()
|
|
83
|
+
if not cleaned or not SAFE_ID_RE.match(cleaned) or cleaned in (".", ".."):
|
|
84
|
+
raise click.BadParameter(f"Invalid {label}: {raw_id!r}")
|
|
85
|
+
return cleaned
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def sanitize_prefix(prefix: str | None) -> str:
|
|
89
|
+
if not prefix:
|
|
90
|
+
return ""
|
|
91
|
+
cleaned = prefix.strip().strip("_")
|
|
92
|
+
if (
|
|
93
|
+
not cleaned
|
|
94
|
+
or "\x00" in cleaned
|
|
95
|
+
or "/" in cleaned
|
|
96
|
+
or "\\" in cleaned
|
|
97
|
+
or ".." in cleaned
|
|
98
|
+
or ":" in cleaned
|
|
99
|
+
):
|
|
100
|
+
raise click.BadParameter(f"Invalid --prefix value: {prefix!r}")
|
|
101
|
+
safe = re.sub(r"[^A-Za-z0-9._-]+", "_", cleaned).lstrip(".")
|
|
102
|
+
if not safe:
|
|
103
|
+
raise click.BadParameter(f"Invalid --prefix value: {prefix!r}")
|
|
104
|
+
return f"{safe}_"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def safe_photo_filename(photo_id: Any, url: str) -> str:
|
|
108
|
+
raw_id = str(photo_id or "").strip()
|
|
109
|
+
if not raw_id or not SAFE_ID_RE.match(raw_id):
|
|
110
|
+
safe_id = hashlib.sha256((url or raw_id).encode("utf-8")).hexdigest()[:16]
|
|
111
|
+
else:
|
|
112
|
+
safe_id = raw_id
|
|
113
|
+
raw_suffix = Path(url.split("?")[0]).suffix.lower()
|
|
114
|
+
suffix = raw_suffix if SAFE_EXT_RE.match(raw_suffix) else ".jpg"
|
|
115
|
+
return f"{safe_id}{suffix}"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def resolve_safe_child(root: Path, filename: str) -> Path:
|
|
119
|
+
if (
|
|
120
|
+
not filename
|
|
121
|
+
or "\x00" in filename
|
|
122
|
+
or "/" in filename
|
|
123
|
+
or "\\" in filename
|
|
124
|
+
or ":" in filename
|
|
125
|
+
or filename in (".", "..")
|
|
126
|
+
):
|
|
127
|
+
raise ValueError(f"Unsafe filename: {filename!r}")
|
|
128
|
+
root_resolved = root.resolve()
|
|
129
|
+
dest = (root_resolved / filename).resolve()
|
|
130
|
+
if dest == root_resolved or not dest.is_relative_to(root_resolved):
|
|
131
|
+
raise ValueError(f"Unsafe path escaping root: {filename!r}")
|
|
132
|
+
return dest
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@contextmanager
|
|
136
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
137
|
+
"""Advisory exclusive file lock (POSIX flock) with safe fallback on non-POSIX."""
|
|
138
|
+
try:
|
|
139
|
+
import fcntl
|
|
140
|
+
except ImportError:
|
|
141
|
+
yield
|
|
142
|
+
return
|
|
143
|
+
|
|
144
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
145
|
+
with open(lock_path, "a+b") as lock_file:
|
|
146
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
147
|
+
try:
|
|
148
|
+
yield
|
|
149
|
+
finally:
|
|
150
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def read_json_if_valid(path: Path) -> dict[str, Any] | None:
|
|
154
|
+
if not path.is_file():
|
|
155
|
+
return None
|
|
156
|
+
try:
|
|
157
|
+
parsed = json.loads(path.read_text(encoding="utf-8"))
|
|
158
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
159
|
+
return None
|
|
160
|
+
return parsed if isinstance(parsed, dict) else None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def atomic_write_bytes(dest: Path, data: bytes) -> None:
|
|
164
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
165
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
166
|
+
try:
|
|
167
|
+
tmp.write_bytes(data)
|
|
168
|
+
os.replace(tmp, dest)
|
|
169
|
+
except Exception:
|
|
170
|
+
tmp.unlink(missing_ok=True)
|
|
171
|
+
raise
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def atomic_write_text(dest: Path, text: str) -> None:
|
|
175
|
+
atomic_write_bytes(dest, text.encode("utf-8"))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
179
|
+
atomic_write_text(dest, json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def atomic_copy_file(src: Path, dest: Path) -> None:
|
|
183
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
184
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
185
|
+
try:
|
|
186
|
+
shutil.copyfile(src, tmp)
|
|
187
|
+
os.replace(tmp, dest)
|
|
188
|
+
except Exception:
|
|
189
|
+
tmp.unlink(missing_ok=True)
|
|
190
|
+
raise
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _read_fresh_envelope(path: Path, ttl_hours: float) -> dict[str, Any] | None:
|
|
194
|
+
ttl_seconds = ttl_hours * 3600.0
|
|
195
|
+
if ttl_seconds <= 0:
|
|
196
|
+
return None
|
|
197
|
+
envelope = read_json_if_valid(path)
|
|
198
|
+
if envelope is None:
|
|
199
|
+
return None
|
|
200
|
+
cached_at = envelope.get("cached_at")
|
|
201
|
+
data = envelope.get("data")
|
|
202
|
+
if not isinstance(cached_at, (int, float)) or not isinstance(data, dict):
|
|
203
|
+
return None
|
|
204
|
+
if (time.time() - float(cached_at)) <= ttl_seconds:
|
|
205
|
+
return data
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _cached_gql_query(
|
|
210
|
+
kind: str,
|
|
211
|
+
canonical_params: dict[str, Any],
|
|
212
|
+
query: str,
|
|
213
|
+
variables: dict[str, Any],
|
|
214
|
+
*,
|
|
215
|
+
cache_root: Path,
|
|
216
|
+
ttl_hours: float,
|
|
217
|
+
refresh: bool,
|
|
218
|
+
) -> dict[str, Any]:
|
|
219
|
+
canonical = json.dumps(
|
|
220
|
+
canonical_params, sort_keys=True, separators=(",", ":"), ensure_ascii=False
|
|
221
|
+
)
|
|
222
|
+
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
223
|
+
cache_path = resolve_safe_child(cache_root / "_queries" / kind, f"{digest}.json")
|
|
224
|
+
if not refresh:
|
|
225
|
+
cached = _read_fresh_envelope(cache_path, ttl_hours)
|
|
226
|
+
if cached is not None:
|
|
227
|
+
return cached
|
|
228
|
+
lock_path = resolve_safe_child(cache_root / "_locks", f"query_{kind}_{digest}.lock")
|
|
229
|
+
with file_lock(lock_path):
|
|
230
|
+
if not refresh:
|
|
231
|
+
cached = _read_fresh_envelope(cache_path, ttl_hours)
|
|
232
|
+
if cached is not None:
|
|
233
|
+
return cached
|
|
234
|
+
data = gql(query, variables)
|
|
235
|
+
atomic_write_json(
|
|
236
|
+
cache_path,
|
|
237
|
+
{"cached_at": time.time(), "params": canonical_params, "data": data},
|
|
238
|
+
)
|
|
239
|
+
return data
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _load_or_fetch_memorials(
|
|
243
|
+
memorial_ids: list[str],
|
|
244
|
+
*,
|
|
245
|
+
cache_root: Path,
|
|
246
|
+
ttl_hours: float,
|
|
247
|
+
refresh: bool,
|
|
248
|
+
) -> list[dict[str, Any]]:
|
|
249
|
+
clean_ids = [validate_entity_id(mid, "memorial id") for mid in memorial_ids]
|
|
250
|
+
by_id: dict[str, dict[str, Any]] = {}
|
|
251
|
+
missing_ids: list[str] = []
|
|
252
|
+
|
|
253
|
+
for mid in clean_ids:
|
|
254
|
+
if mid in by_id or mid in missing_ids:
|
|
255
|
+
continue
|
|
256
|
+
cache_path = resolve_safe_child(cache_root / "memorials", f"{mid}.json")
|
|
257
|
+
if not refresh:
|
|
258
|
+
cached = _read_fresh_envelope(cache_path, ttl_hours)
|
|
259
|
+
if cached is not None:
|
|
260
|
+
by_id[mid] = enrich_memorial(cached)
|
|
261
|
+
continue
|
|
262
|
+
missing_ids.append(mid)
|
|
263
|
+
|
|
264
|
+
if missing_ids:
|
|
265
|
+
data = gql(GET_QUERY, {"ids": missing_ids})
|
|
266
|
+
for raw_mem in data.get("memorialsById") or []:
|
|
267
|
+
mem = enrich_memorial(raw_mem)
|
|
268
|
+
fetched_id = str(mem.get("id") or "").strip()
|
|
269
|
+
if not fetched_id or not SAFE_ID_RE.match(fetched_id):
|
|
270
|
+
continue
|
|
271
|
+
by_id[fetched_id] = mem
|
|
272
|
+
cache_path = resolve_safe_child(cache_root / "memorials", f"{fetched_id}.json")
|
|
273
|
+
lock_path = resolve_safe_child(
|
|
274
|
+
cache_root / "_locks", f"memorial_{fetched_id}.lock"
|
|
275
|
+
)
|
|
276
|
+
with file_lock(lock_path):
|
|
277
|
+
atomic_write_json(
|
|
278
|
+
cache_path, {"cached_at": time.time(), "data": mem}
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
return [by_id[mid] for mid in clean_ids if mid in by_id]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _load_or_fetch_cemetery_by_id(
|
|
285
|
+
cemetery_id: str,
|
|
286
|
+
*,
|
|
287
|
+
cache_root: Path,
|
|
288
|
+
ttl_hours: float,
|
|
289
|
+
refresh: bool,
|
|
290
|
+
) -> dict[str, Any]:
|
|
291
|
+
clean_id = validate_entity_id(cemetery_id, "cemetery id")
|
|
292
|
+
cache_path = resolve_safe_child(cache_root / "cemeteries", f"{clean_id}.json")
|
|
293
|
+
if not refresh:
|
|
294
|
+
cached = _read_fresh_envelope(cache_path, ttl_hours)
|
|
295
|
+
if cached is not None:
|
|
296
|
+
cem = enrich_cemetery(cached)
|
|
297
|
+
return {"total": 1, "cemeteries": [cem]}
|
|
298
|
+
|
|
299
|
+
lock_path = resolve_safe_child(cache_root / "_locks", f"cemetery_{clean_id}.lock")
|
|
300
|
+
with file_lock(lock_path):
|
|
301
|
+
if not refresh:
|
|
302
|
+
cached = _read_fresh_envelope(cache_path, ttl_hours)
|
|
303
|
+
if cached is not None:
|
|
304
|
+
cem = enrich_cemetery(cached)
|
|
305
|
+
return {"total": 1, "cemeteries": [cem]}
|
|
306
|
+
data = gql(CEMETERY_BY_ID_QUERY, {"ids": [clean_id]})
|
|
307
|
+
result = data.get("cemeteries") or {}
|
|
308
|
+
cemeteries_list = [enrich_cemetery(c) for c in (result.get("cemeteries") or [])]
|
|
309
|
+
result["cemeteries"] = cemeteries_list
|
|
310
|
+
if cemeteries_list:
|
|
311
|
+
atomic_write_json(
|
|
312
|
+
cache_path, {"cached_at": time.time(), "data": cemeteries_list[0]}
|
|
313
|
+
)
|
|
314
|
+
return result
|
|
315
|
+
|
|
40
316
|
SEARCH_QUERY = """
|
|
41
317
|
query($s: MemorialSearchInput) {
|
|
42
318
|
memorialSearch(search: $s) {
|
|
@@ -46,7 +322,7 @@ query($s: MemorialSearchInput) {
|
|
|
46
322
|
name { first last maiden }
|
|
47
323
|
birth { date { year month day circa } place { names { name } } }
|
|
48
324
|
death { date { year month day circa } place { names { name } } }
|
|
49
|
-
cemetery { id names { name } memorialCount }
|
|
325
|
+
cemetery { id names { name } memorialCount coordinates { lat lon } }
|
|
50
326
|
plot
|
|
51
327
|
hasGravePhoto
|
|
52
328
|
isVeteran
|
|
@@ -62,7 +338,14 @@ query($ids: [ID!]!) {
|
|
|
62
338
|
name { first last maiden }
|
|
63
339
|
birth { date { year month day circa } place { names { name } } }
|
|
64
340
|
death { date { year month day circa } place { names { name } } }
|
|
65
|
-
|
|
341
|
+
coordinates { lat lon }
|
|
342
|
+
cemetery {
|
|
343
|
+
id
|
|
344
|
+
names { name }
|
|
345
|
+
memorialCount
|
|
346
|
+
coordinates { lat lon }
|
|
347
|
+
physicalAddress { full { value } }
|
|
348
|
+
}
|
|
66
349
|
plot
|
|
67
350
|
inscription { value }
|
|
68
351
|
bio { value }
|
|
@@ -81,7 +364,13 @@ CEMETERY_QUERY = """
|
|
|
81
364
|
query($s: CemeterySearchInput) {
|
|
82
365
|
cemeteries(search: $s) {
|
|
83
366
|
total
|
|
84
|
-
cemeteries {
|
|
367
|
+
cemeteries {
|
|
368
|
+
id
|
|
369
|
+
names { name }
|
|
370
|
+
memorialCount
|
|
371
|
+
coordinates { lat lon }
|
|
372
|
+
physicalAddress { full { value } }
|
|
373
|
+
}
|
|
85
374
|
}
|
|
86
375
|
}
|
|
87
376
|
"""
|
|
@@ -90,7 +379,13 @@ CEMETERY_BY_ID_QUERY = """
|
|
|
90
379
|
query($ids: [ID!]) {
|
|
91
380
|
cemeteries(ids: $ids) {
|
|
92
381
|
total
|
|
93
|
-
cemeteries {
|
|
382
|
+
cemeteries {
|
|
383
|
+
id
|
|
384
|
+
names { name }
|
|
385
|
+
memorialCount
|
|
386
|
+
coordinates { lat lon }
|
|
387
|
+
physicalAddress { full { value } }
|
|
388
|
+
}
|
|
94
389
|
}
|
|
95
390
|
}
|
|
96
391
|
"""
|
|
@@ -200,6 +495,43 @@ def fmt_cemetery(cemetery: dict | None) -> str:
|
|
|
200
495
|
return names[0].get("name") if names else ""
|
|
201
496
|
|
|
202
497
|
|
|
498
|
+
def _coords_pair(obj: dict | None) -> tuple[float | None, float | None]:
|
|
499
|
+
if not isinstance(obj, dict):
|
|
500
|
+
return None, None
|
|
501
|
+
lat = obj.get("lat")
|
|
502
|
+
lon = obj.get("lon")
|
|
503
|
+
if lon is None:
|
|
504
|
+
lon = obj.get("lng")
|
|
505
|
+
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
|
|
506
|
+
return float(lat), float(lon)
|
|
507
|
+
return None, None
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def enrich_cemetery(cemetery: dict | None) -> dict | None:
|
|
511
|
+
"""Attach convenient lat/lng fields alongside GraphQL coordinates { lat lon }."""
|
|
512
|
+
if not isinstance(cemetery, dict):
|
|
513
|
+
return cemetery
|
|
514
|
+
lat, lon = _coords_pair(cemetery.get("coordinates"))
|
|
515
|
+
if lat is not None and lon is not None:
|
|
516
|
+
cemetery["lat"] = lat
|
|
517
|
+
cemetery["lng"] = lon
|
|
518
|
+
return cemetery
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def enrich_memorial(memorial: dict) -> dict:
|
|
522
|
+
"""Attach cemetery_lat/cemetery_lng (and cemetery.lat/lng) from GraphQL GPS coordinates."""
|
|
523
|
+
cem = memorial.get("cemetery")
|
|
524
|
+
if isinstance(cem, dict):
|
|
525
|
+
enrich_cemetery(cem)
|
|
526
|
+
cem_lat, cem_lon = _coords_pair(cem.get("coordinates"))
|
|
527
|
+
memorial["cemetery_lat"] = cem_lat
|
|
528
|
+
memorial["cemetery_lng"] = cem_lon
|
|
529
|
+
else:
|
|
530
|
+
memorial["cemetery_lat"] = None
|
|
531
|
+
memorial["cemetery_lng"] = None
|
|
532
|
+
return memorial
|
|
533
|
+
|
|
534
|
+
|
|
203
535
|
def memorial_url(memorial_id: str) -> str:
|
|
204
536
|
return f"{WEBSITE_BASE}/memorial/{memorial_id}"
|
|
205
537
|
|
|
@@ -219,11 +551,11 @@ def cli() -> None:
|
|
|
219
551
|
|
|
220
552
|
|
|
221
553
|
@cli.command()
|
|
222
|
-
@click.option("--first", "first_name", default=None, help="First name.")
|
|
223
|
-
@click.option("--last", "last_name", default=None, help="Last name.")
|
|
554
|
+
@click.option("--first", "--first-name", "first_name", default=None, help="First name.")
|
|
555
|
+
@click.option("--last", "--last-name", "last_name", default=None, help="Last name.")
|
|
224
556
|
@click.option("--birth-year", type=int, default=None)
|
|
225
557
|
@click.option("--death-year", type=int, default=None)
|
|
226
|
-
@click.option("--year-range", type=int, default=None,
|
|
558
|
+
@click.option("--year-range", "--birth-range", "--date-spread", "year_range", type=int, default=None,
|
|
227
559
|
help="Plus/minus years around a birth/death year.")
|
|
228
560
|
@click.option("--birth-year-filter", default=None,
|
|
229
561
|
help="before, after, exact, or unknown.")
|
|
@@ -233,7 +565,7 @@ def cli() -> None:
|
|
|
233
565
|
@click.option("--location-id", default=None,
|
|
234
566
|
help="Place id, e.g. city_<id> (see the place command).")
|
|
235
567
|
@click.option("--bio", default=None, help="Words in the biography.")
|
|
236
|
-
@click.option("--text", default=None, help="Words anywhere on the memorial.")
|
|
568
|
+
@click.option("--text", "--full-text", "text", default=None, help="Words anywhere on the memorial.")
|
|
237
569
|
@click.option("--relative", default=None,
|
|
238
570
|
help="Name of a linked relative.")
|
|
239
571
|
@click.option("--exact/--no-exact", default=False,
|
|
@@ -243,12 +575,17 @@ def cli() -> None:
|
|
|
243
575
|
@click.option("--limit", type=int, default=10, show_default=True,
|
|
244
576
|
help="Rows per call (max 50).")
|
|
245
577
|
@click.option("--offset", type=int, default=0, show_default=True)
|
|
578
|
+
@click.option("--refresh", is_flag=True, help="Bypass local disk cache and query Find a Grave fresh.")
|
|
579
|
+
@click.option("--cache-ttl-hours", type=float, default=None,
|
|
580
|
+
help="Override cache TTL in hours (default: 168 or $KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS).")
|
|
246
581
|
@click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
|
|
247
582
|
def search(first_name, last_name, birth_year, death_year, year_range,
|
|
248
583
|
birth_year_filter, death_year_filter, cemetery_id, location_id,
|
|
249
584
|
bio, text, relative, exact, include_maiden, limit, offset,
|
|
250
|
-
as_json):
|
|
585
|
+
refresh, cache_ttl_hours, as_json):
|
|
251
586
|
"""Search memorials. Example: search --first Abraham --last Lincoln."""
|
|
587
|
+
ttl_hours = resolve_cache_ttl_hours(cache_ttl_hours)
|
|
588
|
+
cache_root = get_cache_root()
|
|
252
589
|
search_input: dict = {}
|
|
253
590
|
if first_name:
|
|
254
591
|
search_input["firstName"] = first_name
|
|
@@ -282,13 +619,22 @@ def search(first_name, last_name, birth_year, death_year, year_range,
|
|
|
282
619
|
search_input["includeMaidenName"] = include_maiden
|
|
283
620
|
search_input["from"] = offset
|
|
284
621
|
search_input["size"] = min(limit, 50)
|
|
285
|
-
data =
|
|
622
|
+
data = _cached_gql_query(
|
|
623
|
+
"search",
|
|
624
|
+
search_input,
|
|
625
|
+
SEARCH_QUERY,
|
|
626
|
+
{"s": search_input},
|
|
627
|
+
cache_root=cache_root,
|
|
628
|
+
ttl_hours=ttl_hours,
|
|
629
|
+
refresh=refresh,
|
|
630
|
+
)
|
|
286
631
|
result = data.get("memorialSearch") or {}
|
|
632
|
+
memorials = [enrich_memorial(m) for m in (result.get("memorials") or [])]
|
|
633
|
+
result["memorials"] = memorials
|
|
287
634
|
if as_json:
|
|
288
635
|
click.echo(json.dumps(result, indent=2))
|
|
289
636
|
return
|
|
290
637
|
total = result.get("total")
|
|
291
|
-
memorials = result.get("memorials") or []
|
|
292
638
|
click.echo(f"{total} memorials")
|
|
293
639
|
for mem in memorials:
|
|
294
640
|
born = fmt_event(mem.get("birth"))
|
|
@@ -307,15 +653,24 @@ def search(first_name, last_name, birth_year, death_year, year_range,
|
|
|
307
653
|
|
|
308
654
|
@cli.command()
|
|
309
655
|
@click.argument("memorial_ids", nargs=-1, required=True)
|
|
656
|
+
@click.option("--refresh", is_flag=True, help="Bypass local disk cache and fetch fresh memorial data.")
|
|
657
|
+
@click.option("--cache-ttl-hours", type=float, default=None,
|
|
658
|
+
help="Override cache TTL in hours (default: 168 or $KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS).")
|
|
310
659
|
@click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
|
|
311
660
|
@click.option("--full", is_flag=True,
|
|
312
661
|
help="Print full bio and inscription instead of truncated.")
|
|
313
662
|
@click.option("--photos", is_flag=True,
|
|
314
663
|
help="List photo ids, types, and image URLs.")
|
|
315
|
-
def get(memorial_ids, as_json, full, photos):
|
|
316
|
-
"""Read one or more memorials in full by memorial id."""
|
|
317
|
-
|
|
318
|
-
|
|
664
|
+
def get(memorial_ids, refresh, cache_ttl_hours, as_json, full, photos):
|
|
665
|
+
"""Read one or more memorials in full by memorial id (alias: memorial)."""
|
|
666
|
+
ttl_hours = resolve_cache_ttl_hours(cache_ttl_hours)
|
|
667
|
+
cache_root = get_cache_root()
|
|
668
|
+
memorials = _load_or_fetch_memorials(
|
|
669
|
+
list(memorial_ids),
|
|
670
|
+
cache_root=cache_root,
|
|
671
|
+
ttl_hours=ttl_hours,
|
|
672
|
+
refresh=refresh,
|
|
673
|
+
)
|
|
319
674
|
if as_json:
|
|
320
675
|
click.echo(json.dumps(memorials, indent=2))
|
|
321
676
|
return
|
|
@@ -333,6 +688,12 @@ def get(memorial_ids, as_json, full, photos):
|
|
|
333
688
|
cem_name = fmt_cemetery(cem)
|
|
334
689
|
if cem_name:
|
|
335
690
|
click.echo(f" Cemetery: {cem_name} ({cem.get('id')})")
|
|
691
|
+
cem_lat, cem_lon = _coords_pair(cem.get("coordinates"))
|
|
692
|
+
if cem_lat is not None and cem_lon is not None:
|
|
693
|
+
click.echo(f" Cemetery GPS: {cem_lat}, {cem_lon}")
|
|
694
|
+
grave_lat, grave_lon = _coords_pair(mem.get("coordinates"))
|
|
695
|
+
if grave_lat is not None and grave_lon is not None:
|
|
696
|
+
click.echo(f" Grave GPS: {grave_lat}, {grave_lon}")
|
|
336
697
|
if mem.get("plot"):
|
|
337
698
|
click.echo(f" Plot: {mem.get('plot')}")
|
|
338
699
|
click.echo(
|
|
@@ -374,42 +735,70 @@ def get(memorial_ids, as_json, full, photos):
|
|
|
374
735
|
)
|
|
375
736
|
|
|
376
737
|
|
|
738
|
+
cli.add_command(get, name="memorial")
|
|
739
|
+
|
|
740
|
+
|
|
377
741
|
@cli.command()
|
|
742
|
+
@click.argument("cemetery_id_arg", required=False, default=None)
|
|
378
743
|
@click.option("--name", default=None, help="Cemetery name to search.")
|
|
379
744
|
@click.option("--id", "cemetery_id", default=None,
|
|
380
|
-
help="Read one cemetery by id.")
|
|
745
|
+
help="Read one cemetery by id (or pass id as a positional argument).")
|
|
381
746
|
@click.option("--place", default=None,
|
|
382
747
|
help="Containing place name, e.g. 'Sangamon County, Illinois'.")
|
|
383
748
|
@click.option("--limit", type=int, default=10, show_default=True)
|
|
384
749
|
@click.option("--offset", type=int, default=0, show_default=True)
|
|
750
|
+
@click.option("--refresh", is_flag=True, help="Bypass local disk cache and fetch fresh cemetery data.")
|
|
751
|
+
@click.option("--cache-ttl-hours", type=float, default=None,
|
|
752
|
+
help="Override cache TTL in hours (default: 168 or $KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS).")
|
|
385
753
|
@click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
|
|
386
|
-
def cemetery(name, cemetery_id, place, limit, offset, as_json):
|
|
754
|
+
def cemetery(cemetery_id_arg, name, cemetery_id, place, limit, offset, refresh, cache_ttl_hours, as_json):
|
|
387
755
|
"""Search cemeteries by name, or read one by id."""
|
|
388
|
-
|
|
389
|
-
|
|
756
|
+
ttl_hours = resolve_cache_ttl_hours(cache_ttl_hours)
|
|
757
|
+
cache_root = get_cache_root()
|
|
758
|
+
resolved_id = cemetery_id or cemetery_id_arg
|
|
759
|
+
if resolved_id:
|
|
760
|
+
result = _load_or_fetch_cemetery_by_id(
|
|
761
|
+
resolved_id,
|
|
762
|
+
cache_root=cache_root,
|
|
763
|
+
ttl_hours=ttl_hours,
|
|
764
|
+
refresh=refresh,
|
|
765
|
+
)
|
|
766
|
+
cemeteries_list = result.get("cemeteries") or []
|
|
390
767
|
else:
|
|
391
768
|
if not name:
|
|
392
|
-
raise click.UsageError("Pass --
|
|
769
|
+
raise click.UsageError("Pass a cemetery id, --id, or --name.")
|
|
393
770
|
search_input: dict = {"name": name}
|
|
394
771
|
if place:
|
|
395
772
|
search_input["containingLocationName"] = place
|
|
396
773
|
search_input["from"] = offset
|
|
397
774
|
search_input["size"] = min(limit, 100)
|
|
398
|
-
data =
|
|
399
|
-
|
|
775
|
+
data = _cached_gql_query(
|
|
776
|
+
"cemetery_search",
|
|
777
|
+
search_input,
|
|
778
|
+
CEMETERY_QUERY,
|
|
779
|
+
{"s": search_input},
|
|
780
|
+
cache_root=cache_root,
|
|
781
|
+
ttl_hours=ttl_hours,
|
|
782
|
+
refresh=refresh,
|
|
783
|
+
)
|
|
784
|
+
result = data.get("cemeteries") or {}
|
|
785
|
+
cemeteries_list = [enrich_cemetery(c) for c in (result.get("cemeteries") or [])]
|
|
786
|
+
result["cemeteries"] = cemeteries_list
|
|
400
787
|
if as_json:
|
|
401
788
|
click.echo(json.dumps(result, indent=2))
|
|
402
789
|
return
|
|
403
790
|
click.echo(f"{result.get('total')} cemeteries")
|
|
404
|
-
for cem in
|
|
791
|
+
for cem in cemeteries_list:
|
|
405
792
|
names = cem.get("names") or []
|
|
406
793
|
shown = names[0].get("name") if names else ""
|
|
407
794
|
extra = ""
|
|
408
795
|
if len(names) > 1:
|
|
409
796
|
extra = " (also: " + ", ".join(n.get("name") for n in names[1:]) + ")"
|
|
797
|
+
lat, lon = _coords_pair(cem.get("coordinates"))
|
|
798
|
+
gps = f" | GPS: {lat}, {lon}" if lat is not None and lon is not None else ""
|
|
410
799
|
click.echo(
|
|
411
800
|
f"{cem.get('id')} | {shown}{extra} | "
|
|
412
|
-
f"{cem.get('memorialCount')} memorials | "
|
|
801
|
+
f"{cem.get('memorialCount')} memorials{gps} | "
|
|
413
802
|
f"{cemetery_url(str(cem.get('id')))}"
|
|
414
803
|
)
|
|
415
804
|
|
|
@@ -417,13 +806,27 @@ def cemetery(name, cemetery_id, place, limit, offset, as_json):
|
|
|
417
806
|
@cli.command()
|
|
418
807
|
@click.option("--name", required=True, help="Place name, e.g. Springfield.")
|
|
419
808
|
@click.option("--limit", type=int, default=10, show_default=True)
|
|
809
|
+
@click.option("--refresh", is_flag=True, help="Bypass local disk cache and fetch fresh places.")
|
|
810
|
+
@click.option("--cache-ttl-hours", type=float, default=None,
|
|
811
|
+
help="Override cache TTL in hours (default: 168 or $KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS).")
|
|
420
812
|
@click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
|
|
421
|
-
def place(name, limit, as_json):
|
|
813
|
+
def place(name, limit, refresh, cache_ttl_hours, as_json):
|
|
422
814
|
"""Resolve a place name to Find a Grave place ids.
|
|
423
815
|
|
|
424
816
|
Use the returned id (e.g. city_<id>) with search --location-id.
|
|
425
817
|
"""
|
|
426
|
-
|
|
818
|
+
ttl_hours = resolve_cache_ttl_hours(cache_ttl_hours)
|
|
819
|
+
cache_root = get_cache_root()
|
|
820
|
+
search_input = {"name": name, "size": min(limit, 50)}
|
|
821
|
+
data = _cached_gql_query(
|
|
822
|
+
"place",
|
|
823
|
+
search_input,
|
|
824
|
+
PLACE_QUERY,
|
|
825
|
+
{"s": search_input},
|
|
826
|
+
cache_root=cache_root,
|
|
827
|
+
ttl_hours=ttl_hours,
|
|
828
|
+
refresh=refresh,
|
|
829
|
+
)
|
|
427
830
|
result = data.get("locationsByTypeahead") or {}
|
|
428
831
|
if as_json:
|
|
429
832
|
click.echo(json.dumps(result, indent=2))
|
|
@@ -438,6 +841,10 @@ def place(name, limit, as_json):
|
|
|
438
841
|
click.echo(f"{loc.get('id')} | {kind} | {shown}{suffix}")
|
|
439
842
|
|
|
440
843
|
|
|
844
|
+
def _new_photo_client() -> httpx.Client:
|
|
845
|
+
return httpx.Client(timeout=60.0, follow_redirects=True)
|
|
846
|
+
|
|
847
|
+
|
|
441
848
|
@cli.command()
|
|
442
849
|
@click.argument("memorial_id")
|
|
443
850
|
@click.option("--out", default=".", show_default=True,
|
|
@@ -448,12 +855,25 @@ def place(name, limit, as_json):
|
|
|
448
855
|
help="Optional filename prefix, e.g. 'lincoln-abraham' -> '<prefix>_<photo-id>.jpg'.")
|
|
449
856
|
@click.option("--metadata", "save_metadata", is_flag=True,
|
|
450
857
|
help="Also write a sidecar JSON file with memorial and photo provenance.")
|
|
451
|
-
|
|
858
|
+
@click.option("--refresh", is_flag=True,
|
|
859
|
+
help="Bypass local memorial and photo caches and re-download fresh files.")
|
|
860
|
+
@click.option("--cache-ttl-hours", type=float, default=None,
|
|
861
|
+
help="Override memorial metadata cache TTL in hours (default: 168 or $KINLOOM_FINDAGRAVE_CACHE_TTL_HOURS).")
|
|
862
|
+
def photo(memorial_id, out, photo_type, prefix, save_metadata, refresh, cache_ttl_hours):
|
|
452
863
|
"""Download a memorial's photos (grave, portrait, family, other)."""
|
|
453
|
-
|
|
454
|
-
|
|
864
|
+
clean_id = validate_entity_id(memorial_id, "memorial id")
|
|
865
|
+
stem_prefix = sanitize_prefix(prefix)
|
|
866
|
+
ttl_hours = resolve_cache_ttl_hours(cache_ttl_hours)
|
|
867
|
+
cache_root = get_cache_root()
|
|
868
|
+
|
|
869
|
+
memorials = _load_or_fetch_memorials(
|
|
870
|
+
[clean_id],
|
|
871
|
+
cache_root=cache_root,
|
|
872
|
+
ttl_hours=ttl_hours,
|
|
873
|
+
refresh=refresh,
|
|
874
|
+
)
|
|
455
875
|
if not memorials:
|
|
456
|
-
click.echo(f"No memorial found with id {
|
|
876
|
+
click.echo(f"No memorial found with id {clean_id}", err=True)
|
|
457
877
|
raise SystemExit(1)
|
|
458
878
|
memorial = memorials[0]
|
|
459
879
|
photo_list = (memorial.get("photos") or {}).get("photos") or []
|
|
@@ -464,17 +884,39 @@ def photo(memorial_id, out, photo_type, prefix, save_metadata):
|
|
|
464
884
|
return
|
|
465
885
|
out_dir = Path(out)
|
|
466
886
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
467
|
-
|
|
887
|
+
photos_cache_dir = cache_root / "photos" / clean_id
|
|
468
888
|
saved_items = []
|
|
469
|
-
|
|
889
|
+
client: httpx.Client | None = None
|
|
890
|
+
try:
|
|
470
891
|
for item in photo_list:
|
|
471
892
|
url = item.get("path") or ""
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
893
|
+
cache_filename = safe_photo_filename(item.get("id"), url)
|
|
894
|
+
cached_path = resolve_safe_child(photos_cache_dir, cache_filename)
|
|
895
|
+
dest = resolve_safe_child(out_dir, f"{stem_prefix}{cache_filename}")
|
|
896
|
+
|
|
897
|
+
if not refresh and cached_path.is_file():
|
|
898
|
+
atomic_copy_file(cached_path, dest)
|
|
899
|
+
size = dest.stat().st_size
|
|
900
|
+
click.echo(f"{dest} ({size} bytes, cached)")
|
|
901
|
+
else:
|
|
902
|
+
lock_path = resolve_safe_child(
|
|
903
|
+
cache_root / "_locks", f"photo_{clean_id}_{cache_filename}.lock"
|
|
904
|
+
)
|
|
905
|
+
served_from_cache = False
|
|
906
|
+
with file_lock(lock_path):
|
|
907
|
+
if not refresh and cached_path.is_file():
|
|
908
|
+
served_from_cache = True
|
|
909
|
+
else:
|
|
910
|
+
if client is None:
|
|
911
|
+
client = _new_photo_client()
|
|
912
|
+
resp = client.get(url, headers={"User-Agent": USER_AGENT})
|
|
913
|
+
resp.raise_for_status()
|
|
914
|
+
atomic_write_bytes(cached_path, resp.content)
|
|
915
|
+
atomic_copy_file(cached_path, dest)
|
|
916
|
+
size = dest.stat().st_size
|
|
917
|
+
suffix_note = ", cached" if served_from_cache else ""
|
|
918
|
+
click.echo(f"{dest} ({size} bytes{suffix_note})")
|
|
919
|
+
|
|
478
920
|
saved_items.append({
|
|
479
921
|
"id": item.get("id"),
|
|
480
922
|
"type": item.get("type"),
|
|
@@ -482,8 +924,11 @@ def photo(memorial_id, out, photo_type, prefix, save_metadata):
|
|
|
482
924
|
"url": url,
|
|
483
925
|
"file": dest.name,
|
|
484
926
|
})
|
|
927
|
+
finally:
|
|
928
|
+
if client is not None:
|
|
929
|
+
client.close()
|
|
485
930
|
if save_metadata:
|
|
486
|
-
meta_path = out_dir
|
|
931
|
+
meta_path = resolve_safe_child(out_dir, f"{stem_prefix}{clean_id}.metadata.json")
|
|
487
932
|
meta_payload = {
|
|
488
933
|
"memorial_id": str(memorial.get("id")),
|
|
489
934
|
"name": primary_name(memorial),
|
|
@@ -492,7 +937,7 @@ def photo(memorial_id, out, photo_type, prefix, save_metadata):
|
|
|
492
937
|
"plot": memorial.get("plot"),
|
|
493
938
|
"photos": saved_items,
|
|
494
939
|
}
|
|
495
|
-
meta_path
|
|
940
|
+
atomic_write_text(meta_path, json.dumps(meta_payload, indent=2) + "\n")
|
|
496
941
|
click.echo(f"{meta_path} (metadata)")
|
|
497
942
|
|
|
498
943
|
|