@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,103 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: acpl-persi
|
|
3
|
+
description: Search the Allen County Public Library Genealogy Center's free PERSI (Periodical Source Index) via the bundled `persi` CLI or the website, to find articles in county historical society newsletters and other genealogy periodicals. Covers CLI usage, the three search modes (surname, article title, location), what PERSI is and is not, getting article copies, and planning an in-person visit to Fort Wayne, Indiana. Use when hunting periodical citations for a surname or place, or when a lead points to a society newsletter.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# ACPL PERSI
|
|
7
|
+
|
|
8
|
+
This skill includes a standalone executable Python CLI at `skills/acpl-persi/scripts/persi` 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 PERSI is:** the Periodical Source Index, produced by the staff of The Genealogy Center of the Allen County Public Library (ACPL), Fort Wayne, Indiana. It is the largest subject index to genealogy and local history periodicals, with more than 3.2 million citations to articles in 11,000+ periodical titles from local, state, national, and international societies.
|
|
11
|
+
- **What it is not:** a full-text archive. A hit is a citation: article title, periodical, year, publisher. PERSI indexes article titles, not article contents, so search for topics and surnames around an ancestor's life, not for a person's full story. Full text comes from the holding library, the publisher, WorldCat, or the Genealogy Center's copy service.
|
|
12
|
+
- **Cost:** free to search. No account, sign-in, or subscription is needed. PERSI was previously on Ancestry and Findmypast behind paywalls; ACPL has hosted it free on its own site since 2022.
|
|
13
|
+
|
|
14
|
+
## Bundled CLI (`scripts/persi`)
|
|
15
|
+
|
|
16
|
+
Path: `skills/acpl-persi/scripts/persi`
|
|
17
|
+
|
|
18
|
+
### Search by surname
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
# Lincoln articles, first 25 hits (persi search <Surname> is also accepted as an alias)
|
|
22
|
+
skills/acpl-persi/scripts/persi surname Lincoln
|
|
23
|
+
|
|
24
|
+
# JSON output, 50 hits
|
|
25
|
+
skills/acpl-persi/scripts/persi surname Lincoln --limit 50 --json
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Note: PERSI's surname and article-title forms do **not** accept a `--state` filter; use `persi location --state <ST>` for state/county category counts.
|
|
29
|
+
|
|
30
|
+
### Search by article-title keyword
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
skills/acpl-persi/scripts/persi title Lincoln --limit 25
|
|
34
|
+
skills/acpl-persi/scripts/persi title "Clara Barton"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Search by location (category counts)
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
# Illinois statewide: returns article counts per category, not articles
|
|
41
|
+
skills/acpl-persi/scripts/persi location --state IL
|
|
42
|
+
|
|
43
|
+
# A single county (county name as PERSI lists it; blank means statewide)
|
|
44
|
+
skills/acpl-persi/scripts/persi location --state IL --county Sangamon
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The location search returns counts per category (for example History, Cemeteries, Military Records, Census Records, Court Records, Deeds, Directories, Land Records, Maps). Pick a category on the website to drill into its articles; the CLI does not drill down because the drill-down links are session pages, not a stable pattern.
|
|
48
|
+
|
|
49
|
+
### Website search page for a mode
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
skills/acpl-persi/scripts/persi url surname
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
PERSI result pages are POST forms, so there is no shareable result URL. This prints the search form URL instead.
|
|
56
|
+
|
|
57
|
+
## Website search and form rules (verified live 2026-11-24)
|
|
58
|
+
|
|
59
|
+
- Home: `https://www.genealogycenter.info/persi/`
|
|
60
|
+
- Surname form: `https://www.genealogycenter.info/search_persisurname.php`, POST to `results_persisurname.php` with fields `surname`, `sort=title`, `submit=Search`.
|
|
61
|
+
- Article-title form: `https://www.genealogycenter.info/search_persiarttitle.php`, POST to `results_persiarttitle.php` with fields `keyword`, `sort=title`, `submit=Search`.
|
|
62
|
+
- Location form: `https://www.genealogycenter.info/search_persilocation.php`, POST to `results_persilocation.php` with fields `subloc=USA`, `cosearch=USA`, `usloc=<two-letter state code>`, `county=<name or blank>`, `submit=Search`. The state dropdown uses two-letter codes (`IL`, `CA`, `MO`, `GEN` for US general); the county dropdown is populated by JavaScript after a state is picked, so on the website pick the state first, then the county.
|
|
63
|
+
- Results render as a DataTable with columns Article Title, Periodical, Year Published, Publisher. Some rows carry a free-online icon linking directly to a digitized, copyright-clear issue; ACPL adds these links gradually as it finds issues online.
|
|
64
|
+
- No wildcards are available. Quoted phrases work in the search boxes.
|
|
65
|
+
- There is no public PERSI API. Do not invent one; the POST forms above are the machine interface.
|
|
66
|
+
|
|
67
|
+
## Getting the article after a hit
|
|
68
|
+
|
|
69
|
+
1. Check the row for a free-online link first; if present, the issue is one click away.
|
|
70
|
+
2. Search the periodical title on WorldCat to find a holding library near you.
|
|
71
|
+
3. Contact the publishing society directly; many sell back issues cheaply.
|
|
72
|
+
4. Order a copy from the Genealogy Center: the results page links to the article order form. The old form PDF at `acpl.lib.in.us/images/Documents/Gendocs/Forms/articlerequest.pdf` returned 404 on 2026-11-24, so use the link on the live results page and confirm the current fee there before quoting a price. Older guides cite $7.50 per order (up to 6 articles) plus $0.20 per page with a 6-8 week turnaround; treat that as stale until re-confirmed.
|
|
73
|
+
5. In person, the Genealogy Center holds the periodicals indexed in PERSI, so a visit resolves the citation on the spot.
|
|
74
|
+
|
|
75
|
+
## In-person visit
|
|
76
|
+
|
|
77
|
+
- **Genealogy Center, Allen County Public Library, 900 Library Plaza, Fort Wayne, IN 46801.** Phone 260-421-1225, email Genealogy@ACPL.Info.
|
|
78
|
+
- The Center holds more than 558,000 printed volumes and 795,800 microtext items, one of the largest physical genealogy collections in North America.
|
|
79
|
+
- Hours change; confirm on `https://genealogycenter.org` (redirects to the ACPL genealogy pages) before visiting.
|
|
80
|
+
- Beyond PERSI, the Center's free online databases total over 6 million records and images, including Allen County, Indiana resources (obituaries, cemeteries, marriages, deaths, courthouse records) and an African American gateway.
|
|
81
|
+
|
|
82
|
+
## Research workflow
|
|
83
|
+
|
|
84
|
+
1. `persi surname <Surname>` for the broad sweep; note periodical, year, and publisher for every plausible hit.
|
|
85
|
+
2. `persi title <Keyword>` catches articles whose title mentions a surname, place, or historical event but whose surname indexing differs.
|
|
86
|
+
3. `persi location --state <ST>` (then `--county <County>`) for place-first hunting; the Cemeteries, Court Records, and History categories are often the strongest leads.
|
|
87
|
+
4. Repeat across each state along a family's migration path.
|
|
88
|
+
5. Record each citation in `data/` with periodical, volume, issue, year, and ACPL call number when shown; mark whether a free-online link existed.
|
|
89
|
+
|
|
90
|
+
## Disk cache and environment variables
|
|
91
|
+
|
|
92
|
+
`surname`, `title`, `location`, and `search` cache successful non-empty responses on disk under `~/.cache/kinloom-persi/` (default TTL `168` hours, advisory `flock` per cache key, atomic temp-file writes). HTTP errors and empty responses are never cached.
|
|
93
|
+
|
|
94
|
+
- `--refresh`: bypass cached reads and write the fresh response to disk.
|
|
95
|
+
- `--cache-ttl-hours <hours>`: override TTL for one call (`0` disables cached reads).
|
|
96
|
+
- `KINLOOM_PERSI_CACHE_DIR`: override the cache directory path.
|
|
97
|
+
- `KINLOOM_PERSI_CACHE_TTL_HOURS`: override the default TTL in hours.
|
|
98
|
+
|
|
99
|
+
No key or account is needed.
|
|
100
|
+
|
|
101
|
+
## Verified-live note
|
|
102
|
+
|
|
103
|
+
All endpoints and form fields above were verified live on 2026-11-24 by direct HTTP and by reading the live forms. Anything marked stale or reported (the old article-order fee) is labeled as such.
|
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
#!/usr/bin/env -S uv run --script
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.11"
|
|
4
|
+
# dependencies = [
|
|
5
|
+
# "click>=8.1",
|
|
6
|
+
# "httpx>=0.27",
|
|
7
|
+
# ]
|
|
8
|
+
# ///
|
|
9
|
+
"""Search the Allen County Public Library Genealogy Center's free PERSI
|
|
10
|
+
(Periodical Source Index) from the command line.
|
|
11
|
+
|
|
12
|
+
PERSI is a citation index, not a full-text archive: a hit gives the article
|
|
13
|
+
title, periodical, year, and publisher, plus a free link when the issue is
|
|
14
|
+
online and copyright-clear. Use the citation to find the article through a
|
|
15
|
+
library, WorldCat, or the Genealogy Center's article copy service.
|
|
16
|
+
|
|
17
|
+
All three search modes are plain POST forms on genealogycenter.info, verified
|
|
18
|
+
live 2026-11-24. No account, key, or sign-in is required.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import hashlib
|
|
24
|
+
import json
|
|
25
|
+
import math
|
|
26
|
+
import os
|
|
27
|
+
import sys
|
|
28
|
+
import time
|
|
29
|
+
from contextlib import contextmanager
|
|
30
|
+
from html.parser import HTMLParser
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import Any, Callable, Iterator
|
|
33
|
+
|
|
34
|
+
import click
|
|
35
|
+
import httpx
|
|
36
|
+
|
|
37
|
+
DEFAULT_CACHE_TTL_HOURS = 168.0
|
|
38
|
+
CACHE_SCHEMA = 1
|
|
39
|
+
|
|
40
|
+
BASE = "https://www.genealogycenter.info"
|
|
41
|
+
SEARCH_PAGE = BASE + "/persi/"
|
|
42
|
+
SURNAME_URL = BASE + "/results_persisurname.php"
|
|
43
|
+
TITLE_URL = BASE + "/results_persiarttitle.php"
|
|
44
|
+
LOCATION_URL = BASE + "/results_persilocation.php"
|
|
45
|
+
USER_AGENT = "Mozilla/5.0"
|
|
46
|
+
RETRY_WAIT_S = 5.0
|
|
47
|
+
# The Genealogy Center's front door intermittently 412/429s python-httpx's
|
|
48
|
+
# default header set. Plain curl-style headers (short UA, Accept */*) plus
|
|
49
|
+
# a Referer return 200 consistently; fetch() also retries once on 412/429.
|
|
50
|
+
|
|
51
|
+
US_STATES = {
|
|
52
|
+
"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI",
|
|
53
|
+
"ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
|
|
54
|
+
"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH",
|
|
55
|
+
"OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA",
|
|
56
|
+
"WV", "WI", "WY", "GEN",
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cache_dir() -> Path:
|
|
61
|
+
override = os.environ.get("KINLOOM_PERSI_CACHE_DIR")
|
|
62
|
+
if override:
|
|
63
|
+
return Path(override).expanduser()
|
|
64
|
+
return Path.home() / ".cache" / "kinloom-persi"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def resolve_ttl_hours(cli_ttl: float | None) -> float:
|
|
68
|
+
if cli_ttl is not None:
|
|
69
|
+
if not math.isfinite(cli_ttl) or cli_ttl < 0:
|
|
70
|
+
raise click.BadParameter(f"Invalid --cache-ttl-hours value: {cli_ttl!r} (must be >= 0).")
|
|
71
|
+
return float(cli_ttl)
|
|
72
|
+
raw = os.environ.get("KINLOOM_PERSI_CACHE_TTL_HOURS")
|
|
73
|
+
if raw is not None and raw.strip():
|
|
74
|
+
try:
|
|
75
|
+
parsed = float(raw.strip())
|
|
76
|
+
except ValueError as exc:
|
|
77
|
+
raise click.BadParameter(f"Invalid KINLOOM_PERSI_CACHE_TTL_HOURS value: {raw!r}.") from exc
|
|
78
|
+
if not math.isfinite(parsed) or parsed < 0:
|
|
79
|
+
raise click.BadParameter(
|
|
80
|
+
f"Invalid KINLOOM_PERSI_CACHE_TTL_HOURS value: {raw!r} (must be >= 0)."
|
|
81
|
+
)
|
|
82
|
+
return parsed
|
|
83
|
+
return DEFAULT_CACHE_TTL_HOURS
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@contextmanager
|
|
87
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
88
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
89
|
+
try:
|
|
90
|
+
import fcntl
|
|
91
|
+
except ImportError:
|
|
92
|
+
yield
|
|
93
|
+
return
|
|
94
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
with open(lock_path, "a+b") as lock_file:
|
|
96
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
|
97
|
+
try:
|
|
98
|
+
yield
|
|
99
|
+
finally:
|
|
100
|
+
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
104
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
106
|
+
try:
|
|
107
|
+
tmp.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
|
108
|
+
os.replace(tmp, dest)
|
|
109
|
+
except Exception:
|
|
110
|
+
tmp.unlink(missing_ok=True)
|
|
111
|
+
raise
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def cache_key(kind: str, payload: dict) -> str:
|
|
115
|
+
canonical = json.dumps([kind, payload], sort_keys=True, separators=(",", ":"))
|
|
116
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def read_cache(path: Path, ttl_hours: float) -> dict | None:
|
|
120
|
+
if not path.is_file():
|
|
121
|
+
return None
|
|
122
|
+
try:
|
|
123
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
124
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
125
|
+
return None
|
|
126
|
+
if not isinstance(entry, dict) or entry.get("schema") != CACHE_SCHEMA:
|
|
127
|
+
return None
|
|
128
|
+
fetched = entry.get("fetched_at")
|
|
129
|
+
if not isinstance(fetched, (int, float)):
|
|
130
|
+
return None
|
|
131
|
+
if ttl_hours <= 0 or (time.time() - fetched) > ttl_hours * 3600:
|
|
132
|
+
return None
|
|
133
|
+
result = entry.get("result")
|
|
134
|
+
return result if isinstance(result, dict) else None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def cached_call(
|
|
138
|
+
kind: str,
|
|
139
|
+
payload: dict,
|
|
140
|
+
fetch: Callable[[], dict],
|
|
141
|
+
*,
|
|
142
|
+
refresh: bool,
|
|
143
|
+
ttl_hours: float,
|
|
144
|
+
cacheable: Callable[[dict], bool] = lambda _r: True,
|
|
145
|
+
) -> tuple[dict, bool]:
|
|
146
|
+
"""Return (result, cache_hit) with per-key flock and atomic JSON writes."""
|
|
147
|
+
key = cache_key(kind, payload)
|
|
148
|
+
root = cache_dir()
|
|
149
|
+
path = root / f"{key}.json"
|
|
150
|
+
if not refresh:
|
|
151
|
+
hit = read_cache(path, ttl_hours)
|
|
152
|
+
if hit is not None:
|
|
153
|
+
return hit, True
|
|
154
|
+
with file_lock(root / f"{key}.lock"):
|
|
155
|
+
if not refresh:
|
|
156
|
+
hit = read_cache(path, ttl_hours)
|
|
157
|
+
if hit is not None:
|
|
158
|
+
return hit, True
|
|
159
|
+
result = fetch()
|
|
160
|
+
if cacheable(result):
|
|
161
|
+
atomic_write_json(
|
|
162
|
+
path,
|
|
163
|
+
{
|
|
164
|
+
"schema": CACHE_SCHEMA,
|
|
165
|
+
"fetched_at": time.time(),
|
|
166
|
+
"kind": kind,
|
|
167
|
+
"query": payload,
|
|
168
|
+
"result": result,
|
|
169
|
+
},
|
|
170
|
+
)
|
|
171
|
+
return result, False
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def cache_options(func: Callable) -> Callable:
|
|
175
|
+
func = click.option(
|
|
176
|
+
"--cache-ttl-hours",
|
|
177
|
+
type=float,
|
|
178
|
+
default=None,
|
|
179
|
+
help="Cache TTL in hours (default 168, env KINLOOM_PERSI_CACHE_TTL_HOURS; 0 disables reads).",
|
|
180
|
+
)(func)
|
|
181
|
+
func = click.option(
|
|
182
|
+
"--refresh",
|
|
183
|
+
is_flag=True,
|
|
184
|
+
help="Bypass the disk cache for this request (the fresh result is still cached).",
|
|
185
|
+
)(func)
|
|
186
|
+
return func
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _client(headers: dict[str, str]) -> httpx.Client:
|
|
190
|
+
return httpx.Client(headers=headers, timeout=60.0, follow_redirects=True)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class TableParser(HTMLParser):
|
|
194
|
+
"""Collect rows of the first <table> whose cells look like PERSI results."""
|
|
195
|
+
|
|
196
|
+
def __init__(self) -> None:
|
|
197
|
+
super().__init__(convert_charrefs=True)
|
|
198
|
+
self.in_table = False
|
|
199
|
+
self.in_row = False
|
|
200
|
+
self.in_cell = False
|
|
201
|
+
self.current_row: list[str] = []
|
|
202
|
+
self.current_cell = ""
|
|
203
|
+
self.current_links: list[str] = []
|
|
204
|
+
self.cell_links: list[list[str]] = []
|
|
205
|
+
self.rows: list[dict] = []
|
|
206
|
+
|
|
207
|
+
def handle_starttag(self, tag, attrs):
|
|
208
|
+
attrs = dict(attrs)
|
|
209
|
+
if tag == "table":
|
|
210
|
+
self.in_table = True
|
|
211
|
+
if not self.in_table:
|
|
212
|
+
return
|
|
213
|
+
if tag == "tr":
|
|
214
|
+
self.in_row = True
|
|
215
|
+
self.current_row = []
|
|
216
|
+
self.cell_links = []
|
|
217
|
+
elif tag in ("td", "th") and self.in_row:
|
|
218
|
+
self.in_cell = True
|
|
219
|
+
self.current_cell = ""
|
|
220
|
+
self.current_links = []
|
|
221
|
+
elif tag == "a" and self.in_cell:
|
|
222
|
+
href = attrs.get("href", "")
|
|
223
|
+
if href:
|
|
224
|
+
self.current_links.append(href)
|
|
225
|
+
|
|
226
|
+
def handle_endtag(self, tag):
|
|
227
|
+
if tag == "table":
|
|
228
|
+
self.in_table = False
|
|
229
|
+
if not self.in_table and tag != "table":
|
|
230
|
+
return
|
|
231
|
+
if tag in ("td", "th") and self.in_cell:
|
|
232
|
+
self.in_cell = False
|
|
233
|
+
self.current_row.append(" ".join(self.current_cell.split()))
|
|
234
|
+
self.cell_links.append(list(self.current_links))
|
|
235
|
+
elif tag == "tr" and self.in_row:
|
|
236
|
+
self.in_row = False
|
|
237
|
+
if self.current_row:
|
|
238
|
+
self.rows.append(
|
|
239
|
+
{"cells": self.current_row, "links": self.cell_links}
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
def handle_data(self, data):
|
|
243
|
+
if self.in_cell:
|
|
244
|
+
self.current_cell += data
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def fetch(url: str, data: dict, referer: str) -> str:
|
|
248
|
+
headers = {
|
|
249
|
+
"User-Agent": USER_AGENT,
|
|
250
|
+
"Accept": "*/*",
|
|
251
|
+
"Accept-Encoding": "identity",
|
|
252
|
+
"Referer": referer,
|
|
253
|
+
}
|
|
254
|
+
last_exc: Exception | None = None
|
|
255
|
+
for attempt in (1, 2):
|
|
256
|
+
try:
|
|
257
|
+
with _client(headers) as client:
|
|
258
|
+
resp = client.post(url, data=data)
|
|
259
|
+
if resp.status_code in (412, 429) and attempt == 1:
|
|
260
|
+
if RETRY_WAIT_S > 0:
|
|
261
|
+
time.sleep(RETRY_WAIT_S)
|
|
262
|
+
continue
|
|
263
|
+
resp.raise_for_status()
|
|
264
|
+
return resp.text
|
|
265
|
+
except httpx.HTTPError as exc:
|
|
266
|
+
last_exc = exc
|
|
267
|
+
raise click.ClickException(f"PERSI request failed: {last_exc}") from last_exc
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def parse_articles(page: str) -> list[dict]:
|
|
271
|
+
parser = TableParser()
|
|
272
|
+
parser.feed(page)
|
|
273
|
+
articles = []
|
|
274
|
+
for row in parser.rows:
|
|
275
|
+
cells = row["cells"]
|
|
276
|
+
if len(cells) < 3:
|
|
277
|
+
continue
|
|
278
|
+
if cells[0].lower().startswith("article title"):
|
|
279
|
+
continue
|
|
280
|
+
free_links = [
|
|
281
|
+
link
|
|
282
|
+
for cell in row["links"]
|
|
283
|
+
for link in cell
|
|
284
|
+
if link.startswith("http")
|
|
285
|
+
]
|
|
286
|
+
articles.append(
|
|
287
|
+
{
|
|
288
|
+
"title": cells[0],
|
|
289
|
+
"periodical": cells[1] if len(cells) > 1 else "",
|
|
290
|
+
"year": cells[2] if len(cells) > 2 else "",
|
|
291
|
+
"publisher": cells[3] if len(cells) > 3 else "",
|
|
292
|
+
"free_link": free_links[0] if free_links else None,
|
|
293
|
+
}
|
|
294
|
+
)
|
|
295
|
+
return articles
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def parse_categories(page: str) -> list[dict]:
|
|
299
|
+
parser = TableParser()
|
|
300
|
+
parser.feed(page)
|
|
301
|
+
categories = []
|
|
302
|
+
for row in parser.rows:
|
|
303
|
+
cells = row["cells"]
|
|
304
|
+
if len(cells) == 2 and cells[1].replace(",", "").isdigit():
|
|
305
|
+
if cells[0].lower().startswith("category"):
|
|
306
|
+
continue
|
|
307
|
+
categories.append(
|
|
308
|
+
{"category": cells[0], "articles": int(cells[1].replace(",", ""))}
|
|
309
|
+
)
|
|
310
|
+
return categories
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def emit(items: list[dict], as_json: bool, limit: int, *, cache_hit: bool = False) -> None:
|
|
314
|
+
items = items[:limit]
|
|
315
|
+
if as_json:
|
|
316
|
+
click.echo(json.dumps(items, indent=2))
|
|
317
|
+
return
|
|
318
|
+
marker = " [cache]" if cache_hit else ""
|
|
319
|
+
if not items:
|
|
320
|
+
click.echo(f"No results.{marker}")
|
|
321
|
+
return
|
|
322
|
+
for item in items:
|
|
323
|
+
if "articles" in item:
|
|
324
|
+
click.echo(f"{item['articles']:>6} {item['category']}")
|
|
325
|
+
else:
|
|
326
|
+
line = (
|
|
327
|
+
f"{item['title']} | {item['periodical']} | "
|
|
328
|
+
f"{item['year']} | {item['publisher']}"
|
|
329
|
+
)
|
|
330
|
+
click.echo(line)
|
|
331
|
+
if item.get("free_link"):
|
|
332
|
+
click.echo(f" free online: {item['free_link']}")
|
|
333
|
+
click.echo(f"({len(items)} shown){marker}")
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
@click.group()
|
|
337
|
+
def cli() -> None:
|
|
338
|
+
"""Search ACPL's free PERSI (Periodical Source Index)."""
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
@cli.command()
|
|
342
|
+
@click.argument("surname")
|
|
343
|
+
@click.option("--limit", default=25, show_default=True, help="Max results to show.")
|
|
344
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
345
|
+
@cache_options
|
|
346
|
+
def surname(
|
|
347
|
+
surname: str,
|
|
348
|
+
limit: int,
|
|
349
|
+
as_json: bool,
|
|
350
|
+
refresh: bool,
|
|
351
|
+
cache_ttl_hours: float | None,
|
|
352
|
+
) -> None:
|
|
353
|
+
"""Search PERSI by surname, e.g. persi surname Lincoln."""
|
|
354
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
355
|
+
|
|
356
|
+
def _fetch() -> dict:
|
|
357
|
+
page = fetch(
|
|
358
|
+
SURNAME_URL,
|
|
359
|
+
{"surname": surname, "sort": "title", "submit": "Search"},
|
|
360
|
+
BASE + "/search_persisurname.php",
|
|
361
|
+
)
|
|
362
|
+
return {"articles": parse_articles(page)}
|
|
363
|
+
|
|
364
|
+
data, hit = cached_call(
|
|
365
|
+
"surname",
|
|
366
|
+
{"surname": surname.strip().lower()},
|
|
367
|
+
_fetch,
|
|
368
|
+
refresh=refresh,
|
|
369
|
+
ttl_hours=ttl,
|
|
370
|
+
cacheable=lambda r: bool(r.get("articles")),
|
|
371
|
+
)
|
|
372
|
+
emit(data.get("articles") or [], as_json, limit, cache_hit=hit)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
@cli.command()
|
|
376
|
+
@click.argument("keyword")
|
|
377
|
+
@click.option("--limit", default=25, show_default=True, help="Max results to show.")
|
|
378
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
379
|
+
@cache_options
|
|
380
|
+
def title(
|
|
381
|
+
keyword: str,
|
|
382
|
+
limit: int,
|
|
383
|
+
as_json: bool,
|
|
384
|
+
refresh: bool,
|
|
385
|
+
cache_ttl_hours: float | None,
|
|
386
|
+
) -> None:
|
|
387
|
+
"""Search PERSI by article-title keyword, e.g. persi title Lincoln."""
|
|
388
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
389
|
+
|
|
390
|
+
def _fetch() -> dict:
|
|
391
|
+
page = fetch(
|
|
392
|
+
TITLE_URL,
|
|
393
|
+
{"keyword": keyword, "sort": "title", "submit": "Search"},
|
|
394
|
+
BASE + "/search_persiarttitle.php",
|
|
395
|
+
)
|
|
396
|
+
return {"articles": parse_articles(page)}
|
|
397
|
+
|
|
398
|
+
data, hit = cached_call(
|
|
399
|
+
"title",
|
|
400
|
+
{"keyword": keyword.strip().lower()},
|
|
401
|
+
_fetch,
|
|
402
|
+
refresh=refresh,
|
|
403
|
+
ttl_hours=ttl,
|
|
404
|
+
cacheable=lambda r: bool(r.get("articles")),
|
|
405
|
+
)
|
|
406
|
+
emit(data.get("articles") or [], as_json, limit, cache_hit=hit)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@cli.command()
|
|
410
|
+
@click.option("--state", required=True, help="Two-letter state code, e.g. MI. GEN for US general.")
|
|
411
|
+
@click.option("--county", default="", help="County name (optional; leave blank for statewide).")
|
|
412
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
413
|
+
@cache_options
|
|
414
|
+
def location(
|
|
415
|
+
state: str,
|
|
416
|
+
county: str,
|
|
417
|
+
as_json: bool,
|
|
418
|
+
refresh: bool,
|
|
419
|
+
cache_ttl_hours: float | None,
|
|
420
|
+
) -> None:
|
|
421
|
+
"""List PERSI article counts by category for a state/county.
|
|
422
|
+
|
|
423
|
+
Returns category counts, not articles: pick a category on the website
|
|
424
|
+
to drill into its articles.
|
|
425
|
+
"""
|
|
426
|
+
state = state.upper()
|
|
427
|
+
if state not in US_STATES:
|
|
428
|
+
raise click.ClickException(f"Unknown state code: {state}")
|
|
429
|
+
ttl = resolve_ttl_hours(cache_ttl_hours)
|
|
430
|
+
|
|
431
|
+
def _fetch() -> dict:
|
|
432
|
+
page = fetch(
|
|
433
|
+
LOCATION_URL,
|
|
434
|
+
{
|
|
435
|
+
"subloc": "USA",
|
|
436
|
+
"cosearch": "USA",
|
|
437
|
+
"usloc": state,
|
|
438
|
+
"county": county,
|
|
439
|
+
"submit": "Search",
|
|
440
|
+
},
|
|
441
|
+
BASE + "/search_persilocation.php",
|
|
442
|
+
)
|
|
443
|
+
return {"categories": parse_categories(page)}
|
|
444
|
+
|
|
445
|
+
data, hit = cached_call(
|
|
446
|
+
"location",
|
|
447
|
+
{"state": state, "county": county.strip().lower()},
|
|
448
|
+
_fetch,
|
|
449
|
+
refresh=refresh,
|
|
450
|
+
ttl_hours=ttl,
|
|
451
|
+
cacheable=lambda r: bool(r.get("categories")),
|
|
452
|
+
)
|
|
453
|
+
cats = data.get("categories") or []
|
|
454
|
+
if not cats:
|
|
455
|
+
click.echo(
|
|
456
|
+
"No category counts returned. The county value may not match "
|
|
457
|
+
"PERSI's list; try a blank county (statewide) or check the "
|
|
458
|
+
"website form."
|
|
459
|
+
)
|
|
460
|
+
sys.exit(1)
|
|
461
|
+
emit(cats, as_json, len(cats), cache_hit=hit)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
@cli.command("search")
|
|
465
|
+
@click.argument("query", required=False, default=None)
|
|
466
|
+
@click.option("--surname", "surname_opt", default=None, help="Search by surname (alias for `persi surname`).")
|
|
467
|
+
@click.option("--title", "title_opt", default=None, help="Search by article-title keyword (alias for `persi title`).")
|
|
468
|
+
@click.option("--state", default=None, help="Two-letter state code for location counts (alias for `persi location`).")
|
|
469
|
+
@click.option("--county", default="", help="County name (used with --state).")
|
|
470
|
+
@click.option("--limit", default=25, show_default=True, help="Max results to show.")
|
|
471
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit JSON.")
|
|
472
|
+
@cache_options
|
|
473
|
+
@click.pass_context
|
|
474
|
+
def search_cmd(
|
|
475
|
+
ctx: click.Context,
|
|
476
|
+
query: str | None,
|
|
477
|
+
surname_opt: str | None,
|
|
478
|
+
title_opt: str | None,
|
|
479
|
+
state: str | None,
|
|
480
|
+
county: str,
|
|
481
|
+
limit: int,
|
|
482
|
+
as_json: bool,
|
|
483
|
+
refresh: bool,
|
|
484
|
+
cache_ttl_hours: float | None,
|
|
485
|
+
) -> None:
|
|
486
|
+
"""Convenience router to `surname`, `title`, or `location` search."""
|
|
487
|
+
if state and (query or surname_opt or title_opt):
|
|
488
|
+
raise click.UsageError(
|
|
489
|
+
"PERSI's surname and title forms do not accept a --state filter. "
|
|
490
|
+
"Use `persi surname <SURNAME>`, `persi title <KEYWORD>`, or `persi location --state <ST>` separately."
|
|
491
|
+
)
|
|
492
|
+
if state:
|
|
493
|
+
ctx.invoke(
|
|
494
|
+
location,
|
|
495
|
+
state=state,
|
|
496
|
+
county=county,
|
|
497
|
+
as_json=as_json,
|
|
498
|
+
refresh=refresh,
|
|
499
|
+
cache_ttl_hours=cache_ttl_hours,
|
|
500
|
+
)
|
|
501
|
+
return
|
|
502
|
+
if title_opt:
|
|
503
|
+
ctx.invoke(
|
|
504
|
+
title,
|
|
505
|
+
keyword=title_opt,
|
|
506
|
+
limit=limit,
|
|
507
|
+
as_json=as_json,
|
|
508
|
+
refresh=refresh,
|
|
509
|
+
cache_ttl_hours=cache_ttl_hours,
|
|
510
|
+
)
|
|
511
|
+
return
|
|
512
|
+
target_surname = surname_opt or query
|
|
513
|
+
if target_surname:
|
|
514
|
+
ctx.invoke(
|
|
515
|
+
surname,
|
|
516
|
+
surname=target_surname,
|
|
517
|
+
limit=limit,
|
|
518
|
+
as_json=as_json,
|
|
519
|
+
refresh=refresh,
|
|
520
|
+
cache_ttl_hours=cache_ttl_hours,
|
|
521
|
+
)
|
|
522
|
+
return
|
|
523
|
+
raise click.UsageError("Pass a surname, --title <KEYWORD>, or --state <ST>.")
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
@cli.command()
|
|
527
|
+
@click.argument("mode", type=click.Choice(["surname", "title", "location"]))
|
|
528
|
+
def url(mode: str) -> None:
|
|
529
|
+
"""Print the PERSI website search page for a mode (POST forms have no shareable result URL)."""
|
|
530
|
+
pages = {
|
|
531
|
+
"surname": BASE + "/search_persisurname.php",
|
|
532
|
+
"title": BASE + "/search_persiarttitle.php",
|
|
533
|
+
"location": BASE + "/search_persilocation.php",
|
|
534
|
+
}
|
|
535
|
+
click.echo(pages[mode])
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
if __name__ == "__main__":
|
|
539
|
+
cli()
|