@kinloom/cli 0.2.0 → 0.3.1
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 +346 -116
- package/dist/assets/ocr.md +25 -1
- package/dist/assets/prep-scan.md +42 -4
- package/dist/assets/prep-scan.py +432 -10
- package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
- package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
- package/dist/bundled-skills/archive-org/SKILL.md +40 -7
- package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
- package/dist/bundled-skills/california-archives/SKILL.md +10 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
- package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
- package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
- package/dist/bundled-skills/findagrave/SKILL.md +18 -5
- package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
- package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
- package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
- package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
- package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
- package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
- package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
- package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
- package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
- package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
- package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
- package/dist/bundled-skills/wikitree/SKILL.md +7 -1
- package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +107 -2
- 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.map +1 -1
- package/dist/commands/ops/audit.js +5 -0
- package/dist/commands/ops/audit.js.map +1 -1
- 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 +3 -1
- package/dist/commands/ops/help.d.ts.map +1 -1
- package/dist/commands/ops/help.js +33 -0
- package/dist/commands/ops/help.js.map +1 -1
- package/dist/commands/ops/index.d.ts +3 -1
- package/dist/commands/ops/index.d.ts.map +1 -1
- package/dist/commands/ops/index.js +2 -0
- package/dist/commands/ops/index.js.map +1 -1
- package/dist/commands/ops/integrate.d.ts +5 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -1
- package/dist/commands/ops/integrate.js +272 -26
- package/dist/commands/ops/integrate.js.map +1 -1
- package/dist/commands/ops/sync.d.ts +17 -0
- package/dist/commands/ops/sync.d.ts.map +1 -1
- package/dist/commands/ops/sync.js +173 -0
- package/dist/commands/ops/sync.js.map +1 -1
- 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/index.d.ts +1 -1
- package/dist/commands/records/index.d.ts.map +1 -1
- package/dist/commands/records/index.js +1 -1
- package/dist/commands/records/index.js.map +1 -1
- package/dist/commands/records/runner.d.ts +2 -0
- package/dist/commands/records/runner.d.ts.map +1 -1
- package/dist/commands/records/runner.js +33 -2
- package/dist/commands/records/runner.js.map +1 -1
- package/package.json +2 -2
package/dist/assets/prep-scan.md
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: prep-scan
|
|
3
|
-
description: Prepare archival scans for inspection and publication: generate compact JPEG previews in parallel, rotate/crop/redact scans
|
|
3
|
+
description: Prepare archival scans for inspection and publication: generate compact JPEG previews in parallel, overlay original-pixel coordinate grids, rotate/crop/redact scans, stack multi-band header+household crops, stitch census sheet header strips, search PDF text by page via pdftotext, and render selective PDF pages via pdftoppm.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Scan Preparation (`kinloom prep-scan`)
|
|
7
7
|
|
|
8
|
-
Generate lightweight inspection previews, redacted archival crops, census header contact strips, and selective PDF page renders. The bundled Python script uses a PEP 723 `uv run --script` header (`pillow`, `httpx`),
|
|
8
|
+
Generate lightweight inspection previews, original-pixel coordinate grids, redacted archival crops, vertically stitched multi-band crops, census header contact strips, page-indexed PDF regex searches, and selective PDF page renders. The bundled Python script uses a PEP 723 `uv run --script` header (`pillow`, `httpx`), `pdf-pages` uses `pdftoppm`, and `pdf-grep` uses `pdftotext` (or `pypdf` fallback).
|
|
9
9
|
|
|
10
10
|
## Subcommands
|
|
11
11
|
|
|
@@ -39,7 +39,16 @@ kinloom prep-scan sheet-strip ./sheets/ed-12-*.jpg --out ./strips/ed-12-headers.
|
|
|
39
39
|
kinloom prep-scan sheet-strip ./sheets/ed-12-*.jpg --out ./strips/ed-12-streets.jpg --band left --band-pct 12 --max-kb 250
|
|
40
40
|
```
|
|
41
41
|
|
|
42
|
-
### 4. Selective PDF page rendering (`pdf-pages`)
|
|
42
|
+
### 4. Selective PDF page rendering (`pdf-pages`) and page-indexed text search (`pdf-grep`)
|
|
43
|
+
|
|
44
|
+
Search a multi-page PDF's text layer page by page (`pdftotext`, falling back to `pypdf`) to find exact 1-based page numbers, text snippets, and a ready-to-use `--pages` argument before rendering:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
kinloom prep-scan pdf-grep ./archive/county-history.pdf --pattern "Lincoln" -i --context 200 --limit 25
|
|
48
|
+
kinloom prep-scan pdf-grep ./archive/county-history.pdf --pattern "Hardin County" --json
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`pdf-grep` matches line by line (no cross-line backtracking), exits `0` when one or more matches are found, `1` when zero matches are found, and `2` on invalid regex/flags.
|
|
43
52
|
|
|
44
53
|
Render only the requested PDF page numbers via `pdftoppm`, build compact previews in parallel, and optionally emit a labeled contact strip:
|
|
45
54
|
|
|
@@ -48,6 +57,35 @@ kinloom prep-scan pdf-pages ./archive/county-history.pdf --pages 1-4,18,42-45 --
|
|
|
48
57
|
kinloom prep-scan pdf-pages ./archive/packet.pdf --pages 1-6 --out-dir ./rendered --strip ./rendered/contact.jpg --json
|
|
49
58
|
```
|
|
50
59
|
|
|
60
|
+
### 5. Coordinate-grid inspection preview (`grid`)
|
|
61
|
+
|
|
62
|
+
Draw semi-transparent grid lines every `--step` pixels in original image pixel coordinates with crisp coordinate labels along the top and left edges, resize under `--max-width` / `--max-kb`, and print JSON (`original_width`, `original_height`, `preview_width`, `preview_height`, `step`, `out`) so exact `--box x0,y0,x1,y1` values can be read from one compact preview:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
kinloom prep-scan grid ./raw/census-1930.jpg ./previews/census-1930-grid.jpg --step 200 --max-width 1600 --max-kb 280
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 6. Multi-band vertical stitch (`stitch`)
|
|
69
|
+
|
|
70
|
+
Crop two or more boxes from one scan (such as a census sheet column header band plus the target household band, skipping unrelated neighbor rows in between), apply optional black redactions in original image pixel coordinates before cropping, center/pad narrower bands, stack them vertically separated by `--gap` pixels of `--divider-color`, and print JSON (`width`, `height`, `bytes`, `bands`, `out`):
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
kinloom prep-scan stitch ./raw/census-1930.jpg ./scans/census-1930-household.jpg \
|
|
74
|
+
--box 80,140,3200,520 \
|
|
75
|
+
--box 80,1420,3200,1760 \
|
|
76
|
+
--redact 80,1710,3200,1760 \
|
|
77
|
+
--gap 6 \
|
|
78
|
+
--divider-color "#222222" \
|
|
79
|
+
--quality 90
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Output flags (forgiving)
|
|
83
|
+
|
|
84
|
+
- `grid`, `stitch`, and `crop` take the output path positionally (`<in> <out.jpg>`) or as `--out <out.jpg>` (aliases `-o`, `--output`). Giving both with different paths exits 2.
|
|
85
|
+
- `preview` and `pdf-pages` take `--out-dir <dir>`; `--out`, `-o`, `--output-dir`, and `--output` are aliases.
|
|
86
|
+
- `--box` and `--redact` accept `x0,y0,x1,y1`, `"x0, y0, x1, y1"`, `"x0 y0 x1 y1"`, and shell-split `--box 10, 20, 30, 40`.
|
|
87
|
+
- `crop` accepts `--quality 1..100` for the archival output (default `92`).
|
|
88
|
+
|
|
51
89
|
## Environment variables
|
|
52
90
|
|
|
53
91
|
- `KINLOOM_OCR_CACHE_DIR` (optional): overrides the default preview cache root (`$XDG_CACHE_HOME/kinloom-ocr` or `~/.cache/kinloom-ocr`).
|
|
@@ -56,4 +94,4 @@ kinloom prep-scan pdf-pages ./archive/packet.pdf --pages 1-6 --out-dir ./rendere
|
|
|
56
94
|
## Requirements
|
|
57
95
|
|
|
58
96
|
- `uv` (or Python 3.11+ with `pillow`, plus `httpx` for URL inputs in `sheet-strip`).
|
|
59
|
-
- `pdftoppm` (`poppler-utils` on Linux or `poppler` on macOS) for `pdf-pages
|
|
97
|
+
- `pdftoppm` and `pdftotext` (`poppler-utils` on Linux or `poppler` on macOS) for `pdf-pages` and `pdf-grep` (`pdf-grep` falls back to `pypdf` if `pdftotext` is unavailable).
|
package/dist/assets/prep-scan.py
CHANGED
|
@@ -119,11 +119,12 @@ class SavedImage:
|
|
|
119
119
|
|
|
120
120
|
|
|
121
121
|
def parse_box(raw: str) -> Box:
|
|
122
|
-
|
|
122
|
+
# Accept "x0,y0,x1,y1", "x0, y0, x1, y1", and "x0 y0 x1 y1".
|
|
123
|
+
parts = [p for p in re.split(r"[,\s]+", raw.strip()) if p]
|
|
123
124
|
if len(parts) != 4:
|
|
124
125
|
raise argparse.ArgumentTypeError(f"Invalid box '{raw}': expected x0,y0,x1,y1.")
|
|
125
126
|
try:
|
|
126
|
-
x0, y0, x1, y1 = (int(p) for p in parts)
|
|
127
|
+
x0, y0, x1, y1 = (int(round(float(p))) for p in parts)
|
|
127
128
|
except ValueError as exc:
|
|
128
129
|
raise argparse.ArgumentTypeError(f"Invalid integer coordinates in box '{raw}'.") from exc
|
|
129
130
|
if x0 < 0 or y0 < 0 or x1 <= x0 or y1 <= y0:
|
|
@@ -271,21 +272,40 @@ def save_compact_jpeg(
|
|
|
271
272
|
return SavedImage(path=out_path, width=width, height=height, bytes=len(data))
|
|
272
273
|
|
|
273
274
|
|
|
274
|
-
def save_archival_image(
|
|
275
|
+
def save_archival_image(
|
|
276
|
+
im: PILImageModule.Image, out_path: Path, quality: int = 92
|
|
277
|
+
) -> SavedImage:
|
|
275
278
|
rgb = to_rgb(im)
|
|
276
279
|
ext = out_path.suffix.lower()
|
|
277
280
|
buf = io.BytesIO()
|
|
278
281
|
if ext == ".png":
|
|
279
282
|
rgb.save(buf, format="PNG", optimize=True)
|
|
280
283
|
elif ext == ".webp":
|
|
281
|
-
rgb.save(buf, format="WEBP", quality=
|
|
284
|
+
rgb.save(buf, format="WEBP", quality=quality)
|
|
282
285
|
else:
|
|
283
|
-
rgb.save(buf, format="JPEG", quality=
|
|
286
|
+
rgb.save(buf, format="JPEG", quality=quality, optimize=True)
|
|
284
287
|
data = buf.getvalue()
|
|
285
288
|
atomic_write_bytes(out_path, data)
|
|
286
289
|
return SavedImage(path=out_path, width=rgb.size[0], height=rgb.size[1], bytes=len(data))
|
|
287
290
|
|
|
288
291
|
|
|
292
|
+
def parse_rgb_color(raw: str) -> tuple[int, int, int]:
|
|
293
|
+
try:
|
|
294
|
+
from PIL import ImageColor
|
|
295
|
+
|
|
296
|
+
rgb = ImageColor.getrgb(raw.strip())
|
|
297
|
+
except Exception as exc:
|
|
298
|
+
raise ValueError(f"Invalid --divider-color '{raw}': expected hex or named RGB color.") from exc
|
|
299
|
+
return (int(rgb[0]), int(rgb[1]), int(rgb[2]))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def load_label_font(image_font_mod: Any, size: int = 14) -> Any:
|
|
303
|
+
try:
|
|
304
|
+
return image_font_mod.load_default(size=size)
|
|
305
|
+
except TypeError:
|
|
306
|
+
return image_font_mod.load_default()
|
|
307
|
+
|
|
308
|
+
|
|
289
309
|
def safe_stem(name: str) -> str:
|
|
290
310
|
cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("_")
|
|
291
311
|
return cleaned or "scan"
|
|
@@ -346,6 +366,8 @@ def cmd_preview(args: argparse.Namespace) -> tuple[int, int]:
|
|
|
346
366
|
|
|
347
367
|
|
|
348
368
|
def cmd_crop(args: argparse.Namespace) -> tuple[int, int]:
|
|
369
|
+
if not 1 <= args.quality <= 100:
|
|
370
|
+
raise ValueError(f"--quality must be between 1 and 100, got {args.quality}.")
|
|
349
371
|
Image, ImageDraw, _, _ = require_pillow()
|
|
350
372
|
src = Path(args.input).resolve()
|
|
351
373
|
out_path = Path(args.output).resolve()
|
|
@@ -367,7 +389,7 @@ def cmd_crop(args: argparse.Namespace) -> tuple[int, int]:
|
|
|
367
389
|
draw.rectangle((clamped.x0, clamped.y0, clamped.x1, clamped.y1), fill=(0, 0, 0))
|
|
368
390
|
redactions.append([clamped.x0, clamped.y0, clamped.x1, clamped.y1])
|
|
369
391
|
|
|
370
|
-
saved = save_archival_image(cropped, out_path)
|
|
392
|
+
saved = save_archival_image(cropped, out_path, quality=args.quality)
|
|
371
393
|
|
|
372
394
|
if args.preview_out:
|
|
373
395
|
preview_path = Path(args.preview_out).resolve()
|
|
@@ -737,6 +759,256 @@ def cmd_pdf_pages(args: argparse.Namespace) -> tuple[int, int]:
|
|
|
737
759
|
return 0, out_bytes
|
|
738
760
|
|
|
739
761
|
|
|
762
|
+
def extract_pdf_pages_text(pdf_path: Path, timeout_s: int = 600) -> list[str]:
|
|
763
|
+
"""Return one text string per PDF page (index 0 = page 1).
|
|
764
|
+
|
|
765
|
+
pdftotext emits a form feed after every page, so splitting on \\x0c keeps
|
|
766
|
+
page numbers exact even when a page has no text layer.
|
|
767
|
+
"""
|
|
768
|
+
pdftotext_bin = shutil.which("pdftotext")
|
|
769
|
+
if pdftotext_bin:
|
|
770
|
+
proc = subprocess.run(
|
|
771
|
+
[pdftotext_bin, "-enc", "UTF-8", str(pdf_path), "-"],
|
|
772
|
+
capture_output=True,
|
|
773
|
+
timeout=timeout_s,
|
|
774
|
+
)
|
|
775
|
+
if proc.returncode != 0:
|
|
776
|
+
detail = proc.stderr.decode("utf-8", "replace").strip()
|
|
777
|
+
raise RuntimeError(f"pdftotext failed (exit {proc.returncode}): {detail}")
|
|
778
|
+
pages = proc.stdout.decode("utf-8", "replace").split("\x0c")
|
|
779
|
+
if pages and not pages[-1].strip():
|
|
780
|
+
pages.pop()
|
|
781
|
+
return pages
|
|
782
|
+
try:
|
|
783
|
+
from pypdf import PdfReader # type: ignore[import-not-found]
|
|
784
|
+
except ImportError as exc:
|
|
785
|
+
raise RuntimeError(
|
|
786
|
+
"pdftotext not found on PATH and pypdf is not installed. Install poppler-utils "
|
|
787
|
+
"(for example `apt install poppler-utils` or `brew install poppler`)."
|
|
788
|
+
) from exc
|
|
789
|
+
return [page.extract_text() or "" for page in PdfReader(str(pdf_path)).pages]
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def format_page_spec(pages: list[int]) -> str:
|
|
793
|
+
if not pages:
|
|
794
|
+
return ""
|
|
795
|
+
return ",".join(str(a) if a == b else f"{a}-{b}" for a, b in coalesce_ranges(pages))
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def cmd_pdf_grep(args: argparse.Namespace) -> tuple[int, int]:
|
|
799
|
+
pdf_path = Path(args.pdf_path).resolve()
|
|
800
|
+
if not pdf_path.is_file():
|
|
801
|
+
print(f"Error: PDF file not found: {pdf_path}", file=sys.stderr)
|
|
802
|
+
return 1, 0
|
|
803
|
+
if args.limit < 1 or args.context < 0:
|
|
804
|
+
raise ValueError("--limit must be >= 1 and --context must be >= 0.")
|
|
805
|
+
try:
|
|
806
|
+
regex = re.compile(args.pattern, re.IGNORECASE if args.ignore_case else 0)
|
|
807
|
+
except re.error as exc:
|
|
808
|
+
raise ValueError(f"Invalid --pattern regex {args.pattern!r}: {exc}") from exc
|
|
809
|
+
|
|
810
|
+
page_texts = extract_pdf_pages_text(pdf_path)
|
|
811
|
+
matches: list[dict[str, Any]] = []
|
|
812
|
+
hit_pages: list[int] = []
|
|
813
|
+
total = 0
|
|
814
|
+
ctx = args.context
|
|
815
|
+
for page_no, text in enumerate(page_texts, start=1):
|
|
816
|
+
page_hit = False
|
|
817
|
+
offset = 0
|
|
818
|
+
for line_no, line in enumerate(text.split("\n"), start=1):
|
|
819
|
+
for m in regex.finditer(line):
|
|
820
|
+
if m.end() == m.start():
|
|
821
|
+
continue
|
|
822
|
+
total += 1
|
|
823
|
+
page_hit = True
|
|
824
|
+
if len(matches) < args.limit:
|
|
825
|
+
start = offset + m.start()
|
|
826
|
+
end = offset + m.end()
|
|
827
|
+
snippet = " ".join(text[max(0, start - ctx):end + ctx].split())
|
|
828
|
+
matches.append({"page": page_no, "line": line_no,
|
|
829
|
+
"match": m.group(0), "snippet": snippet})
|
|
830
|
+
offset += len(line) + 1
|
|
831
|
+
if page_hit:
|
|
832
|
+
hit_pages.append(page_no)
|
|
833
|
+
|
|
834
|
+
pages_arg = format_page_spec(hit_pages)
|
|
835
|
+
result = {
|
|
836
|
+
"pdf": str(pdf_path),
|
|
837
|
+
"pattern": args.pattern,
|
|
838
|
+
"ignore_case": bool(args.ignore_case),
|
|
839
|
+
"page_count": len(page_texts),
|
|
840
|
+
"match_count": total,
|
|
841
|
+
"returned": len(matches),
|
|
842
|
+
"truncated": total > len(matches),
|
|
843
|
+
"pages": hit_pages,
|
|
844
|
+
"pages_arg": pages_arg,
|
|
845
|
+
"matches": matches,
|
|
846
|
+
}
|
|
847
|
+
if args.json:
|
|
848
|
+
out_bytes = emit_output(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
|
849
|
+
else:
|
|
850
|
+
lines = [f"p.{m['page']} L{m['line']}: {m['snippet']}" for m in matches]
|
|
851
|
+
summary = (f"{total} match(es) on {len(hit_pages)} of {len(page_texts)} page(s)"
|
|
852
|
+
+ (f"; showing first {len(matches)} (raise --limit)" if result["truncated"] else ""))
|
|
853
|
+
lines.append(summary)
|
|
854
|
+
if pages_arg:
|
|
855
|
+
lines.append(f"next: kinloom prep-scan pdf-pages {pdf_path} --pages {pages_arg} --out-dir <dir>")
|
|
856
|
+
out_bytes = emit_output("\n".join(lines) + "\n")
|
|
857
|
+
return (0 if total else 1), out_bytes
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def cmd_grid(args: argparse.Namespace) -> tuple[int, int]:
|
|
861
|
+
Image, ImageDraw, ImageFont, _ = require_pillow()
|
|
862
|
+
if args.step <= 0:
|
|
863
|
+
raise ValueError(f"--step must be a positive integer, got {args.step}.")
|
|
864
|
+
if args.max_width <= 0:
|
|
865
|
+
raise ValueError(f"--max-width must be a positive integer, got {args.max_width}.")
|
|
866
|
+
if args.max_kb <= 0:
|
|
867
|
+
raise ValueError(f"--max-kb must be a positive integer, got {args.max_kb}.")
|
|
868
|
+
|
|
869
|
+
src = Path(args.image).resolve()
|
|
870
|
+
out_path = Path(args.out).resolve()
|
|
871
|
+
if not src.is_file():
|
|
872
|
+
print(f"Error: input file not found: {src}", file=sys.stderr)
|
|
873
|
+
return 1, 0
|
|
874
|
+
|
|
875
|
+
with Image.open(src) as raw_im:
|
|
876
|
+
rgb = rotate_clockwise(to_rgb(raw_im), args.rotate)
|
|
877
|
+
|
|
878
|
+
orig_w, orig_h = rgb.size
|
|
879
|
+
if orig_w > args.max_width:
|
|
880
|
+
scaled_h = max(1, int(round(orig_h * (args.max_width / orig_w))))
|
|
881
|
+
base = rgb.resize((args.max_width, scaled_h), Image.Resampling.LANCZOS)
|
|
882
|
+
else:
|
|
883
|
+
base = rgb.copy()
|
|
884
|
+
|
|
885
|
+
scale_x = base.width / orig_w
|
|
886
|
+
scale_y = base.height / orig_h
|
|
887
|
+
overlay = Image.new("RGBA", base.size, (0, 0, 0, 0))
|
|
888
|
+
draw = ImageDraw.Draw(overlay)
|
|
889
|
+
font = load_label_font(ImageFont, size=14)
|
|
890
|
+
|
|
891
|
+
def draw_pill(x_pos: int, y_pos: int, label: str, accent: tuple[int, int, int, int]) -> None:
|
|
892
|
+
bbox = draw.textbbox((0, 0), label, font=font)
|
|
893
|
+
tw = bbox[2] - bbox[0]
|
|
894
|
+
th = bbox[3] - bbox[1]
|
|
895
|
+
pad_x = 4
|
|
896
|
+
pad_y = 2
|
|
897
|
+
left = max(0, min(base.width - (tw + pad_x * 2), x_pos))
|
|
898
|
+
top = max(0, min(base.height - (th + pad_y * 2), y_pos))
|
|
899
|
+
draw.rectangle(
|
|
900
|
+
(left, top, left + tw + pad_x * 2, top + th + pad_y * 2),
|
|
901
|
+
fill=(15, 18, 24, 195),
|
|
902
|
+
outline=accent,
|
|
903
|
+
width=1,
|
|
904
|
+
)
|
|
905
|
+
draw.text((left + pad_x - bbox[0], top + pad_y - bbox[1]), label, fill=(255, 255, 255, 255), font=font)
|
|
906
|
+
|
|
907
|
+
major_step = args.step * 5
|
|
908
|
+
last_x_label = -1000
|
|
909
|
+
for orig_x in range(0, orig_w, args.step):
|
|
910
|
+
px = min(base.width - 1, int(round(orig_x * scale_x)))
|
|
911
|
+
is_major = orig_x % major_step == 0
|
|
912
|
+
line_color = (220, 38, 38, 175) if is_major else (220, 38, 38, 110)
|
|
913
|
+
draw.line([(px, 0), (px, base.height - 1)], fill=line_color, width=2 if is_major else 1)
|
|
914
|
+
if orig_x == 0 or px - last_x_label >= 48:
|
|
915
|
+
draw_pill(px + 2, 2, str(orig_x), (220, 38, 38, 220))
|
|
916
|
+
last_x_label = px
|
|
917
|
+
|
|
918
|
+
last_y_label = -1000
|
|
919
|
+
for orig_y in range(0, orig_h, args.step):
|
|
920
|
+
py = min(base.height - 1, int(round(orig_y * scale_y)))
|
|
921
|
+
is_major = orig_y % major_step == 0
|
|
922
|
+
line_color = (37, 99, 235, 175) if is_major else (37, 99, 235, 110)
|
|
923
|
+
draw.line([(0, py), (base.width - 1, py)], fill=line_color, width=2 if is_major else 1)
|
|
924
|
+
if orig_y > 0 and py - last_y_label >= 24:
|
|
925
|
+
draw_pill(2, py + 2, str(orig_y), (37, 99, 235, 220))
|
|
926
|
+
last_y_label = py
|
|
927
|
+
|
|
928
|
+
composited = Image.alpha_composite(base.convert("RGBA"), overlay).convert("RGB")
|
|
929
|
+
saved = save_compact_jpeg(composited, out_path, max_width=args.max_width, max_kb=args.max_kb)
|
|
930
|
+
|
|
931
|
+
payload = {
|
|
932
|
+
"original_width": orig_w,
|
|
933
|
+
"original_height": orig_h,
|
|
934
|
+
"preview_width": saved.width,
|
|
935
|
+
"preview_height": saved.height,
|
|
936
|
+
"step": args.step,
|
|
937
|
+
"bytes": saved.bytes,
|
|
938
|
+
"out": str(saved.path),
|
|
939
|
+
}
|
|
940
|
+
out_bytes = emit_output(json.dumps(payload, indent=2) + "\n")
|
|
941
|
+
return 0, out_bytes
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def cmd_stitch(args: argparse.Namespace) -> tuple[int, int]:
|
|
945
|
+
Image, ImageDraw, _, _ = require_pillow()
|
|
946
|
+
if len(args.box) < 2:
|
|
947
|
+
raise ValueError("stitch requires at least 2 --box regions (for example header + target band).")
|
|
948
|
+
if args.gap < 0:
|
|
949
|
+
raise ValueError(f"--gap must be >= 0, got {args.gap}.")
|
|
950
|
+
if args.quality < 1 or args.quality > 100:
|
|
951
|
+
raise ValueError(f"--quality must be between 1 and 100, got {args.quality}.")
|
|
952
|
+
|
|
953
|
+
divider_rgb = parse_rgb_color(args.divider_color)
|
|
954
|
+
src = Path(args.image).resolve()
|
|
955
|
+
out_path = Path(args.out).resolve()
|
|
956
|
+
if not src.is_file():
|
|
957
|
+
print(f"Error: input file not found: {src}", file=sys.stderr)
|
|
958
|
+
return 1, 0
|
|
959
|
+
|
|
960
|
+
with Image.open(src) as raw_im:
|
|
961
|
+
img = rotate_clockwise(to_rgb(raw_im), args.rotate)
|
|
962
|
+
|
|
963
|
+
redactions: list[list[int]] = []
|
|
964
|
+
if args.redact:
|
|
965
|
+
draw_src = ImageDraw.Draw(img)
|
|
966
|
+
for idx, rbox in enumerate(args.redact, 1):
|
|
967
|
+
clamped = clamp_box(rbox, img.width, img.height, f"--redact #{idx}")
|
|
968
|
+
draw_src.rectangle((clamped.x0, clamped.y0, clamped.x1, clamped.y1), fill=(0, 0, 0))
|
|
969
|
+
redactions.append([clamped.x0, clamped.y0, clamped.x1, clamped.y1])
|
|
970
|
+
|
|
971
|
+
cropped_bands: list[tuple[Box, Any]] = []
|
|
972
|
+
for idx, box in enumerate(args.box, 1):
|
|
973
|
+
clamped = clamp_box(box, img.width, img.height, f"--box #{idx}")
|
|
974
|
+
cropped_bands.append((clamped, img.crop((clamped.x0, clamped.y0, clamped.x1, clamped.y1))))
|
|
975
|
+
|
|
976
|
+
canvas_w = max(band.width for _, band in cropped_bands)
|
|
977
|
+
canvas_h = sum(band.height for _, band in cropped_bands) + args.gap * (len(cropped_bands) - 1)
|
|
978
|
+
canvas = Image.new("RGB", (canvas_w, max(1, canvas_h)), divider_rgb)
|
|
979
|
+
draw = ImageDraw.Draw(canvas)
|
|
980
|
+
|
|
981
|
+
y = 0
|
|
982
|
+
band_reports: list[dict[str, object]] = []
|
|
983
|
+
for cbox, band in cropped_bands:
|
|
984
|
+
if band.width < canvas_w:
|
|
985
|
+
draw.rectangle((0, y, canvas_w - 1, y + band.height - 1), fill=(255, 255, 255))
|
|
986
|
+
x_offset = (canvas_w - band.width) // 2
|
|
987
|
+
canvas.paste(band, (x_offset, y))
|
|
988
|
+
band_reports.append(
|
|
989
|
+
{
|
|
990
|
+
"box": [cbox.x0, cbox.y0, cbox.x1, cbox.y1],
|
|
991
|
+
"width": band.width,
|
|
992
|
+
"height": band.height,
|
|
993
|
+
"x_offset": x_offset,
|
|
994
|
+
"y_offset": y,
|
|
995
|
+
}
|
|
996
|
+
)
|
|
997
|
+
y += band.height + args.gap
|
|
998
|
+
|
|
999
|
+
saved = save_archival_image(canvas, out_path, quality=args.quality)
|
|
1000
|
+
payload = {
|
|
1001
|
+
"width": saved.width,
|
|
1002
|
+
"height": saved.height,
|
|
1003
|
+
"bytes": saved.bytes,
|
|
1004
|
+
"bands": band_reports,
|
|
1005
|
+
"redactions": redactions,
|
|
1006
|
+
"out": str(saved.path),
|
|
1007
|
+
}
|
|
1008
|
+
out_bytes = emit_output(json.dumps(payload, indent=2) + "\n")
|
|
1009
|
+
return 0, out_bytes
|
|
1010
|
+
|
|
1011
|
+
|
|
740
1012
|
def build_parser() -> argparse.ArgumentParser:
|
|
741
1013
|
parser = argparse.ArgumentParser(
|
|
742
1014
|
prog="kinloom prep-scan",
|
|
@@ -749,7 +1021,10 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
749
1021
|
|
|
750
1022
|
p_prev = sub.add_parser("preview", help="Generate compact JPEG inspection previews in parallel.")
|
|
751
1023
|
p_prev.add_argument("images", nargs="+", help="Input image path(s).")
|
|
752
|
-
p_prev.add_argument(
|
|
1024
|
+
p_prev.add_argument(
|
|
1025
|
+
"--out-dir", "--out", "-o", "--output-dir", "--output", dest="out_dir", required=True,
|
|
1026
|
+
help="Output directory for preview JPEGs (--out/-o are aliases).",
|
|
1027
|
+
)
|
|
753
1028
|
p_prev.add_argument(
|
|
754
1029
|
"--max-width", type=int, default=1400, help="Maximum pixel width (default: 1400)."
|
|
755
1030
|
)
|
|
@@ -764,7 +1039,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
764
1039
|
help="Rotate, crop, apply solid black redaction boxes (in cropped coordinates), and auto-write a verification preview.",
|
|
765
1040
|
)
|
|
766
1041
|
p_crop.add_argument("input", help="Source scan path.")
|
|
767
|
-
p_crop.add_argument("output",
|
|
1042
|
+
p_crop.add_argument("output", nargs="?", default=None,
|
|
1043
|
+
help="Final archival output scan path (or pass --out).")
|
|
1044
|
+
p_crop.add_argument("--out", "-o", "--output", dest="output_opt", default=None,
|
|
1045
|
+
help="Alias for the positional output path.")
|
|
1046
|
+
p_crop.add_argument("--quality", type=int, default=92,
|
|
1047
|
+
help="Archival output JPEG/WEBP quality 1..100 (default: 92).")
|
|
768
1048
|
p_crop.add_argument(
|
|
769
1049
|
"--box", required=True, type=parse_box, help="Crop box x0,y0,x1,y1 after optional --rotate."
|
|
770
1050
|
)
|
|
@@ -844,7 +1124,8 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
844
1124
|
p_pdf.add_argument("pdf_path", help="Path to source PDF file.")
|
|
845
1125
|
p_pdf.add_argument("--pages", required=True, help="Page range spec, e.g. 1-5,8.")
|
|
846
1126
|
p_pdf.add_argument(
|
|
847
|
-
"--out-dir",
|
|
1127
|
+
"--out-dir", "--out", "-o", "--output-dir", "--output", dest="out_dir", required=True,
|
|
1128
|
+
help="Output directory for rendered pages and previews (--out/-o are aliases).",
|
|
848
1129
|
)
|
|
849
1130
|
p_pdf.add_argument(
|
|
850
1131
|
"--dpi", type=int, default=150, help="Rendering DPI for pdftoppm (default: 150)."
|
|
@@ -861,13 +1142,154 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
861
1142
|
p_pdf.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
862
1143
|
p_pdf.set_defaults(func=cmd_pdf_pages)
|
|
863
1144
|
|
|
1145
|
+
p_pgrep = sub.add_parser(
|
|
1146
|
+
"pdf-grep",
|
|
1147
|
+
help="Search PDF text page by page (pdftotext, pypdf fallback) and print 1-based page "
|
|
1148
|
+
"numbers + snippets to feed `pdf-pages --pages`. Exit 1 when nothing matches.",
|
|
1149
|
+
)
|
|
1150
|
+
p_pgrep.add_argument("pdf_path", help="Path to source PDF file.")
|
|
1151
|
+
p_pgrep.add_argument("--pattern", "-e", required=True,
|
|
1152
|
+
help="Python regex, matched within each text line.")
|
|
1153
|
+
p_pgrep.add_argument("-i", "--ignore-case", action="store_true", help="Case-insensitive match.")
|
|
1154
|
+
p_pgrep.add_argument("--context", type=int, default=200,
|
|
1155
|
+
help="Characters of page text to show on each side of a match (default: 200).")
|
|
1156
|
+
p_pgrep.add_argument("--limit", type=int, default=25,
|
|
1157
|
+
help="Maximum matches to print (default: 25); all matches still count.")
|
|
1158
|
+
p_pgrep.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
1159
|
+
p_pgrep.set_defaults(func=cmd_pdf_grep)
|
|
1160
|
+
|
|
1161
|
+
p_grid = sub.add_parser(
|
|
1162
|
+
"grid",
|
|
1163
|
+
help="Draw an original-pixel coordinate grid overlay onto a compact JPEG preview.",
|
|
1164
|
+
)
|
|
1165
|
+
p_grid.add_argument("image", help="Source scan image path.")
|
|
1166
|
+
p_grid.add_argument("out", nargs="?", default=None,
|
|
1167
|
+
help="Output JPEG path for the coordinate-grid preview (or pass --out).")
|
|
1168
|
+
p_grid.add_argument("--out", "-o", "--output", dest="out_opt", default=None,
|
|
1169
|
+
help="Alias for the positional output path.")
|
|
1170
|
+
p_grid.add_argument(
|
|
1171
|
+
"--step",
|
|
1172
|
+
type=int,
|
|
1173
|
+
default=200,
|
|
1174
|
+
help="Grid line interval in original image pixels (default: 200).",
|
|
1175
|
+
)
|
|
1176
|
+
p_grid.add_argument(
|
|
1177
|
+
"--max-width",
|
|
1178
|
+
type=int,
|
|
1179
|
+
default=1600,
|
|
1180
|
+
help="Maximum preview width in pixels (default: 1600).",
|
|
1181
|
+
)
|
|
1182
|
+
p_grid.add_argument(
|
|
1183
|
+
"--max-kb",
|
|
1184
|
+
type=int,
|
|
1185
|
+
default=280,
|
|
1186
|
+
help="Maximum preview file size in KB (default: 280).",
|
|
1187
|
+
)
|
|
1188
|
+
p_grid.add_argument(
|
|
1189
|
+
"--rotate",
|
|
1190
|
+
type=int,
|
|
1191
|
+
choices=(90, 180, 270),
|
|
1192
|
+
default=None,
|
|
1193
|
+
help="Optional clockwise rotation applied before measuring coordinates.",
|
|
1194
|
+
)
|
|
1195
|
+
p_grid.add_argument("--json", action="store_true", help="Emit JSON output (always enabled).")
|
|
1196
|
+
p_grid.set_defaults(func=cmd_grid)
|
|
1197
|
+
|
|
1198
|
+
p_stitch = sub.add_parser(
|
|
1199
|
+
"stitch",
|
|
1200
|
+
help="Crop 2+ boxes from one scan, apply optional redactions, and stack bands vertically.",
|
|
1201
|
+
)
|
|
1202
|
+
p_stitch.add_argument("image", help="Source scan image path.")
|
|
1203
|
+
p_stitch.add_argument("out", nargs="?", default=None,
|
|
1204
|
+
help="Output stitched JPEG path (or pass --out).")
|
|
1205
|
+
p_stitch.add_argument("--out", "-o", "--output", dest="out_opt", default=None,
|
|
1206
|
+
help="Alias for the positional output path.")
|
|
1207
|
+
p_stitch.add_argument(
|
|
1208
|
+
"--box",
|
|
1209
|
+
action="extend",
|
|
1210
|
+
nargs="+",
|
|
1211
|
+
type=parse_box,
|
|
1212
|
+
required=True,
|
|
1213
|
+
help="Crop box x0,y0,x1,y1 in original image coordinates (repeatable; at least 2 required).",
|
|
1214
|
+
)
|
|
1215
|
+
p_stitch.add_argument(
|
|
1216
|
+
"--redact",
|
|
1217
|
+
action="extend",
|
|
1218
|
+
nargs="+",
|
|
1219
|
+
type=parse_box,
|
|
1220
|
+
default=[],
|
|
1221
|
+
help="Optional x0,y0,x1,y1 black redaction boxes in original image coordinates applied before cropping.",
|
|
1222
|
+
)
|
|
1223
|
+
p_stitch.add_argument(
|
|
1224
|
+
"--rotate",
|
|
1225
|
+
type=int,
|
|
1226
|
+
choices=(90, 180, 270),
|
|
1227
|
+
default=None,
|
|
1228
|
+
help="Optional clockwise rotation applied before redacting and cropping.",
|
|
1229
|
+
)
|
|
1230
|
+
p_stitch.add_argument(
|
|
1231
|
+
"--gap",
|
|
1232
|
+
type=int,
|
|
1233
|
+
default=6,
|
|
1234
|
+
help="Divider gap height in pixels between stacked bands (default: 6).",
|
|
1235
|
+
)
|
|
1236
|
+
p_stitch.add_argument(
|
|
1237
|
+
"--divider-color",
|
|
1238
|
+
default="#222222",
|
|
1239
|
+
help='Divider fill color as hex or RGB name (default: "#222222").',
|
|
1240
|
+
)
|
|
1241
|
+
p_stitch.add_argument(
|
|
1242
|
+
"--quality",
|
|
1243
|
+
type=int,
|
|
1244
|
+
default=90,
|
|
1245
|
+
help="Output JPEG quality 1..100 (default: 90).",
|
|
1246
|
+
)
|
|
1247
|
+
p_stitch.add_argument("--json", action="store_true", help="Emit JSON output (always enabled).")
|
|
1248
|
+
p_stitch.set_defaults(func=cmd_stitch)
|
|
1249
|
+
|
|
864
1250
|
return parser
|
|
865
1251
|
|
|
866
1252
|
|
|
1253
|
+
_BOX_FRAGMENT = re.compile(r"^-?[\d.]+(?:\s*,\s*-?[\d.]+)*\s*,$")
|
|
1254
|
+
|
|
1255
|
+
|
|
1256
|
+
def normalize_argv(argv: list[str]) -> list[str]:
|
|
1257
|
+
"""Rejoin box values the shell split on spaces: `--box 10, 20, 30, 40`."""
|
|
1258
|
+
out: list[str] = []
|
|
1259
|
+
for token in argv:
|
|
1260
|
+
if out and _BOX_FRAGMENT.match(out[-1]) and re.match(r"^-?[\d.]", token):
|
|
1261
|
+
out[-1] = out[-1] + token
|
|
1262
|
+
else:
|
|
1263
|
+
out.append(token)
|
|
1264
|
+
return out
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
# Subcommand -> (positional dest, --out alias dest).
|
|
1268
|
+
OUTPUT_ALIASES = {"crop": ("output", "output_opt"), "grid": ("out", "out_opt"),
|
|
1269
|
+
"stitch": ("out", "out_opt")}
|
|
1270
|
+
|
|
1271
|
+
|
|
1272
|
+
def resolve_output_alias(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
|
|
1273
|
+
dests = OUTPUT_ALIASES.get(getattr(args, "command", ""))
|
|
1274
|
+
if not dests:
|
|
1275
|
+
return
|
|
1276
|
+
positional, alias = dests
|
|
1277
|
+
pos_val, alias_val = getattr(args, positional), getattr(args, alias)
|
|
1278
|
+
if pos_val and alias_val and Path(pos_val) != Path(alias_val):
|
|
1279
|
+
parser.error(f"{args.command}: output given twice ({pos_val!r} and --out {alias_val!r}); "
|
|
1280
|
+
"pass it once.")
|
|
1281
|
+
value = pos_val or alias_val
|
|
1282
|
+
if not value:
|
|
1283
|
+
parser.error(f"{args.command}: missing output path; pass it positionally "
|
|
1284
|
+
f"(`prep-scan {args.command} <in> <out.jpg>`) or with --out <out.jpg>.")
|
|
1285
|
+
setattr(args, positional, value)
|
|
1286
|
+
|
|
1287
|
+
|
|
867
1288
|
def main(argv: list[str] | None = None) -> int:
|
|
868
1289
|
t0 = time.perf_counter()
|
|
869
1290
|
parser = build_parser()
|
|
870
|
-
args = parser.parse_args(argv)
|
|
1291
|
+
args = parser.parse_args(normalize_argv(list(sys.argv[1:] if argv is None else argv)))
|
|
1292
|
+
resolve_output_alias(parser, args)
|
|
871
1293
|
rc = 1
|
|
872
1294
|
bytes_out = 0
|
|
873
1295
|
try:
|
|
@@ -18,13 +18,15 @@ Path: `skills/acpl-persi/scripts/persi`
|
|
|
18
18
|
### Search by surname
|
|
19
19
|
|
|
20
20
|
```bash
|
|
21
|
-
# Lincoln articles, first 25 hits
|
|
21
|
+
# Lincoln articles, first 25 hits (persi search <Surname> is also accepted as an alias)
|
|
22
22
|
skills/acpl-persi/scripts/persi surname Lincoln
|
|
23
23
|
|
|
24
24
|
# JSON output, 50 hits
|
|
25
25
|
skills/acpl-persi/scripts/persi surname Lincoln --limit 50 --json
|
|
26
26
|
```
|
|
27
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
|
+
|
|
28
30
|
### Search by article-title keyword
|
|
29
31
|
|
|
30
32
|
```bash
|
|
@@ -85,9 +87,16 @@ PERSI result pages are POST forms, so there is no shareable result URL. This pri
|
|
|
85
87
|
4. Repeat across each state along a family's migration path.
|
|
86
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.
|
|
87
89
|
|
|
88
|
-
##
|
|
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.
|
|
89
98
|
|
|
90
|
-
|
|
99
|
+
No key or account is needed.
|
|
91
100
|
|
|
92
101
|
## Verified-live note
|
|
93
102
|
|