@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.
Files changed (111) hide show
  1. package/dist/assets/cached-ocr.py +786 -0
  2. package/dist/assets/ocr.md +76 -0
  3. package/dist/assets/prep-scan.md +97 -0
  4. package/dist/assets/prep-scan.py +1313 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +162 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +130 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +129 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +154 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +488 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +30 -5
  50. package/dist/client.js.map +1 -1
  51. package/dist/commands/ops/audit.d.ts +138 -0
  52. package/dist/commands/ops/audit.d.ts.map +1 -0
  53. package/dist/commands/ops/audit.js +872 -0
  54. package/dist/commands/ops/audit.js.map +1 -0
  55. package/dist/commands/ops/context.d.ts +100 -0
  56. package/dist/commands/ops/context.d.ts.map +1 -0
  57. package/dist/commands/ops/context.js +917 -0
  58. package/dist/commands/ops/context.js.map +1 -0
  59. package/dist/commands/ops/dates.d.ts +87 -0
  60. package/dist/commands/ops/dates.d.ts.map +1 -0
  61. package/dist/commands/ops/dates.js +228 -0
  62. package/dist/commands/ops/dates.js.map +1 -0
  63. package/dist/commands/ops/help.d.ts +8 -0
  64. package/dist/commands/ops/help.d.ts.map +1 -0
  65. package/dist/commands/ops/help.js +107 -0
  66. package/dist/commands/ops/help.js.map +1 -0
  67. package/dist/commands/ops/index.d.ts +8 -0
  68. package/dist/commands/ops/index.d.ts.map +1 -0
  69. package/dist/commands/ops/index.js +8 -0
  70. package/dist/commands/ops/index.js.map +1 -0
  71. package/dist/commands/ops/integrate.d.ts +61 -0
  72. package/dist/commands/ops/integrate.d.ts.map +1 -0
  73. package/dist/commands/ops/integrate.js +1063 -0
  74. package/dist/commands/ops/integrate.js.map +1 -0
  75. package/dist/commands/ops/sync.d.ts +194 -0
  76. package/dist/commands/ops/sync.d.ts.map +1 -0
  77. package/dist/commands/ops/sync.js +1251 -0
  78. package/dist/commands/ops/sync.js.map +1 -0
  79. package/dist/commands/ops/telemetry.d.ts +79 -0
  80. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  81. package/dist/commands/ops/telemetry.js +249 -0
  82. package/dist/commands/ops/telemetry.js.map +1 -0
  83. package/dist/commands/ops/verify.d.ts +76 -0
  84. package/dist/commands/ops/verify.d.ts.map +1 -0
  85. package/dist/commands/ops/verify.js +325 -0
  86. package/dist/commands/ops/verify.js.map +1 -0
  87. package/dist/commands/records/help.d.ts +18 -0
  88. package/dist/commands/records/help.d.ts.map +1 -0
  89. package/dist/commands/records/help.js +174 -0
  90. package/dist/commands/records/help.js.map +1 -0
  91. package/dist/commands/records/index.d.ts +5 -0
  92. package/dist/commands/records/index.d.ts.map +1 -0
  93. package/dist/commands/records/index.js +5 -0
  94. package/dist/commands/records/index.js.map +1 -0
  95. package/dist/commands/records/registry.d.ts +32 -0
  96. package/dist/commands/records/registry.d.ts.map +1 -0
  97. package/dist/commands/records/registry.js +227 -0
  98. package/dist/commands/records/registry.js.map +1 -0
  99. package/dist/commands/records/resolve.d.ts +14 -0
  100. package/dist/commands/records/resolve.d.ts.map +1 -0
  101. package/dist/commands/records/resolve.js +61 -0
  102. package/dist/commands/records/resolve.js.map +1 -0
  103. package/dist/commands/records/runner.d.ts +27 -0
  104. package/dist/commands/records/runner.d.ts.map +1 -0
  105. package/dist/commands/records/runner.js +255 -0
  106. package/dist/commands/records/runner.js.map +1 -0
  107. package/dist/index.d.ts +2 -0
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +2 -0
  110. package/dist/index.js.map +1 -1
  111. package/package.json +3 -3
@@ -0,0 +1,965 @@
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
+ """Find a Grave CLI: search and read memorials, cemeteries, and places.
10
+
11
+ Uses the site's own GraphQL API (POST https://www.findagrave.com/orc/graphql),
12
+ verified live 2026-11-24. The API is undocumented and internal: no key or
13
+ login is needed, but it can change without notice. Requests are spaced
14
+ 0.3 s apart; bursts can trigger Cloudflare challenges.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from contextlib import contextmanager
20
+ import hashlib
21
+ import json
22
+ import math
23
+ import os
24
+ import re
25
+ import shutil
26
+ import sys
27
+ import time
28
+ from pathlib import Path
29
+ from typing import Any, Iterator
30
+ from urllib.parse import urlencode
31
+
32
+ import click
33
+ import httpx
34
+
35
+ GRAPHQL_URL = "https://www.findagrave.com/orc/graphql"
36
+ WEBSITE_BASE = "https://www.findagrave.com"
37
+ USER_AGENT = (
38
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
39
+ "Chrome/131.0 Safari/537.36"
40
+ )
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}$")
45
+ MONTHS = [
46
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
47
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
48
+ ]
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
+
316
+ SEARCH_QUERY = """
317
+ query($s: MemorialSearchInput) {
318
+ memorialSearch(search: $s) {
319
+ total
320
+ memorials {
321
+ id
322
+ name { first last maiden }
323
+ birth { date { year month day circa } place { names { name } } }
324
+ death { date { year month day circa } place { names { name } } }
325
+ cemetery { id names { name } memorialCount coordinates { lat lon } }
326
+ plot
327
+ hasGravePhoto
328
+ isVeteran
329
+ }
330
+ }
331
+ }
332
+ """
333
+
334
+ GET_QUERY = """
335
+ query($ids: [ID!]!) {
336
+ memorialsById(ids: $ids) {
337
+ id
338
+ name { first last maiden }
339
+ birth { date { year month day circa } place { names { name } } }
340
+ death { date { year month day circa } place { names { name } } }
341
+ coordinates { lat lon }
342
+ cemetery {
343
+ id
344
+ names { name }
345
+ memorialCount
346
+ coordinates { lat lon }
347
+ physicalAddress { full { value } }
348
+ }
349
+ plot
350
+ inscription { value }
351
+ bio { value }
352
+ isVeteran
353
+ hasGravePhoto
354
+ hasPersonPhoto
355
+ dateCreated
356
+ dateModified
357
+ relationships { type yearMarried memorial { id name { first last } } }
358
+ photos(size: 50) { total photos { id path caption type } }
359
+ }
360
+ }
361
+ """
362
+
363
+ CEMETERY_QUERY = """
364
+ query($s: CemeterySearchInput) {
365
+ cemeteries(search: $s) {
366
+ total
367
+ cemeteries {
368
+ id
369
+ names { name }
370
+ memorialCount
371
+ coordinates { lat lon }
372
+ physicalAddress { full { value } }
373
+ }
374
+ }
375
+ }
376
+ """
377
+
378
+ CEMETERY_BY_ID_QUERY = """
379
+ query($ids: [ID!]) {
380
+ cemeteries(ids: $ids) {
381
+ total
382
+ cemeteries {
383
+ id
384
+ names { name }
385
+ memorialCount
386
+ coordinates { lat lon }
387
+ physicalAddress { full { value } }
388
+ }
389
+ }
390
+ }
391
+ """
392
+
393
+ PLACE_QUERY = """
394
+ query($s: LocationSearchInput) {
395
+ locationsByTypeahead(search: $s) {
396
+ total
397
+ locations {
398
+ __typename
399
+ ... on Location { id names { name } type }
400
+ ... on Cemetery { id names { name } memorialCount }
401
+ }
402
+ }
403
+ }
404
+ """
405
+
406
+
407
+ def gql(query: str, variables: dict) -> dict:
408
+ """Run one GraphQL query and return its data dict."""
409
+ time.sleep(MIN_INTERVAL_S)
410
+ headers = {
411
+ "Content-Type": "application/json",
412
+ "User-Agent": USER_AGENT,
413
+ "Accept": "application/json",
414
+ }
415
+ try:
416
+ with httpx.Client(timeout=30.0, follow_redirects=True) as client:
417
+ resp = client.post(
418
+ GRAPHQL_URL,
419
+ json={"query": query, "variables": variables},
420
+ headers=headers,
421
+ )
422
+ except httpx.HTTPError as exc:
423
+ click.echo(f"Request failed: {exc}", err=True)
424
+ raise SystemExit(1)
425
+ if resp.status_code == 403:
426
+ click.echo(
427
+ "Find a Grave returned 403 (Cloudflare challenge). "
428
+ "Wait a few minutes and retry, or use the website in a browser.",
429
+ err=True,
430
+ )
431
+ raise SystemExit(1)
432
+ if resp.status_code != 200:
433
+ click.echo(f"HTTP {resp.status_code} from {GRAPHQL_URL}", err=True)
434
+ raise SystemExit(1)
435
+ body = resp.json()
436
+ if body.get("errors"):
437
+ for err in body["errors"]:
438
+ click.echo(f"GraphQL error: {err.get('message')}", err=True)
439
+ raise SystemExit(1)
440
+ return body.get("data") or {}
441
+
442
+
443
+ def primary_name(memorial: dict) -> str:
444
+ names = memorial.get("name") or []
445
+ if not names:
446
+ return ""
447
+ first = names[0] or {}
448
+ parts = [first.get("first"), first.get("last")]
449
+ text = " ".join(p for p in parts if p)
450
+ maiden = first.get("maiden")
451
+ if maiden:
452
+ text += f" (nee {maiden})"
453
+ return text
454
+
455
+
456
+ def first_place_name(place: dict | None) -> str:
457
+ if not place:
458
+ return ""
459
+ names = place.get("names") or []
460
+ if not names:
461
+ return ""
462
+ return names[0].get("name") or ""
463
+
464
+
465
+ def fmt_date(date: dict | None) -> str:
466
+ if not date:
467
+ return ""
468
+ year = date.get("year")
469
+ month = date.get("month")
470
+ day = date.get("day")
471
+ if year is None:
472
+ return ""
473
+ text = str(year)
474
+ if month:
475
+ text = f"{MONTHS[month - 1]} {text}" if 1 <= month <= 12 else text
476
+ if day:
477
+ text = f"{day} {text}"
478
+ if date.get("circa"):
479
+ text = f"c. {text}"
480
+ return text
481
+
482
+
483
+ def fmt_event(event: dict | None) -> str:
484
+ if not event:
485
+ return ""
486
+ date = fmt_date(event.get("date"))
487
+ place = first_place_name(event.get("place"))
488
+ return ", ".join(p for p in (date, place) if p)
489
+
490
+
491
+ def fmt_cemetery(cemetery: dict | None) -> str:
492
+ if not cemetery:
493
+ return ""
494
+ names = cemetery.get("names") or []
495
+ return names[0].get("name") if names else ""
496
+
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
+
535
+ def memorial_url(memorial_id: str) -> str:
536
+ return f"{WEBSITE_BASE}/memorial/{memorial_id}"
537
+
538
+
539
+ def cemetery_url(cemetery_id: str) -> str:
540
+ return f"{WEBSITE_BASE}/cemetery/{cemetery_id}"
541
+
542
+
543
+ def emit(data: dict, as_json: bool) -> None:
544
+ if as_json:
545
+ click.echo(json.dumps(data, indent=2))
546
+
547
+
548
+ @click.group()
549
+ def cli() -> None:
550
+ """Search and read Find a Grave memorials, cemeteries, and places."""
551
+
552
+
553
+ @cli.command()
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.")
556
+ @click.option("--birth-year", type=int, default=None)
557
+ @click.option("--death-year", type=int, default=None)
558
+ @click.option("--year-range", "--birth-range", "--date-spread", "year_range", type=int, default=None,
559
+ help="Plus/minus years around a birth/death year.")
560
+ @click.option("--birth-year-filter", default=None,
561
+ help="before, after, exact, or unknown.")
562
+ @click.option("--death-year-filter", default=None,
563
+ help="before, after, exact, or unknown.")
564
+ @click.option("--cemetery-id", multiple=True, help="Repeatable.")
565
+ @click.option("--location-id", default=None,
566
+ help="Place id, e.g. city_<id> (see the place command).")
567
+ @click.option("--bio", default=None, help="Words in the biography.")
568
+ @click.option("--text", "--full-text", "text", default=None, help="Words anywhere on the memorial.")
569
+ @click.option("--relative", default=None,
570
+ help="Name of a linked relative.")
571
+ @click.option("--exact/--no-exact", default=False,
572
+ help="Exact name match (default: site matching).")
573
+ @click.option("--include-maiden/--no-include-maiden", default=True,
574
+ help="Also match married women under maiden names.")
575
+ @click.option("--limit", type=int, default=10, show_default=True,
576
+ help="Rows per call (max 50).")
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).")
581
+ @click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
582
+ def search(first_name, last_name, birth_year, death_year, year_range,
583
+ birth_year_filter, death_year_filter, cemetery_id, location_id,
584
+ bio, text, relative, exact, include_maiden, limit, offset,
585
+ refresh, cache_ttl_hours, as_json):
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()
589
+ search_input: dict = {}
590
+ if first_name:
591
+ search_input["firstName"] = first_name
592
+ if last_name:
593
+ search_input["lastName"] = last_name
594
+ if birth_year is not None:
595
+ search_input["birthYear"] = birth_year
596
+ if death_year is not None:
597
+ search_input["deathYear"] = death_year
598
+ if year_range is not None:
599
+ if birth_year is not None:
600
+ search_input["birthYearRange"] = year_range
601
+ if death_year is not None:
602
+ search_input["deathYearRange"] = year_range
603
+ if birth_year_filter:
604
+ search_input["birthYearFilter"] = birth_year_filter
605
+ if death_year_filter:
606
+ search_input["deathYearFilter"] = death_year_filter
607
+ if cemetery_id:
608
+ search_input["cemeteryIds"] = list(cemetery_id)
609
+ if location_id:
610
+ search_input["locationId"] = location_id
611
+ if bio:
612
+ search_input["bio"] = bio
613
+ if text:
614
+ search_input["fullText"] = text
615
+ if relative:
616
+ search_input["linkedToName"] = relative
617
+ if exact:
618
+ search_input["exactName"] = True
619
+ search_input["includeMaidenName"] = include_maiden
620
+ search_input["from"] = offset
621
+ search_input["size"] = min(limit, 50)
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
+ )
631
+ result = data.get("memorialSearch") or {}
632
+ memorials = [enrich_memorial(m) for m in (result.get("memorials") or [])]
633
+ result["memorials"] = memorials
634
+ if as_json:
635
+ click.echo(json.dumps(result, indent=2))
636
+ return
637
+ total = result.get("total")
638
+ click.echo(f"{total} memorials")
639
+ for mem in memorials:
640
+ born = fmt_event(mem.get("birth"))
641
+ died = fmt_event(mem.get("death"))
642
+ cem = fmt_cemetery(mem.get("cemetery"))
643
+ photo = "yes" if mem.get("hasGravePhoto") else "no"
644
+ vet = " veteran" if mem.get("isVeteran") else ""
645
+ plot = mem.get("plot") or ""
646
+ row = (
647
+ f"{mem.get('id')} | {primary_name(mem)} | "
648
+ f"b. {born} | d. {died} | {cem} | plot: {plot} | "
649
+ f"grave photo: {photo}{vet} | {memorial_url(str(mem.get('id')))}"
650
+ )
651
+ click.echo(row)
652
+
653
+
654
+ @cli.command()
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).")
659
+ @click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
660
+ @click.option("--full", is_flag=True,
661
+ help="Print full bio and inscription instead of truncated.")
662
+ @click.option("--photos", is_flag=True,
663
+ help="List photo ids, types, and image URLs.")
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
+ )
674
+ if as_json:
675
+ click.echo(json.dumps(memorials, indent=2))
676
+ return
677
+ for mem in memorials:
678
+ mid = str(mem.get("id"))
679
+ click.echo(f"Memorial {mid}: {primary_name(mem)}")
680
+ click.echo(f" URL: {memorial_url(mid)}")
681
+ born = fmt_event(mem.get("birth"))
682
+ died = fmt_event(mem.get("death"))
683
+ if born:
684
+ click.echo(f" Born: {born}")
685
+ if died:
686
+ click.echo(f" Died: {died}")
687
+ cem = mem.get("cemetery") or {}
688
+ cem_name = fmt_cemetery(cem)
689
+ if cem_name:
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}")
697
+ if mem.get("plot"):
698
+ click.echo(f" Plot: {mem.get('plot')}")
699
+ click.echo(
700
+ f" Veteran: {'yes' if mem.get('isVeteran') else 'no'} | "
701
+ f"Grave photo: {'yes' if mem.get('hasGravePhoto') else 'no'} | "
702
+ f"Photos: {(mem.get('photos') or {}).get('total')}"
703
+ )
704
+ inscription = (mem.get("inscription") or {}).get("value")
705
+ bio = (mem.get("bio") or {}).get("value")
706
+ if inscription:
707
+ shown = inscription if full else inscription[:500]
708
+ click.echo(f" Inscription: {shown}")
709
+ if bio:
710
+ shown = bio if full else bio[:500]
711
+ click.echo(f" Bio: {shown}")
712
+ relations = mem.get("relationships") or []
713
+ if relations:
714
+ click.echo(" Relationships:")
715
+ for rel in relations:
716
+ target = rel.get("memorial") or {}
717
+ target_name = primary_name(target)
718
+ click.echo(
719
+ f" {rel.get('type')}: {target_name} "
720
+ f"({target.get('id')})"
721
+ )
722
+ if photos:
723
+ photo_list = (mem.get("photos") or {}).get("photos") or []
724
+ if photo_list:
725
+ click.echo(" Photos:")
726
+ for photo in photo_list:
727
+ click.echo(
728
+ f" {photo.get('id')} | {photo.get('type')} | "
729
+ f"{photo.get('path')}"
730
+ )
731
+ if mem.get("dateCreated"):
732
+ click.echo(
733
+ f" Created: {mem.get('dateCreated')} | "
734
+ f"Modified: {mem.get('dateModified')}"
735
+ )
736
+
737
+
738
+ cli.add_command(get, name="memorial")
739
+
740
+
741
+ @cli.command()
742
+ @click.argument("cemetery_id_arg", required=False, default=None)
743
+ @click.option("--name", default=None, help="Cemetery name to search.")
744
+ @click.option("--id", "cemetery_id", default=None,
745
+ help="Read one cemetery by id (or pass id as a positional argument).")
746
+ @click.option("--place", default=None,
747
+ help="Containing place name, e.g. 'Sangamon County, Illinois'.")
748
+ @click.option("--limit", type=int, default=10, show_default=True)
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).")
753
+ @click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
754
+ def cemetery(cemetery_id_arg, name, cemetery_id, place, limit, offset, refresh, cache_ttl_hours, as_json):
755
+ """Search cemeteries by name, or read one by id."""
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 []
767
+ else:
768
+ if not name:
769
+ raise click.UsageError("Pass a cemetery id, --id, or --name.")
770
+ search_input: dict = {"name": name}
771
+ if place:
772
+ search_input["containingLocationName"] = place
773
+ search_input["from"] = offset
774
+ search_input["size"] = min(limit, 100)
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
787
+ if as_json:
788
+ click.echo(json.dumps(result, indent=2))
789
+ return
790
+ click.echo(f"{result.get('total')} cemeteries")
791
+ for cem in cemeteries_list:
792
+ names = cem.get("names") or []
793
+ shown = names[0].get("name") if names else ""
794
+ extra = ""
795
+ if len(names) > 1:
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 ""
799
+ click.echo(
800
+ f"{cem.get('id')} | {shown}{extra} | "
801
+ f"{cem.get('memorialCount')} memorials{gps} | "
802
+ f"{cemetery_url(str(cem.get('id')))}"
803
+ )
804
+
805
+
806
+ @cli.command()
807
+ @click.option("--name", required=True, help="Place name, e.g. Springfield.")
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).")
812
+ @click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
813
+ def place(name, limit, refresh, cache_ttl_hours, as_json):
814
+ """Resolve a place name to Find a Grave place ids.
815
+
816
+ Use the returned id (e.g. city_<id>) with search --location-id.
817
+ """
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
+ )
830
+ result = data.get("locationsByTypeahead") or {}
831
+ if as_json:
832
+ click.echo(json.dumps(result, indent=2))
833
+ return
834
+ click.echo(f"{result.get('total')} places")
835
+ for loc in result.get("locations") or []:
836
+ names = loc.get("names") or []
837
+ shown = names[0].get("name") if names else ""
838
+ kind = loc.get("__typename")
839
+ count = loc.get("memorialCount")
840
+ suffix = f" | {count} memorials" if count is not None else ""
841
+ click.echo(f"{loc.get('id')} | {kind} | {shown}{suffix}")
842
+
843
+
844
+ def _new_photo_client() -> httpx.Client:
845
+ return httpx.Client(timeout=60.0, follow_redirects=True)
846
+
847
+
848
+ @cli.command()
849
+ @click.argument("memorial_id")
850
+ @click.option("--out", default=".", show_default=True,
851
+ help="Directory to save photos into.")
852
+ @click.option("--type", "photo_type", default=None,
853
+ help="Only download this photo type, e.g. Grave.")
854
+ @click.option("--prefix", default=None,
855
+ help="Optional filename prefix, e.g. 'lincoln-abraham' -> '<prefix>_<photo-id>.jpg'.")
856
+ @click.option("--metadata", "save_metadata", is_flag=True,
857
+ help="Also write a sidecar JSON file with memorial and photo provenance.")
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):
863
+ """Download a memorial's photos (grave, portrait, family, other)."""
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
+ )
875
+ if not memorials:
876
+ click.echo(f"No memorial found with id {clean_id}", err=True)
877
+ raise SystemExit(1)
878
+ memorial = memorials[0]
879
+ photo_list = (memorial.get("photos") or {}).get("photos") or []
880
+ if photo_type:
881
+ photo_list = [p for p in photo_list if p.get("type") == photo_type]
882
+ if not photo_list:
883
+ click.echo("No photos found.")
884
+ return
885
+ out_dir = Path(out)
886
+ out_dir.mkdir(parents=True, exist_ok=True)
887
+ photos_cache_dir = cache_root / "photos" / clean_id
888
+ saved_items = []
889
+ client: httpx.Client | None = None
890
+ try:
891
+ for item in photo_list:
892
+ url = item.get("path") or ""
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
+
920
+ saved_items.append({
921
+ "id": item.get("id"),
922
+ "type": item.get("type"),
923
+ "caption": item.get("caption"),
924
+ "url": url,
925
+ "file": dest.name,
926
+ })
927
+ finally:
928
+ if client is not None:
929
+ client.close()
930
+ if save_metadata:
931
+ meta_path = resolve_safe_child(out_dir, f"{stem_prefix}{clean_id}.metadata.json")
932
+ meta_payload = {
933
+ "memorial_id": str(memorial.get("id")),
934
+ "name": primary_name(memorial),
935
+ "url": memorial_url(str(memorial.get("id"))),
936
+ "cemetery": fmt_cemetery(memorial.get("cemetery")),
937
+ "plot": memorial.get("plot"),
938
+ "photos": saved_items,
939
+ }
940
+ atomic_write_text(meta_path, json.dumps(meta_payload, indent=2) + "\n")
941
+ click.echo(f"{meta_path} (metadata)")
942
+
943
+
944
+ @cli.command()
945
+ @click.option("--first", "first_name", default=None)
946
+ @click.option("--last", "last_name", default=None)
947
+ @click.option("--birth-year", type=int, default=None)
948
+ @click.option("--death-year", type=int, default=None)
949
+ def url(first_name, last_name, birth_year, death_year):
950
+ """Print the website search URL for a name (open it in a browser)."""
951
+ params = []
952
+ if first_name:
953
+ params.append(("firstname", first_name))
954
+ if last_name:
955
+ params.append(("lastname", last_name))
956
+ if birth_year is not None:
957
+ params.append(("birthyear", str(birth_year)))
958
+ if death_year is not None:
959
+ params.append(("deathyear", str(death_year)))
960
+ base = f"{WEBSITE_BASE}/memorial/search"
961
+ click.echo(f"{base}?{urlencode(params)}" if params else base)
962
+
963
+
964
+ if __name__ == "__main__":
965
+ cli()