@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,1313 @@
|
|
|
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
|
+
# 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]
|
|
124
|
+
if len(parts) != 4:
|
|
125
|
+
raise argparse.ArgumentTypeError(f"Invalid box '{raw}': expected x0,y0,x1,y1.")
|
|
126
|
+
try:
|
|
127
|
+
x0, y0, x1, y1 = (int(round(float(p))) for p in parts)
|
|
128
|
+
except ValueError as exc:
|
|
129
|
+
raise argparse.ArgumentTypeError(f"Invalid integer coordinates in box '{raw}'.") from exc
|
|
130
|
+
if x0 < 0 or y0 < 0 or x1 <= x0 or y1 <= y0:
|
|
131
|
+
raise argparse.ArgumentTypeError(
|
|
132
|
+
f"Invalid box '{raw}': require 0 <= x0 < x1 and 0 <= y0 < y1."
|
|
133
|
+
)
|
|
134
|
+
return Box(x0, y0, x1, y1)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def parse_page_spec(raw: str) -> list[int]:
|
|
138
|
+
pages: set[int] = set()
|
|
139
|
+
for part in raw.split(","):
|
|
140
|
+
token = part.strip()
|
|
141
|
+
if not token:
|
|
142
|
+
continue
|
|
143
|
+
if "-" in token:
|
|
144
|
+
bounds = token.split("-", 1)
|
|
145
|
+
try:
|
|
146
|
+
start = int(bounds[0].strip())
|
|
147
|
+
end = int(bounds[1].strip())
|
|
148
|
+
except ValueError as exc:
|
|
149
|
+
raise ValueError(f"Invalid page range '{token}' in --pages '{raw}'.") from exc
|
|
150
|
+
if start < 1 or end < start:
|
|
151
|
+
raise ValueError(f"Invalid page range '{token}': require 1 <= start <= end.")
|
|
152
|
+
if end - start > 500:
|
|
153
|
+
raise ValueError(f"Page range '{token}' exceeds 500-page safety limit.")
|
|
154
|
+
pages.update(range(start, end + 1))
|
|
155
|
+
else:
|
|
156
|
+
try:
|
|
157
|
+
num = int(token)
|
|
158
|
+
except ValueError as exc:
|
|
159
|
+
raise ValueError(f"Invalid page number '{token}' in --pages '{raw}'.") from exc
|
|
160
|
+
if num < 1:
|
|
161
|
+
raise ValueError(f"Page number must be >= 1, got {num}.")
|
|
162
|
+
pages.add(num)
|
|
163
|
+
if not pages:
|
|
164
|
+
raise ValueError(f"No valid pages parsed from --pages '{raw}'.")
|
|
165
|
+
return sorted(pages)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def coalesce_ranges(pages: list[int]) -> list[tuple[int, int]]:
|
|
169
|
+
ranges: list[tuple[int, int]] = []
|
|
170
|
+
start = prev = pages[0]
|
|
171
|
+
for p in pages[1:]:
|
|
172
|
+
if p == prev + 1:
|
|
173
|
+
prev = p
|
|
174
|
+
else:
|
|
175
|
+
ranges.append((start, prev))
|
|
176
|
+
start = prev = p
|
|
177
|
+
ranges.append((start, prev))
|
|
178
|
+
return ranges
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def clamp_box(box: Box, width: int, height: int, label: str) -> Box:
|
|
182
|
+
if box.x0 >= width or box.y0 >= height:
|
|
183
|
+
raise ValueError(
|
|
184
|
+
f"{label} ({box.x0},{box.y0},{box.x1},{box.y1}) starts outside {width}x{height} image."
|
|
185
|
+
)
|
|
186
|
+
x1 = min(box.x1, width)
|
|
187
|
+
y1 = min(box.y1, height)
|
|
188
|
+
if x1 <= box.x0 or y1 <= box.y0:
|
|
189
|
+
raise ValueError(f"{label} collapses to empty area inside {width}x{height} image.")
|
|
190
|
+
return Box(box.x0, box.y0, x1, y1)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def to_rgb(im: PILImageModule.Image) -> PILImageModule.Image:
|
|
194
|
+
Image, _, _, ImageOps = require_pillow()
|
|
195
|
+
im = ImageOps.exif_transpose(im)
|
|
196
|
+
if im.mode == "RGB":
|
|
197
|
+
return im
|
|
198
|
+
if im.mode in ("RGBA", "LA") or (im.mode == "P" and "transparency" in im.info):
|
|
199
|
+
rgba = im.convert("RGBA")
|
|
200
|
+
bg = Image.new("RGB", rgba.size, (255, 255, 255))
|
|
201
|
+
bg.paste(rgba, mask=rgba.split()[3])
|
|
202
|
+
return bg
|
|
203
|
+
return im.convert("RGB")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def rotate_clockwise(im: PILImageModule.Image, degrees: int | None) -> PILImageModule.Image:
|
|
207
|
+
if not degrees:
|
|
208
|
+
return im
|
|
209
|
+
Image, _, _, _ = require_pillow()
|
|
210
|
+
if degrees == 90:
|
|
211
|
+
return im.transpose(Image.Transpose.ROTATE_270)
|
|
212
|
+
if degrees == 180:
|
|
213
|
+
return im.transpose(Image.Transpose.ROTATE_180)
|
|
214
|
+
if degrees == 270:
|
|
215
|
+
return im.transpose(Image.Transpose.ROTATE_90)
|
|
216
|
+
raise ValueError(f"Unsupported rotation '{degrees}': expected 90, 180, or 270.")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def atomic_write_bytes(dest: Path, data: bytes) -> None:
|
|
220
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
221
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.tmp")
|
|
222
|
+
try:
|
|
223
|
+
tmp.write_bytes(data)
|
|
224
|
+
os.replace(tmp, dest)
|
|
225
|
+
except Exception:
|
|
226
|
+
if tmp.exists():
|
|
227
|
+
tmp.unlink(missing_ok=True)
|
|
228
|
+
raise
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def encode_jpeg_under_kb(
|
|
232
|
+
im: PILImageModule.Image, max_width: int, max_kb: int
|
|
233
|
+
) -> tuple[bytes, int, int]:
|
|
234
|
+
Image, _, _, _ = require_pillow()
|
|
235
|
+
rgb = to_rgb(im)
|
|
236
|
+
w, h = rgb.size
|
|
237
|
+
if max_width > 0 and w > max_width:
|
|
238
|
+
new_h = max(1, int(round(h * (max_width / w))))
|
|
239
|
+
rgb = rgb.resize((max_width, new_h), Image.Resampling.LANCZOS)
|
|
240
|
+
|
|
241
|
+
limit_bytes = max(1024, int(max_kb * 1024))
|
|
242
|
+
base_w, base_h = rgb.size
|
|
243
|
+
best_data: bytes = b""
|
|
244
|
+
best_size = (base_w, base_h)
|
|
245
|
+
|
|
246
|
+
for scale in (1.0, 0.88, 0.76, 0.64, 0.52, 0.42, 0.34, 0.25):
|
|
247
|
+
cur = (
|
|
248
|
+
rgb
|
|
249
|
+
if scale == 1.0
|
|
250
|
+
else rgb.resize(
|
|
251
|
+
(max(1, int(round(base_w * scale))), max(1, int(round(base_h * scale)))),
|
|
252
|
+
Image.Resampling.LANCZOS,
|
|
253
|
+
)
|
|
254
|
+
)
|
|
255
|
+
for quality in (84, 76, 68, 60, 52, 44, 36):
|
|
256
|
+
buf = io.BytesIO()
|
|
257
|
+
cur.save(buf, format="JPEG", quality=quality, optimize=True)
|
|
258
|
+
data = buf.getvalue()
|
|
259
|
+
best_data = data
|
|
260
|
+
best_size = cur.size
|
|
261
|
+
if len(data) <= limit_bytes:
|
|
262
|
+
return data, cur.size[0], cur.size[1]
|
|
263
|
+
|
|
264
|
+
return best_data, best_size[0], best_size[1]
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def save_compact_jpeg(
|
|
268
|
+
im: PILImageModule.Image, out_path: Path, max_width: int, max_kb: int
|
|
269
|
+
) -> SavedImage:
|
|
270
|
+
data, width, height = encode_jpeg_under_kb(im, max_width=max_width, max_kb=max_kb)
|
|
271
|
+
atomic_write_bytes(out_path, data)
|
|
272
|
+
return SavedImage(path=out_path, width=width, height=height, bytes=len(data))
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def save_archival_image(
|
|
276
|
+
im: PILImageModule.Image, out_path: Path, quality: int = 92
|
|
277
|
+
) -> SavedImage:
|
|
278
|
+
rgb = to_rgb(im)
|
|
279
|
+
ext = out_path.suffix.lower()
|
|
280
|
+
buf = io.BytesIO()
|
|
281
|
+
if ext == ".png":
|
|
282
|
+
rgb.save(buf, format="PNG", optimize=True)
|
|
283
|
+
elif ext == ".webp":
|
|
284
|
+
rgb.save(buf, format="WEBP", quality=quality)
|
|
285
|
+
else:
|
|
286
|
+
rgb.save(buf, format="JPEG", quality=quality, optimize=True)
|
|
287
|
+
data = buf.getvalue()
|
|
288
|
+
atomic_write_bytes(out_path, data)
|
|
289
|
+
return SavedImage(path=out_path, width=rgb.size[0], height=rgb.size[1], bytes=len(data))
|
|
290
|
+
|
|
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
|
+
|
|
309
|
+
def safe_stem(name: str) -> str:
|
|
310
|
+
cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("_")
|
|
311
|
+
return cleaned or "scan"
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def emit_output(text: str) -> int:
|
|
315
|
+
sys.stdout.write(text)
|
|
316
|
+
return len(text.encode("utf-8"))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def cmd_preview(args: argparse.Namespace) -> tuple[int, int]:
|
|
320
|
+
Image, _, _, ImageOps = require_pillow()
|
|
321
|
+
out_dir = Path(args.out_dir).resolve()
|
|
322
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
323
|
+
|
|
324
|
+
inputs = [Path(p).resolve() for p in args.images]
|
|
325
|
+
missing = [str(p) for p in inputs if not p.is_file()]
|
|
326
|
+
if missing:
|
|
327
|
+
for m in missing:
|
|
328
|
+
print(f"Error: input file not found: {m}", file=sys.stderr)
|
|
329
|
+
return 1, 0
|
|
330
|
+
|
|
331
|
+
stem_counts: dict[str, int] = {}
|
|
332
|
+
for p in inputs:
|
|
333
|
+
stem = safe_stem(p.stem)
|
|
334
|
+
stem_counts[stem] = stem_counts.get(stem, 0) + 1
|
|
335
|
+
|
|
336
|
+
def build_one(src: Path) -> dict[str, object]:
|
|
337
|
+
stem = safe_stem(src.stem)
|
|
338
|
+
if stem_counts[stem] > 1:
|
|
339
|
+
suffix = hashlib.sha256(str(src).encode("utf-8")).hexdigest()[:8]
|
|
340
|
+
out_name = f"{stem}_{suffix}.preview.jpg"
|
|
341
|
+
else:
|
|
342
|
+
out_name = f"{stem}.preview.jpg"
|
|
343
|
+
out_path = out_dir / out_name
|
|
344
|
+
with Image.open(src) as im:
|
|
345
|
+
orig_w, orig_h = ImageOps.exif_transpose(im).size
|
|
346
|
+
saved = save_compact_jpeg(im, out_path, max_width=args.max_width, max_kb=args.max_kb)
|
|
347
|
+
return {
|
|
348
|
+
"source": str(src),
|
|
349
|
+
"source_size": [orig_w, orig_h],
|
|
350
|
+
**saved.to_dict(),
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
workers = min(DEFAULT_MAX_WORKERS, max(1, len(inputs)))
|
|
354
|
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
|
355
|
+
results = list(pool.map(build_one, inputs))
|
|
356
|
+
|
|
357
|
+
if args.json:
|
|
358
|
+
out_bytes = emit_output(json.dumps(results, indent=2) + "\n")
|
|
359
|
+
else:
|
|
360
|
+
lines = [
|
|
361
|
+
f"{item['path']} {item['width']}x{item['height']} {item['kb']:.1f} KB"
|
|
362
|
+
for item in results
|
|
363
|
+
]
|
|
364
|
+
out_bytes = emit_output("\n".join(lines) + ("\n" if lines else ""))
|
|
365
|
+
return 0, out_bytes
|
|
366
|
+
|
|
367
|
+
|
|
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}.")
|
|
371
|
+
Image, ImageDraw, _, _ = require_pillow()
|
|
372
|
+
src = Path(args.input).resolve()
|
|
373
|
+
out_path = Path(args.output).resolve()
|
|
374
|
+
if not src.is_file():
|
|
375
|
+
print(f"Error: input file not found: {src}", file=sys.stderr)
|
|
376
|
+
return 1, 0
|
|
377
|
+
|
|
378
|
+
with Image.open(src) as raw_im:
|
|
379
|
+
img = rotate_clockwise(to_rgb(raw_im), args.rotate)
|
|
380
|
+
|
|
381
|
+
crop_box = clamp_box(args.box, img.width, img.height, "crop --box")
|
|
382
|
+
cropped = img.crop((crop_box.x0, crop_box.y0, crop_box.x1, crop_box.y1))
|
|
383
|
+
|
|
384
|
+
redactions: list[list[int]] = []
|
|
385
|
+
if args.redact:
|
|
386
|
+
draw = ImageDraw.Draw(cropped)
|
|
387
|
+
for idx, rbox in enumerate(args.redact, 1):
|
|
388
|
+
clamped = clamp_box(rbox, cropped.width, cropped.height, f"--redact #{idx}")
|
|
389
|
+
draw.rectangle((clamped.x0, clamped.y0, clamped.x1, clamped.y1), fill=(0, 0, 0))
|
|
390
|
+
redactions.append([clamped.x0, clamped.y0, clamped.x1, clamped.y1])
|
|
391
|
+
|
|
392
|
+
saved = save_archival_image(cropped, out_path, quality=args.quality)
|
|
393
|
+
|
|
394
|
+
if args.preview_out:
|
|
395
|
+
preview_path = Path(args.preview_out).resolve()
|
|
396
|
+
else:
|
|
397
|
+
digest = hashlib.sha256(str(out_path).encode("utf-8")).hexdigest()[:8]
|
|
398
|
+
preview_path = (
|
|
399
|
+
default_cache_root()
|
|
400
|
+
/ "previews"
|
|
401
|
+
/ f"{safe_stem(out_path.stem)}_{digest}.preview.jpg"
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
preview = save_compact_jpeg(cropped, preview_path, max_width=args.max_width, max_kb=args.max_kb)
|
|
405
|
+
|
|
406
|
+
payload = {
|
|
407
|
+
"source": str(src),
|
|
408
|
+
"rotate": args.rotate or 0,
|
|
409
|
+
"box": [crop_box.x0, crop_box.y0, crop_box.x1, crop_box.y1],
|
|
410
|
+
"redactions": redactions,
|
|
411
|
+
"output": saved.to_dict(),
|
|
412
|
+
"preview": preview.to_dict(),
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
if args.json:
|
|
416
|
+
out_bytes = emit_output(json.dumps(payload, indent=2) + "\n")
|
|
417
|
+
else:
|
|
418
|
+
text = (
|
|
419
|
+
f"output: {saved.path} {saved.width}x{saved.height} {saved.bytes / 1024:.1f} KB\n"
|
|
420
|
+
f"preview: {preview.path} {preview.width}x{preview.height} {preview.bytes / 1024:.1f} KB\n"
|
|
421
|
+
)
|
|
422
|
+
out_bytes = emit_output(text)
|
|
423
|
+
return 0, out_bytes
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def is_url(target: str) -> bool:
|
|
427
|
+
parsed = urlparse(target)
|
|
428
|
+
return parsed.scheme in ("http", "https") and bool(parsed.netloc)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def short_label(target: str, index: int) -> str:
|
|
432
|
+
if is_url(target):
|
|
433
|
+
parsed = urlparse(target)
|
|
434
|
+
tail = Path(parsed.path).name or parsed.netloc
|
|
435
|
+
return f"[{index:02d}] {tail}"
|
|
436
|
+
return f"[{index:02d}] {Path(target).name}"
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def load_image_from_source(target: str, timeout_s: float) -> PILImageModule.Image:
|
|
440
|
+
Image, _, _, _ = require_pillow()
|
|
441
|
+
if is_url(target):
|
|
442
|
+
try:
|
|
443
|
+
import httpx
|
|
444
|
+
except ImportError as exc:
|
|
445
|
+
raise RuntimeError(
|
|
446
|
+
"httpx is required for URL downloads. Run via `uv run --script` "
|
|
447
|
+
"or install it with `pip install httpx`."
|
|
448
|
+
) from exc
|
|
449
|
+
|
|
450
|
+
with httpx.Client(
|
|
451
|
+
timeout=timeout_s,
|
|
452
|
+
follow_redirects=True,
|
|
453
|
+
headers={"User-Agent": USER_AGENT},
|
|
454
|
+
) as client:
|
|
455
|
+
resp = client.get(target)
|
|
456
|
+
resp.raise_for_status()
|
|
457
|
+
return to_rgb(Image.open(io.BytesIO(resp.content)))
|
|
458
|
+
path = Path(target).resolve()
|
|
459
|
+
if not path.is_file():
|
|
460
|
+
raise FileNotFoundError(f"file not found: {path}")
|
|
461
|
+
with Image.open(path) as im:
|
|
462
|
+
return to_rgb(im.copy())
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def extract_band(
|
|
466
|
+
im: PILImageModule.Image, band: str, band_pct: float, rotate_left: bool
|
|
467
|
+
) -> PILImageModule.Image:
|
|
468
|
+
Image, _, _, _ = require_pillow()
|
|
469
|
+
frac = max(0.02, min(1.0, band_pct / 100.0))
|
|
470
|
+
w, h = im.size
|
|
471
|
+
if band == "top":
|
|
472
|
+
cut_h = max(1, int(round(h * frac)))
|
|
473
|
+
return im.crop((0, 0, w, cut_h))
|
|
474
|
+
cut_w = max(1, int(round(w * frac)))
|
|
475
|
+
strip = im.crop((0, 0, cut_w, h))
|
|
476
|
+
if rotate_left:
|
|
477
|
+
strip = strip.transpose(Image.Transpose.ROTATE_270)
|
|
478
|
+
return strip
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def build_labeled_contact_strip(
|
|
482
|
+
items: list[tuple[str, PILImageModule.Image]],
|
|
483
|
+
out_path: Path,
|
|
484
|
+
target_width: int,
|
|
485
|
+
max_kb: int,
|
|
486
|
+
) -> SavedImage:
|
|
487
|
+
Image, ImageDraw, ImageFont, _ = require_pillow()
|
|
488
|
+
resized: list[tuple[str, Any]] = []
|
|
489
|
+
for label, im in items:
|
|
490
|
+
rgb = to_rgb(im)
|
|
491
|
+
if rgb.width != target_width:
|
|
492
|
+
scaled_h = max(1, int(round(rgb.height * (target_width / rgb.width))))
|
|
493
|
+
rgb = rgb.resize((target_width, scaled_h), Image.Resampling.LANCZOS)
|
|
494
|
+
resized.append((label, rgb))
|
|
495
|
+
|
|
496
|
+
font = ImageFont.load_default()
|
|
497
|
+
header_h = 26
|
|
498
|
+
gap_h = 6
|
|
499
|
+
total_h = sum(header_h + im.height + gap_h for _, im in resized)
|
|
500
|
+
canvas = Image.new("RGB", (target_width, max(1, total_h)), (24, 24, 24))
|
|
501
|
+
draw = ImageDraw.Draw(canvas)
|
|
502
|
+
y = 0
|
|
503
|
+
for label, im in resized:
|
|
504
|
+
draw.rectangle((0, y, target_width, y + header_h), fill=(20, 28, 38))
|
|
505
|
+
draw.text((8, y + 6), label[:180], fill=(255, 255, 255), font=font)
|
|
506
|
+
y += header_h
|
|
507
|
+
canvas.paste(im, (0, y))
|
|
508
|
+
y += im.height + gap_h
|
|
509
|
+
return save_compact_jpeg(canvas, out_path, max_width=target_width, max_kb=max_kb)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def cmd_sheet_strip(args: argparse.Namespace) -> tuple[int, int]:
|
|
513
|
+
Image, ImageDraw, ImageFont, _ = require_pillow()
|
|
514
|
+
sources: list[str] = list(args.sources)
|
|
515
|
+
out_path = Path(args.out).resolve()
|
|
516
|
+
target_width = args.width
|
|
517
|
+
|
|
518
|
+
def fetch_one(item: tuple[int, str]) -> dict[str, Any]:
|
|
519
|
+
idx, src = item
|
|
520
|
+
label = short_label(src, idx)
|
|
521
|
+
try:
|
|
522
|
+
im = load_image_from_source(src, timeout_s=args.timeout)
|
|
523
|
+
band_im = extract_band(
|
|
524
|
+
im, args.band, args.band_pct, rotate_left=not args.no_rotate_left
|
|
525
|
+
)
|
|
526
|
+
if band_im.width != target_width:
|
|
527
|
+
scaled_h = max(1, int(round(band_im.height * (target_width / band_im.width))))
|
|
528
|
+
band_im = band_im.resize((target_width, scaled_h), Image.Resampling.LANCZOS)
|
|
529
|
+
return {
|
|
530
|
+
"index": idx,
|
|
531
|
+
"source": src,
|
|
532
|
+
"label": label,
|
|
533
|
+
"image": band_im,
|
|
534
|
+
"error": None,
|
|
535
|
+
}
|
|
536
|
+
except Exception as exc:
|
|
537
|
+
return {
|
|
538
|
+
"index": idx,
|
|
539
|
+
"source": src,
|
|
540
|
+
"label": label,
|
|
541
|
+
"image": None,
|
|
542
|
+
"error": str(exc),
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
workers = min(DEFAULT_MAX_WORKERS, max(1, len(sources)))
|
|
546
|
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
|
547
|
+
fetched = list(pool.map(fetch_one, enumerate(sources, 1)))
|
|
548
|
+
|
|
549
|
+
ok_count = sum(1 for row in fetched if row["image"] is not None)
|
|
550
|
+
if ok_count == 0:
|
|
551
|
+
for row in fetched:
|
|
552
|
+
print(f"Error {row['label']}: {row['error']}", file=sys.stderr)
|
|
553
|
+
return 1, 0
|
|
554
|
+
|
|
555
|
+
font = ImageFont.load_default()
|
|
556
|
+
header_h = 26
|
|
557
|
+
error_h = 36
|
|
558
|
+
gap_h = 6
|
|
559
|
+
total_h = sum(
|
|
560
|
+
header_h + (row["image"].height if row["image"] is not None else error_h) + gap_h
|
|
561
|
+
for row in fetched
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
canvas = Image.new("RGB", (target_width, max(1, total_h)), (24, 24, 24))
|
|
565
|
+
draw = ImageDraw.Draw(canvas)
|
|
566
|
+
y = 0
|
|
567
|
+
for row in fetched:
|
|
568
|
+
draw.rectangle((0, y, target_width, y + header_h), fill=(20, 28, 38))
|
|
569
|
+
header_text = str(row["label"])
|
|
570
|
+
if row["error"]:
|
|
571
|
+
header_text = f"{header_text} ERROR: {row['error']}"
|
|
572
|
+
draw.text((8, y + 6), header_text[:180], fill=(255, 255, 255), font=font)
|
|
573
|
+
y += header_h
|
|
574
|
+
band_im = row["image"]
|
|
575
|
+
if band_im is not None:
|
|
576
|
+
canvas.paste(band_im, (0, y))
|
|
577
|
+
y += band_im.height + gap_h
|
|
578
|
+
else:
|
|
579
|
+
draw.rectangle((0, y, target_width, y + error_h), fill=(90, 20, 20))
|
|
580
|
+
draw.text((8, y + 10), str(row["error"])[:180], fill=(255, 220, 220), font=font)
|
|
581
|
+
y += error_h + gap_h
|
|
582
|
+
|
|
583
|
+
saved = save_compact_jpeg(canvas, out_path, max_width=target_width, max_kb=args.max_kb)
|
|
584
|
+
errors = [{"source": r["source"], "error": r["error"]} for r in fetched if r["error"]]
|
|
585
|
+
|
|
586
|
+
payload = {
|
|
587
|
+
"band": args.band,
|
|
588
|
+
"band_pct": args.band_pct,
|
|
589
|
+
"count": len(sources),
|
|
590
|
+
"ok": ok_count,
|
|
591
|
+
"errors": errors,
|
|
592
|
+
**saved.to_dict(),
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
if args.json:
|
|
596
|
+
out_bytes = emit_output(json.dumps(payload, indent=2) + "\n")
|
|
597
|
+
else:
|
|
598
|
+
text = (
|
|
599
|
+
f"{saved.path} {saved.width}x{saved.height} {saved.bytes / 1024:.1f} KB "
|
|
600
|
+
f"({ok_count}/{len(sources)} bands)\n"
|
|
601
|
+
)
|
|
602
|
+
out_bytes = emit_output(text)
|
|
603
|
+
for err in errors:
|
|
604
|
+
print(f"warning: {err['source']}: {err['error']}", file=sys.stderr)
|
|
605
|
+
return 0, out_bytes
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def cmd_pdf_pages(args: argparse.Namespace) -> tuple[int, int]:
|
|
609
|
+
Image, _, _, ImageOps = require_pillow()
|
|
610
|
+
pdf_path = Path(args.pdf_path).resolve()
|
|
611
|
+
if not pdf_path.is_file():
|
|
612
|
+
print(f"Error: PDF file not found: {pdf_path}", file=sys.stderr)
|
|
613
|
+
return 1, 0
|
|
614
|
+
|
|
615
|
+
pdftoppm_bin = shutil.which("pdftoppm")
|
|
616
|
+
if not pdftoppm_bin:
|
|
617
|
+
print(
|
|
618
|
+
"Error: pdftoppm executable not found on PATH. Install poppler-utils "
|
|
619
|
+
"(for example `apt install poppler-utils` or `brew install poppler`).",
|
|
620
|
+
file=sys.stderr,
|
|
621
|
+
)
|
|
622
|
+
return 1, 0
|
|
623
|
+
timeout_bin = shutil.which("timeout")
|
|
624
|
+
|
|
625
|
+
requested_pages = parse_page_spec(args.pages)
|
|
626
|
+
ranges = coalesce_ranges(requested_pages)
|
|
627
|
+
|
|
628
|
+
out_dir = Path(args.out_dir).resolve()
|
|
629
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
630
|
+
# Keep intermediate files inside out_dir instead of /tmp tmpfs RAM.
|
|
631
|
+
stage_dir = out_dir / f".pdf_stage_{os.getpid()}_{time.time_ns()}"
|
|
632
|
+
stage_dir.mkdir(parents=True, exist_ok=True)
|
|
633
|
+
|
|
634
|
+
rendered_by_page: dict[int, Path] = {}
|
|
635
|
+
try:
|
|
636
|
+
for r_idx, (start_p, end_p) in enumerate(ranges):
|
|
637
|
+
prefix = stage_dir / f"r{r_idx}"
|
|
638
|
+
base_cmd = [
|
|
639
|
+
pdftoppm_bin,
|
|
640
|
+
"-jpeg",
|
|
641
|
+
"-r",
|
|
642
|
+
str(args.dpi),
|
|
643
|
+
"-f",
|
|
644
|
+
str(start_p),
|
|
645
|
+
"-l",
|
|
646
|
+
str(end_p),
|
|
647
|
+
str(pdf_path),
|
|
648
|
+
str(prefix),
|
|
649
|
+
]
|
|
650
|
+
cmd = (
|
|
651
|
+
[timeout_bin, str(DEFAULT_PDF_TIMEOUT_S), *base_cmd]
|
|
652
|
+
if timeout_bin
|
|
653
|
+
else base_cmd
|
|
654
|
+
)
|
|
655
|
+
try:
|
|
656
|
+
proc = subprocess.run(
|
|
657
|
+
cmd, capture_output=True, text=True, timeout=DEFAULT_PDF_TIMEOUT_S + 5
|
|
658
|
+
)
|
|
659
|
+
except subprocess.TimeoutExpired:
|
|
660
|
+
print(
|
|
661
|
+
f"Error: pdftoppm timed out after {DEFAULT_PDF_TIMEOUT_S}s on pages {start_p}-{end_p}.",
|
|
662
|
+
file=sys.stderr,
|
|
663
|
+
)
|
|
664
|
+
return 1, 0
|
|
665
|
+
if proc.returncode != 0:
|
|
666
|
+
detail = (proc.stderr or proc.stdout).strip()[:300]
|
|
667
|
+
print(
|
|
668
|
+
f"Error: pdftoppm failed (exit {proc.returncode}) on pages {start_p}-{end_p}: {detail}",
|
|
669
|
+
file=sys.stderr,
|
|
670
|
+
)
|
|
671
|
+
return 1, 0
|
|
672
|
+
|
|
673
|
+
for img_file in sorted(stage_dir.glob(f"r{r_idx}-*.jpg")):
|
|
674
|
+
m = PDF_PAGE_NUM_RE.search(img_file.name)
|
|
675
|
+
if not m:
|
|
676
|
+
continue
|
|
677
|
+
page_num = int(m.group(1))
|
|
678
|
+
dest_page = out_dir / f"page-{page_num:03d}.jpg"
|
|
679
|
+
os.replace(img_file, dest_page)
|
|
680
|
+
rendered_by_page[page_num] = dest_page
|
|
681
|
+
finally:
|
|
682
|
+
shutil.rmtree(stage_dir, ignore_errors=True)
|
|
683
|
+
|
|
684
|
+
if not rendered_by_page:
|
|
685
|
+
print(
|
|
686
|
+
f"Error: no pages were rendered for --pages '{args.pages}' from {pdf_path}.",
|
|
687
|
+
file=sys.stderr,
|
|
688
|
+
)
|
|
689
|
+
return 1, 0
|
|
690
|
+
|
|
691
|
+
ordered_pages = [(p, rendered_by_page[p]) for p in requested_pages if p in rendered_by_page]
|
|
692
|
+
|
|
693
|
+
def build_preview(item: tuple[int, Path]) -> dict[str, Any]:
|
|
694
|
+
page_num, page_path = item
|
|
695
|
+
preview_path = out_dir / f"page-{page_num:03d}.preview.jpg"
|
|
696
|
+
page_bytes = page_path.stat().st_size
|
|
697
|
+
with Image.open(page_path) as im:
|
|
698
|
+
orig_w, orig_h = ImageOps.exif_transpose(im).size
|
|
699
|
+
saved_prev = save_compact_jpeg(
|
|
700
|
+
im, preview_path, max_width=args.max_width, max_kb=args.max_kb
|
|
701
|
+
)
|
|
702
|
+
return {
|
|
703
|
+
"page": page_num,
|
|
704
|
+
"path": str(page_path),
|
|
705
|
+
"width": orig_w,
|
|
706
|
+
"height": orig_h,
|
|
707
|
+
"bytes": page_bytes,
|
|
708
|
+
"kb": round(page_bytes / 1024.0, 1),
|
|
709
|
+
"preview": saved_prev.to_dict(),
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
workers = min(DEFAULT_MAX_WORKERS, max(1, len(ordered_pages)))
|
|
713
|
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
|
714
|
+
page_records = list(pool.map(build_preview, ordered_pages))
|
|
715
|
+
|
|
716
|
+
strip_info: dict[str, Any] | None = None
|
|
717
|
+
if args.strip:
|
|
718
|
+
strip_items: list[tuple[str, Any]] = []
|
|
719
|
+
for rec in page_records:
|
|
720
|
+
p_num = int(rec["page"])
|
|
721
|
+
prev_path = Path(str(rec["preview"]["path"]))
|
|
722
|
+
with Image.open(prev_path) as im:
|
|
723
|
+
strip_items.append((f"[p.{p_num:03d}] {pdf_path.name}", im.copy()))
|
|
724
|
+
strip_saved = build_labeled_contact_strip(
|
|
725
|
+
strip_items,
|
|
726
|
+
Path(args.strip).resolve(),
|
|
727
|
+
target_width=args.max_width,
|
|
728
|
+
max_kb=args.max_kb,
|
|
729
|
+
)
|
|
730
|
+
strip_info = strip_saved.to_dict()
|
|
731
|
+
|
|
732
|
+
missing_pages = [p for p in requested_pages if p not in rendered_by_page]
|
|
733
|
+
payload: dict[str, object] = {
|
|
734
|
+
"pdf": str(pdf_path),
|
|
735
|
+
"dpi": args.dpi,
|
|
736
|
+
"requested_pages": requested_pages,
|
|
737
|
+
"missing_pages": missing_pages,
|
|
738
|
+
"pages": page_records,
|
|
739
|
+
}
|
|
740
|
+
if strip_info is not None:
|
|
741
|
+
payload["strip"] = strip_info
|
|
742
|
+
|
|
743
|
+
if args.json:
|
|
744
|
+
out_bytes = emit_output(json.dumps(payload, indent=2) + "\n")
|
|
745
|
+
else:
|
|
746
|
+
lines: list[str] = []
|
|
747
|
+
for rec in page_records:
|
|
748
|
+
prev = rec["preview"]
|
|
749
|
+
lines.append(
|
|
750
|
+
f"p.{int(rec['page']):03d} {rec['path']} ({rec['kb']:.1f} KB) "
|
|
751
|
+
f"preview: {prev['path']} ({prev['kb']:.1f} KB)"
|
|
752
|
+
)
|
|
753
|
+
if strip_info is not None:
|
|
754
|
+
lines.append(
|
|
755
|
+
f"strip: {strip_info['path']} {strip_info['width']}x{strip_info['height']} "
|
|
756
|
+
f"{strip_info['kb']:.1f} KB"
|
|
757
|
+
)
|
|
758
|
+
out_bytes = emit_output("\n".join(lines) + "\n")
|
|
759
|
+
return 0, out_bytes
|
|
760
|
+
|
|
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
|
+
|
|
1012
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
1013
|
+
parser = argparse.ArgumentParser(
|
|
1014
|
+
prog="kinloom prep-scan",
|
|
1015
|
+
description=(
|
|
1016
|
+
"Generate compact inspection previews, redacted archival crops, "
|
|
1017
|
+
"census sheet-strip contact sheets, and selective PDF page renders."
|
|
1018
|
+
),
|
|
1019
|
+
)
|
|
1020
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
1021
|
+
|
|
1022
|
+
p_prev = sub.add_parser("preview", help="Generate compact JPEG inspection previews in parallel.")
|
|
1023
|
+
p_prev.add_argument("images", nargs="+", help="Input image path(s).")
|
|
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
|
+
)
|
|
1028
|
+
p_prev.add_argument(
|
|
1029
|
+
"--max-width", type=int, default=1400, help="Maximum pixel width (default: 1400)."
|
|
1030
|
+
)
|
|
1031
|
+
p_prev.add_argument(
|
|
1032
|
+
"--max-kb", type=int, default=280, help="Maximum file size in KB (default: 280)."
|
|
1033
|
+
)
|
|
1034
|
+
p_prev.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
1035
|
+
p_prev.set_defaults(func=cmd_preview)
|
|
1036
|
+
|
|
1037
|
+
p_crop = sub.add_parser(
|
|
1038
|
+
"crop",
|
|
1039
|
+
help="Rotate, crop, apply solid black redaction boxes (in cropped coordinates), and auto-write a verification preview.",
|
|
1040
|
+
)
|
|
1041
|
+
p_crop.add_argument("input", help="Source scan path.")
|
|
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).")
|
|
1048
|
+
p_crop.add_argument(
|
|
1049
|
+
"--box", required=True, type=parse_box, help="Crop box x0,y0,x1,y1 after optional --rotate."
|
|
1050
|
+
)
|
|
1051
|
+
p_crop.add_argument(
|
|
1052
|
+
"--rotate",
|
|
1053
|
+
type=int,
|
|
1054
|
+
choices=(90, 180, 270),
|
|
1055
|
+
default=None,
|
|
1056
|
+
help="Optional clockwise rotation applied before cropping.",
|
|
1057
|
+
)
|
|
1058
|
+
p_crop.add_argument(
|
|
1059
|
+
"--redact",
|
|
1060
|
+
action="extend",
|
|
1061
|
+
nargs="+",
|
|
1062
|
+
type=parse_box,
|
|
1063
|
+
default=[],
|
|
1064
|
+
help="One or more x0,y0,x1,y1 black redaction boxes in cropped-image coordinates.",
|
|
1065
|
+
)
|
|
1066
|
+
p_crop.add_argument(
|
|
1067
|
+
"--preview-out",
|
|
1068
|
+
default=None,
|
|
1069
|
+
help="Optional explicit path for the < 280 KB verification preview (defaults to cache previews dir).",
|
|
1070
|
+
)
|
|
1071
|
+
p_crop.add_argument(
|
|
1072
|
+
"--max-width", type=int, default=1400, help="Preview maximum pixel width (default: 1400)."
|
|
1073
|
+
)
|
|
1074
|
+
p_crop.add_argument(
|
|
1075
|
+
"--max-kb", type=int, default=280, help="Preview maximum size in KB (default: 280)."
|
|
1076
|
+
)
|
|
1077
|
+
p_crop.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
1078
|
+
p_crop.set_defaults(func=cmd_crop)
|
|
1079
|
+
|
|
1080
|
+
p_strip = sub.add_parser(
|
|
1081
|
+
"sheet-strip",
|
|
1082
|
+
help="Download or read census sheet header/street bands in parallel and stitch one labeled contact sheet.",
|
|
1083
|
+
)
|
|
1084
|
+
p_strip.add_argument("sources", nargs="+", help="Image URLs or local file paths.")
|
|
1085
|
+
p_strip.add_argument(
|
|
1086
|
+
"--out", required=True, help="Output JPEG path for the stitched contact sheet."
|
|
1087
|
+
)
|
|
1088
|
+
p_strip.add_argument(
|
|
1089
|
+
"--band",
|
|
1090
|
+
choices=("top", "left"),
|
|
1091
|
+
default="top",
|
|
1092
|
+
help="Band edge to slice (default: top).",
|
|
1093
|
+
)
|
|
1094
|
+
p_strip.add_argument(
|
|
1095
|
+
"--band-pct",
|
|
1096
|
+
type=float,
|
|
1097
|
+
default=18.0,
|
|
1098
|
+
help="Percent of image height/width to slice (default: 18).",
|
|
1099
|
+
)
|
|
1100
|
+
p_strip.add_argument(
|
|
1101
|
+
"--max-kb", type=int, default=250, help="Maximum output file size in KB (default: 250)."
|
|
1102
|
+
)
|
|
1103
|
+
p_strip.add_argument(
|
|
1104
|
+
"--width", type=int, default=1400, help="Normalized strip width in pixels (default: 1400)."
|
|
1105
|
+
)
|
|
1106
|
+
p_strip.add_argument(
|
|
1107
|
+
"--timeout",
|
|
1108
|
+
type=float,
|
|
1109
|
+
default=DEFAULT_TIMEOUT_S,
|
|
1110
|
+
help="Per-URL HTTP timeout seconds (default: 12).",
|
|
1111
|
+
)
|
|
1112
|
+
p_strip.add_argument(
|
|
1113
|
+
"--no-rotate-left",
|
|
1114
|
+
action="store_true",
|
|
1115
|
+
help="Keep --band left vertical instead of rotating 90 deg CW for horizontal reading.",
|
|
1116
|
+
)
|
|
1117
|
+
p_strip.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
1118
|
+
p_strip.set_defaults(func=cmd_sheet_strip)
|
|
1119
|
+
|
|
1120
|
+
p_pdf = sub.add_parser(
|
|
1121
|
+
"pdf-pages",
|
|
1122
|
+
help="Render only requested PDF pages via pdftoppm, build < 280 KB previews in parallel, and optionally build a contact strip.",
|
|
1123
|
+
)
|
|
1124
|
+
p_pdf.add_argument("pdf_path", help="Path to source PDF file.")
|
|
1125
|
+
p_pdf.add_argument("--pages", required=True, help="Page range spec, e.g. 1-5,8.")
|
|
1126
|
+
p_pdf.add_argument(
|
|
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).",
|
|
1129
|
+
)
|
|
1130
|
+
p_pdf.add_argument(
|
|
1131
|
+
"--dpi", type=int, default=150, help="Rendering DPI for pdftoppm (default: 150)."
|
|
1132
|
+
)
|
|
1133
|
+
p_pdf.add_argument(
|
|
1134
|
+
"--max-width", type=int, default=1400, help="Preview maximum pixel width (default: 1400)."
|
|
1135
|
+
)
|
|
1136
|
+
p_pdf.add_argument(
|
|
1137
|
+
"--max-kb", type=int, default=280, help="Maximum preview/strip size in KB (default: 280)."
|
|
1138
|
+
)
|
|
1139
|
+
p_pdf.add_argument(
|
|
1140
|
+
"--strip", default=None, help="Optional output JPEG path for a labeled contact strip."
|
|
1141
|
+
)
|
|
1142
|
+
p_pdf.add_argument("--json", action="store_true", help="Emit JSON output.")
|
|
1143
|
+
p_pdf.set_defaults(func=cmd_pdf_pages)
|
|
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
|
+
|
|
1250
|
+
return parser
|
|
1251
|
+
|
|
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
|
+
|
|
1288
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1289
|
+
t0 = time.perf_counter()
|
|
1290
|
+
parser = build_parser()
|
|
1291
|
+
args = parser.parse_args(normalize_argv(list(sys.argv[1:] if argv is None else argv)))
|
|
1292
|
+
resolve_output_alias(parser, args)
|
|
1293
|
+
rc = 1
|
|
1294
|
+
bytes_out = 0
|
|
1295
|
+
try:
|
|
1296
|
+
rc, bytes_out = args.func(args)
|
|
1297
|
+
return rc
|
|
1298
|
+
except ValueError as exc:
|
|
1299
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
1300
|
+
rc = 2
|
|
1301
|
+
return rc
|
|
1302
|
+
except RuntimeError as exc:
|
|
1303
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
1304
|
+
rc = 1
|
|
1305
|
+
return rc
|
|
1306
|
+
finally:
|
|
1307
|
+
append_telemetry(
|
|
1308
|
+
getattr(args, "command", ""), (time.perf_counter() - t0) * 1000.0, rc, bytes_out
|
|
1309
|
+
)
|
|
1310
|
+
|
|
1311
|
+
|
|
1312
|
+
if __name__ == "__main__":
|
|
1313
|
+
raise SystemExit(main())
|