@kinloom/cli 0.1.1 → 0.2.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 (101) hide show
  1. package/dist/assets/cached-ocr.py +556 -0
  2. package/dist/assets/ocr.md +52 -0
  3. package/dist/assets/prep-scan.md +59 -0
  4. package/dist/assets/prep-scan.py +891 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +94 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +268 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +129 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +879 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +120 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +373 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +100 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +250 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +116 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +520 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +110 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +194 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +123 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +358 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +111 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +346 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +100 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +528 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +118 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +934 -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 +118 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +585 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +90 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +432 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +93 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +441 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +101 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +391 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +89 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +254 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +104 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +466 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +148 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +219 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +383 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.js +1 -1
  49. package/dist/commands/ops/audit.d.ts +138 -0
  50. package/dist/commands/ops/audit.d.ts.map +1 -0
  51. package/dist/commands/ops/audit.js +867 -0
  52. package/dist/commands/ops/audit.js.map +1 -0
  53. package/dist/commands/ops/context.d.ts +100 -0
  54. package/dist/commands/ops/context.d.ts.map +1 -0
  55. package/dist/commands/ops/context.js +917 -0
  56. package/dist/commands/ops/context.js.map +1 -0
  57. package/dist/commands/ops/help.d.ts +6 -0
  58. package/dist/commands/ops/help.d.ts.map +1 -0
  59. package/dist/commands/ops/help.js +74 -0
  60. package/dist/commands/ops/help.js.map +1 -0
  61. package/dist/commands/ops/index.d.ts +6 -0
  62. package/dist/commands/ops/index.d.ts.map +1 -0
  63. package/dist/commands/ops/index.js +6 -0
  64. package/dist/commands/ops/index.js.map +1 -0
  65. package/dist/commands/ops/integrate.d.ts +56 -0
  66. package/dist/commands/ops/integrate.d.ts.map +1 -0
  67. package/dist/commands/ops/integrate.js +872 -0
  68. package/dist/commands/ops/integrate.js.map +1 -0
  69. package/dist/commands/ops/sync.d.ts +177 -0
  70. package/dist/commands/ops/sync.d.ts.map +1 -0
  71. package/dist/commands/ops/sync.js +1078 -0
  72. package/dist/commands/ops/sync.js.map +1 -0
  73. package/dist/commands/ops/telemetry.d.ts +79 -0
  74. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  75. package/dist/commands/ops/telemetry.js +249 -0
  76. package/dist/commands/ops/telemetry.js.map +1 -0
  77. package/dist/commands/records/help.d.ts +18 -0
  78. package/dist/commands/records/help.d.ts.map +1 -0
  79. package/dist/commands/records/help.js +174 -0
  80. package/dist/commands/records/help.js.map +1 -0
  81. package/dist/commands/records/index.d.ts +5 -0
  82. package/dist/commands/records/index.d.ts.map +1 -0
  83. package/dist/commands/records/index.js +5 -0
  84. package/dist/commands/records/index.js.map +1 -0
  85. package/dist/commands/records/registry.d.ts +32 -0
  86. package/dist/commands/records/registry.d.ts.map +1 -0
  87. package/dist/commands/records/registry.js +227 -0
  88. package/dist/commands/records/registry.js.map +1 -0
  89. package/dist/commands/records/resolve.d.ts +14 -0
  90. package/dist/commands/records/resolve.d.ts.map +1 -0
  91. package/dist/commands/records/resolve.js +61 -0
  92. package/dist/commands/records/resolve.js.map +1 -0
  93. package/dist/commands/records/runner.d.ts +25 -0
  94. package/dist/commands/records/runner.d.ts.map +1 -0
  95. package/dist/commands/records/runner.js +224 -0
  96. package/dist/commands/records/runner.js.map +1 -0
  97. package/dist/index.d.ts +2 -0
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +2 -0
  100. package/dist/index.js.map +1 -1
  101. package/package.json +3 -3
@@ -0,0 +1,520 @@
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = [
5
+ # "click>=8.1",
6
+ # "httpx>=0.27",
7
+ # ]
8
+ # ///
9
+ """Find a Grave CLI: search and read memorials, cemeteries, and places.
10
+
11
+ Uses the site's own GraphQL API (POST https://www.findagrave.com/orc/graphql),
12
+ verified live 2026-11-24. The API is undocumented and internal: no key or
13
+ login is needed, but it can change without notice. Requests are spaced
14
+ 0.3 s apart; bursts can trigger Cloudflare challenges.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import sys
21
+ import time
22
+ from pathlib import Path
23
+ from urllib.parse import urlencode
24
+
25
+ import click
26
+ import httpx
27
+
28
+ GRAPHQL_URL = "https://www.findagrave.com/orc/graphql"
29
+ WEBSITE_BASE = "https://www.findagrave.com"
30
+ USER_AGENT = (
31
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
32
+ "Chrome/131.0 Safari/537.36"
33
+ )
34
+ MIN_INTERVAL_S = 0.3
35
+ MONTHS = [
36
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
37
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
38
+ ]
39
+
40
+ SEARCH_QUERY = """
41
+ query($s: MemorialSearchInput) {
42
+ memorialSearch(search: $s) {
43
+ total
44
+ memorials {
45
+ id
46
+ name { first last maiden }
47
+ birth { date { year month day circa } place { names { name } } }
48
+ death { date { year month day circa } place { names { name } } }
49
+ cemetery { id names { name } memorialCount }
50
+ plot
51
+ hasGravePhoto
52
+ isVeteran
53
+ }
54
+ }
55
+ }
56
+ """
57
+
58
+ GET_QUERY = """
59
+ query($ids: [ID!]!) {
60
+ memorialsById(ids: $ids) {
61
+ id
62
+ name { first last maiden }
63
+ birth { date { year month day circa } place { names { name } } }
64
+ death { date { year month day circa } place { names { name } } }
65
+ cemetery { id names { name } memorialCount }
66
+ plot
67
+ inscription { value }
68
+ bio { value }
69
+ isVeteran
70
+ hasGravePhoto
71
+ hasPersonPhoto
72
+ dateCreated
73
+ dateModified
74
+ relationships { type yearMarried memorial { id name { first last } } }
75
+ photos(size: 50) { total photos { id path caption type } }
76
+ }
77
+ }
78
+ """
79
+
80
+ CEMETERY_QUERY = """
81
+ query($s: CemeterySearchInput) {
82
+ cemeteries(search: $s) {
83
+ total
84
+ cemeteries { id names { name } memorialCount }
85
+ }
86
+ }
87
+ """
88
+
89
+ CEMETERY_BY_ID_QUERY = """
90
+ query($ids: [ID!]) {
91
+ cemeteries(ids: $ids) {
92
+ total
93
+ cemeteries { id names { name } memorialCount }
94
+ }
95
+ }
96
+ """
97
+
98
+ PLACE_QUERY = """
99
+ query($s: LocationSearchInput) {
100
+ locationsByTypeahead(search: $s) {
101
+ total
102
+ locations {
103
+ __typename
104
+ ... on Location { id names { name } type }
105
+ ... on Cemetery { id names { name } memorialCount }
106
+ }
107
+ }
108
+ }
109
+ """
110
+
111
+
112
+ def gql(query: str, variables: dict) -> dict:
113
+ """Run one GraphQL query and return its data dict."""
114
+ time.sleep(MIN_INTERVAL_S)
115
+ headers = {
116
+ "Content-Type": "application/json",
117
+ "User-Agent": USER_AGENT,
118
+ "Accept": "application/json",
119
+ }
120
+ try:
121
+ with httpx.Client(timeout=30.0, follow_redirects=True) as client:
122
+ resp = client.post(
123
+ GRAPHQL_URL,
124
+ json={"query": query, "variables": variables},
125
+ headers=headers,
126
+ )
127
+ except httpx.HTTPError as exc:
128
+ click.echo(f"Request failed: {exc}", err=True)
129
+ raise SystemExit(1)
130
+ if resp.status_code == 403:
131
+ click.echo(
132
+ "Find a Grave returned 403 (Cloudflare challenge). "
133
+ "Wait a few minutes and retry, or use the website in a browser.",
134
+ err=True,
135
+ )
136
+ raise SystemExit(1)
137
+ if resp.status_code != 200:
138
+ click.echo(f"HTTP {resp.status_code} from {GRAPHQL_URL}", err=True)
139
+ raise SystemExit(1)
140
+ body = resp.json()
141
+ if body.get("errors"):
142
+ for err in body["errors"]:
143
+ click.echo(f"GraphQL error: {err.get('message')}", err=True)
144
+ raise SystemExit(1)
145
+ return body.get("data") or {}
146
+
147
+
148
+ def primary_name(memorial: dict) -> str:
149
+ names = memorial.get("name") or []
150
+ if not names:
151
+ return ""
152
+ first = names[0] or {}
153
+ parts = [first.get("first"), first.get("last")]
154
+ text = " ".join(p for p in parts if p)
155
+ maiden = first.get("maiden")
156
+ if maiden:
157
+ text += f" (nee {maiden})"
158
+ return text
159
+
160
+
161
+ def first_place_name(place: dict | None) -> str:
162
+ if not place:
163
+ return ""
164
+ names = place.get("names") or []
165
+ if not names:
166
+ return ""
167
+ return names[0].get("name") or ""
168
+
169
+
170
+ def fmt_date(date: dict | None) -> str:
171
+ if not date:
172
+ return ""
173
+ year = date.get("year")
174
+ month = date.get("month")
175
+ day = date.get("day")
176
+ if year is None:
177
+ return ""
178
+ text = str(year)
179
+ if month:
180
+ text = f"{MONTHS[month - 1]} {text}" if 1 <= month <= 12 else text
181
+ if day:
182
+ text = f"{day} {text}"
183
+ if date.get("circa"):
184
+ text = f"c. {text}"
185
+ return text
186
+
187
+
188
+ def fmt_event(event: dict | None) -> str:
189
+ if not event:
190
+ return ""
191
+ date = fmt_date(event.get("date"))
192
+ place = first_place_name(event.get("place"))
193
+ return ", ".join(p for p in (date, place) if p)
194
+
195
+
196
+ def fmt_cemetery(cemetery: dict | None) -> str:
197
+ if not cemetery:
198
+ return ""
199
+ names = cemetery.get("names") or []
200
+ return names[0].get("name") if names else ""
201
+
202
+
203
+ def memorial_url(memorial_id: str) -> str:
204
+ return f"{WEBSITE_BASE}/memorial/{memorial_id}"
205
+
206
+
207
+ def cemetery_url(cemetery_id: str) -> str:
208
+ return f"{WEBSITE_BASE}/cemetery/{cemetery_id}"
209
+
210
+
211
+ def emit(data: dict, as_json: bool) -> None:
212
+ if as_json:
213
+ click.echo(json.dumps(data, indent=2))
214
+
215
+
216
+ @click.group()
217
+ def cli() -> None:
218
+ """Search and read Find a Grave memorials, cemeteries, and places."""
219
+
220
+
221
+ @cli.command()
222
+ @click.option("--first", "first_name", default=None, help="First name.")
223
+ @click.option("--last", "last_name", default=None, help="Last name.")
224
+ @click.option("--birth-year", type=int, default=None)
225
+ @click.option("--death-year", type=int, default=None)
226
+ @click.option("--year-range", type=int, default=None,
227
+ help="Plus/minus years around a birth/death year.")
228
+ @click.option("--birth-year-filter", default=None,
229
+ help="before, after, exact, or unknown.")
230
+ @click.option("--death-year-filter", default=None,
231
+ help="before, after, exact, or unknown.")
232
+ @click.option("--cemetery-id", multiple=True, help="Repeatable.")
233
+ @click.option("--location-id", default=None,
234
+ help="Place id, e.g. city_<id> (see the place command).")
235
+ @click.option("--bio", default=None, help="Words in the biography.")
236
+ @click.option("--text", default=None, help="Words anywhere on the memorial.")
237
+ @click.option("--relative", default=None,
238
+ help="Name of a linked relative.")
239
+ @click.option("--exact/--no-exact", default=False,
240
+ help="Exact name match (default: site matching).")
241
+ @click.option("--include-maiden/--no-include-maiden", default=True,
242
+ help="Also match married women under maiden names.")
243
+ @click.option("--limit", type=int, default=10, show_default=True,
244
+ help="Rows per call (max 50).")
245
+ @click.option("--offset", type=int, default=0, show_default=True)
246
+ @click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
247
+ def search(first_name, last_name, birth_year, death_year, year_range,
248
+ birth_year_filter, death_year_filter, cemetery_id, location_id,
249
+ bio, text, relative, exact, include_maiden, limit, offset,
250
+ as_json):
251
+ """Search memorials. Example: search --first Abraham --last Lincoln."""
252
+ search_input: dict = {}
253
+ if first_name:
254
+ search_input["firstName"] = first_name
255
+ if last_name:
256
+ search_input["lastName"] = last_name
257
+ if birth_year is not None:
258
+ search_input["birthYear"] = birth_year
259
+ if death_year is not None:
260
+ search_input["deathYear"] = death_year
261
+ if year_range is not None:
262
+ if birth_year is not None:
263
+ search_input["birthYearRange"] = year_range
264
+ if death_year is not None:
265
+ search_input["deathYearRange"] = year_range
266
+ if birth_year_filter:
267
+ search_input["birthYearFilter"] = birth_year_filter
268
+ if death_year_filter:
269
+ search_input["deathYearFilter"] = death_year_filter
270
+ if cemetery_id:
271
+ search_input["cemeteryIds"] = list(cemetery_id)
272
+ if location_id:
273
+ search_input["locationId"] = location_id
274
+ if bio:
275
+ search_input["bio"] = bio
276
+ if text:
277
+ search_input["fullText"] = text
278
+ if relative:
279
+ search_input["linkedToName"] = relative
280
+ if exact:
281
+ search_input["exactName"] = True
282
+ search_input["includeMaidenName"] = include_maiden
283
+ search_input["from"] = offset
284
+ search_input["size"] = min(limit, 50)
285
+ data = gql(SEARCH_QUERY, {"s": search_input})
286
+ result = data.get("memorialSearch") or {}
287
+ if as_json:
288
+ click.echo(json.dumps(result, indent=2))
289
+ return
290
+ total = result.get("total")
291
+ memorials = result.get("memorials") or []
292
+ click.echo(f"{total} memorials")
293
+ for mem in memorials:
294
+ born = fmt_event(mem.get("birth"))
295
+ died = fmt_event(mem.get("death"))
296
+ cem = fmt_cemetery(mem.get("cemetery"))
297
+ photo = "yes" if mem.get("hasGravePhoto") else "no"
298
+ vet = " veteran" if mem.get("isVeteran") else ""
299
+ plot = mem.get("plot") or ""
300
+ row = (
301
+ f"{mem.get('id')} | {primary_name(mem)} | "
302
+ f"b. {born} | d. {died} | {cem} | plot: {plot} | "
303
+ f"grave photo: {photo}{vet} | {memorial_url(str(mem.get('id')))}"
304
+ )
305
+ click.echo(row)
306
+
307
+
308
+ @cli.command()
309
+ @click.argument("memorial_ids", nargs=-1, required=True)
310
+ @click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
311
+ @click.option("--full", is_flag=True,
312
+ help="Print full bio and inscription instead of truncated.")
313
+ @click.option("--photos", is_flag=True,
314
+ help="List photo ids, types, and image URLs.")
315
+ def get(memorial_ids, as_json, full, photos):
316
+ """Read one or more memorials in full by memorial id."""
317
+ data = gql(GET_QUERY, {"ids": list(memorial_ids)})
318
+ memorials = data.get("memorialsById") or []
319
+ if as_json:
320
+ click.echo(json.dumps(memorials, indent=2))
321
+ return
322
+ for mem in memorials:
323
+ mid = str(mem.get("id"))
324
+ click.echo(f"Memorial {mid}: {primary_name(mem)}")
325
+ click.echo(f" URL: {memorial_url(mid)}")
326
+ born = fmt_event(mem.get("birth"))
327
+ died = fmt_event(mem.get("death"))
328
+ if born:
329
+ click.echo(f" Born: {born}")
330
+ if died:
331
+ click.echo(f" Died: {died}")
332
+ cem = mem.get("cemetery") or {}
333
+ cem_name = fmt_cemetery(cem)
334
+ if cem_name:
335
+ click.echo(f" Cemetery: {cem_name} ({cem.get('id')})")
336
+ if mem.get("plot"):
337
+ click.echo(f" Plot: {mem.get('plot')}")
338
+ click.echo(
339
+ f" Veteran: {'yes' if mem.get('isVeteran') else 'no'} | "
340
+ f"Grave photo: {'yes' if mem.get('hasGravePhoto') else 'no'} | "
341
+ f"Photos: {(mem.get('photos') or {}).get('total')}"
342
+ )
343
+ inscription = (mem.get("inscription") or {}).get("value")
344
+ bio = (mem.get("bio") or {}).get("value")
345
+ if inscription:
346
+ shown = inscription if full else inscription[:500]
347
+ click.echo(f" Inscription: {shown}")
348
+ if bio:
349
+ shown = bio if full else bio[:500]
350
+ click.echo(f" Bio: {shown}")
351
+ relations = mem.get("relationships") or []
352
+ if relations:
353
+ click.echo(" Relationships:")
354
+ for rel in relations:
355
+ target = rel.get("memorial") or {}
356
+ target_name = primary_name(target)
357
+ click.echo(
358
+ f" {rel.get('type')}: {target_name} "
359
+ f"({target.get('id')})"
360
+ )
361
+ if photos:
362
+ photo_list = (mem.get("photos") or {}).get("photos") or []
363
+ if photo_list:
364
+ click.echo(" Photos:")
365
+ for photo in photo_list:
366
+ click.echo(
367
+ f" {photo.get('id')} | {photo.get('type')} | "
368
+ f"{photo.get('path')}"
369
+ )
370
+ if mem.get("dateCreated"):
371
+ click.echo(
372
+ f" Created: {mem.get('dateCreated')} | "
373
+ f"Modified: {mem.get('dateModified')}"
374
+ )
375
+
376
+
377
+ @cli.command()
378
+ @click.option("--name", default=None, help="Cemetery name to search.")
379
+ @click.option("--id", "cemetery_id", default=None,
380
+ help="Read one cemetery by id.")
381
+ @click.option("--place", default=None,
382
+ help="Containing place name, e.g. 'Sangamon County, Illinois'.")
383
+ @click.option("--limit", type=int, default=10, show_default=True)
384
+ @click.option("--offset", type=int, default=0, show_default=True)
385
+ @click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
386
+ def cemetery(name, cemetery_id, place, limit, offset, as_json):
387
+ """Search cemeteries by name, or read one by id."""
388
+ if cemetery_id:
389
+ data = gql(CEMETERY_BY_ID_QUERY, {"ids": [cemetery_id]})
390
+ else:
391
+ if not name:
392
+ raise click.UsageError("Pass --name or --id.")
393
+ search_input: dict = {"name": name}
394
+ if place:
395
+ search_input["containingLocationName"] = place
396
+ search_input["from"] = offset
397
+ search_input["size"] = min(limit, 100)
398
+ data = gql(CEMETERY_QUERY, {"s": search_input})
399
+ result = data.get("cemeteries") or {}
400
+ if as_json:
401
+ click.echo(json.dumps(result, indent=2))
402
+ return
403
+ click.echo(f"{result.get('total')} cemeteries")
404
+ for cem in result.get("cemeteries") or []:
405
+ names = cem.get("names") or []
406
+ shown = names[0].get("name") if names else ""
407
+ extra = ""
408
+ if len(names) > 1:
409
+ extra = " (also: " + ", ".join(n.get("name") for n in names[1:]) + ")"
410
+ click.echo(
411
+ f"{cem.get('id')} | {shown}{extra} | "
412
+ f"{cem.get('memorialCount')} memorials | "
413
+ f"{cemetery_url(str(cem.get('id')))}"
414
+ )
415
+
416
+
417
+ @cli.command()
418
+ @click.option("--name", required=True, help="Place name, e.g. Springfield.")
419
+ @click.option("--limit", type=int, default=10, show_default=True)
420
+ @click.option("--json", "as_json", is_flag=True, help="Full JSON output.")
421
+ def place(name, limit, as_json):
422
+ """Resolve a place name to Find a Grave place ids.
423
+
424
+ Use the returned id (e.g. city_<id>) with search --location-id.
425
+ """
426
+ data = gql(PLACE_QUERY, {"s": {"name": name, "size": min(limit, 50)}})
427
+ result = data.get("locationsByTypeahead") or {}
428
+ if as_json:
429
+ click.echo(json.dumps(result, indent=2))
430
+ return
431
+ click.echo(f"{result.get('total')} places")
432
+ for loc in result.get("locations") or []:
433
+ names = loc.get("names") or []
434
+ shown = names[0].get("name") if names else ""
435
+ kind = loc.get("__typename")
436
+ count = loc.get("memorialCount")
437
+ suffix = f" | {count} memorials" if count is not None else ""
438
+ click.echo(f"{loc.get('id')} | {kind} | {shown}{suffix}")
439
+
440
+
441
+ @cli.command()
442
+ @click.argument("memorial_id")
443
+ @click.option("--out", default=".", show_default=True,
444
+ help="Directory to save photos into.")
445
+ @click.option("--type", "photo_type", default=None,
446
+ help="Only download this photo type, e.g. Grave.")
447
+ @click.option("--prefix", default=None,
448
+ help="Optional filename prefix, e.g. 'lincoln-abraham' -> '<prefix>_<photo-id>.jpg'.")
449
+ @click.option("--metadata", "save_metadata", is_flag=True,
450
+ help="Also write a sidecar JSON file with memorial and photo provenance.")
451
+ def photo(memorial_id, out, photo_type, prefix, save_metadata):
452
+ """Download a memorial's photos (grave, portrait, family, other)."""
453
+ data = gql(GET_QUERY, {"ids": [memorial_id]})
454
+ memorials = data.get("memorialsById") or []
455
+ if not memorials:
456
+ click.echo(f"No memorial found with id {memorial_id}", err=True)
457
+ raise SystemExit(1)
458
+ memorial = memorials[0]
459
+ photo_list = (memorial.get("photos") or {}).get("photos") or []
460
+ if photo_type:
461
+ photo_list = [p for p in photo_list if p.get("type") == photo_type]
462
+ if not photo_list:
463
+ click.echo("No photos found.")
464
+ return
465
+ out_dir = Path(out)
466
+ out_dir.mkdir(parents=True, exist_ok=True)
467
+ stem_prefix = f"{prefix.strip('_')}_" if prefix else ""
468
+ saved_items = []
469
+ with httpx.Client(timeout=60.0, follow_redirects=True) as client:
470
+ for item in photo_list:
471
+ url = item.get("path") or ""
472
+ suffix = Path(url.split("?")[0]).suffix or ".jpg"
473
+ dest = out_dir / f"{stem_prefix}{item.get('id')}{suffix}"
474
+ resp = client.get(url, headers={"User-Agent": USER_AGENT})
475
+ resp.raise_for_status()
476
+ dest.write_bytes(resp.content)
477
+ click.echo(f"{dest} ({len(resp.content)} bytes)")
478
+ saved_items.append({
479
+ "id": item.get("id"),
480
+ "type": item.get("type"),
481
+ "caption": item.get("caption"),
482
+ "url": url,
483
+ "file": dest.name,
484
+ })
485
+ if save_metadata:
486
+ meta_path = out_dir / f"{stem_prefix}{memorial_id}.metadata.json"
487
+ meta_payload = {
488
+ "memorial_id": str(memorial.get("id")),
489
+ "name": primary_name(memorial),
490
+ "url": memorial_url(str(memorial.get("id"))),
491
+ "cemetery": fmt_cemetery(memorial.get("cemetery")),
492
+ "plot": memorial.get("plot"),
493
+ "photos": saved_items,
494
+ }
495
+ meta_path.write_text(json.dumps(meta_payload, indent=2) + "\n", encoding="utf-8")
496
+ click.echo(f"{meta_path} (metadata)")
497
+
498
+
499
+ @cli.command()
500
+ @click.option("--first", "first_name", default=None)
501
+ @click.option("--last", "last_name", default=None)
502
+ @click.option("--birth-year", type=int, default=None)
503
+ @click.option("--death-year", type=int, default=None)
504
+ def url(first_name, last_name, birth_year, death_year):
505
+ """Print the website search URL for a name (open it in a browser)."""
506
+ params = []
507
+ if first_name:
508
+ params.append(("firstname", first_name))
509
+ if last_name:
510
+ params.append(("lastname", last_name))
511
+ if birth_year is not None:
512
+ params.append(("birthyear", str(birth_year)))
513
+ if death_year is not None:
514
+ params.append(("deathyear", str(death_year)))
515
+ base = f"{WEBSITE_BASE}/memorial/search"
516
+ click.echo(f"{base}?{urlencode(params)}" if params else base)
517
+
518
+
519
+ if __name__ == "__main__":
520
+ cli()
@@ -0,0 +1,110 @@
1
+ ---
2
+ name: hathitrust
3
+ description: Search HathiTrust Digital Library for out-of-copyright county histories, regimental rosters, and published genealogies via the bundled uv-based `hathi` CLI (no key needed), the catalog website, or the Data API with a key. Covers the Bibliographic API by identifier, catalog search URL patterns, rights (Full view vs Limited search-only), and worked examples. Use when checking whether a book is in HathiTrust, reading its rights and volume list, or finding a readable copy.
4
+ ---
5
+
6
+ # HathiTrust Digital Library
7
+
8
+ This skill includes a standalone executable Python CLI at `skills/hathitrust/scripts/hathi` 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 for the Bibliographic API or the catalog search URLs.
9
+
10
+ - **Bibliographic API (no key, no login):** returns bibliographic, rights, and volume information for a known identifier (OCLC, LCCN, ISBN, ISSN, HathiTrust ID, record number). This is what the CLI uses. It is identifier lookup only: it cannot keyword-search by title or author.
11
+ - **Catalog website (no login for searching):** keyword search by title, author, subject, or all fields. Use the `hathi url` command to build a verified search URL and open it in a browser.
12
+ - **Full-text search (login):** searching inside the text of volumes needs a partner-institution login or a free University of Michigan "Friend" account. The CLI does not cover it.
13
+ - **Data API (key needed):** page images, OCR text, and whole-volume packages need an access key from the Key Generation Service at `https://babel.hathitrust.org/cgi/kgs/request`. The CLI does not implement it; see below.
14
+
15
+ ## Bundled CLI (`scripts/hathi`)
16
+
17
+ Path: `skills/hathitrust/scripts/hathi` (note the short binary name `hathi`, not `hathitrust`).
18
+
19
+ ### Look up a record by identifier (Bibliographic API)
20
+
21
+ ```bash
22
+ # Official HathiTrust Bib API example (OCLC 424023)
23
+ skills/hathitrust/scripts/hathi bib oclc 424023
24
+
25
+ # Same record by its 9-digit HathiTrust record number
26
+ skills/hathitrust/scripts/hathi bib recordnumber 000578050
27
+
28
+ # One volume by its HathiTrust ID, with full MARC-XML
29
+ skills/hathitrust/scripts/hathi bib htid <htid> --full
30
+
31
+ # Several identifiers in one call (fetched one at a time, merged output)
32
+ skills/hathitrust/scripts/hathi bib --id oclc:424023 --id recordnumber:000578050
33
+
34
+ # Raw JSON exactly as the API returned it
35
+ skills/hathitrust/scripts/hathi bib oclc 424023 --json
36
+ ```
37
+
38
+ Identifier types: `oclc`, `lccn`, `issn`, `isbn`, `htid`, `recordnumber`. Values are URL-encoded by the CLI (LCCNs can contain spaces and slashes). A lookup that finds nothing prints empty `records` / `items` (the API returns `{ "records": {}, "items": [] }`, not an error), so check for that before concluding a title is absent under a different identifier.
39
+
40
+ Compact output keeps title, record URL, publish dates, identifiers, and for each item: originating library, HathiTrust ID, rights string, and item URL. `--full` adds the complete MARC-XML for the record.
41
+
42
+ ### Build a verified catalog search URL
43
+
44
+ ```bash
45
+ # Title search (open the printed URL in a browser)
46
+ skills/hathitrust/scripts/hathi url "Abraham Lincoln" --type title
47
+
48
+ # Author search
49
+ skills/hathitrust/scripts/hathi url "Douglass, Frederick" --type author
50
+
51
+ # Keyword search across all fields
52
+ skills/hathitrust/scripts/hathi url "Clara Barton" --type all
53
+ ```
54
+
55
+ This only prints the URL; it does not fetch results. Fetching catalog search HTML from a server is unreliable (Cloudflare challenges curl intermittently; see "Verified live"), so run the search in a real browser.
56
+
57
+ ## Website search and URL rules (verified live 2026-11-24)
58
+
59
+ - Catalog search: `https://catalog.hathitrust.org/Search/Home?lookfor=<query>&type=<type>&inst=`
60
+ - `lookfor` is the URL-encoded query. `type` is `all`, `title`, `author`, or `subject`. `inst=` is left empty when no partner institution is selected.
61
+ - Verified URL patterns:
62
+ - Author: `https://catalog.hathitrust.org/Search/Home?lookfor=%22Douglass%2C+Frederick%22&type=author&inst=`
63
+ - Subject: `https://catalog.hathitrust.org/Search/Home?lookfor=%22+Astrolabes%22&type=subject&inst=`
64
+ - `type=all` returned HTTP 200 with a results page in a live fetch on 2026-11-24. `type=title` is the catalog's field name for title search (per HathiTrust library guides) but a live fetch of a title search on the same day was met with a Cloudflare challenge (403), so treat `type=title` as documented and open it in a browser.
65
+ - Catalog record page: `https://catalog.hathitrust.org/Record/<9-digit-record-number>`, for example `https://catalog.hathitrust.org/Record/000578050`.
66
+ - Item (PageTurner) page: `https://babel.hathitrust.org/cgi/pt?id=<htid>`, or the persistent form `https://hdl.handle.net/2027/<htid>`.
67
+ - Search tips: use the catalog search for descriptive data (title, author, date); use full-text search for words inside a volume. Filter results by Full View to show only volumes readable online.
68
+
69
+ ## Bibliographic API reference (no key)
70
+
71
+ - Docs: `https://www.hathitrust.org/bib_api` and `https://www.hathitrust.org/member-libraries/resources-for-librarians/improve-discovery/integrate-records/`
72
+ - Brief: `https://catalog.hathitrust.org/api/volumes/brief/<id-type>/<id-value>.json`
73
+ - Full (adds complete MARC-XML): `https://catalog.hathitrust.org/api/volumes/full/<id-type>/<id-value>.json`
74
+ - Id types: `oclc` (digits only), `lccn`, `issn`, `isbn` (ISBN-10 is searched as both ISBN-10 and ISBN-13), `htid` (for example `mdp.39015058510069`), `recordnumber` (9-digit HathiTrust record number, also the `ht_bib_key` in the HathiFiles).
75
+ - Response shape: `records` keyed by record number (recordURL, titles, isbns, issns, oclcs, lccns, publishDates, plus `marc-xml` for full), and `items` (orig, fromRecord, htid, itemURL, rightsCode, lastUpdate, enumcron, usRightsString).
76
+ - Intended for small numbers of items at a time (multi-id form supports up to 20 records). Bulk retrieval uses OAI or the HathiFiles tab-delimited inventory files; do not bulk-scrape the Bib API.
77
+
78
+ ## Rights: what you can actually read
79
+
80
+ The `usRightsString` on each item decides readability:
81
+
82
+ - `Full view`: public domain (or otherwise open). Readable online by anyone, no login.
83
+ - `Limited (search-only)`: in copyright or undetermined. Searchable, but pages are not readable online without a partner-institution login.
84
+ - Common `rightsCode` values: `pd` (public domain), `pdus` (public domain in the US only), `ic` (in copyright), `und` (undetermined), `icus` (in copyright in the US), plus Creative Commons codes (`cc-by-4.0`, etc.).
85
+
86
+ Check the rights string before promising a readable copy. A title can be in HathiTrust and still not be readable online.
87
+
88
+ ## Data API (key needed, not in the CLI)
89
+
90
+ - Docs: `https://www.hathitrust.org/data_api` (Data API v2, revised 26 May 2015).
91
+ - What it returns: page images, OCR text, structural metadata, and in some cases whole-volume packages, plus metadata resources.
92
+ - Access: metadata resources are unrestricted; content (data) resources vary. Two routes: the web client at `https://babel.hathitrust.org/cgi/htdc` (needs login; non-members use a University of Michigan "Friend" account), or programmatic access with a key from the Key Generation Service at `https://babel.hathitrust.org/cgi/kgs/request`.
93
+ - URL scheme: `https://babel.hathitrust.org/cgi/htd/<resource>/<id>[/<fileid|seq>]`.
94
+ - The CLI does not implement the Data API. If a Full View volume is needed as OCR text, first try the item URL in a browser; request a key only if programmatic bulk access is genuinely needed.
95
+
96
+ ## Environment variables
97
+
98
+ - None. The Bibliographic API needs no key and the CLI reads no environment variables.
99
+
100
+ ## Research workflow notes
101
+
102
+ - **County histories and regimental rosters:** these are usually pre-1929 and therefore often `Full view`. Search the catalog by title or subject, then confirm `usRightsString` is `Full view` with `hathi bib` before linking a readable copy. Use the HathiTrust record number as the stable citation, not the item URL alone, since items are per-scan.
103
+ - **Check WorldCat OCLC numbers carefully:** do not assume a title is in HathiTrust from a WorldCat listing alone, because WorldCat OCLC numbers and HathiTrust holdings differ. Confirm any hit with `hathi bib` before citing it; if HathiTrust returns empty records, check Internet Archive (`archive-org` skill) for an alternate scan.
104
+
105
+ ## Verified live 2026-11-24
106
+
107
+ - Bib API brief `oclc/424023` returns 200 JSON: record `000578050`, "Infinite series", 1962 (the documentation's own example).
108
+ - Bib API full `oclc/424023` returns 200 JSON including `marc-xml`.
109
+ - Catalog search `type=all` returned 200 HTML in one live fetch; subsequent fetches of catalog search pages and record pages returned 403 Cloudflare challenge pages (about 5.7 KB). The Bib API was reliable on every attempt; catalog HTML was not. That is why the CLI looks records up through the Bib API and only builds catalog search URLs for a real browser instead of scraping result pages.
110
+ - Full-text Large Scale Search (`https://babel.hathitrust.org/cgi/ls?a=srchls&q1=...`) returns 403 unauthenticated, so full-text search is documented as login-only and is not in the CLI.