@kinloom/cli 0.1.0 → 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 (102) 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/init.js +3 -3
  50. package/dist/commands/ops/audit.d.ts +138 -0
  51. package/dist/commands/ops/audit.d.ts.map +1 -0
  52. package/dist/commands/ops/audit.js +867 -0
  53. package/dist/commands/ops/audit.js.map +1 -0
  54. package/dist/commands/ops/context.d.ts +100 -0
  55. package/dist/commands/ops/context.d.ts.map +1 -0
  56. package/dist/commands/ops/context.js +917 -0
  57. package/dist/commands/ops/context.js.map +1 -0
  58. package/dist/commands/ops/help.d.ts +6 -0
  59. package/dist/commands/ops/help.d.ts.map +1 -0
  60. package/dist/commands/ops/help.js +74 -0
  61. package/dist/commands/ops/help.js.map +1 -0
  62. package/dist/commands/ops/index.d.ts +6 -0
  63. package/dist/commands/ops/index.d.ts.map +1 -0
  64. package/dist/commands/ops/index.js +6 -0
  65. package/dist/commands/ops/index.js.map +1 -0
  66. package/dist/commands/ops/integrate.d.ts +56 -0
  67. package/dist/commands/ops/integrate.d.ts.map +1 -0
  68. package/dist/commands/ops/integrate.js +872 -0
  69. package/dist/commands/ops/integrate.js.map +1 -0
  70. package/dist/commands/ops/sync.d.ts +177 -0
  71. package/dist/commands/ops/sync.d.ts.map +1 -0
  72. package/dist/commands/ops/sync.js +1078 -0
  73. package/dist/commands/ops/sync.js.map +1 -0
  74. package/dist/commands/ops/telemetry.d.ts +79 -0
  75. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  76. package/dist/commands/ops/telemetry.js +249 -0
  77. package/dist/commands/ops/telemetry.js.map +1 -0
  78. package/dist/commands/records/help.d.ts +18 -0
  79. package/dist/commands/records/help.d.ts.map +1 -0
  80. package/dist/commands/records/help.js +174 -0
  81. package/dist/commands/records/help.js.map +1 -0
  82. package/dist/commands/records/index.d.ts +5 -0
  83. package/dist/commands/records/index.d.ts.map +1 -0
  84. package/dist/commands/records/index.js +5 -0
  85. package/dist/commands/records/index.js.map +1 -0
  86. package/dist/commands/records/registry.d.ts +32 -0
  87. package/dist/commands/records/registry.d.ts.map +1 -0
  88. package/dist/commands/records/registry.js +227 -0
  89. package/dist/commands/records/registry.js.map +1 -0
  90. package/dist/commands/records/resolve.d.ts +14 -0
  91. package/dist/commands/records/resolve.d.ts.map +1 -0
  92. package/dist/commands/records/resolve.js +61 -0
  93. package/dist/commands/records/resolve.js.map +1 -0
  94. package/dist/commands/records/runner.d.ts +25 -0
  95. package/dist/commands/records/runner.d.ts.map +1 -0
  96. package/dist/commands/records/runner.js +224 -0
  97. package/dist/commands/records/runner.js.map +1 -0
  98. package/dist/index.d.ts +2 -0
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +2 -0
  101. package/dist/index.js.map +1 -1
  102. package/package.json +3 -3
@@ -0,0 +1,891 @@
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = [
5
+ # "httpx>=0.27",
6
+ # "pillow>=10.0",
7
+ # ]
8
+ # ///
9
+ """Scan preparation CLI: compact previews, redacted crops, census strips, and selective PDF page renders."""
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ from concurrent.futures import ThreadPoolExecutor
15
+ from dataclasses import dataclass
16
+ from datetime import datetime, timezone
17
+ import hashlib
18
+ import io
19
+ import json
20
+ import os
21
+ from pathlib import Path
22
+ import re
23
+ import shutil
24
+ import subprocess
25
+ import sys
26
+ import time
27
+ from typing import TYPE_CHECKING, Any
28
+ from urllib.parse import urlparse
29
+
30
+ if TYPE_CHECKING:
31
+ from PIL import Image as PILImageModule
32
+
33
+ DEFAULT_MAX_WORKERS = 8
34
+ DEFAULT_TIMEOUT_S = 12.0
35
+ DEFAULT_PDF_TIMEOUT_S = 60
36
+ USER_AGENT = "kinloom-prep-scan/1.0 (genealogy archival tooling)"
37
+ PDF_PAGE_NUM_RE = re.compile(r"-(\d+)\.jpg$", re.IGNORECASE)
38
+
39
+
40
+ def default_cache_root() -> Path:
41
+ env_dir = os.environ.get("KINLOOM_OCR_CACHE_DIR", "").strip()
42
+ if env_dir:
43
+ return Path(env_dir).expanduser()
44
+ xdg = os.environ.get("XDG_CACHE_HOME", "").strip()
45
+ if xdg:
46
+ return Path(xdg).expanduser() / "kinloom-ocr"
47
+ return Path.home() / ".cache" / "kinloom-ocr"
48
+
49
+
50
+ def default_telemetry_file() -> Path:
51
+ env_file = os.environ.get("KINLOOM_TELEMETRY_FILE", "").strip()
52
+ if env_file:
53
+ return Path(env_file).expanduser()
54
+ xdg = os.environ.get("XDG_CACHE_HOME", "").strip()
55
+ if xdg:
56
+ return Path(xdg).expanduser() / "kinloom-telemetry" / "calls.jsonl"
57
+ return Path.home() / ".cache" / "kinloom-telemetry" / "calls.jsonl"
58
+
59
+
60
+ def require_pillow() -> tuple[Any, Any, Any, Any]:
61
+ try:
62
+ from PIL import Image, ImageDraw, ImageFont, ImageOps
63
+ except ImportError as exc:
64
+ raise RuntimeError(
65
+ "Pillow is required for image operations. Run via `uv run --script` "
66
+ "or install it with `pip install pillow`."
67
+ ) from exc
68
+ return Image, ImageDraw, ImageFont, ImageOps
69
+
70
+
71
+ def append_telemetry(subcmd: str, duration_ms: float, exit_code: int, bytes_out: int) -> None:
72
+ if (
73
+ os.environ.get("KINLOOM_TELEMETRY_PARENT") == "1"
74
+ or os.environ.get("KINLOOM_TELEMETRY_ACTIVE") == "1"
75
+ ):
76
+ return
77
+ try:
78
+ target = default_telemetry_file()
79
+ target.parent.mkdir(parents=True, exist_ok=True)
80
+ entry = {
81
+ "ts": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
82
+ "cmd": "prep-scan.py",
83
+ "subcmd": f"prep-scan {subcmd}" if subcmd else "prep-scan",
84
+ "person_id": None,
85
+ "duration_ms": max(0, int(round(duration_ms))),
86
+ "cache_hit": None,
87
+ "exit_code": int(exit_code),
88
+ "bytes_out": max(0, int(bytes_out)),
89
+ }
90
+ with open(target, "a", encoding="utf-8") as fh:
91
+ fh.write(json.dumps(entry, separators=(",", ":")) + "\n")
92
+ except Exception:
93
+ pass
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class Box:
98
+ x0: int
99
+ y0: int
100
+ x1: int
101
+ y1: int
102
+
103
+
104
+ @dataclass(frozen=True)
105
+ class SavedImage:
106
+ path: Path
107
+ width: int
108
+ height: int
109
+ bytes: int
110
+
111
+ def to_dict(self) -> dict[str, object]:
112
+ return {
113
+ "path": str(self.path),
114
+ "width": self.width,
115
+ "height": self.height,
116
+ "bytes": self.bytes,
117
+ "kb": round(self.bytes / 1024.0, 1),
118
+ }
119
+
120
+
121
+ def parse_box(raw: str) -> Box:
122
+ parts = [p.strip() for p in raw.split(",")]
123
+ if len(parts) != 4:
124
+ raise argparse.ArgumentTypeError(f"Invalid box '{raw}': expected x0,y0,x1,y1.")
125
+ try:
126
+ x0, y0, x1, y1 = (int(p) for p in parts)
127
+ except ValueError as exc:
128
+ raise argparse.ArgumentTypeError(f"Invalid integer coordinates in box '{raw}'.") from exc
129
+ if x0 < 0 or y0 < 0 or x1 <= x0 or y1 <= y0:
130
+ raise argparse.ArgumentTypeError(
131
+ f"Invalid box '{raw}': require 0 <= x0 < x1 and 0 <= y0 < y1."
132
+ )
133
+ return Box(x0, y0, x1, y1)
134
+
135
+
136
+ def parse_page_spec(raw: str) -> list[int]:
137
+ pages: set[int] = set()
138
+ for part in raw.split(","):
139
+ token = part.strip()
140
+ if not token:
141
+ continue
142
+ if "-" in token:
143
+ bounds = token.split("-", 1)
144
+ try:
145
+ start = int(bounds[0].strip())
146
+ end = int(bounds[1].strip())
147
+ except ValueError as exc:
148
+ raise ValueError(f"Invalid page range '{token}' in --pages '{raw}'.") from exc
149
+ if start < 1 or end < start:
150
+ raise ValueError(f"Invalid page range '{token}': require 1 <= start <= end.")
151
+ if end - start > 500:
152
+ raise ValueError(f"Page range '{token}' exceeds 500-page safety limit.")
153
+ pages.update(range(start, end + 1))
154
+ else:
155
+ try:
156
+ num = int(token)
157
+ except ValueError as exc:
158
+ raise ValueError(f"Invalid page number '{token}' in --pages '{raw}'.") from exc
159
+ if num < 1:
160
+ raise ValueError(f"Page number must be >= 1, got {num}.")
161
+ pages.add(num)
162
+ if not pages:
163
+ raise ValueError(f"No valid pages parsed from --pages '{raw}'.")
164
+ return sorted(pages)
165
+
166
+
167
+ def coalesce_ranges(pages: list[int]) -> list[tuple[int, int]]:
168
+ ranges: list[tuple[int, int]] = []
169
+ start = prev = pages[0]
170
+ for p in pages[1:]:
171
+ if p == prev + 1:
172
+ prev = p
173
+ else:
174
+ ranges.append((start, prev))
175
+ start = prev = p
176
+ ranges.append((start, prev))
177
+ return ranges
178
+
179
+
180
+ def clamp_box(box: Box, width: int, height: int, label: str) -> Box:
181
+ if box.x0 >= width or box.y0 >= height:
182
+ raise ValueError(
183
+ f"{label} ({box.x0},{box.y0},{box.x1},{box.y1}) starts outside {width}x{height} image."
184
+ )
185
+ x1 = min(box.x1, width)
186
+ y1 = min(box.y1, height)
187
+ if x1 <= box.x0 or y1 <= box.y0:
188
+ raise ValueError(f"{label} collapses to empty area inside {width}x{height} image.")
189
+ return Box(box.x0, box.y0, x1, y1)
190
+
191
+
192
+ def to_rgb(im: PILImageModule.Image) -> PILImageModule.Image:
193
+ Image, _, _, ImageOps = require_pillow()
194
+ im = ImageOps.exif_transpose(im)
195
+ if im.mode == "RGB":
196
+ return im
197
+ if im.mode in ("RGBA", "LA") or (im.mode == "P" and "transparency" in im.info):
198
+ rgba = im.convert("RGBA")
199
+ bg = Image.new("RGB", rgba.size, (255, 255, 255))
200
+ bg.paste(rgba, mask=rgba.split()[3])
201
+ return bg
202
+ return im.convert("RGB")
203
+
204
+
205
+ def rotate_clockwise(im: PILImageModule.Image, degrees: int | None) -> PILImageModule.Image:
206
+ if not degrees:
207
+ return im
208
+ Image, _, _, _ = require_pillow()
209
+ if degrees == 90:
210
+ return im.transpose(Image.Transpose.ROTATE_270)
211
+ if degrees == 180:
212
+ return im.transpose(Image.Transpose.ROTATE_180)
213
+ if degrees == 270:
214
+ return im.transpose(Image.Transpose.ROTATE_90)
215
+ raise ValueError(f"Unsupported rotation '{degrees}': expected 90, 180, or 270.")
216
+
217
+
218
+ def atomic_write_bytes(dest: Path, data: bytes) -> None:
219
+ dest.parent.mkdir(parents=True, exist_ok=True)
220
+ tmp = dest.with_name(f".{dest.name}.{os.getpid()}.tmp")
221
+ try:
222
+ tmp.write_bytes(data)
223
+ os.replace(tmp, dest)
224
+ except Exception:
225
+ if tmp.exists():
226
+ tmp.unlink(missing_ok=True)
227
+ raise
228
+
229
+
230
+ def encode_jpeg_under_kb(
231
+ im: PILImageModule.Image, max_width: int, max_kb: int
232
+ ) -> tuple[bytes, int, int]:
233
+ Image, _, _, _ = require_pillow()
234
+ rgb = to_rgb(im)
235
+ w, h = rgb.size
236
+ if max_width > 0 and w > max_width:
237
+ new_h = max(1, int(round(h * (max_width / w))))
238
+ rgb = rgb.resize((max_width, new_h), Image.Resampling.LANCZOS)
239
+
240
+ limit_bytes = max(1024, int(max_kb * 1024))
241
+ base_w, base_h = rgb.size
242
+ best_data: bytes = b""
243
+ best_size = (base_w, base_h)
244
+
245
+ for scale in (1.0, 0.88, 0.76, 0.64, 0.52, 0.42, 0.34, 0.25):
246
+ cur = (
247
+ rgb
248
+ if scale == 1.0
249
+ else rgb.resize(
250
+ (max(1, int(round(base_w * scale))), max(1, int(round(base_h * scale)))),
251
+ Image.Resampling.LANCZOS,
252
+ )
253
+ )
254
+ for quality in (84, 76, 68, 60, 52, 44, 36):
255
+ buf = io.BytesIO()
256
+ cur.save(buf, format="JPEG", quality=quality, optimize=True)
257
+ data = buf.getvalue()
258
+ best_data = data
259
+ best_size = cur.size
260
+ if len(data) <= limit_bytes:
261
+ return data, cur.size[0], cur.size[1]
262
+
263
+ return best_data, best_size[0], best_size[1]
264
+
265
+
266
+ def save_compact_jpeg(
267
+ im: PILImageModule.Image, out_path: Path, max_width: int, max_kb: int
268
+ ) -> SavedImage:
269
+ data, width, height = encode_jpeg_under_kb(im, max_width=max_width, max_kb=max_kb)
270
+ atomic_write_bytes(out_path, data)
271
+ return SavedImage(path=out_path, width=width, height=height, bytes=len(data))
272
+
273
+
274
+ def save_archival_image(im: PILImageModule.Image, out_path: Path) -> SavedImage:
275
+ rgb = to_rgb(im)
276
+ ext = out_path.suffix.lower()
277
+ buf = io.BytesIO()
278
+ if ext == ".png":
279
+ rgb.save(buf, format="PNG", optimize=True)
280
+ elif ext == ".webp":
281
+ rgb.save(buf, format="WEBP", quality=92)
282
+ else:
283
+ rgb.save(buf, format="JPEG", quality=92, optimize=True)
284
+ data = buf.getvalue()
285
+ atomic_write_bytes(out_path, data)
286
+ return SavedImage(path=out_path, width=rgb.size[0], height=rgb.size[1], bytes=len(data))
287
+
288
+
289
+ def safe_stem(name: str) -> str:
290
+ cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("_")
291
+ return cleaned or "scan"
292
+
293
+
294
+ def emit_output(text: str) -> int:
295
+ sys.stdout.write(text)
296
+ return len(text.encode("utf-8"))
297
+
298
+
299
+ def cmd_preview(args: argparse.Namespace) -> tuple[int, int]:
300
+ Image, _, _, ImageOps = require_pillow()
301
+ out_dir = Path(args.out_dir).resolve()
302
+ out_dir.mkdir(parents=True, exist_ok=True)
303
+
304
+ inputs = [Path(p).resolve() for p in args.images]
305
+ missing = [str(p) for p in inputs if not p.is_file()]
306
+ if missing:
307
+ for m in missing:
308
+ print(f"Error: input file not found: {m}", file=sys.stderr)
309
+ return 1, 0
310
+
311
+ stem_counts: dict[str, int] = {}
312
+ for p in inputs:
313
+ stem = safe_stem(p.stem)
314
+ stem_counts[stem] = stem_counts.get(stem, 0) + 1
315
+
316
+ def build_one(src: Path) -> dict[str, object]:
317
+ stem = safe_stem(src.stem)
318
+ if stem_counts[stem] > 1:
319
+ suffix = hashlib.sha256(str(src).encode("utf-8")).hexdigest()[:8]
320
+ out_name = f"{stem}_{suffix}.preview.jpg"
321
+ else:
322
+ out_name = f"{stem}.preview.jpg"
323
+ out_path = out_dir / out_name
324
+ with Image.open(src) as im:
325
+ orig_w, orig_h = ImageOps.exif_transpose(im).size
326
+ saved = save_compact_jpeg(im, out_path, max_width=args.max_width, max_kb=args.max_kb)
327
+ return {
328
+ "source": str(src),
329
+ "source_size": [orig_w, orig_h],
330
+ **saved.to_dict(),
331
+ }
332
+
333
+ workers = min(DEFAULT_MAX_WORKERS, max(1, len(inputs)))
334
+ with ThreadPoolExecutor(max_workers=workers) as pool:
335
+ results = list(pool.map(build_one, inputs))
336
+
337
+ if args.json:
338
+ out_bytes = emit_output(json.dumps(results, indent=2) + "\n")
339
+ else:
340
+ lines = [
341
+ f"{item['path']} {item['width']}x{item['height']} {item['kb']:.1f} KB"
342
+ for item in results
343
+ ]
344
+ out_bytes = emit_output("\n".join(lines) + ("\n" if lines else ""))
345
+ return 0, out_bytes
346
+
347
+
348
+ def cmd_crop(args: argparse.Namespace) -> tuple[int, int]:
349
+ Image, ImageDraw, _, _ = require_pillow()
350
+ src = Path(args.input).resolve()
351
+ out_path = Path(args.output).resolve()
352
+ if not src.is_file():
353
+ print(f"Error: input file not found: {src}", file=sys.stderr)
354
+ return 1, 0
355
+
356
+ with Image.open(src) as raw_im:
357
+ img = rotate_clockwise(to_rgb(raw_im), args.rotate)
358
+
359
+ crop_box = clamp_box(args.box, img.width, img.height, "crop --box")
360
+ cropped = img.crop((crop_box.x0, crop_box.y0, crop_box.x1, crop_box.y1))
361
+
362
+ redactions: list[list[int]] = []
363
+ if args.redact:
364
+ draw = ImageDraw.Draw(cropped)
365
+ for idx, rbox in enumerate(args.redact, 1):
366
+ clamped = clamp_box(rbox, cropped.width, cropped.height, f"--redact #{idx}")
367
+ draw.rectangle((clamped.x0, clamped.y0, clamped.x1, clamped.y1), fill=(0, 0, 0))
368
+ redactions.append([clamped.x0, clamped.y0, clamped.x1, clamped.y1])
369
+
370
+ saved = save_archival_image(cropped, out_path)
371
+
372
+ if args.preview_out:
373
+ preview_path = Path(args.preview_out).resolve()
374
+ else:
375
+ digest = hashlib.sha256(str(out_path).encode("utf-8")).hexdigest()[:8]
376
+ preview_path = (
377
+ default_cache_root()
378
+ / "previews"
379
+ / f"{safe_stem(out_path.stem)}_{digest}.preview.jpg"
380
+ )
381
+
382
+ preview = save_compact_jpeg(cropped, preview_path, max_width=args.max_width, max_kb=args.max_kb)
383
+
384
+ payload = {
385
+ "source": str(src),
386
+ "rotate": args.rotate or 0,
387
+ "box": [crop_box.x0, crop_box.y0, crop_box.x1, crop_box.y1],
388
+ "redactions": redactions,
389
+ "output": saved.to_dict(),
390
+ "preview": preview.to_dict(),
391
+ }
392
+
393
+ if args.json:
394
+ out_bytes = emit_output(json.dumps(payload, indent=2) + "\n")
395
+ else:
396
+ text = (
397
+ f"output: {saved.path} {saved.width}x{saved.height} {saved.bytes / 1024:.1f} KB\n"
398
+ f"preview: {preview.path} {preview.width}x{preview.height} {preview.bytes / 1024:.1f} KB\n"
399
+ )
400
+ out_bytes = emit_output(text)
401
+ return 0, out_bytes
402
+
403
+
404
+ def is_url(target: str) -> bool:
405
+ parsed = urlparse(target)
406
+ return parsed.scheme in ("http", "https") and bool(parsed.netloc)
407
+
408
+
409
+ def short_label(target: str, index: int) -> str:
410
+ if is_url(target):
411
+ parsed = urlparse(target)
412
+ tail = Path(parsed.path).name or parsed.netloc
413
+ return f"[{index:02d}] {tail}"
414
+ return f"[{index:02d}] {Path(target).name}"
415
+
416
+
417
+ def load_image_from_source(target: str, timeout_s: float) -> PILImageModule.Image:
418
+ Image, _, _, _ = require_pillow()
419
+ if is_url(target):
420
+ try:
421
+ import httpx
422
+ except ImportError as exc:
423
+ raise RuntimeError(
424
+ "httpx is required for URL downloads. Run via `uv run --script` "
425
+ "or install it with `pip install httpx`."
426
+ ) from exc
427
+
428
+ with httpx.Client(
429
+ timeout=timeout_s,
430
+ follow_redirects=True,
431
+ headers={"User-Agent": USER_AGENT},
432
+ ) as client:
433
+ resp = client.get(target)
434
+ resp.raise_for_status()
435
+ return to_rgb(Image.open(io.BytesIO(resp.content)))
436
+ path = Path(target).resolve()
437
+ if not path.is_file():
438
+ raise FileNotFoundError(f"file not found: {path}")
439
+ with Image.open(path) as im:
440
+ return to_rgb(im.copy())
441
+
442
+
443
+ def extract_band(
444
+ im: PILImageModule.Image, band: str, band_pct: float, rotate_left: bool
445
+ ) -> PILImageModule.Image:
446
+ Image, _, _, _ = require_pillow()
447
+ frac = max(0.02, min(1.0, band_pct / 100.0))
448
+ w, h = im.size
449
+ if band == "top":
450
+ cut_h = max(1, int(round(h * frac)))
451
+ return im.crop((0, 0, w, cut_h))
452
+ cut_w = max(1, int(round(w * frac)))
453
+ strip = im.crop((0, 0, cut_w, h))
454
+ if rotate_left:
455
+ strip = strip.transpose(Image.Transpose.ROTATE_270)
456
+ return strip
457
+
458
+
459
+ def build_labeled_contact_strip(
460
+ items: list[tuple[str, PILImageModule.Image]],
461
+ out_path: Path,
462
+ target_width: int,
463
+ max_kb: int,
464
+ ) -> SavedImage:
465
+ Image, ImageDraw, ImageFont, _ = require_pillow()
466
+ resized: list[tuple[str, Any]] = []
467
+ for label, im in items:
468
+ rgb = to_rgb(im)
469
+ if rgb.width != target_width:
470
+ scaled_h = max(1, int(round(rgb.height * (target_width / rgb.width))))
471
+ rgb = rgb.resize((target_width, scaled_h), Image.Resampling.LANCZOS)
472
+ resized.append((label, rgb))
473
+
474
+ font = ImageFont.load_default()
475
+ header_h = 26
476
+ gap_h = 6
477
+ total_h = sum(header_h + im.height + gap_h for _, im in resized)
478
+ canvas = Image.new("RGB", (target_width, max(1, total_h)), (24, 24, 24))
479
+ draw = ImageDraw.Draw(canvas)
480
+ y = 0
481
+ for label, im in resized:
482
+ draw.rectangle((0, y, target_width, y + header_h), fill=(20, 28, 38))
483
+ draw.text((8, y + 6), label[:180], fill=(255, 255, 255), font=font)
484
+ y += header_h
485
+ canvas.paste(im, (0, y))
486
+ y += im.height + gap_h
487
+ return save_compact_jpeg(canvas, out_path, max_width=target_width, max_kb=max_kb)
488
+
489
+
490
+ def cmd_sheet_strip(args: argparse.Namespace) -> tuple[int, int]:
491
+ Image, ImageDraw, ImageFont, _ = require_pillow()
492
+ sources: list[str] = list(args.sources)
493
+ out_path = Path(args.out).resolve()
494
+ target_width = args.width
495
+
496
+ def fetch_one(item: tuple[int, str]) -> dict[str, Any]:
497
+ idx, src = item
498
+ label = short_label(src, idx)
499
+ try:
500
+ im = load_image_from_source(src, timeout_s=args.timeout)
501
+ band_im = extract_band(
502
+ im, args.band, args.band_pct, rotate_left=not args.no_rotate_left
503
+ )
504
+ if band_im.width != target_width:
505
+ scaled_h = max(1, int(round(band_im.height * (target_width / band_im.width))))
506
+ band_im = band_im.resize((target_width, scaled_h), Image.Resampling.LANCZOS)
507
+ return {
508
+ "index": idx,
509
+ "source": src,
510
+ "label": label,
511
+ "image": band_im,
512
+ "error": None,
513
+ }
514
+ except Exception as exc:
515
+ return {
516
+ "index": idx,
517
+ "source": src,
518
+ "label": label,
519
+ "image": None,
520
+ "error": str(exc),
521
+ }
522
+
523
+ workers = min(DEFAULT_MAX_WORKERS, max(1, len(sources)))
524
+ with ThreadPoolExecutor(max_workers=workers) as pool:
525
+ fetched = list(pool.map(fetch_one, enumerate(sources, 1)))
526
+
527
+ ok_count = sum(1 for row in fetched if row["image"] is not None)
528
+ if ok_count == 0:
529
+ for row in fetched:
530
+ print(f"Error {row['label']}: {row['error']}", file=sys.stderr)
531
+ return 1, 0
532
+
533
+ font = ImageFont.load_default()
534
+ header_h = 26
535
+ error_h = 36
536
+ gap_h = 6
537
+ total_h = sum(
538
+ header_h + (row["image"].height if row["image"] is not None else error_h) + gap_h
539
+ for row in fetched
540
+ )
541
+
542
+ canvas = Image.new("RGB", (target_width, max(1, total_h)), (24, 24, 24))
543
+ draw = ImageDraw.Draw(canvas)
544
+ y = 0
545
+ for row in fetched:
546
+ draw.rectangle((0, y, target_width, y + header_h), fill=(20, 28, 38))
547
+ header_text = str(row["label"])
548
+ if row["error"]:
549
+ header_text = f"{header_text} ERROR: {row['error']}"
550
+ draw.text((8, y + 6), header_text[:180], fill=(255, 255, 255), font=font)
551
+ y += header_h
552
+ band_im = row["image"]
553
+ if band_im is not None:
554
+ canvas.paste(band_im, (0, y))
555
+ y += band_im.height + gap_h
556
+ else:
557
+ draw.rectangle((0, y, target_width, y + error_h), fill=(90, 20, 20))
558
+ draw.text((8, y + 10), str(row["error"])[:180], fill=(255, 220, 220), font=font)
559
+ y += error_h + gap_h
560
+
561
+ saved = save_compact_jpeg(canvas, out_path, max_width=target_width, max_kb=args.max_kb)
562
+ errors = [{"source": r["source"], "error": r["error"]} for r in fetched if r["error"]]
563
+
564
+ payload = {
565
+ "band": args.band,
566
+ "band_pct": args.band_pct,
567
+ "count": len(sources),
568
+ "ok": ok_count,
569
+ "errors": errors,
570
+ **saved.to_dict(),
571
+ }
572
+
573
+ if args.json:
574
+ out_bytes = emit_output(json.dumps(payload, indent=2) + "\n")
575
+ else:
576
+ text = (
577
+ f"{saved.path} {saved.width}x{saved.height} {saved.bytes / 1024:.1f} KB "
578
+ f"({ok_count}/{len(sources)} bands)\n"
579
+ )
580
+ out_bytes = emit_output(text)
581
+ for err in errors:
582
+ print(f"warning: {err['source']}: {err['error']}", file=sys.stderr)
583
+ return 0, out_bytes
584
+
585
+
586
+ def cmd_pdf_pages(args: argparse.Namespace) -> tuple[int, int]:
587
+ Image, _, _, ImageOps = require_pillow()
588
+ pdf_path = Path(args.pdf_path).resolve()
589
+ if not pdf_path.is_file():
590
+ print(f"Error: PDF file not found: {pdf_path}", file=sys.stderr)
591
+ return 1, 0
592
+
593
+ pdftoppm_bin = shutil.which("pdftoppm")
594
+ if not pdftoppm_bin:
595
+ print(
596
+ "Error: pdftoppm executable not found on PATH. Install poppler-utils "
597
+ "(for example `apt install poppler-utils` or `brew install poppler`).",
598
+ file=sys.stderr,
599
+ )
600
+ return 1, 0
601
+ timeout_bin = shutil.which("timeout")
602
+
603
+ requested_pages = parse_page_spec(args.pages)
604
+ ranges = coalesce_ranges(requested_pages)
605
+
606
+ out_dir = Path(args.out_dir).resolve()
607
+ out_dir.mkdir(parents=True, exist_ok=True)
608
+ # Keep intermediate files inside out_dir instead of /tmp tmpfs RAM.
609
+ stage_dir = out_dir / f".pdf_stage_{os.getpid()}_{time.time_ns()}"
610
+ stage_dir.mkdir(parents=True, exist_ok=True)
611
+
612
+ rendered_by_page: dict[int, Path] = {}
613
+ try:
614
+ for r_idx, (start_p, end_p) in enumerate(ranges):
615
+ prefix = stage_dir / f"r{r_idx}"
616
+ base_cmd = [
617
+ pdftoppm_bin,
618
+ "-jpeg",
619
+ "-r",
620
+ str(args.dpi),
621
+ "-f",
622
+ str(start_p),
623
+ "-l",
624
+ str(end_p),
625
+ str(pdf_path),
626
+ str(prefix),
627
+ ]
628
+ cmd = (
629
+ [timeout_bin, str(DEFAULT_PDF_TIMEOUT_S), *base_cmd]
630
+ if timeout_bin
631
+ else base_cmd
632
+ )
633
+ try:
634
+ proc = subprocess.run(
635
+ cmd, capture_output=True, text=True, timeout=DEFAULT_PDF_TIMEOUT_S + 5
636
+ )
637
+ except subprocess.TimeoutExpired:
638
+ print(
639
+ f"Error: pdftoppm timed out after {DEFAULT_PDF_TIMEOUT_S}s on pages {start_p}-{end_p}.",
640
+ file=sys.stderr,
641
+ )
642
+ return 1, 0
643
+ if proc.returncode != 0:
644
+ detail = (proc.stderr or proc.stdout).strip()[:300]
645
+ print(
646
+ f"Error: pdftoppm failed (exit {proc.returncode}) on pages {start_p}-{end_p}: {detail}",
647
+ file=sys.stderr,
648
+ )
649
+ return 1, 0
650
+
651
+ for img_file in sorted(stage_dir.glob(f"r{r_idx}-*.jpg")):
652
+ m = PDF_PAGE_NUM_RE.search(img_file.name)
653
+ if not m:
654
+ continue
655
+ page_num = int(m.group(1))
656
+ dest_page = out_dir / f"page-{page_num:03d}.jpg"
657
+ os.replace(img_file, dest_page)
658
+ rendered_by_page[page_num] = dest_page
659
+ finally:
660
+ shutil.rmtree(stage_dir, ignore_errors=True)
661
+
662
+ if not rendered_by_page:
663
+ print(
664
+ f"Error: no pages were rendered for --pages '{args.pages}' from {pdf_path}.",
665
+ file=sys.stderr,
666
+ )
667
+ return 1, 0
668
+
669
+ ordered_pages = [(p, rendered_by_page[p]) for p in requested_pages if p in rendered_by_page]
670
+
671
+ def build_preview(item: tuple[int, Path]) -> dict[str, Any]:
672
+ page_num, page_path = item
673
+ preview_path = out_dir / f"page-{page_num:03d}.preview.jpg"
674
+ page_bytes = page_path.stat().st_size
675
+ with Image.open(page_path) as im:
676
+ orig_w, orig_h = ImageOps.exif_transpose(im).size
677
+ saved_prev = save_compact_jpeg(
678
+ im, preview_path, max_width=args.max_width, max_kb=args.max_kb
679
+ )
680
+ return {
681
+ "page": page_num,
682
+ "path": str(page_path),
683
+ "width": orig_w,
684
+ "height": orig_h,
685
+ "bytes": page_bytes,
686
+ "kb": round(page_bytes / 1024.0, 1),
687
+ "preview": saved_prev.to_dict(),
688
+ }
689
+
690
+ workers = min(DEFAULT_MAX_WORKERS, max(1, len(ordered_pages)))
691
+ with ThreadPoolExecutor(max_workers=workers) as pool:
692
+ page_records = list(pool.map(build_preview, ordered_pages))
693
+
694
+ strip_info: dict[str, Any] | None = None
695
+ if args.strip:
696
+ strip_items: list[tuple[str, Any]] = []
697
+ for rec in page_records:
698
+ p_num = int(rec["page"])
699
+ prev_path = Path(str(rec["preview"]["path"]))
700
+ with Image.open(prev_path) as im:
701
+ strip_items.append((f"[p.{p_num:03d}] {pdf_path.name}", im.copy()))
702
+ strip_saved = build_labeled_contact_strip(
703
+ strip_items,
704
+ Path(args.strip).resolve(),
705
+ target_width=args.max_width,
706
+ max_kb=args.max_kb,
707
+ )
708
+ strip_info = strip_saved.to_dict()
709
+
710
+ missing_pages = [p for p in requested_pages if p not in rendered_by_page]
711
+ payload: dict[str, object] = {
712
+ "pdf": str(pdf_path),
713
+ "dpi": args.dpi,
714
+ "requested_pages": requested_pages,
715
+ "missing_pages": missing_pages,
716
+ "pages": page_records,
717
+ }
718
+ if strip_info is not None:
719
+ payload["strip"] = strip_info
720
+
721
+ if args.json:
722
+ out_bytes = emit_output(json.dumps(payload, indent=2) + "\n")
723
+ else:
724
+ lines: list[str] = []
725
+ for rec in page_records:
726
+ prev = rec["preview"]
727
+ lines.append(
728
+ f"p.{int(rec['page']):03d} {rec['path']} ({rec['kb']:.1f} KB) "
729
+ f"preview: {prev['path']} ({prev['kb']:.1f} KB)"
730
+ )
731
+ if strip_info is not None:
732
+ lines.append(
733
+ f"strip: {strip_info['path']} {strip_info['width']}x{strip_info['height']} "
734
+ f"{strip_info['kb']:.1f} KB"
735
+ )
736
+ out_bytes = emit_output("\n".join(lines) + "\n")
737
+ return 0, out_bytes
738
+
739
+
740
+ def build_parser() -> argparse.ArgumentParser:
741
+ parser = argparse.ArgumentParser(
742
+ prog="kinloom prep-scan",
743
+ description=(
744
+ "Generate compact inspection previews, redacted archival crops, "
745
+ "census sheet-strip contact sheets, and selective PDF page renders."
746
+ ),
747
+ )
748
+ sub = parser.add_subparsers(dest="command", required=True)
749
+
750
+ p_prev = sub.add_parser("preview", help="Generate compact JPEG inspection previews in parallel.")
751
+ p_prev.add_argument("images", nargs="+", help="Input image path(s).")
752
+ p_prev.add_argument("--out-dir", required=True, help="Output directory for preview JPEGs.")
753
+ p_prev.add_argument(
754
+ "--max-width", type=int, default=1400, help="Maximum pixel width (default: 1400)."
755
+ )
756
+ p_prev.add_argument(
757
+ "--max-kb", type=int, default=280, help="Maximum file size in KB (default: 280)."
758
+ )
759
+ p_prev.add_argument("--json", action="store_true", help="Emit JSON output.")
760
+ p_prev.set_defaults(func=cmd_preview)
761
+
762
+ p_crop = sub.add_parser(
763
+ "crop",
764
+ help="Rotate, crop, apply solid black redaction boxes (in cropped coordinates), and auto-write a verification preview.",
765
+ )
766
+ p_crop.add_argument("input", help="Source scan path.")
767
+ p_crop.add_argument("output", help="Final archival output scan path.")
768
+ p_crop.add_argument(
769
+ "--box", required=True, type=parse_box, help="Crop box x0,y0,x1,y1 after optional --rotate."
770
+ )
771
+ p_crop.add_argument(
772
+ "--rotate",
773
+ type=int,
774
+ choices=(90, 180, 270),
775
+ default=None,
776
+ help="Optional clockwise rotation applied before cropping.",
777
+ )
778
+ p_crop.add_argument(
779
+ "--redact",
780
+ action="extend",
781
+ nargs="+",
782
+ type=parse_box,
783
+ default=[],
784
+ help="One or more x0,y0,x1,y1 black redaction boxes in cropped-image coordinates.",
785
+ )
786
+ p_crop.add_argument(
787
+ "--preview-out",
788
+ default=None,
789
+ help="Optional explicit path for the < 280 KB verification preview (defaults to cache previews dir).",
790
+ )
791
+ p_crop.add_argument(
792
+ "--max-width", type=int, default=1400, help="Preview maximum pixel width (default: 1400)."
793
+ )
794
+ p_crop.add_argument(
795
+ "--max-kb", type=int, default=280, help="Preview maximum size in KB (default: 280)."
796
+ )
797
+ p_crop.add_argument("--json", action="store_true", help="Emit JSON output.")
798
+ p_crop.set_defaults(func=cmd_crop)
799
+
800
+ p_strip = sub.add_parser(
801
+ "sheet-strip",
802
+ help="Download or read census sheet header/street bands in parallel and stitch one labeled contact sheet.",
803
+ )
804
+ p_strip.add_argument("sources", nargs="+", help="Image URLs or local file paths.")
805
+ p_strip.add_argument(
806
+ "--out", required=True, help="Output JPEG path for the stitched contact sheet."
807
+ )
808
+ p_strip.add_argument(
809
+ "--band",
810
+ choices=("top", "left"),
811
+ default="top",
812
+ help="Band edge to slice (default: top).",
813
+ )
814
+ p_strip.add_argument(
815
+ "--band-pct",
816
+ type=float,
817
+ default=18.0,
818
+ help="Percent of image height/width to slice (default: 18).",
819
+ )
820
+ p_strip.add_argument(
821
+ "--max-kb", type=int, default=250, help="Maximum output file size in KB (default: 250)."
822
+ )
823
+ p_strip.add_argument(
824
+ "--width", type=int, default=1400, help="Normalized strip width in pixels (default: 1400)."
825
+ )
826
+ p_strip.add_argument(
827
+ "--timeout",
828
+ type=float,
829
+ default=DEFAULT_TIMEOUT_S,
830
+ help="Per-URL HTTP timeout seconds (default: 12).",
831
+ )
832
+ p_strip.add_argument(
833
+ "--no-rotate-left",
834
+ action="store_true",
835
+ help="Keep --band left vertical instead of rotating 90 deg CW for horizontal reading.",
836
+ )
837
+ p_strip.add_argument("--json", action="store_true", help="Emit JSON output.")
838
+ p_strip.set_defaults(func=cmd_sheet_strip)
839
+
840
+ p_pdf = sub.add_parser(
841
+ "pdf-pages",
842
+ help="Render only requested PDF pages via pdftoppm, build < 280 KB previews in parallel, and optionally build a contact strip.",
843
+ )
844
+ p_pdf.add_argument("pdf_path", help="Path to source PDF file.")
845
+ p_pdf.add_argument("--pages", required=True, help="Page range spec, e.g. 1-5,8.")
846
+ p_pdf.add_argument(
847
+ "--out-dir", required=True, help="Output directory for rendered pages and previews."
848
+ )
849
+ p_pdf.add_argument(
850
+ "--dpi", type=int, default=150, help="Rendering DPI for pdftoppm (default: 150)."
851
+ )
852
+ p_pdf.add_argument(
853
+ "--max-width", type=int, default=1400, help="Preview maximum pixel width (default: 1400)."
854
+ )
855
+ p_pdf.add_argument(
856
+ "--max-kb", type=int, default=280, help="Maximum preview/strip size in KB (default: 280)."
857
+ )
858
+ p_pdf.add_argument(
859
+ "--strip", default=None, help="Optional output JPEG path for a labeled contact strip."
860
+ )
861
+ p_pdf.add_argument("--json", action="store_true", help="Emit JSON output.")
862
+ p_pdf.set_defaults(func=cmd_pdf_pages)
863
+
864
+ return parser
865
+
866
+
867
+ def main(argv: list[str] | None = None) -> int:
868
+ t0 = time.perf_counter()
869
+ parser = build_parser()
870
+ args = parser.parse_args(argv)
871
+ rc = 1
872
+ bytes_out = 0
873
+ try:
874
+ rc, bytes_out = args.func(args)
875
+ return rc
876
+ except ValueError as exc:
877
+ print(f"Error: {exc}", file=sys.stderr)
878
+ rc = 2
879
+ return rc
880
+ except RuntimeError as exc:
881
+ print(f"Error: {exc}", file=sys.stderr)
882
+ rc = 1
883
+ return rc
884
+ finally:
885
+ append_telemetry(
886
+ getattr(args, "command", ""), (time.perf_counter() - t0) * 1000.0, rc, bytes_out
887
+ )
888
+
889
+
890
+ if __name__ == "__main__":
891
+ raise SystemExit(main())