@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,751 @@
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 the Missouri State Archives vital-records databases.
10
+
11
+ Machine interface verified live 2026-11-24: the two
12
+ s1.sos.mo.gov databases are plain HTML POST forms (no API, no login,
13
+ no key). A browser User-Agent is required: the default curl/httpx
14
+ User-Agent gets 403 from sos.mo.gov. Search results are paged
15
+ 50 per page in a cookie session; this CLI keeps one session per run
16
+ and follows the session pager links.
17
+
18
+ Databases:
19
+ Death Certificates 1910-1975 (with certificate images as PDF)
20
+ Birth and Death Records Database, Pre-1910 (abstracts + detail pages)
21
+
22
+ Missouri Digital Heritage itself has no verified machine interface:
23
+ its CONTENTdm dmwebservices endpoint returns 403 (Cloudflare) to
24
+ automated requests, and its Advanced Search (mdh.deepwebaccess.com) has no
25
+ verified GET search URL. Use the `mdh` command for the browser path.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import json
32
+ import math
33
+ import os
34
+ import re
35
+ import sys
36
+ import time
37
+ from contextlib import contextmanager
38
+ from html.parser import HTMLParser
39
+ from pathlib import Path
40
+ from typing import Any, Callable, Iterator
41
+ from urllib.parse import urljoin
42
+
43
+ import click
44
+ import httpx
45
+
46
+ DEFAULT_CACHE_TTL_HOURS = 168.0
47
+ CACHE_SCHEMA = 1
48
+
49
+
50
+ def cache_dir() -> Path:
51
+ override = os.environ.get("KINLOOM_MO_ARCHIVES_CACHE_DIR")
52
+ if override:
53
+ return Path(override).expanduser()
54
+ return Path.home() / ".cache" / "kinloom-mo-archives"
55
+
56
+
57
+ def resolve_ttl_hours(cli_ttl: float | None) -> float:
58
+ if cli_ttl is not None:
59
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
60
+ raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
61
+ return float(cli_ttl)
62
+ raw = os.environ.get("KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS")
63
+ if raw is not None and raw.strip():
64
+ try:
65
+ parsed = float(raw.strip())
66
+ except ValueError as exc:
67
+ raise click.BadParameter(f"Invalid KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS value: {raw!r}.") from exc
68
+ if not math.isfinite(parsed) or parsed < 0:
69
+ raise click.BadParameter(
70
+ f"Invalid KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
71
+ )
72
+ return parsed
73
+ return DEFAULT_CACHE_TTL_HOURS
74
+
75
+
76
+ @contextmanager
77
+ def file_lock(lock_path: Path) -> Iterator[None]:
78
+ """Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
79
+ try:
80
+ import fcntl
81
+ except ImportError:
82
+ yield
83
+ return
84
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
85
+ with open(lock_path, "a+b") as lock_file:
86
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
87
+ try:
88
+ yield
89
+ finally:
90
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
91
+
92
+
93
+ def atomic_write_json(dest: Path, payload: Any) -> None:
94
+ dest.parent.mkdir(parents=True, exist_ok=True)
95
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
96
+ try:
97
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
98
+ os.replace(tmp, dest)
99
+ except Exception:
100
+ tmp.unlink(missing_ok=True)
101
+ raise
102
+
103
+
104
+ def cache_key(kind: str, payload: dict) -> str:
105
+ canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
106
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
107
+
108
+
109
+ def read_cache(path: Path, ttl_hours: float) -> dict | None:
110
+ if not path.is_file():
111
+ return None
112
+ try:
113
+ entry = json.loads(path.read_text(encoding="utf-8"))
114
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
115
+ return None
116
+ if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
117
+ return None
118
+ fetched = entry.get("fetched_at")
119
+ if not isinstance(fetched, (int, float)):
120
+ return None
121
+ if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
122
+ return None
123
+ result = entry.get("result")
124
+ return result if isinstance(result, dict) else None
125
+
126
+
127
+ def cached_call(
128
+ kind: str,
129
+ payload: dict,
130
+ fetch: Callable[[], dict],
131
+ *,
132
+ refresh: bool,
133
+ ttl_hours: float,
134
+ cacheable: Callable[[dict], bool] = lambda _r: True,
135
+ ) -> tuple[dict, bool]:
136
+ """Return (result, cache_hit) with per-key flock and atomic JSON writes."""
137
+ key = cache_key(kind, payload)
138
+ root = cache_dir()
139
+ path = root / f"{key}.json"
140
+ if not refresh:
141
+ hit = read_cache(path, ttl_hours)
142
+ if hit is not None:
143
+ return hit, True
144
+ with file_lock(root / f"{key}.lock"):
145
+ if not refresh:
146
+ hit = read_cache(path, ttl_hours)
147
+ if hit is not None:
148
+ return hit, True
149
+ result = fetch()
150
+ if cacheable(result):
151
+ atomic_write_json(
152
+ path,
153
+ {
154
+ "schema": CACHE_SCHEMA,
155
+ "fetched_at": time.time(),
156
+ "kind": kind,
157
+ "query": payload,
158
+ "result": result,
159
+ },
160
+ )
161
+ return result, False
162
+
163
+
164
+ def cache_options(func: Callable) -> Callable:
165
+ func = click.option(
166
+ "--cache-ttl-hours",
167
+ type=float,
168
+ default=None,
169
+ help="Cache TTL in hours (default 168, env KINLOOM_MO_ARCHIVES_CACHE_TTL_HOURS; 0 disables reads).",
170
+ )(func)
171
+ func = click.option(
172
+ "--refresh",
173
+ is_flag=True,
174
+ help="Bypass the disk cache for this request (the fresh result is still cached).",
175
+ )(func)
176
+ return func
177
+
178
+ BASE = "https://s1.sos.mo.gov"
179
+ DEATH_PAGE = BASE + "/records/Archives/ArchivesMvc/DeathCertificates/"
180
+ DEATH_POST = BASE + "/Records/Archives/ArchivesMvc/"
181
+ DEATH_RESULTS = BASE + "/Records/Archives/ArchivesMvc/DeathCertificates/Results"
182
+ PRE1910_PAGE = BASE + "/records/archives/ArchivesMVC/birthdeath/"
183
+ PRE1910_POST = BASE + "/Records/Archives/ArchivesMvc/BirthDeath"
184
+ PRE1910_RESULTS = BASE + "/Records/Archives/ArchivesMvc/birthdeath/Results"
185
+ PRE1910_DETAIL = BASE + "/records/archives/ArchivesMVC/birthdeath/Detail"
186
+ MDH_HOME = "https://www.sos.mo.gov/mdh"
187
+ MDH_SEARCH = "https://mdh.deepwebaccess.com/mdh/"
188
+ ARCHIVES_HOME = "https://www.sos.mo.gov/archives"
189
+ USER_AGENT = (
190
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
191
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
192
+ )
193
+ ALL_COUNTIES = "-- Search All --"
194
+ ALL_COUNTIES_PRE1910 = "-- All Counties --"
195
+ MATCH_METHODS = {
196
+ "contains": "Contains",
197
+ "starts-with": "StartsWith",
198
+ "ends-with": "EndsWith",
199
+ }
200
+
201
+
202
+ class _Cell:
203
+ __slots__ = ("text", "hrefs")
204
+
205
+ def __init__(self):
206
+ self.text = ""
207
+ self.hrefs = []
208
+
209
+
210
+ class _TableParser(HTMLParser):
211
+ """Collect every <table> as a list of rows of _Cell."""
212
+
213
+ def __init__(self):
214
+ super().__init__(convert_charrefs=True)
215
+ self.tables = []
216
+ self._table = None
217
+ self._row = None
218
+ self._cell = None
219
+
220
+ def handle_starttag(self, tag, attrs):
221
+ if tag == "table":
222
+ self._table = []
223
+ self.tables.append(self._table)
224
+ elif tag == "tr" and self._table is not None:
225
+ self._row = []
226
+ self._table.append(self._row)
227
+ elif tag in ("td", "th") and self._row is not None:
228
+ self._cell = _Cell()
229
+ self._row.append(self._cell)
230
+ elif tag == "a" and self._cell is not None:
231
+ href = dict(attrs).get("href")
232
+ if href:
233
+ self._cell.hrefs.append(href)
234
+ elif tag in ("br", "li", "p", "div") and self._cell is not None:
235
+ # Detail pages stack labels/values with <br/> and <li> and no
236
+ # whitespace; keep the pieces from running together.
237
+ self._cell.text += " "
238
+
239
+ def handle_endtag(self, tag):
240
+ if tag in ("td", "th"):
241
+ self._cell = None
242
+ elif tag == "tr":
243
+ self._row = None
244
+ elif tag == "table":
245
+ self._table = None
246
+
247
+ def handle_data(self, data):
248
+ if self._cell is not None:
249
+ self._cell.text += data
250
+
251
+
252
+ def _clean(text):
253
+ return " ".join(text.split())
254
+
255
+
256
+ def _parse_tables(html):
257
+ parser = _TableParser()
258
+ parser.feed(html)
259
+ return parser.tables
260
+
261
+
262
+ def _find_results_table(html, *header_markers):
263
+ for table in _parse_tables(html):
264
+ if not table:
265
+ continue
266
+ header = [_clean(c.text) for c in table[0]]
267
+ joined = " ".join(header)
268
+ if any(m in joined for m in header_markers):
269
+ return header, table[1:]
270
+ return None, []
271
+
272
+
273
+ def _total_results(html):
274
+ m = re.search(r"Showing records \d+ to \d+ of (\d+)", html)
275
+ return int(m.group(1)) if m else None
276
+
277
+
278
+ def _client():
279
+ return httpx.Client(
280
+ headers={"User-Agent": USER_AGENT},
281
+ follow_redirects=True,
282
+ timeout=60.0,
283
+ )
284
+
285
+
286
+ def _form_token(html):
287
+ m = re.search(r'name="__ncforminfo" value="([^"]+)"', html)
288
+ return m.group(1) if m else None
289
+
290
+
291
+ def _post_search(client, page_url, post_url, data):
292
+ """GET the form page first (cookies + anti-bot token), then POST."""
293
+ try:
294
+ page = client.get(page_url)
295
+ page.raise_for_status()
296
+ token = _form_token(page.text)
297
+ if token:
298
+ data = dict(data)
299
+ data["__ncforminfo"] = token
300
+ resp = client.post(post_url, data=data)
301
+ resp.raise_for_status()
302
+ return resp.text
303
+ except httpx.HTTPStatusError as exc:
304
+ raise click.ClickException(
305
+ f"HTTP error {exc.response.status_code}: {exc.request.url}"
306
+ ) from exc
307
+ except httpx.HTTPError as exc:
308
+ raise click.ClickException(f"Missouri Archives request failed: {exc}") from exc
309
+
310
+
311
+ def _parse_death_name(text):
312
+ """Split 'Jane Doe - Deceased John Doe - Spouse ...' into roles.
313
+
314
+ For 1953-1975 certificates the name cell also lists spouse, father,
315
+ and mother. Returns a dict with at least 'name' (the deceased).
316
+ """
317
+ out = {}
318
+ parts = re.split(r"\s+-\s+(Deceased|Spouse|Father|Mother)\s*", _clean(text))
319
+ if not parts:
320
+ return out
321
+ # Each role label FOLLOWS the name it describes:
322
+ # "Jane Doe - Deceased John Doe - Spouse ..."
323
+ for i in range(1, len(parts), 2):
324
+ name = _clean(parts[i - 1])
325
+ if name:
326
+ out[parts[i].lower()] = name
327
+ if "deceased" in out:
328
+ out["name"] = out["deceased"]
329
+ elif parts:
330
+ out["name"] = _clean(parts[0])
331
+ return out
332
+
333
+
334
+ def _death_rows(html):
335
+ _header, rows = _find_results_table(html, "Date of Death")
336
+ out = []
337
+ for row in rows:
338
+ cells = [_clean(c.text) for c in row]
339
+ if len(cells) < 5 or not cells[0]:
340
+ continue
341
+ rec = _parse_death_name(cells[0])
342
+ rec["age"] = cells[1]
343
+ rec["date_of_death"] = cells[2]
344
+ rec["county"] = cells[3]
345
+ rec["cert"] = cells[4]
346
+ rec["ssn4"] = cells[5] if len(cells) > 5 else ""
347
+ img = row[6].hrefs[0] if len(row) > 6 and row[6].hrefs else ""
348
+ rec["image"] = urljoin(BASE, img) if img else ""
349
+ out.append(rec)
350
+ return out
351
+
352
+
353
+ def _pre1910_rows(html, kind):
354
+ if kind == "death":
355
+ _header, rows = _find_results_table(html, "Date Of Death")
356
+ else:
357
+ _header, rows = _find_results_table(html, "Date Of Birth")
358
+ out = []
359
+ for row in rows:
360
+ cells = [_clean(c.text) for c in row]
361
+ if not cells or not cells[0]:
362
+ continue
363
+ detail_href = row[-1].hrefs[0] if row and row[-1].hrefs else ""
364
+ m = re.search(r"id=(\d+)", detail_href or "")
365
+ detail_id = m.group(1) if m else ""
366
+ if kind == "death":
367
+ rec = {
368
+ "name": cells[0],
369
+ "age": cells[1] if len(cells) > 1 else "",
370
+ "sex": cells[2] if len(cells) > 2 else "",
371
+ "color": cells[3] if len(cells) > 3 else "",
372
+ "date_of_death": cells[4] if len(cells) > 4 else "",
373
+ "county": cells[5] if len(cells) > 5 else "",
374
+ }
375
+ else:
376
+ rec = {
377
+ "name": cells[0],
378
+ "place": cells[1] if len(cells) > 1 else "",
379
+ "county": cells[2] if len(cells) > 2 else "",
380
+ "date_of_birth": cells[3] if len(cells) > 3 else "",
381
+ "father": cells[4] if len(cells) > 4 else "",
382
+ "mother": cells[5] if len(cells) > 5 else "",
383
+ "attendant": cells[6] if len(cells) > 6 else "",
384
+ }
385
+ rec["detail_id"] = detail_id
386
+ rec["detail_url"] = urljoin(PRE1910_PAGE, detail_href) if detail_href else ""
387
+ out.append(rec)
388
+ return out
389
+
390
+
391
+ def _fetch_pages(client, first_html, results_url, parse, limit):
392
+ """Follow the session pager (50/page) until limit or total reached."""
393
+ raw_total = _total_results(first_html)
394
+ records = parse(first_html)
395
+ total = raw_total if raw_total is not None else len(records)
396
+ page = 2
397
+ while len(records) < min(limit, total):
398
+ try:
399
+ resp = client.get(
400
+ results_url, params={"PageNumber": page, "recordsPerPage": 50}
401
+ )
402
+ resp.raise_for_status()
403
+ except httpx.HTTPStatusError as exc:
404
+ raise click.ClickException(
405
+ f"HTTP error {exc.response.status_code}: {exc.request.url}"
406
+ ) from exc
407
+ except httpx.HTTPError as exc:
408
+ raise click.ClickException(f"Missouri Archives request failed: {exc}") from exc
409
+ records.extend(parse(resp.text))
410
+ page += 1
411
+ verified = bool(records) or raw_total is not None
412
+ return total, records[:limit], verified
413
+
414
+
415
+ def _detail_fields(html):
416
+ """Pair each header row on a pre-1910 detail page with its value row."""
417
+ fields = {}
418
+ notes = []
419
+ for table in _parse_tables(html):
420
+ rows = [[_clean(c.text) for c in r] for r in table]
421
+ i = 0
422
+ while i < len(rows):
423
+ row = rows[i]
424
+ if len(row) == 1:
425
+ if row[0] and row[0] != "NOTE":
426
+ notes.append(row[0])
427
+ i += 1
428
+ continue
429
+ if i + 1 < len(rows) and len(rows[i + 1]) == len(row):
430
+ for key, val in zip(row, rows[i + 1]):
431
+ if key:
432
+ fields[key] = val
433
+ i += 2
434
+ else:
435
+ i += 1
436
+ if notes:
437
+ fields["notes"] = "; ".join(notes)
438
+ return fields
439
+
440
+
441
+ def _download_pdf(client, url, dest, overwrite):
442
+ if dest.exists() and not overwrite:
443
+ return dest, True
444
+ try:
445
+ with client.stream("GET", url) as resp:
446
+ resp.raise_for_status()
447
+ with dest.open("wb") as fh:
448
+ for chunk in resp.iter_bytes():
449
+ fh.write(chunk)
450
+ except httpx.HTTPStatusError as exc:
451
+ raise click.ClickException(
452
+ f"HTTP error {exc.response.status_code}: {exc.request.url}"
453
+ ) from exc
454
+ except httpx.HTTPError as exc:
455
+ raise click.ClickException(f"Missouri Archives download failed: {exc}") from exc
456
+ return dest, False
457
+
458
+
459
+ def _search_death(data: dict, limit: int) -> dict:
460
+ with _client() as client:
461
+ first_html = _post_search(client, DEATH_PAGE, DEATH_POST, data)
462
+ total, records, verified = _fetch_pages(
463
+ client, first_html, DEATH_RESULTS, _death_rows, limit
464
+ )
465
+ return {"total": total, "results": records, "verified": verified}
466
+
467
+
468
+ def _search_pre1910(kind: str, data: dict, limit: int) -> dict:
469
+ parse = lambda html: _pre1910_rows(html, kind)
470
+ with _client() as client:
471
+ first_html = _post_search(client, PRE1910_PAGE, PRE1910_POST, data)
472
+ total, records, verified = _fetch_pages(
473
+ client, first_html, PRE1910_RESULTS, parse, limit
474
+ )
475
+ return {"total": total, "results": records, "verified": verified}
476
+
477
+
478
+ def _fetch_detail(clean_id: str) -> dict:
479
+ url = f"{PRE1910_DETAIL}?id={clean_id}"
480
+ try:
481
+ with _client() as client:
482
+ resp = client.get(url)
483
+ resp.raise_for_status()
484
+ except httpx.HTTPStatusError as exc:
485
+ raise click.ClickException(
486
+ f"HTTP error {exc.response.status_code}: {exc.request.url}"
487
+ ) from exc
488
+ except httpx.HTTPError as exc:
489
+ raise click.ClickException(f"Missouri Archives request failed: {exc}") from exc
490
+ return {"id": clean_id, "url": url, "fields": _detail_fields(resp.text)}
491
+
492
+
493
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
494
+ def cli():
495
+ """Search Missouri State Archives vital records (no key, no login)."""
496
+
497
+
498
+ @cli.command("death")
499
+ @click.option("--last", required=True, help="Last name (surname).")
500
+ @click.option("--first", default="", help="First name.")
501
+ @click.option("--middle", default="", help="Middle name.")
502
+ @click.option(
503
+ "--role",
504
+ type=click.Choice(["deceased", "spouse", "father", "mother"]),
505
+ default="deceased",
506
+ show_default=True,
507
+ help="Whose name to search. Spouse/father/mother only for 1953-1975.",
508
+ )
509
+ @click.option(
510
+ "--match",
511
+ type=click.Choice(["contains", "starts-with", "ends-with"]),
512
+ default="contains",
513
+ show_default=True,
514
+ help="Name match type, applied to every name field given.",
515
+ )
516
+ @click.option("--county", default="", help="County as spelled on the site; default all counties.")
517
+ @click.option("--begin-year", type=int, default=1910, show_default=True)
518
+ @click.option("--end-year", type=int, default=1975, show_default=True)
519
+ @click.option("--begin-month", type=int, default=0, show_default=True, help="1-12, 0 = all months.")
520
+ @click.option("--end-month", type=int, default=0, show_default=True, help="1-12, 0 = all months.")
521
+ @click.option("--limit", type=int, default=50, show_default=True, help="Max records (50 per page).")
522
+ @click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
523
+ @click.option(
524
+ "--download",
525
+ "download_dir",
526
+ type=click.Path(path_type=Path),
527
+ default=None,
528
+ help="Download each result's certificate PDF into DIR.",
529
+ )
530
+ @cache_options
531
+ def cmd_death(
532
+ last, first, middle, role, match, county,
533
+ begin_year, end_year, begin_month, end_month,
534
+ limit, as_json, download_dir, refresh, cache_ttl_hours,
535
+ ):
536
+ """Search Missouri Death Certificates, 1910-1975 (with images)."""
537
+ if not 1910 <= begin_year <= end_year <= 1975:
538
+ raise click.BadParameter("year range must sit inside 1910-1975.")
539
+ for m in (begin_month, end_month):
540
+ if not 0 <= m <= 12:
541
+ raise click.BadParameter("months must be 0-12 (0 = all).")
542
+ if limit < 1:
543
+ raise click.BadParameter("--limit must be at least 1.")
544
+ method = MATCH_METHODS[match]
545
+ data = {
546
+ "DeathCertNameSearchType": role.capitalize(),
547
+ "LastName": last,
548
+ "LNSearchMethod": method,
549
+ "FirstName": first,
550
+ "FNSearchMethod": method,
551
+ "MiddleName": middle,
552
+ "MNSearchMethod": method,
553
+ "BeginMonth": str(begin_month),
554
+ "BeginYear": str(begin_year),
555
+ "EndMonth": str(end_month),
556
+ "EndYear": str(end_year),
557
+ "CountyName": county or ALL_COUNTIES,
558
+ "Search": "Search",
559
+ }
560
+ cache_payload = {
561
+ "last": last, "first": first, "middle": middle, "role": role,
562
+ "match": match, "county": county, "begin_year": begin_year,
563
+ "end_year": end_year, "begin_month": begin_month,
564
+ "end_month": end_month, "limit": limit,
565
+ }
566
+ ttl = resolve_ttl_hours(cache_ttl_hours)
567
+ result, hit = cached_call(
568
+ "death",
569
+ cache_payload,
570
+ lambda: _search_death(data, limit),
571
+ refresh=refresh,
572
+ ttl_hours=ttl,
573
+ cacheable=lambda r: bool(r.get("verified")),
574
+ )
575
+ total = result["total"]
576
+ records = result["results"]
577
+ if download_dir:
578
+ download_dir.mkdir(parents=True, exist_ok=True)
579
+ to_download = [rec for rec in records if rec.get("image")]
580
+ if to_download:
581
+ with _client() as client:
582
+ for rec in to_download:
583
+ fname = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(rec["image"]).name)
584
+ dest, skipped = _download_pdf(
585
+ client, rec["image"], download_dir / fname, overwrite=False
586
+ )
587
+ click.echo(
588
+ f"{'Exists (skip)' if skipped else 'Downloaded'}: {dest} "
589
+ f"({dest.stat().st_size:,} bytes)"
590
+ )
591
+ if as_json:
592
+ click.echo(json.dumps({"total": total, "results": records, "cache_hit": hit}, indent=2))
593
+ return
594
+ marker = " [cache]" if hit else ""
595
+ click.echo(f"Total: {total} | showing {len(records)}{marker}")
596
+ for rec in records:
597
+ parts = [rec["name"]]
598
+ if rec.get("age"):
599
+ parts.append(f"age {rec['age']}")
600
+ parts.append(rec["date_of_death"])
601
+ parts.append(rec["county"])
602
+ parts.append(f"cert {rec['cert']}")
603
+ if rec.get("image"):
604
+ parts.append(rec["image"])
605
+ click.echo(" | ".join(p for p in parts if p))
606
+
607
+
608
+ @cli.command("pre1910")
609
+ @click.option(
610
+ "--type", "kind",
611
+ type=click.Choice(["birth", "death"]),
612
+ default="death",
613
+ show_default=True,
614
+ help="Record type in the pre-1910 database.",
615
+ )
616
+ @click.option("--name", required=True, help="All or part of a name; the site recommends last name only.")
617
+ @click.option("--county", default="", help="County as spelled on the site; default all counties.")
618
+ @click.option("--limit", type=int, default=50, show_default=True, help="Max records (50 per page).")
619
+ @click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
620
+ @cache_options
621
+ def cmd_pre1910(kind, name, county, limit, as_json, refresh, cache_ttl_hours):
622
+ """Search the pre-1910 Birth and Death Records Database (abstracts)."""
623
+ if limit < 1:
624
+ raise click.BadParameter("--limit must be at least 1.")
625
+ if kind == "death":
626
+ data = {
627
+ "DeathCounty": county or ALL_COUNTIES_PRE1910,
628
+ "DeathNameSearch": name,
629
+ "DeathSubmit": "Search",
630
+ }
631
+ else:
632
+ data = {
633
+ "BirthCounty": county or ALL_COUNTIES_PRE1910,
634
+ "BirthNameSearch": name,
635
+ "BirthSubmit": "Search",
636
+ }
637
+ cache_payload = {"kind": kind, "name": name, "county": county, "limit": limit}
638
+ ttl = resolve_ttl_hours(cache_ttl_hours)
639
+ result, hit = cached_call(
640
+ "pre1910",
641
+ cache_payload,
642
+ lambda: _search_pre1910(kind, data, limit),
643
+ refresh=refresh,
644
+ ttl_hours=ttl,
645
+ cacheable=lambda r: bool(r.get("verified")),
646
+ )
647
+ total = result["total"]
648
+ records = result["results"]
649
+ if as_json:
650
+ click.echo(json.dumps({"total": total, "results": records, "cache_hit": hit}, indent=2))
651
+ return
652
+ marker = " [cache]" if hit else ""
653
+ click.echo(f"Total: {total} | showing {len(records)}{marker}")
654
+ for rec in records:
655
+ if kind == "death":
656
+ parts = [
657
+ rec["name"],
658
+ f"age {rec['age']}" if rec.get("age") else "",
659
+ rec.get("sex", ""),
660
+ rec.get("color", ""),
661
+ rec["date_of_death"],
662
+ rec["county"],
663
+ f"detail {rec['detail_id']}" if rec.get("detail_id") else "",
664
+ ]
665
+ else:
666
+ parts = [
667
+ rec["name"],
668
+ rec.get("place", ""),
669
+ rec["county"],
670
+ rec["date_of_birth"],
671
+ f"father {rec['father']}" if rec.get("father") else "",
672
+ f"mother {rec['mother']}" if rec.get("mother") else "",
673
+ f"detail {rec['detail_id']}" if rec.get("detail_id") else "",
674
+ ]
675
+ click.echo(" | ".join(p for p in parts if p))
676
+
677
+
678
+ @cli.command("detail")
679
+ @click.argument("ids", nargs=-1, required=True)
680
+ @click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
681
+ @cache_options
682
+ def cmd_detail(ids, as_json, refresh, cache_ttl_hours):
683
+ """Fetch full abstracts for pre-1910 record IDs (from `pre1910`)."""
684
+ ttl = resolve_ttl_hours(cache_ttl_hours)
685
+ records = []
686
+ for rid in ids:
687
+ clean = re.sub(r"\D+", "", rid)
688
+ rec, hit = cached_call(
689
+ "detail",
690
+ {"id": clean},
691
+ lambda cid=clean: _fetch_detail(cid),
692
+ refresh=refresh,
693
+ ttl_hours=ttl,
694
+ cacheable=lambda r: bool(r.get("fields")),
695
+ )
696
+ records.append({**rec, "cache_hit": hit})
697
+ if as_json:
698
+ click.echo(json.dumps(records[0] if len(records) == 1 else records, indent=2))
699
+ return
700
+ for idx, rec in enumerate(records):
701
+ if idx > 0:
702
+ click.echo("")
703
+ marker = " [cache]" if rec.get("cache_hit") else ""
704
+ click.echo(f"Detail {rec['id']}: {rec['url']}{marker}")
705
+ for key, val in rec["fields"].items():
706
+ click.echo(f" {key}: {val}")
707
+
708
+
709
+ @cli.command("download")
710
+ @click.argument("urls", nargs=-1, required=True)
711
+ @click.option(
712
+ "--out", "out_dir",
713
+ type=click.Path(path_type=Path),
714
+ default=Path("mo-death-certs"),
715
+ show_default=True,
716
+ help="Output directory.",
717
+ )
718
+ @click.option("--overwrite", is_flag=True, help="Re-download files that already exist.")
719
+ def cmd_download(urls, out_dir, overwrite):
720
+ """Download death-certificate PDFs by image URL (from `death`)."""
721
+ out_dir.mkdir(parents=True, exist_ok=True)
722
+ with _client() as client:
723
+ for url in urls:
724
+ fname = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(url).name) or "certificate.pdf"
725
+ dest, skipped = _download_pdf(client, url, out_dir / fname, overwrite)
726
+ click.echo(
727
+ f"{'Exists (skip)' if skipped else 'Downloaded'}: {dest} "
728
+ f"({dest.stat().st_size:,} bytes)"
729
+ )
730
+
731
+
732
+ @cli.command("mdh")
733
+ def cmd_mdh():
734
+ """Show the Missouri Digital Heritage browser path (no machine interface)."""
735
+ click.echo("Missouri Digital Heritage has no verified machine interface.")
736
+ click.echo(f" Home: {MDH_HOME}")
737
+ click.echo(f" Advanced Search (browser): {MDH_SEARCH}")
738
+ click.echo(f" Missouri State Archives: {ARCHIVES_HOME}")
739
+ click.echo(" CONTENTdm dmwebservices returns 403 (Cloudflare) to automated requests,")
740
+ click.echo(" and no GET search URL for the Advanced Search was verified.")
741
+ click.echo(" Use the browser for MDH collections (soldiers, land patents,")
742
+ click.echo(" naturalization, newspapers, plat books). The two vital-records")
743
+ click.echo(" databases are covered by this CLI: `death` and `pre1910`.")
744
+
745
+
746
+ if __name__ == "__main__":
747
+ try:
748
+ cli()
749
+ except httpx.HTTPStatusError as exc:
750
+ click.echo(f"HTTP error {exc.response.status_code}: {exc.request.url}", err=True)
751
+ sys.exit(1)