@kinloom/cli 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/cached-ocr.py +786 -0
- package/dist/assets/ocr.md +76 -0
- package/dist/assets/prep-scan.md +97 -0
- package/dist/assets/prep-scan.py +1313 -0
- package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
- package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
- package/dist/bundled-skills/archive-org/SKILL.md +162 -0
- package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
- package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
- package/dist/bundled-skills/california-archives/SKILL.md +130 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
- package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
- package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
- package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
- package/dist/bundled-skills/findagrave/SKILL.md +129 -0
- package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
- package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
- package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
- package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
- package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
- package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
- package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
- package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
- package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
- package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
- package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
- package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
- package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
- package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
- package/dist/bundled-skills/wikitree/SKILL.md +154 -0
- package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +488 -26
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +30 -5
- package/dist/client.js.map +1 -1
- package/dist/commands/ops/audit.d.ts +138 -0
- package/dist/commands/ops/audit.d.ts.map +1 -0
- package/dist/commands/ops/audit.js +872 -0
- package/dist/commands/ops/audit.js.map +1 -0
- package/dist/commands/ops/context.d.ts +100 -0
- package/dist/commands/ops/context.d.ts.map +1 -0
- package/dist/commands/ops/context.js +917 -0
- package/dist/commands/ops/context.js.map +1 -0
- package/dist/commands/ops/dates.d.ts +87 -0
- package/dist/commands/ops/dates.d.ts.map +1 -0
- package/dist/commands/ops/dates.js +228 -0
- package/dist/commands/ops/dates.js.map +1 -0
- package/dist/commands/ops/help.d.ts +8 -0
- package/dist/commands/ops/help.d.ts.map +1 -0
- package/dist/commands/ops/help.js +107 -0
- package/dist/commands/ops/help.js.map +1 -0
- package/dist/commands/ops/index.d.ts +8 -0
- package/dist/commands/ops/index.d.ts.map +1 -0
- package/dist/commands/ops/index.js +8 -0
- package/dist/commands/ops/index.js.map +1 -0
- package/dist/commands/ops/integrate.d.ts +61 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -0
- package/dist/commands/ops/integrate.js +1063 -0
- package/dist/commands/ops/integrate.js.map +1 -0
- package/dist/commands/ops/sync.d.ts +194 -0
- package/dist/commands/ops/sync.d.ts.map +1 -0
- package/dist/commands/ops/sync.js +1251 -0
- package/dist/commands/ops/sync.js.map +1 -0
- package/dist/commands/ops/telemetry.d.ts +79 -0
- package/dist/commands/ops/telemetry.d.ts.map +1 -0
- package/dist/commands/ops/telemetry.js +249 -0
- package/dist/commands/ops/telemetry.js.map +1 -0
- package/dist/commands/ops/verify.d.ts +76 -0
- package/dist/commands/ops/verify.d.ts.map +1 -0
- package/dist/commands/ops/verify.js +325 -0
- package/dist/commands/ops/verify.js.map +1 -0
- package/dist/commands/records/help.d.ts +18 -0
- package/dist/commands/records/help.d.ts.map +1 -0
- package/dist/commands/records/help.js +174 -0
- package/dist/commands/records/help.js.map +1 -0
- package/dist/commands/records/index.d.ts +5 -0
- package/dist/commands/records/index.d.ts.map +1 -0
- package/dist/commands/records/index.js +5 -0
- package/dist/commands/records/index.js.map +1 -0
- package/dist/commands/records/registry.d.ts +32 -0
- package/dist/commands/records/registry.d.ts.map +1 -0
- package/dist/commands/records/registry.js +227 -0
- package/dist/commands/records/registry.js.map +1 -0
- package/dist/commands/records/resolve.d.ts +14 -0
- package/dist/commands/records/resolve.d.ts.map +1 -0
- package/dist/commands/records/resolve.js +61 -0
- package/dist/commands/records/resolve.js.map +1 -0
- package/dist/commands/records/runner.d.ts +27 -0
- package/dist/commands/records/runner.d.ts.map +1 -0
- package/dist/commands/records/runner.js +255 -0
- package/dist/commands/records/runner.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: library-of-michigan
|
|
3
|
+
description: Research Michigan branches at the Library of Michigan (Lansing) and its Michiganology digital portal via the bundled `michiganology` CLI or the website. Covers CLI search, the searchable digital collections (death certificates 1897-1952, Michigan state census, naturalization, WWI service cards, surveyor notebooks and maps, photographs, maps), what is online vs in-person only (tax rolls, plat maps, state census schedules, Abrams Foundation Historical Collection), and planning a Lansing visit. Use when family lines touch Michigan or neighboring Midwest migration routes.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Library of Michigan
|
|
7
|
+
|
|
8
|
+
This skill includes a standalone executable Python CLI at `skills/library-of-michigan/scripts/michiganology` using a PEP 723 `#!/usr/bin/env -S uv run --script` shebang with inline dependency (`click`). It shells out to system `curl` for fetches, because Preservica's front door 403s Python httpx requests while curl succeeds; curl must be installed. No virtualenv setup or API key is required.
|
|
9
|
+
|
|
10
|
+
Two institutions share one building and one research mission in Lansing, and the skill covers both:
|
|
11
|
+
|
|
12
|
+
- **Library of Michigan**, 702 W. Kalamazoo St., Lansing, MI 48915. Reference desk 517-335-1477, librarian@michigan.gov. Open Mon-Fri 10 am to 5 pm, Sat 10 am to 4 pm; free admission. Its Abrams Foundation Historical Collection (2nd floor) is one of the largest genealogy collections in the US: census records, cemetery transcriptions, city directories, county and family histories, newspapers from all 83 Michigan counties, land records, vital records, and military indexes.
|
|
13
|
+
- **Archives of Michigan**, same building. Open Mon-Fri 1 to 5 pm, Sat 10 am to 4 pm, phone 517-335-2576. Holds state government records, including the collections digitized on Michiganology.
|
|
14
|
+
|
|
15
|
+
## Bundled CLI (`scripts/michiganology`)
|
|
16
|
+
|
|
17
|
+
Path: `skills/library-of-michigan/scripts/michiganology`
|
|
18
|
+
|
|
19
|
+
### Search all digital collections
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
# Search a surname across every Michiganology collection
|
|
23
|
+
skills/library-of-michigan/scripts/michiganology search Lincoln
|
|
24
|
+
|
|
25
|
+
# JSON output, 20 hits
|
|
26
|
+
skills/library-of-michigan/scripts/michiganology search Lincoln --limit 20 --json
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Note on multi-word queries: Preservica simple search treats unquoted multi-word queries (such as `"Abraham Lincoln"`) as broad OR matches across collections, so a broad search can return county tax rolls or unrelated files. Inspect individual hits with `get` or narrow with Advanced Search on the website.
|
|
30
|
+
|
|
31
|
+
### Inspect an item (`get`) and download the scan (`download`)
|
|
32
|
+
|
|
33
|
+
Search output prints only the item title (often just a surname or certificate number) and URL. Use `get` to read the full Preservica `Item Data` fields (given name, death date, county, city, parents) and `download` to pull the full-resolution JPEG or PDF directly via `curl`:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
# Read parsed Item Data metadata and direct download link
|
|
37
|
+
skills/library-of-michigan/scripts/michiganology get IO_<uuid>
|
|
38
|
+
skills/library-of-michigan/scripts/michiganology get "https://michigan.access.preservica.com/uncategorized/IO_<uuid>/" --json
|
|
39
|
+
|
|
40
|
+
# Download the full-resolution file (filename inferred from Content-Disposition)
|
|
41
|
+
skills/library-of-michigan/scripts/michiganology download IO_<uuid> --out ./downloads/michiganology
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### List the digital collections
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
skills/library-of-michigan/scripts/michiganology collections
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Shareable search URL
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
skills/library-of-michigan/scripts/michiganology url Lincoln
|
|
54
|
+
# https://michigan.access.preservica.com/?s=Lincoln
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Michiganology: what is searchable online (verified live 2026-11-24)
|
|
58
|
+
|
|
59
|
+
Michiganology (`https://michiganology.org/`) is the Michigan History Center portal; its searchable collections live on Preservica Universal Access at `https://michigan.access.preservica.com/`. Simple search is a stable GET, `/?s=<query>`, and results are server-rendered, so plain HTTP works with no browser, no key, and no sign-in. The CLI shows the first page only; use the website (with its sort and filter sidebar) to page through large result sets.
|
|
60
|
+
|
|
61
|
+
Collections and their live URLs:
|
|
62
|
+
|
|
63
|
+
| Collection | URL |
|
|
64
|
+
|---|---|
|
|
65
|
+
| Death Certificates, 1897-1952 | `https://michigan.access.preservica.com/death-certificates-1897-1952/` |
|
|
66
|
+
| Michigan State Census, 1827-1894 | `https://michigan.access.preservica.com/michigan-state-census/` |
|
|
67
|
+
| Naturalization Records | `https://michigan.access.preservica.com/naturalization-records/` |
|
|
68
|
+
| World War I, Service Cards | `https://michigan.access.preservica.com/world-war-i-service-cards/` |
|
|
69
|
+
| Surveyor Field Notebooks, 1815-1918 | `https://michigan.access.preservica.com/surveyor-field-notebooks/` |
|
|
70
|
+
| Surveyor Maps, 1816-1860 | `https://michigan.access.preservica.com/surveyor-maps/` |
|
|
71
|
+
| General Photograph Collection, ca. 1860-1990 | `https://michigan.access.preservica.com/general-photograph-collection/` |
|
|
72
|
+
| Archives of Michigan Map Collection, ca. 1810-1970 | `https://michigan.access.preservica.com/archives-of-michigan-map-collection/` |
|
|
73
|
+
| Corporation Annual Reports, 1997-2006 | `https://michigan.access.preservica.com/corporation-annual-reports/` |
|
|
74
|
+
|
|
75
|
+
Collection notes:
|
|
76
|
+
|
|
77
|
+
- Death certificates: the index covers 1897-1952. Per library guides (reported, not verified live), digitized certificate images are viewable for records older than 75 years; newer entries are index-only. Michigan death records 1867-1897 predate this collection; use FamilySearch for those.
|
|
78
|
+
- Michigan state census schedules (1827-1894) fill gaps between federal censuses and are a strong online source for pre-1900 Michigan households.
|
|
79
|
+
- Naturalization indexes cover 29 counties (per library guides); the actual records may need an in-person or copy request.
|
|
80
|
+
- The website also has an Advanced Search page with fielded filters (Family Name, Given Name, County, Birth/Death Date, Place, and more), but it is JavaScript-driven with no stable GET pattern verified, so the CLI covers simple search only. Use the website for fielded searches.
|
|
81
|
+
|
|
82
|
+
## What is in-person only
|
|
83
|
+
|
|
84
|
+
Not everything is digitized. Expect to visit Lansing (or order copies) for:
|
|
85
|
+
|
|
86
|
+
- County-level tax rolls and plat maps in physical form; some plat maps and atlases are digitized through the Michigan County Histories and Atlases project (University of Michigan), not Michiganology.
|
|
87
|
+
- State census schedules beyond what Michiganology has digitized, and manuscript census material.
|
|
88
|
+
- Most newspapers: the library holds microfilm newspapers from all 83 counties, but only a subset is online (see the Digital Michigan Newspaper Portal at Central Michigan University's Clarke Historical Library).
|
|
89
|
+
- Vital records on microfilm, probate and court records, and manuscript collections in the Archives.
|
|
90
|
+
- The library catalog (ANSWER) is searchable online before a visit; use it to pull call numbers in advance so reading-room time is spent reading, not searching.
|
|
91
|
+
|
|
92
|
+
## Subscription databases (Michigan residents, library card required)
|
|
93
|
+
|
|
94
|
+
Michigan residents can use the Library of Michigan's subscription databases remotely with a Library of Michigan library card and PIN, via `michigan.gov/libraryofmichigan` online resources. This includes Ancestry Library Edition style resources and MyHeritage Library Edition. These need a personal library card; the CLI does not touch them and no credentials belong in this repo.
|
|
95
|
+
|
|
96
|
+
## Research workflow
|
|
97
|
+
|
|
98
|
+
1. `michiganology search <Surname>` for the broad sweep; note the total count and the strongest first-page hits.
|
|
99
|
+
2. Narrow on the website with Advanced Search: Family Name plus County (for example Wayne, Ingham, or Washtenaw), and filter to the Death Certificates collection for 1897-1952 deaths.
|
|
100
|
+
3. Combine surname and locality (for example `michiganology search "Lincoln Detroit"`) when the surname alone is too noisy; simple search matches either word anywhere, so quote exact names to narrow.
|
|
101
|
+
4. For pre-1897 Michigan deaths and marriages, cross-check FamilySearch Michigan collections; Michiganology's death run starts in 1897.
|
|
102
|
+
5. For land and neighborhood context, pair surveyor maps and the map collection with county plat maps and atlases held in Lansing or digitized at the University of Michigan.
|
|
103
|
+
6. Record every hit in `data/` with its Michiganology item URL; item URLs are stable (`michigan.access.preservica.com/uncategorized/SO_<uuid>` or `IO_<uuid>`).
|
|
104
|
+
|
|
105
|
+
## Disk cache and environment variables
|
|
106
|
+
|
|
107
|
+
`search` and `get` cache successful responses on disk under `~/.cache/kinloom-michiganology/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP/curl errors and unparsed or blocked pages are never cached.
|
|
108
|
+
|
|
109
|
+
- `--refresh`: bypass cached reads and write the fresh response to disk.
|
|
110
|
+
- `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
|
|
111
|
+
- `KINLOOM_MICHIGANOLOGY_CACHE_DIR`: override the cache directory path.
|
|
112
|
+
- `KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS`: override the default TTL in hours.
|
|
113
|
+
|
|
114
|
+
No key or account is needed for Michiganology search.
|
|
115
|
+
|
|
116
|
+
## Verified-live note
|
|
117
|
+
|
|
118
|
+
The Michiganology homepage, the Preservica search (`/?s=<query>`), the collections list, and the Library of Michigan address, hours, and phone were verified live on 2026-11-24. Items marked "per library guides" or "reported" were not re-verified live and are labeled as such.
|
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
#!/usr/bin/env -S uv run --script
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.11"
|
|
4
|
+
# dependencies = [
|
|
5
|
+
# "click>=8.1",
|
|
6
|
+
# ]
|
|
7
|
+
# ///
|
|
8
|
+
"""Search Michiganology, the Archives of Michigan digital collections
|
|
9
|
+
(Preservica Universal Access), from the command line.
|
|
10
|
+
|
|
11
|
+
Simple search is a stable GET: https://michigan.access.preservica.com/?s=<query>
|
|
12
|
+
Results are server-rendered, so plain HTTP works, no browser and no key.
|
|
13
|
+
Transport note: Preservica's front door 403s Python httpx requests (TLS
|
|
14
|
+
fingerprint) while curl succeeds with any User-Agent, so this CLI shells out
|
|
15
|
+
to curl for the fetch. curl must be installed; it is on any normal Unix box.
|
|
16
|
+
Verified live 2026-11-24: simple search returns server-rendered HTML results.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hashlib
|
|
22
|
+
import html as htmlmod
|
|
23
|
+
import json
|
|
24
|
+
import math
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import shutil
|
|
28
|
+
import subprocess
|
|
29
|
+
import tempfile
|
|
30
|
+
import time
|
|
31
|
+
from contextlib import contextmanager
|
|
32
|
+
from html.parser import HTMLParser
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any, Callable, Iterator
|
|
35
|
+
from urllib.parse import quote_plus, unquote
|
|
36
|
+
|
|
37
|
+
import click
|
|
38
|
+
|
|
39
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
40
|
+
CACHE_SCHEMA = 1
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cache_dir() -> Path:
|
|
44
|
+
override = os.environ.get("KINLOOM_MICHIGANOLOGY_CACHE_DIR")
|
|
45
|
+
if override:
|
|
46
|
+
return Path(override).expanduser()
|
|
47
|
+
return Path.home() / ".cache" / "kinloom-michiganology"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
51
|
+
if cli_ttl is not None:
|
|
52
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
53
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
54
|
+
return float(cli_ttl)
|
|
55
|
+
raw = os.environ.get("KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS")
|
|
56
|
+
if raw is not None and raw.strip():
|
|
57
|
+
try:
|
|
58
|
+
parsed = float(raw.strip())
|
|
59
|
+
except ValueError as exc:
|
|
60
|
+
raise click.BadParameter(
|
|
61
|
+
f"Invalid KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
62
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
63
|
+
raise click.BadParameter(
|
|
64
|
+
f"Invalid KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS value: {raw!r} (must be >= 0).")
|
|
65
|
+
return parsed
|
|
66
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@contextmanager
|
|
70
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
71
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
72
|
+
try:
|
|
73
|
+
import fcntl
|
|
74
|
+
except ImportError:
|
|
75
|
+
yield
|
|
76
|
+
return
|
|
77
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
with open(lock_path, "a+b") as lock_file:
|
|
79
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
80
|
+
try:
|
|
81
|
+
yield
|
|
82
|
+
finally:
|
|
83
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
87
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
88
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
89
|
+
try:
|
|
90
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
91
|
+
os.replace(tmp, dest)
|
|
92
|
+
except Exception:
|
|
93
|
+
tmp.unlink(missing_ok=True)
|
|
94
|
+
raise
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
98
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
99
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
103
|
+
if not path.is_file():
|
|
104
|
+
return None
|
|
105
|
+
try:
|
|
106
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
107
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
108
|
+
return None
|
|
109
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
110
|
+
return None
|
|
111
|
+
fetched = entry.get("fetched_at")
|
|
112
|
+
if not isinstance(fetched, (int, float)):
|
|
113
|
+
return None
|
|
114
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
115
|
+
return None
|
|
116
|
+
result = entry.get("result")
|
|
117
|
+
return result if isinstance(result, dict) else None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def cached_call(kind: str, payload: dict, fetch: Callable[[], dict], *,
|
|
121
|
+
refresh: bool, ttl_hours: float,
|
|
122
|
+
cacheable: Callable[[dict], bool] = lambda _r: True) -> tuple[dict, bool]:
|
|
123
|
+
"""Return (result, cache_hit). Concurrent callers of one query serialize
|
|
124
|
+
on a per-key flock, so the second caller reads the first caller's file.
|
|
125
|
+
Exceptions from fetch propagate and write nothing; results rejected by
|
|
126
|
+
`cacheable` (doubtful empties) are returned but not stored."""
|
|
127
|
+
key = cache_key(kind, payload)
|
|
128
|
+
root = cache_dir()
|
|
129
|
+
path = root / f"{key}.json"
|
|
130
|
+
if not refresh:
|
|
131
|
+
hit = read_cache(path, ttl_hours)
|
|
132
|
+
if hit is not None:
|
|
133
|
+
return hit, True
|
|
134
|
+
with file_lock(root / f"{key}.lock"):
|
|
135
|
+
if not refresh:
|
|
136
|
+
hit = read_cache(path, ttl_hours)
|
|
137
|
+
if hit is not None:
|
|
138
|
+
return hit, True
|
|
139
|
+
result = fetch()
|
|
140
|
+
if cacheable(result):
|
|
141
|
+
atomic_write_json(path, {"schema": CACHE_SCHEMA, "fetched_at": time.time(),
|
|
142
|
+
"kind": kind, "query": payload, "result": result})
|
|
143
|
+
return result, False
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def cache_options(func: Callable) -> Callable:
|
|
147
|
+
func = click.option("--cache-ttl-hours", type=float, default=None,
|
|
148
|
+
help="Cache TTL in hours (default 168, env KINLOOM_MICHIGANOLOGY_CACHE_TTL_HOURS; 0 disables reads).")(func)
|
|
149
|
+
func = click.option("--refresh", is_flag=True,
|
|
150
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).")(func)
|
|
151
|
+
return func
|
|
152
|
+
|
|
153
|
+
BASE = "https://michigan.access.preservica.com"
|
|
154
|
+
# Preservica 403s python-httpx's default header set. Plain curl-style headers
|
|
155
|
+
# (short UA, Accept */*) return 200 consistently.
|
|
156
|
+
USER_AGENT = "Mozilla/5.0"
|
|
157
|
+
|
|
158
|
+
COLLECTIONS = [
|
|
159
|
+
("Death Certificates, 1897-1952", BASE + "/death-certificates-1897-1952/"),
|
|
160
|
+
("Michigan State Census, 1827-1894", BASE + "/michigan-state-census/"),
|
|
161
|
+
("Naturalization Records", BASE + "/naturalization-records/"),
|
|
162
|
+
("World War I, Service Cards", BASE + "/world-war-i-service-cards/"),
|
|
163
|
+
("Surveyor Field Notebooks, 1815-1918", BASE + "/surveyor-field-notebooks/"),
|
|
164
|
+
("Surveyor Maps, 1816-1860", BASE + "/surveyor-maps/"),
|
|
165
|
+
("General Photograph Collection, ca. 1860-1990", BASE + "/general-photograph-collection/"),
|
|
166
|
+
("Archives of Michigan Map Collection, ca. 1810-1970", BASE + "/archives-of-michigan-map-collection/"),
|
|
167
|
+
("Corporation Annual Reports, 1997-2006", BASE + "/corporation-annual-reports/"),
|
|
168
|
+
]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class ResultParser(HTMLParser):
|
|
172
|
+
"""Collect result-item blocks: first link href plus its text."""
|
|
173
|
+
|
|
174
|
+
def __init__(self) -> None:
|
|
175
|
+
super().__init__(convert_charrefs=True)
|
|
176
|
+
self.depth = 0
|
|
177
|
+
self.results: list[dict] = []
|
|
178
|
+
self.current: dict | None = None
|
|
179
|
+
self.in_link = False
|
|
180
|
+
self.link_text = ""
|
|
181
|
+
|
|
182
|
+
def handle_starttag(self, tag, attrs):
|
|
183
|
+
attrs = dict(attrs)
|
|
184
|
+
classes = attrs.get("class", "")
|
|
185
|
+
if tag == "div" and "result-item" in classes and self.depth == 0:
|
|
186
|
+
self.depth = 1
|
|
187
|
+
self.current = {"title": "", "url": ""}
|
|
188
|
+
return
|
|
189
|
+
if self.depth > 0:
|
|
190
|
+
if tag == "div":
|
|
191
|
+
self.depth += 1
|
|
192
|
+
elif tag == "a" and not self.current["url"]:
|
|
193
|
+
href = attrs.get("href", "")
|
|
194
|
+
if href:
|
|
195
|
+
self.current["url"] = href
|
|
196
|
+
self.in_link = True
|
|
197
|
+
self.link_text = ""
|
|
198
|
+
|
|
199
|
+
def handle_endtag(self, tag):
|
|
200
|
+
if self.depth > 0 and tag == "div":
|
|
201
|
+
self.depth -= 1
|
|
202
|
+
if self.depth == 0 and self.current:
|
|
203
|
+
self.current["title"] = " ".join(self.link_text.split()) or "(no title)"
|
|
204
|
+
if self.current["url"]:
|
|
205
|
+
self.results.append(self.current)
|
|
206
|
+
self.current = None
|
|
207
|
+
if tag == "a" and self.in_link:
|
|
208
|
+
self.in_link = False
|
|
209
|
+
|
|
210
|
+
def handle_data(self, data):
|
|
211
|
+
if self.in_link:
|
|
212
|
+
self.link_text += data
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class ItemMetadataParser(HTMLParser):
|
|
216
|
+
"""Parse Preservica item page title, Item Data fields, and download link."""
|
|
217
|
+
|
|
218
|
+
def __init__(self) -> None:
|
|
219
|
+
super().__init__(convert_charrefs=True)
|
|
220
|
+
self.in_h1 = False
|
|
221
|
+
self.title = ""
|
|
222
|
+
self.in_key = False
|
|
223
|
+
self.in_val = False
|
|
224
|
+
self.cur_key = ""
|
|
225
|
+
self.cur_val = ""
|
|
226
|
+
self.fields: list[tuple[str, str]] = []
|
|
227
|
+
self.download_url: str | None = None
|
|
228
|
+
|
|
229
|
+
def handle_starttag(self, tag, attrs):
|
|
230
|
+
attr_map = dict(attrs)
|
|
231
|
+
classes = attr_map.get("class", "")
|
|
232
|
+
if tag == "h1" and not self.title:
|
|
233
|
+
self.in_h1 = True
|
|
234
|
+
elif tag == "span" and "metadata-title" in classes:
|
|
235
|
+
self.in_key = True
|
|
236
|
+
self.cur_key = ""
|
|
237
|
+
elif tag == "span" and "metadata-content" in classes:
|
|
238
|
+
self.in_val = True
|
|
239
|
+
self.cur_val = ""
|
|
240
|
+
elif tag == "a":
|
|
241
|
+
href = attr_map.get("href", "")
|
|
242
|
+
if "/download/file/" in href and not self.download_url:
|
|
243
|
+
self.download_url = href
|
|
244
|
+
|
|
245
|
+
def handle_endtag(self, tag):
|
|
246
|
+
if tag == "h1" and self.in_h1:
|
|
247
|
+
self.in_h1 = False
|
|
248
|
+
elif tag == "span" and self.in_key:
|
|
249
|
+
self.in_key = False
|
|
250
|
+
elif tag == "span" and self.in_val:
|
|
251
|
+
self.in_val = False
|
|
252
|
+
key = " ".join(self.cur_key.split()).strip(":")
|
|
253
|
+
val = " ".join(self.cur_val.split())
|
|
254
|
+
if key:
|
|
255
|
+
self.fields.append((key, val))
|
|
256
|
+
|
|
257
|
+
def handle_data(self, data):
|
|
258
|
+
if self.in_h1:
|
|
259
|
+
self.title += data
|
|
260
|
+
elif self.in_key:
|
|
261
|
+
self.cur_key += data
|
|
262
|
+
elif self.in_val:
|
|
263
|
+
self.cur_val += data
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _require_curl() -> str:
|
|
267
|
+
curl = shutil.which("curl")
|
|
268
|
+
if not curl:
|
|
269
|
+
raise click.ClickException("curl is required but was not found on PATH.")
|
|
270
|
+
return curl
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
_STATUS_MARKER = "\n__KINLOOM_HTTP_STATUS__:"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _curl_get_text(url: str) -> str:
|
|
277
|
+
"""GET a page via curl; raise ClickException on transport or non-200 status."""
|
|
278
|
+
curl = _require_curl()
|
|
279
|
+
try:
|
|
280
|
+
proc = subprocess.run(
|
|
281
|
+
[curl, "-sSL", "-A", USER_AGENT, "--max-time", "60",
|
|
282
|
+
"-w", _STATUS_MARKER + "%{http_code}", url],
|
|
283
|
+
capture_output=True,
|
|
284
|
+
text=True,
|
|
285
|
+
timeout=70,
|
|
286
|
+
)
|
|
287
|
+
except (subprocess.SubprocessError, OSError) as exc:
|
|
288
|
+
raise click.ClickException(f"Michiganology request failed: {exc}") from exc
|
|
289
|
+
if proc.returncode != 0:
|
|
290
|
+
raise click.ClickException(
|
|
291
|
+
f"Michiganology request failed (curl exit {proc.returncode}): "
|
|
292
|
+
f"{proc.stderr.strip()[:300]}"
|
|
293
|
+
)
|
|
294
|
+
body, sep, status = proc.stdout.rpartition(_STATUS_MARKER)
|
|
295
|
+
if not sep:
|
|
296
|
+
raise click.ClickException("Michiganology request failed: no HTTP status from curl.")
|
|
297
|
+
status = status.strip()
|
|
298
|
+
if status != "200":
|
|
299
|
+
raise click.ClickException(f"Michiganology returned HTTP {status} for {url}")
|
|
300
|
+
return body
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _resolve_item_ref(url_or_id: str) -> tuple[str, str]:
|
|
304
|
+
"""Return (item_id, item_page_url) from a Preservica URL or IO_/SO_ identifier."""
|
|
305
|
+
raw = url_or_id.strip()
|
|
306
|
+
match = re.search(r"((?:IO|SO)_[A-Za-z0-9-]+)", raw)
|
|
307
|
+
if match:
|
|
308
|
+
item_id = match.group(1)
|
|
309
|
+
if raw.startswith("http://") or raw.startswith("https://"):
|
|
310
|
+
return item_id, raw
|
|
311
|
+
return item_id, f"{BASE}/uncategorized/{item_id}/"
|
|
312
|
+
if raw.startswith("http://") or raw.startswith("https://"):
|
|
313
|
+
return raw.rstrip("/").rsplit("/", 1)[-1], raw
|
|
314
|
+
raise click.UsageError(
|
|
315
|
+
"Pass a Michiganology item URL or a Preservica ID starting with IO_ or SO_."
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _filename_from_headers(headers_text: str, fallback: str) -> str:
|
|
320
|
+
match_star = re.search(r"filename\*\s*=\s*UTF-8''([^\r\n;]+)", headers_text, re.I)
|
|
321
|
+
if match_star:
|
|
322
|
+
candidate = Path(unquote(match_star.group(1).strip().strip('"'))).name
|
|
323
|
+
if candidate:
|
|
324
|
+
return candidate
|
|
325
|
+
match_plain = re.search(r'filename\s*=\s*"?([^"\r\n;]+)"?', headers_text, re.I)
|
|
326
|
+
if match_plain:
|
|
327
|
+
candidate = Path(match_plain.group(1).strip()).name
|
|
328
|
+
if candidate:
|
|
329
|
+
return candidate
|
|
330
|
+
return fallback
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def fetch_search(query: str) -> str:
|
|
334
|
+
return _curl_get_text(f"{BASE}/?s={quote_plus(query)}")
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def total_results(page: str) -> int | None:
|
|
338
|
+
match = re.search(r"([\d,]+)\s+total results", page)
|
|
339
|
+
return int(match.group(1).replace(",", "")) if match else None
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def search_page(query: str) -> dict:
|
|
343
|
+
"""Fetch + parse the first search results page into a JSON-able dict."""
|
|
344
|
+
page = fetch_search(query)
|
|
345
|
+
parser = ResultParser()
|
|
346
|
+
parser.feed(page)
|
|
347
|
+
return {"query": query, "total": total_results(page), "results": parser.results}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _search_cacheable(result: dict) -> bool:
|
|
351
|
+
# Cache hits; cache an empty result only when the page was clearly a real
|
|
352
|
+
# search page reporting a total (e.g. "0 total results").
|
|
353
|
+
return bool(result.get("results")) or result.get("total") is not None
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def item_details(item_id: str, item_url: str) -> dict:
|
|
357
|
+
"""Fetch + parse an item page into a JSON-able dict."""
|
|
358
|
+
page = _curl_get_text(item_url)
|
|
359
|
+
parser = ItemMetadataParser()
|
|
360
|
+
parser.feed(page)
|
|
361
|
+
title = " ".join(parser.title.split())
|
|
362
|
+
download_url = parser.download_url
|
|
363
|
+
if not download_url and item_id.startswith("IO_"):
|
|
364
|
+
download_url = f"{BASE}/download/file/{item_id}"
|
|
365
|
+
return {
|
|
366
|
+
"id": item_id,
|
|
367
|
+
"title": title or item_id,
|
|
368
|
+
"url": item_url,
|
|
369
|
+
"download_url": download_url,
|
|
370
|
+
"fields": [[k, v] for k, v in parser.fields],
|
|
371
|
+
"parsed": bool(title or parser.fields),
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
@click.group()
|
|
376
|
+
def cli() -> None:
|
|
377
|
+
"""Search Michiganology (Archives of Michigan digital collections)."""
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
@cli.command()
|
|
381
|
+
@click.argument("query")
|
|
382
|
+
@click.option("--limit", default=10, show_default=True, help="Max results to show (first page only).")
|
|
383
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
384
|
+
@cache_options
|
|
385
|
+
def search(query: str, limit: int, as_json: bool, refresh: bool, cache_ttl_hours: float | None) -> None:
|
|
386
|
+
"""Search all Michiganology collections, e.g. michiganology search Lincoln."""
|
|
387
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
388
|
+
data, hit = cached_call("search", {"query": query}, lambda: search_page(query),
|
|
389
|
+
refresh=refresh, ttl_hours=ttl, cacheable=_search_cacheable)
|
|
390
|
+
total = data.get("total")
|
|
391
|
+
results = list(data.get("results") or [])[:limit]
|
|
392
|
+
if as_json:
|
|
393
|
+
click.echo(json.dumps({"query": query, "total": total, "results": results,
|
|
394
|
+
"cache_hit": hit}, indent=2))
|
|
395
|
+
return
|
|
396
|
+
marker = " [cache]" if hit else ""
|
|
397
|
+
click.echo(f"Query: {query} | Total results: {total if total is not None else 'unknown'}{marker}")
|
|
398
|
+
if not results:
|
|
399
|
+
click.echo("No results on the first page.")
|
|
400
|
+
return
|
|
401
|
+
for item in results:
|
|
402
|
+
click.echo(f"- {item['title']}\n {item['url']}")
|
|
403
|
+
click.echo(f"({len(results)} of {total} shown; first page only)")
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
@cli.command()
|
|
407
|
+
@click.argument("url_or_id")
|
|
408
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
409
|
+
@cache_options
|
|
410
|
+
def get(url_or_id: str, as_json: bool, refresh: bool, cache_ttl_hours: float | None) -> None:
|
|
411
|
+
"""Inspect a Michiganology item page (Item Data fields and file download URL)."""
|
|
412
|
+
item_id, item_url = _resolve_item_ref(url_or_id)
|
|
413
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
414
|
+
data, hit = cached_call("get", {"id": item_id, "url": item_url},
|
|
415
|
+
lambda: item_details(item_id, item_url), refresh=refresh,
|
|
416
|
+
ttl_hours=ttl, cacheable=lambda r: bool(r.get("parsed")))
|
|
417
|
+
title = data["title"]
|
|
418
|
+
download_url = data.get("download_url")
|
|
419
|
+
fields = [(k, v) for k, v in data.get("fields") or []]
|
|
420
|
+
metadata: dict[str, str | list[str]] = {}
|
|
421
|
+
for key, val in fields:
|
|
422
|
+
if key in metadata:
|
|
423
|
+
prev = metadata[key]
|
|
424
|
+
metadata[key] = [*prev, val] if isinstance(prev, list) else [prev, val]
|
|
425
|
+
else:
|
|
426
|
+
metadata[key] = val
|
|
427
|
+
payload = {
|
|
428
|
+
"id": item_id,
|
|
429
|
+
"title": title,
|
|
430
|
+
"url": item_url,
|
|
431
|
+
"download_url": download_url,
|
|
432
|
+
"metadata": metadata,
|
|
433
|
+
"cache_hit": hit,
|
|
434
|
+
}
|
|
435
|
+
if as_json:
|
|
436
|
+
click.echo(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
437
|
+
return
|
|
438
|
+
click.echo(f"Item {item_id}: {title}{' [cache]' if hit else ''}")
|
|
439
|
+
click.echo(f" URL: {item_url}")
|
|
440
|
+
if download_url:
|
|
441
|
+
click.echo(f" Download: {download_url}")
|
|
442
|
+
for key, val in fields:
|
|
443
|
+
click.echo(f" {key}: {val}")
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
@cli.command()
|
|
447
|
+
@click.argument("url_or_id")
|
|
448
|
+
@click.option("--out", "-o", default=".", show_default=True, help="Output directory.")
|
|
449
|
+
@click.option("--filename", default=None, help="Override output filename (default: from Content-Disposition).")
|
|
450
|
+
def download(url_or_id: str, out: str, filename: str | None) -> None:
|
|
451
|
+
"""Download the full-resolution file for a Michiganology IO_ item."""
|
|
452
|
+
item_id, item_url = _resolve_item_ref(url_or_id)
|
|
453
|
+
if not item_id.startswith("IO_"):
|
|
454
|
+
raise click.ClickException(
|
|
455
|
+
f"{item_id} is a folder/collection object (SO_); pass an IO_ item URL or ID to download."
|
|
456
|
+
)
|
|
457
|
+
download_url = f"{BASE}/download/file/{item_id}"
|
|
458
|
+
curl = _require_curl()
|
|
459
|
+
out_dir = Path(out)
|
|
460
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
461
|
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
|
462
|
+
hdr_path = Path(tmp_dir) / "headers.txt"
|
|
463
|
+
body_path = Path(tmp_dir) / "body.bin"
|
|
464
|
+
try:
|
|
465
|
+
proc = subprocess.run(
|
|
466
|
+
[
|
|
467
|
+
curl, "-sSL", "-A", USER_AGENT, "--max-time", "120",
|
|
468
|
+
"-D", str(hdr_path), "-o", str(body_path),
|
|
469
|
+
"-w", "%{http_code}", download_url,
|
|
470
|
+
],
|
|
471
|
+
capture_output=True,
|
|
472
|
+
text=True,
|
|
473
|
+
timeout=130,
|
|
474
|
+
)
|
|
475
|
+
except (subprocess.SubprocessError, OSError) as exc:
|
|
476
|
+
raise click.ClickException(f"Michiganology download failed: {exc}") from exc
|
|
477
|
+
if proc.returncode != 0:
|
|
478
|
+
raise click.ClickException(
|
|
479
|
+
f"Michiganology download failed (curl exit {proc.returncode}): "
|
|
480
|
+
f"{proc.stderr.strip()[:300]}"
|
|
481
|
+
)
|
|
482
|
+
status = proc.stdout.strip()
|
|
483
|
+
if status != "200":
|
|
484
|
+
raise click.ClickException(
|
|
485
|
+
f"Michiganology download returned HTTP {status} for {download_url} (source page: {item_url})"
|
|
486
|
+
)
|
|
487
|
+
headers_text = hdr_path.read_text(encoding="utf-8", errors="replace")
|
|
488
|
+
chosen_name = filename or _filename_from_headers(headers_text, f"{item_id}.bin")
|
|
489
|
+
dest = out_dir / Path(chosen_name).name
|
|
490
|
+
dest.write_bytes(body_path.read_bytes())
|
|
491
|
+
click.echo(f"{dest} ({dest.stat().st_size} bytes)")
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
@cli.command()
|
|
495
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
496
|
+
def collections(as_json: bool) -> None:
|
|
497
|
+
"""List the Michiganology digital collections (verified 2026-11-24)."""
|
|
498
|
+
if as_json:
|
|
499
|
+
click.echo(json.dumps(
|
|
500
|
+
[{"name": name, "url": url} for name, url in COLLECTIONS], indent=2
|
|
501
|
+
))
|
|
502
|
+
return
|
|
503
|
+
for name, url in COLLECTIONS:
|
|
504
|
+
click.echo(f"- {name}\n {url}")
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
@cli.command()
|
|
508
|
+
@click.argument("query")
|
|
509
|
+
def url(query: str) -> None:
|
|
510
|
+
"""Print the shareable Michiganology search URL for a query."""
|
|
511
|
+
click.echo(f"{BASE}/?s={quote_plus(query)}")
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
if __name__ == "__main__":
|
|
515
|
+
cli()
|