@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,99 @@
1
+ ---
2
+ name: usgs-gnis
3
+ description: Look up historical and current U.S. place names in the USGS Geographic Names Information System (GNIS) via the bundled uv-based `gnis` CLI or the GNIS Domestic Names Search web app. Covers cached per-state bulk downloads, feature-name search, feature classes, coordinates, and defunct places. Use when a deed, memoir, or obituary names a place that no longer exists, or to pin a migration path to exact coordinates.
4
+ ---
5
+
6
+ # USGS GNIS (Geographic Names Information System)
7
+
8
+ This skill includes a standalone executable Python CLI at `skills/usgs-gnis/scripts/gnis` using a PEP 723 `#!/usr/bin/env -S uv run --script` shebang with inline dependencies (`click`, `httpx`). No virtualenv setup or API key is required.
9
+
10
+ - **What GNIS is:** the federal repository of official geographic names for the U.S., its territories, and Antarctica: natural features, populated places, post offices, schools, cemeteries, churches, and more, current and historical.
11
+ - **Access route:** there is **no documented public GNIS search API**. The GNIS Domestic Names Search web app is a JavaScript app whose backing services use authenticated tokens. The verified machine interface is the USGS staged-products bulk download (public S3, no key): per-state pipe-delimited text files plus national topical files. The CLI downloads a state file once, caches it, and searches locally.
12
+ - **Refresh cadence:** USGS refreshes the downloadable names data every other month.
13
+
14
+ ## Bundled CLI (`scripts/gnis`)
15
+
16
+ Path: `skills/usgs-gnis/scripts/gnis`
17
+
18
+ ### Persistent local disk cache
19
+
20
+ Downloaded state/historical files and `search` query results are cached atomically under `~/.cache/kinloom-gnis/` (overrideable via `KINLOOM_GNIS_CACHE_DIR`, with legacy `GNIS_CACHE_DIR` fallback) using advisory file locks (`fcntl.flock` on POSIX, safe fallback elsewhere) so concurrent processes never race on downloads and repeated searches return immediately with zero HTTP requests or re-parsing.
21
+
22
+ Cache layout:
23
+
24
+ - `<STATE>.txt` and `HistoricalFeatures.txt`: extracted pipe-delimited USGS tables.
25
+ - `_queries/<sha256>.json`: cached `search` query JSON keyed by canonical parameters with a 720-hour (30-day) default TTL (`--cache-ttl-hours` or `KINLOOM_GNIS_QUERY_TTL_HOURS`). Pass `--refresh` on `search`, `get`, or `download` to bypass the cache and re-download fresh USGS data.
26
+
27
+ ### Download a state file
28
+
29
+ ```bash
30
+ # Cache Illinois
31
+ skills/usgs-gnis/scripts/gnis download IL
32
+
33
+ # Cache California (about 2.7 MB zipped)
34
+ skills/usgs-gnis/scripts/gnis download CA
35
+ ```
36
+
37
+ Files land in `~/.cache/kinloom-gnis/<STATE>.txt` (override with `KINLOOM_GNIS_CACHE_DIR`).
38
+
39
+ ### Search feature names
40
+
41
+ ```bash
42
+ # Any feature in Illinois with "New Salem" in the name
43
+ skills/usgs-gnis/scripts/gnis search "New Salem" --state IL
44
+
45
+ # Exact name match, populated places only, in Sangamon County
46
+ skills/usgs-gnis/scripts/gnis search Springfield --state IL --exact --class "Populated Place" --county Sangamon
47
+
48
+ # JSON output for scripting
49
+ skills/usgs-gnis/scripts/gnis search Hannibal --state MO --json
50
+
51
+ # Defunct places (historical features file, national, downloaded on demand)
52
+ skills/usgs-gnis/scripts/gnis search "New Salem" --historical
53
+ ```
54
+
55
+ Search matches on `feature_name` (substring unless `--exact`). Output gives the GNIS feature ID, name, class, county, state, decimal latitude/longitude, and map name.
56
+
57
+ ### Look up one feature by ID
58
+
59
+ ```bash
60
+ skills/usgs-gnis/scripts/gnis get <feature-id> --state IL
61
+ skills/usgs-gnis/scripts/gnis get <feature-id> --state MO --json
62
+ ```
63
+
64
+ ### Open the web search app
65
+
66
+ ```bash
67
+ skills/usgs-gnis/scripts/gnis url "New Salem"
68
+ # Prints https://edits.nationalmap.gov/apps/gaz-domestic/public/search/names
69
+ # (the app has no stable query-string search URL; enter the name by hand)
70
+ ```
71
+
72
+ ## Website & download rules (verified live 2026-11-24)
73
+
74
+ - GNIS search app: `https://edits.nationalmap.gov/apps/gaz-domestic/public/search/names` (200, React app v2.3.1). From the app, up to 2,000 features may be downloaded to CSV. No sign-in is needed for public search.
75
+ - Downloads index: `https://www.usgs.gov/us-board-on-geographic-names/download-gnis-data`
76
+ - Per-state files: `https://prd-tnm.s3.amazonaws.com/StagedProducts/GeographicNames/DomesticNames/DomesticNames_<ST>_Text.zip`, where `<ST>` is the two-letter state/territory code (AK, AL, ..., WY, plus AS, DC, GU, MP, PR, VI). Verified: MI zip 1,014,149 bytes, CA zip 2,695,362 bytes.
77
+ - National topical files under `StagedProducts/GeographicNames/Topical/`, including `HistoricalFeatures_National_Text.zip` (defunct features), `AllNames_National_Text.zip`, `PopulatedPlaces_National_Text.zip`, `GovernmentUnits_National_Text.zip`, `FeatureDescriptionHistory_National_Text.zip`.
78
+ - File format (verified against live state files): a zip containing one pipe-delimited `.txt` with header `feature_id|feature_name|feature_class|state_name|state_numeric|county_name|county_numeric|map_name|date_created|date_edited|bgn_type|bgn_authority|bgn_date|prim_lat_dms|prim_long_dms|prim_lat_dec|prim_long_dec|source_lat_dms|source_long_dms|source_lat_dec|source_long_dec`. Full column documentation: `https://prd-tnm.s3.amazonaws.com/StagedProducts/GeographicNames/GNIS_file_format.pdf`.
79
+ - **Coordinates:** use `prim_lat_dec` / `prim_long_dec` (primary location). `source_*` coordinates are where the name was sourced, and can differ. Some rows carry `0.0, 0.0` for source coordinates; treat those as absent, not as a real location.
80
+ - **State files are not perfectly state-scoped:** border quads can include neighboring-state rows. Always check the `state_name` field on a hit, and filter by county.
81
+ - **No API key, no account.** The S3 downloads and the search app are public.
82
+
83
+ ### What was checked and not found
84
+
85
+ - The app's JavaScript bundle (`/apps/gaz-domestic/assets/index-*.js`, ~3.8 MB) was inspected 2026-11-24: `search/names` is only a client-side route, and no public `/api` search endpoint is exposed. The app's config (`env-config.js`) shows it uses secure tokens and DOI login for editing. Do not build against undocumented app endpoints; use the bulk downloads.
86
+ - The older USGS Search API (a JavaScript location-search widget library from the Texas Water Science Center) is a web widget, not a GNIS query API, and was not used.
87
+
88
+ ## Environment variables
89
+
90
+ - `KINLOOM_GNIS_CACHE_DIR`: where state text files and query results are cached (default `~/.cache/kinloom-gnis`; `GNIS_CACHE_DIR` is still accepted as a fallback).
91
+ - `KINLOOM_GNIS_QUERY_TTL_HOURS`: optional override for the `search` query cache TTL in hours (default `720`, 30 days).
92
+
93
+ ## Research workflow notes
94
+
95
+ - Start from the place as written in the source (deed, memoir, obituary), then check GNIS for the current name, variant names, feature class, and county: county boundaries and names change, and the county on a hit is the modern one.
96
+ - **Civil townships vs populated places:** rural townships are indexed with the suffix `"Township"` under feature class `Civil` (not `Populated Place`). When searching for a township name, omit `--exact` and `--class "Populated Place"`, or pass `--class Civil`.
97
+ - Defunct post offices and railroad stops usually appear as `Post Office` / `Locale` / historical features; if a state-file search comes up empty, retry with `--historical`.
98
+ - Record the GNIS `feature_id` alongside any place you cite in `data/`: it is the stable identifier when names collide (there are many repeated place names across states).
99
+ - Coordinates from GNIS place a feature, not a parcel. For the parcel itself, pair the GNIS hit with the BLM GLO patent's township/range/section (see the `blm-glo` skill).
@@ -0,0 +1,418 @@
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 USGS GNIS geographic names from the official staged-products downloads.
10
+
11
+ There is no documented public GNIS search API: the GNIS Domestic Names
12
+ Search web app is a JavaScript app backed by authenticated services.
13
+ This CLI downloads the USGS per-state pipe-delimited text files
14
+ (prd-tnm.s3.amazonaws.com) once, caches them, and searches locally.
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 sys
25
+ import time
26
+ import zipfile
27
+ from io import BytesIO
28
+ from pathlib import Path
29
+ from typing import Any, Iterator
30
+
31
+ import click
32
+ import httpx
33
+
34
+ S3_BASE = "https://prd-tnm.s3.amazonaws.com/StagedProducts/GeographicNames"
35
+ SEARCH_APP = "https://edits.nationalmap.gov/apps/gaz-domestic/public/search/names"
36
+ HEADERS = {"User-Agent": "kinloom/1.0 (genealogy research)"}
37
+ TIMEOUT = 120.0
38
+ DEFAULT_QUERY_TTL_HOURS = 720.0
39
+
40
+ STATE_CODES = {
41
+ "AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
42
+ "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME",
43
+ "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM",
44
+ "NV", "NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX",
45
+ "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY",
46
+ }
47
+
48
+
49
+ def cache_dir() -> Path:
50
+ override = os.environ.get("KINLOOM_GNIS_CACHE_DIR") or os.environ.get("GNIS_CACHE_DIR")
51
+ if override:
52
+ return Path(override).expanduser()
53
+ return Path.home() / ".cache" / "kinloom-gnis"
54
+
55
+
56
+ def resolve_query_ttl_hours(cli_ttl: float | None) -> float:
57
+ if cli_ttl is not None:
58
+ if not math.isfinite(cli_ttl) or cli_ttl < 0:
59
+ raise click.BadParameter(
60
+ f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0)."
61
+ )
62
+ return float(cli_ttl)
63
+ raw = os.environ.get("KINLOOM_GNIS_QUERY_TTL_HOURS")
64
+ if raw is not None and raw.strip():
65
+ try:
66
+ parsed = float(raw.strip())
67
+ except ValueError as exc:
68
+ raise click.BadParameter(
69
+ f"Invalid KINLOOM_GNIS_QUERY_TTL_HOURS value: {raw!r}."
70
+ ) from exc
71
+ if not math.isfinite(parsed) or parsed < 0:
72
+ raise click.BadParameter(
73
+ f"Invalid KINLOOM_GNIS_QUERY_TTL_HOURS value: {raw!r} (must be >= 0)."
74
+ )
75
+ return parsed
76
+ return DEFAULT_QUERY_TTL_HOURS
77
+
78
+
79
+ def resolve_safe_child(root: Path, filename: str) -> Path:
80
+ if (
81
+ not filename
82
+ or "\x00" in filename
83
+ or "/" in filename
84
+ or "\\" in filename
85
+ or ":" in filename
86
+ or filename in (".", "..")
87
+ ):
88
+ raise ValueError(f"Unsafe filename: {filename!r}")
89
+ root_resolved = root.resolve()
90
+ dest = (root_resolved / filename).resolve()
91
+ if dest == root_resolved or not dest.is_relative_to(root_resolved):
92
+ raise ValueError(f"Unsafe path escaping root: {filename!r}")
93
+ return dest
94
+
95
+
96
+ @contextmanager
97
+ def file_lock(lock_path: Path) -> Iterator[None]:
98
+ """Advisory exclusive file lock (POSIX flock) with safe fallback on non-POSIX."""
99
+ try:
100
+ import fcntl
101
+ except ImportError:
102
+ yield
103
+ return
104
+
105
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
106
+ with open(lock_path, "a+b") as lock_file:
107
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
108
+ try:
109
+ yield
110
+ finally:
111
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
112
+
113
+
114
+ def read_json_if_valid(path: Path) -> dict[str, Any] | None:
115
+ if not path.is_file():
116
+ return None
117
+ try:
118
+ parsed = json.loads(path.read_text(encoding="utf-8"))
119
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
120
+ return None
121
+ return parsed if isinstance(parsed, dict) else None
122
+
123
+
124
+ def atomic_write_bytes(dest: Path, data: bytes) -> None:
125
+ dest.parent.mkdir(parents=True, exist_ok=True)
126
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
127
+ try:
128
+ tmp.write_bytes(data)
129
+ os.replace(tmp, dest)
130
+ except Exception:
131
+ tmp.unlink(missing_ok=True)
132
+ raise
133
+
134
+
135
+ def atomic_write_text(dest: Path, text: str) -> None:
136
+ atomic_write_bytes(dest, text.encode("utf-8"))
137
+
138
+
139
+ def atomic_write_json(dest: Path, payload: Any) -> None:
140
+ atomic_write_text(dest, json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
141
+
142
+
143
+ def query_cache_path(canonical_params: dict[str, Any], cdir: Path) -> tuple[str, Path]:
144
+ canonical = json.dumps(
145
+ canonical_params, sort_keys=True, separators=(",", ":"), ensure_ascii=False
146
+ )
147
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
148
+ return digest, resolve_safe_child(cdir / "_queries", f"{digest}.json")
149
+
150
+
151
+ def _read_cached_search(
152
+ canonical_params: dict[str, Any], *, cdir: Path, ttl_hours: float
153
+ ) -> dict[str, Any] | None:
154
+ ttl_seconds = ttl_hours * 3600.0
155
+ if ttl_seconds <= 0:
156
+ return None
157
+ _, path = query_cache_path(canonical_params, cdir)
158
+ envelope = read_json_if_valid(path)
159
+ if envelope is None:
160
+ return None
161
+ cached_at = envelope.get("cached_at")
162
+ data = envelope.get("data")
163
+ if not isinstance(cached_at, (int, float)) or not isinstance(data, dict):
164
+ return None
165
+ if not isinstance(data.get("results"), list):
166
+ return None
167
+ if (time.time() - float(cached_at)) <= ttl_seconds:
168
+ return data
169
+ return None
170
+
171
+
172
+ def _state_zip_url(state: str) -> str:
173
+ return f"{S3_BASE}/DomesticNames/DomesticNames_{state}_Text.zip"
174
+
175
+
176
+ def _historical_zip_url() -> str:
177
+ return f"{S3_BASE}/Topical/HistoricalFeatures_National_Text.zip"
178
+
179
+
180
+ def _download_zip(url: str) -> bytes:
181
+ with httpx.Client(headers=HEADERS, timeout=TIMEOUT, follow_redirects=True) as client:
182
+ resp = client.get(url)
183
+ resp.raise_for_status()
184
+ return resp.content
185
+
186
+
187
+ def _extract_txt(zip_bytes: bytes) -> tuple[str, str]:
188
+ zf = zipfile.ZipFile(BytesIO(zip_bytes))
189
+ txt_names = [n for n in zf.namelist() if n.lower().endswith(".txt")]
190
+ if not txt_names:
191
+ raise click.ClickException(f"No .txt member in downloaded zip (members: {zf.namelist()})")
192
+ name = txt_names[0]
193
+ return name, zf.read(name).decode("utf-8-sig")
194
+
195
+
196
+ def _load_rows(path: Path) -> list[dict]:
197
+ lines = path.read_text(encoding="utf-8-sig").splitlines()
198
+ if not lines:
199
+ return []
200
+ header = [h.strip() for h in lines[0].split("|")]
201
+ rows = []
202
+ for line in lines[1:]:
203
+ if not line.strip():
204
+ continue
205
+ fields = line.split("|")
206
+ fields += [""] * (len(header) - len(fields))
207
+ rows.append(dict(zip(header, fields)))
208
+ return rows
209
+
210
+
211
+ def _ensure_state_file(state: str, *, refresh: bool = False) -> Path:
212
+ state = state.upper()
213
+ if state not in STATE_CODES:
214
+ raise click.ClickException(f"Unknown state/territory code: {state}")
215
+ cdir = cache_dir()
216
+ cdir.mkdir(parents=True, exist_ok=True)
217
+ path = resolve_safe_child(cdir, f"{state}.txt")
218
+ if path.exists() and not refresh:
219
+ return path
220
+ lock_path = resolve_safe_child(cdir / "_locks", f"state_{state}.lock")
221
+ with file_lock(lock_path):
222
+ if path.exists() and not refresh:
223
+ return path
224
+ click.echo(f"Downloading GNIS data for {state} ...", err=True)
225
+ _, text = _extract_txt(_download_zip(_state_zip_url(state)))
226
+ atomic_write_text(path, text)
227
+ click.echo(f"Cached {path} ({len(text.splitlines()) - 1} features)", err=True)
228
+ return path
229
+
230
+
231
+ def _ensure_historical_file(*, refresh: bool = False) -> Path:
232
+ cdir = cache_dir()
233
+ cdir.mkdir(parents=True, exist_ok=True)
234
+ path = resolve_safe_child(cdir, "HistoricalFeatures.txt")
235
+ if path.exists() and not refresh:
236
+ return path
237
+ lock_path = resolve_safe_child(cdir / "_locks", "historical.lock")
238
+ with file_lock(lock_path):
239
+ if path.exists() and not refresh:
240
+ return path
241
+ click.echo("Downloading national Historical Features file (large) ...", err=True)
242
+ _, text = _extract_txt(_download_zip(_historical_zip_url()))
243
+ atomic_write_text(path, text)
244
+ click.echo(f"Cached {path} ({len(text.splitlines()) - 1} features)", err=True)
245
+ return path
246
+
247
+
248
+ def _compact(row: dict) -> dict:
249
+ return {
250
+ "feature_id": row.get("feature_id"),
251
+ "feature_name": row.get("feature_name"),
252
+ "feature_class": row.get("feature_class"),
253
+ "state": row.get("state_name"),
254
+ "county": row.get("county_name"),
255
+ "map_name": row.get("map_name"),
256
+ "latitude": row.get("prim_lat_dec"),
257
+ "longitude": row.get("prim_long_dec"),
258
+ "date_created": row.get("date_created"),
259
+ "date_edited": row.get("date_edited"),
260
+ }
261
+
262
+
263
+ def _match(rows: list[dict], name: str, exact: bool, feature_class: str | None,
264
+ county: str | None) -> list[dict]:
265
+ needle = name.lower()
266
+ out = []
267
+ for row in rows:
268
+ fname = (row.get("feature_name") or "").lower()
269
+ if exact:
270
+ if fname != needle:
271
+ continue
272
+ elif needle not in fname:
273
+ continue
274
+ if feature_class and (row.get("feature_class") or "").lower() != feature_class.lower():
275
+ continue
276
+ if county and county.lower() not in (row.get("county_name") or "").lower():
277
+ continue
278
+ out.append(row)
279
+ return out
280
+
281
+
282
+ @click.group()
283
+ def cli() -> None:
284
+ """Search USGS GNIS geographic names (cached state downloads)."""
285
+
286
+
287
+ @cli.command()
288
+ @click.argument("state")
289
+ @click.option("--force", "--refresh", "force", is_flag=True, help="Re-download even if cached.")
290
+ def download(state, force):
291
+ """Download and cache the GNIS text file for a state (e.g. MI, CA, MO)."""
292
+ state = state.upper()
293
+ if state not in STATE_CODES:
294
+ raise click.ClickException(f"Unknown state/territory code: {state}")
295
+ path = resolve_safe_child(cache_dir(), f"{state}.txt")
296
+ if path.exists() and not force:
297
+ rows = _load_rows(path)
298
+ click.echo(f"Already cached: {path} ({len(rows)} features). Use --force or --refresh to re-download.")
299
+ return
300
+ path = _ensure_state_file(state, refresh=force)
301
+ rows = _load_rows(path)
302
+ click.echo(f"Cached {path} ({len(rows)} features)")
303
+
304
+
305
+ @cli.command()
306
+ @click.argument("name")
307
+ @click.option("--state", "-s", default=None,
308
+ help="State code to search (downloads and caches the state file if needed).")
309
+ @click.option("--exact", is_flag=True, help="Match the full feature name, not a substring.")
310
+ @click.option("--class", "feature_class", default=None, help="Filter by feature class, e.g. 'Populated Place'.")
311
+ @click.option("--county", default=None, help="Filter by county name (substring).")
312
+ @click.option("--historical", is_flag=True,
313
+ help="Search the national Historical Features file instead of a state file (defunct places, post offices).")
314
+ @click.option("--limit", "-n", default=20, show_default=True)
315
+ @click.option("--refresh", is_flag=True,
316
+ help="Bypass cached query and state data and re-download fresh GNIS data.")
317
+ @click.option("--cache-ttl-hours", type=float, default=None,
318
+ help="Override query cache TTL in hours (default: 720 or $KINLOOM_GNIS_QUERY_TTL_HOURS).")
319
+ @click.option("--json", "as_json", is_flag=True, help="Emit JSON instead of compact text.")
320
+ def search(name, state, exact, feature_class, county, historical, limit, refresh, cache_ttl_hours, as_json):
321
+ """Search feature names (substring unless --exact)."""
322
+ ttl_hours = resolve_query_ttl_hours(cache_ttl_hours)
323
+ normalized_state: str | None = None
324
+ if not historical:
325
+ if not state:
326
+ raise click.UsageError("Give --state (e.g. --state CA) or --historical.")
327
+ normalized_state = state.upper()
328
+ if normalized_state not in STATE_CODES:
329
+ raise click.ClickException(f"Unknown state/territory code: {normalized_state}")
330
+
331
+ cdir = cache_dir()
332
+ canonical_params: dict[str, Any] = {
333
+ "name": name,
334
+ "state": None if historical else normalized_state,
335
+ "exact": bool(exact),
336
+ "feature_class": feature_class,
337
+ "county": county,
338
+ "historical": bool(historical),
339
+ "limit": int(limit),
340
+ }
341
+
342
+ payload: dict[str, Any] | None = None
343
+ if not refresh:
344
+ payload = _read_cached_search(canonical_params, cdir=cdir, ttl_hours=ttl_hours)
345
+
346
+ if payload is None:
347
+ digest, cache_path = query_cache_path(canonical_params, cdir)
348
+ lock_path = resolve_safe_child(cdir / "_locks", f"query_{digest}.lock")
349
+ with file_lock(lock_path):
350
+ if not refresh:
351
+ payload = _read_cached_search(canonical_params, cdir=cdir, ttl_hours=ttl_hours)
352
+ if payload is None:
353
+ if historical:
354
+ rows = _load_rows(_ensure_historical_file(refresh=refresh))
355
+ source = "HistoricalFeatures (national)"
356
+ else:
357
+ assert normalized_state is not None
358
+ rows = _load_rows(_ensure_state_file(normalized_state, refresh=refresh))
359
+ source = f"DomesticNames_{normalized_state}"
360
+ matches = _match(rows, name, exact, feature_class, county)[:limit]
361
+ payload = {
362
+ "source": source,
363
+ "matches": len(matches),
364
+ "results": [_compact(r) for r in matches],
365
+ }
366
+ atomic_write_json(
367
+ cache_path,
368
+ {"cached_at": time.time(), "params": canonical_params, "data": payload},
369
+ )
370
+
371
+ if as_json:
372
+ click.echo(json.dumps(payload, indent=2, ensure_ascii=False))
373
+ return
374
+ click.echo(f"source: {payload['source']} | matches shown: {payload['matches']}")
375
+ for c in payload["results"]:
376
+ click.echo(f"- {c['feature_id']} | {c['feature_name']} ({c['feature_class']}) | "
377
+ f"{c['county']} County, {c['state']} | {c['latitude']}, {c['longitude']} | map: {c['map_name']}")
378
+
379
+
380
+ @cli.command()
381
+ @click.argument("feature_id")
382
+ @click.option("--state", "-s", default=None, help="State code (downloads and caches if needed).")
383
+ @click.option("--historical", is_flag=True, help="Look in the national Historical Features file.")
384
+ @click.option("--refresh", is_flag=True, help="Re-download the underlying GNIS file before lookup.")
385
+ @click.option("--json", "as_json", is_flag=True)
386
+ def get(feature_id, state, historical, refresh, as_json):
387
+ """Show one feature by its GNIS feature_id."""
388
+ if historical:
389
+ rows = _load_rows(_ensure_historical_file(refresh=refresh))
390
+ else:
391
+ if not state:
392
+ raise click.UsageError("Give --state or --historical.")
393
+ rows = _load_rows(_ensure_state_file(state, refresh=refresh))
394
+ for row in rows:
395
+ if (row.get("feature_id") or "") == str(feature_id):
396
+ if as_json:
397
+ click.echo(json.dumps(row, indent=2, ensure_ascii=False))
398
+ else:
399
+ for key, value in row.items():
400
+ if value != "":
401
+ click.echo(f"{key}: {value}")
402
+ return
403
+ click.echo(f"Feature {feature_id} not found in the searched file.", err=True)
404
+ sys.exit(1)
405
+
406
+
407
+ @cli.command()
408
+ @click.argument("name", required=False)
409
+ def url(name):
410
+ """Print the GNIS Domestic Names Search web app URL (open in a browser)."""
411
+ click.echo(SEARCH_APP)
412
+ if name:
413
+ click.echo(f"(Enter {name!r} in the Feature Name field; the app has no stable "
414
+ "query-string search URL.)")
415
+
416
+
417
+ if __name__ == "__main__":
418
+ cli()