@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.
- package/dist/assets/cached-ocr.py +556 -0
- package/dist/assets/ocr.md +52 -0
- package/dist/assets/prep-scan.md +59 -0
- package/dist/assets/prep-scan.py +891 -0
- package/dist/bundled-skills/acpl-persi/SKILL.md +94 -0
- package/dist/bundled-skills/acpl-persi/scripts/persi +268 -0
- package/dist/bundled-skills/archive-org/SKILL.md +129 -0
- package/dist/bundled-skills/archive-org/scripts/archive-org +879 -0
- package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
- package/dist/bundled-skills/california-archives/SKILL.md +120 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +373 -0
- package/dist/bundled-skills/chronicling-america/SKILL.md +100 -0
- package/dist/bundled-skills/chronicling-america/scripts/chronam +250 -0
- package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
- package/dist/bundled-skills/findagrave/SKILL.md +116 -0
- package/dist/bundled-skills/findagrave/scripts/findagrave +520 -0
- package/dist/bundled-skills/hathitrust/SKILL.md +110 -0
- package/dist/bundled-skills/hathitrust/scripts/hathi +194 -0
- package/dist/bundled-skills/kentucky-archives/SKILL.md +123 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +358 -0
- package/dist/bundled-skills/library-of-michigan/SKILL.md +111 -0
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +346 -0
- package/dist/bundled-skills/missouri-archives/SKILL.md +100 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +528 -0
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +118 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +934 -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 +118 -0
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +585 -0
- package/dist/bundled-skills/openarchieven/SKILL.md +90 -0
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +432 -0
- package/dist/bundled-skills/texas-archives/SKILL.md +93 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +441 -0
- package/dist/bundled-skills/uk-archives/SKILL.md +101 -0
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +391 -0
- package/dist/bundled-skills/usgs-gnis/SKILL.md +89 -0
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +254 -0
- package/dist/bundled-skills/virginia-archives/SKILL.md +104 -0
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +466 -0
- package/dist/bundled-skills/wikitree/SKILL.md +148 -0
- package/dist/bundled-skills/wikitree/scripts/wikitree +219 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +383 -26
- package/dist/cli.js.map +1 -1
- package/dist/client.js +1 -1
- package/dist/commands/init.js +3 -3
- 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 +867 -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/help.d.ts +6 -0
- package/dist/commands/ops/help.d.ts.map +1 -0
- package/dist/commands/ops/help.js +74 -0
- package/dist/commands/ops/help.js.map +1 -0
- package/dist/commands/ops/index.d.ts +6 -0
- package/dist/commands/ops/index.d.ts.map +1 -0
- package/dist/commands/ops/index.js +6 -0
- package/dist/commands/ops/index.js.map +1 -0
- package/dist/commands/ops/integrate.d.ts +56 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -0
- package/dist/commands/ops/integrate.js +872 -0
- package/dist/commands/ops/integrate.js.map +1 -0
- package/dist/commands/ops/sync.d.ts +177 -0
- package/dist/commands/ops/sync.d.ts.map +1 -0
- package/dist/commands/ops/sync.js +1078 -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/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 +25 -0
- package/dist/commands/records/runner.d.ts.map +1 -0
- package/dist/commands/records/runner.js +224 -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,556 @@
|
|
|
1
|
+
#!/usr/bin/env -S python3 -S
|
|
2
|
+
"""Content-addressed cached OCR CLI for printed scans (tesseract) and handwritten cursive (vision CLI)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
DEFAULT_CURSIVE_EFFORT = "low"
|
|
13
|
+
DEFAULT_VISION_CLI = "agy"
|
|
14
|
+
DEFAULT_PRINTED_TIMEOUT_S = 30
|
|
15
|
+
DEFAULT_CURSIVE_TIMEOUT_S = 90
|
|
16
|
+
CURSIVE_MAX_INPUT_BYTES = 350 * 1024
|
|
17
|
+
CURSIVE_TARGET_KB = 285
|
|
18
|
+
CURSIVE_TARGET_MAX_WIDTH = 2400
|
|
19
|
+
VALID_MODES = ("printed", "cursive")
|
|
20
|
+
VALID_EFFORTS = ("low", "medium", "high", "xhigh")
|
|
21
|
+
|
|
22
|
+
DEFAULT_CURSIVE_PROMPT = (
|
|
23
|
+
"Call read_file ONCE on {image_path}. Do not run shell commands, do not write files, "
|
|
24
|
+
"and do not invoke subagents. Transcribe verbatim all handwritten cursive text visible on "
|
|
25
|
+
"this archival document: first the sheet/page header (state, county, township/city, date, "
|
|
26
|
+
"ED/page/sheet numbers), then each legible household/person row with line number, "
|
|
27
|
+
"dwelling/family numbers, full name, relation, sex, color/race, age, occupation, property "
|
|
28
|
+
"values, and birthplace. Mark genuinely illegible words or characters as [?]; never invent "
|
|
29
|
+
"or extrapolate obscured rows."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def default_cache_dir() -> str:
|
|
34
|
+
env_dir = os.environ.get("KINLOOM_OCR_CACHE_DIR", "").strip()
|
|
35
|
+
if env_dir:
|
|
36
|
+
return os.path.expanduser(env_dir)
|
|
37
|
+
xdg = os.environ.get("XDG_CACHE_HOME", "").strip()
|
|
38
|
+
if xdg:
|
|
39
|
+
return os.path.join(os.path.expanduser(xdg), "kinloom-ocr")
|
|
40
|
+
return os.path.join(os.path.expanduser("~"), ".cache", "kinloom-ocr")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def default_telemetry_file() -> str:
|
|
44
|
+
env_file = os.environ.get("KINLOOM_TELEMETRY_FILE", "").strip()
|
|
45
|
+
if env_file:
|
|
46
|
+
return os.path.expanduser(env_file)
|
|
47
|
+
xdg = os.environ.get("XDG_CACHE_HOME", "").strip()
|
|
48
|
+
if xdg:
|
|
49
|
+
return os.path.join(os.path.expanduser(xdg), "kinloom-telemetry", "calls.jsonl")
|
|
50
|
+
return os.path.join(os.path.expanduser("~"), ".cache", "kinloom-telemetry", "calls.jsonl")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def resolve_vision_cli() -> str:
|
|
54
|
+
configured = os.environ.get("KINLOOM_OCR_CLI", "").strip()
|
|
55
|
+
return configured or DEFAULT_VISION_CLI
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def print_usage() -> None:
|
|
59
|
+
cache_default = default_cache_dir()
|
|
60
|
+
cli_default = resolve_vision_cli()
|
|
61
|
+
sys.stdout.write(
|
|
62
|
+
"Usage: kinloom ocr <image> [options]\n\n"
|
|
63
|
+
"Options:\n"
|
|
64
|
+
" --mode <printed|cursive> OCR mode (default: printed)\n"
|
|
65
|
+
" --psm <int> Tesseract PSM for --mode printed (default: 6)\n"
|
|
66
|
+
f" --effort <low|medium|high|xhigh> Reasoning effort for --mode cursive (default: {DEFAULT_CURSIVE_EFFORT})\n"
|
|
67
|
+
f" --cache-dir <dir> Cache directory (default: {cache_default})\n"
|
|
68
|
+
f" --timeout <seconds> Subprocess timeout (default: {DEFAULT_PRINTED_TIMEOUT_S} printed, {DEFAULT_CURSIVE_TIMEOUT_S} cursive)\n"
|
|
69
|
+
" --prompt <text> Custom prompt for --mode cursive (supports {image_path})\n"
|
|
70
|
+
" --force Bypass cache and recompute OCR\n"
|
|
71
|
+
" --json Emit structured JSON output\n"
|
|
72
|
+
" -h, --help Show this help message\n\n"
|
|
73
|
+
"Environment:\n"
|
|
74
|
+
f" KINLOOM_OCR_CACHE_DIR Override cache directory (default: {cache_default})\n"
|
|
75
|
+
f" KINLOOM_OCR_CLI Vision CLI executable for --mode cursive (default: {cli_default})\n"
|
|
76
|
+
" KINLOOM_OCR_MODEL Override model name passed to --mode cursive vision CLI\n"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def parse_args(argv: list[str]) -> dict[str, object]:
|
|
81
|
+
opts: dict[str, object] = {
|
|
82
|
+
"image": None,
|
|
83
|
+
"mode": "printed",
|
|
84
|
+
"psm": 6,
|
|
85
|
+
"effort": DEFAULT_CURSIVE_EFFORT,
|
|
86
|
+
"cache_dir": default_cache_dir(),
|
|
87
|
+
"timeout": None,
|
|
88
|
+
"prompt": None,
|
|
89
|
+
"force": False,
|
|
90
|
+
"json": False,
|
|
91
|
+
}
|
|
92
|
+
i = 0
|
|
93
|
+
n = len(argv)
|
|
94
|
+
while i < n:
|
|
95
|
+
arg = argv[i]
|
|
96
|
+
if arg in ("-h", "--help"):
|
|
97
|
+
print_usage()
|
|
98
|
+
raise SystemExit(0)
|
|
99
|
+
if arg == "--force":
|
|
100
|
+
opts["force"] = True
|
|
101
|
+
i += 1
|
|
102
|
+
continue
|
|
103
|
+
if arg == "--json":
|
|
104
|
+
opts["json"] = True
|
|
105
|
+
i += 1
|
|
106
|
+
continue
|
|
107
|
+
if arg.startswith("--"):
|
|
108
|
+
if "=" in arg:
|
|
109
|
+
key, val = arg.split("=", 1)
|
|
110
|
+
else:
|
|
111
|
+
key = arg
|
|
112
|
+
if i + 1 >= n:
|
|
113
|
+
raise ValueError(f"Option {key} requires a value.")
|
|
114
|
+
i += 1
|
|
115
|
+
val = argv[i]
|
|
116
|
+
if key == "--mode":
|
|
117
|
+
if val not in VALID_MODES:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"Invalid --mode '{val}': choose from {', '.join(VALID_MODES)}."
|
|
120
|
+
)
|
|
121
|
+
opts["mode"] = val
|
|
122
|
+
elif key == "--psm":
|
|
123
|
+
opts["psm"] = int(val)
|
|
124
|
+
elif key == "--effort":
|
|
125
|
+
if val not in VALID_EFFORTS:
|
|
126
|
+
raise ValueError(
|
|
127
|
+
f"Invalid --effort '{val}': choose from {', '.join(VALID_EFFORTS)}."
|
|
128
|
+
)
|
|
129
|
+
opts["effort"] = val
|
|
130
|
+
elif key == "--cache-dir":
|
|
131
|
+
opts["cache_dir"] = val
|
|
132
|
+
elif key == "--timeout":
|
|
133
|
+
parsed_timeout = int(val)
|
|
134
|
+
if parsed_timeout <= 0:
|
|
135
|
+
raise ValueError(
|
|
136
|
+
f"Invalid --timeout '{val}': must be a positive integer in seconds."
|
|
137
|
+
)
|
|
138
|
+
opts["timeout"] = parsed_timeout
|
|
139
|
+
elif key == "--prompt":
|
|
140
|
+
opts["prompt"] = val
|
|
141
|
+
else:
|
|
142
|
+
raise ValueError(f"Unknown option: {key}")
|
|
143
|
+
i += 1
|
|
144
|
+
continue
|
|
145
|
+
if opts["image"] is None:
|
|
146
|
+
opts["image"] = arg
|
|
147
|
+
i += 1
|
|
148
|
+
continue
|
|
149
|
+
raise ValueError(f"Unexpected positional argument: {arg}")
|
|
150
|
+
|
|
151
|
+
if not opts["image"]:
|
|
152
|
+
raise ValueError("Missing required positional argument: <image>.")
|
|
153
|
+
return opts
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def mode_slug(mode: str, psm: int, effort: str, custom_prompt: str | None) -> str:
|
|
157
|
+
if mode == "printed":
|
|
158
|
+
return f"printed_psm{psm}"
|
|
159
|
+
base = f"cursive_hydrogen_{effort}"
|
|
160
|
+
if custom_prompt:
|
|
161
|
+
digest = hashlib.sha256(custom_prompt.encode("utf-8")).hexdigest()[:8]
|
|
162
|
+
return f"{base}_p{digest}"
|
|
163
|
+
return base
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def atomic_write_json(dest: str, payload: dict[str, object]) -> None:
|
|
167
|
+
parent = os.path.dirname(dest)
|
|
168
|
+
os.makedirs(parent, exist_ok=True)
|
|
169
|
+
tmp = os.path.join(parent, f".{os.path.basename(dest)}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
170
|
+
try:
|
|
171
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
172
|
+
fh.write(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
|
|
173
|
+
os.replace(tmp, dest)
|
|
174
|
+
except Exception:
|
|
175
|
+
if os.path.exists(tmp):
|
|
176
|
+
try:
|
|
177
|
+
os.unlink(tmp)
|
|
178
|
+
except OSError:
|
|
179
|
+
pass
|
|
180
|
+
raise
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def run_printed_ocr(img_path: str, psm: int, timeout_s: int) -> tuple[str, dict[str, object]]:
|
|
184
|
+
import shutil
|
|
185
|
+
import subprocess
|
|
186
|
+
|
|
187
|
+
tesseract_bin = shutil.which("tesseract")
|
|
188
|
+
if not tesseract_bin:
|
|
189
|
+
raise RuntimeError(
|
|
190
|
+
"tesseract executable not found on PATH. Install tesseract-ocr "
|
|
191
|
+
"(for example `apt install tesseract-ocr` or `brew install tesseract`)."
|
|
192
|
+
)
|
|
193
|
+
# Pin OpenMP to a single thread so parallel OCR calls cannot thrash CPU cores.
|
|
194
|
+
tesseract_env = {**os.environ, "OMP_THREAD_LIMIT": "1"}
|
|
195
|
+
timeout_bin = shutil.which("timeout")
|
|
196
|
+
cmd = (
|
|
197
|
+
[
|
|
198
|
+
timeout_bin,
|
|
199
|
+
"-k",
|
|
200
|
+
"2",
|
|
201
|
+
str(timeout_s),
|
|
202
|
+
tesseract_bin,
|
|
203
|
+
img_path,
|
|
204
|
+
"stdout",
|
|
205
|
+
"--psm",
|
|
206
|
+
str(psm),
|
|
207
|
+
]
|
|
208
|
+
if timeout_bin
|
|
209
|
+
else [tesseract_bin, img_path, "stdout", "--psm", str(psm)]
|
|
210
|
+
)
|
|
211
|
+
try:
|
|
212
|
+
proc = subprocess.run(
|
|
213
|
+
cmd,
|
|
214
|
+
capture_output=True,
|
|
215
|
+
text=True,
|
|
216
|
+
timeout=timeout_s + 3 if timeout_bin else timeout_s,
|
|
217
|
+
env=tesseract_env,
|
|
218
|
+
)
|
|
219
|
+
except subprocess.TimeoutExpired as exc:
|
|
220
|
+
raise RuntimeError(
|
|
221
|
+
f"tesseract timed out after {timeout_s}s on {os.path.basename(img_path)} "
|
|
222
|
+
f"(increase --timeout or use --mode cursive for handwritten pages)."
|
|
223
|
+
) from exc
|
|
224
|
+
if timeout_bin and proc.returncode in (124, 137):
|
|
225
|
+
raise RuntimeError(
|
|
226
|
+
f"tesseract timed out after {timeout_s}s on {os.path.basename(img_path)} "
|
|
227
|
+
f"(increase --timeout or use --mode cursive for handwritten pages)."
|
|
228
|
+
)
|
|
229
|
+
if proc.returncode != 0:
|
|
230
|
+
detail = (proc.stderr or proc.stdout).strip()
|
|
231
|
+
raise RuntimeError(f"tesseract exited {proc.returncode}: {detail[:300]}")
|
|
232
|
+
return proc.stdout.strip(), {"psm": psm, "omp_thread_limit": 1, "timeout_s": timeout_s}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def prepare_cursive_image(img_path: str, raw_len: int, work_dir: str) -> tuple[str, str | None, int]:
|
|
236
|
+
if raw_len <= CURSIVE_MAX_INPUT_BYTES:
|
|
237
|
+
return img_path, None, raw_len
|
|
238
|
+
|
|
239
|
+
import shutil
|
|
240
|
+
import subprocess
|
|
241
|
+
|
|
242
|
+
prep_script = os.path.join(os.path.dirname(os.path.realpath(__file__)), "prep-scan.py")
|
|
243
|
+
if not os.path.isfile(prep_script):
|
|
244
|
+
raise RuntimeError(f"Companion script not found: {prep_script}")
|
|
245
|
+
|
|
246
|
+
uv_bin = shutil.which("uv")
|
|
247
|
+
prep_cmd = (
|
|
248
|
+
[uv_bin, "run", "--script", prep_script]
|
|
249
|
+
if uv_bin
|
|
250
|
+
else [sys.executable, prep_script]
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
os.makedirs(work_dir, exist_ok=True)
|
|
254
|
+
job_dir = os.path.join(work_dir, f"job_{os.getpid()}_{time.time_ns()}")
|
|
255
|
+
os.makedirs(job_dir, exist_ok=True)
|
|
256
|
+
child_env = {
|
|
257
|
+
**os.environ,
|
|
258
|
+
"KINLOOM_TELEMETRY_PARENT": "1",
|
|
259
|
+
"KINLOOM_TELEMETRY_ACTIVE": "1",
|
|
260
|
+
}
|
|
261
|
+
try:
|
|
262
|
+
proc = subprocess.run(
|
|
263
|
+
[
|
|
264
|
+
*prep_cmd,
|
|
265
|
+
"preview",
|
|
266
|
+
img_path,
|
|
267
|
+
"--out-dir",
|
|
268
|
+
job_dir,
|
|
269
|
+
"--max-width",
|
|
270
|
+
str(CURSIVE_TARGET_MAX_WIDTH),
|
|
271
|
+
"--max-kb",
|
|
272
|
+
str(CURSIVE_TARGET_KB),
|
|
273
|
+
"--json",
|
|
274
|
+
],
|
|
275
|
+
capture_output=True,
|
|
276
|
+
text=True,
|
|
277
|
+
timeout=60,
|
|
278
|
+
env=child_env,
|
|
279
|
+
)
|
|
280
|
+
if proc.returncode != 0:
|
|
281
|
+
raise RuntimeError(
|
|
282
|
+
f"prep-scan.py failed ({proc.returncode}): {(proc.stderr or proc.stdout).strip()[:300]}"
|
|
283
|
+
)
|
|
284
|
+
info = json.loads(proc.stdout)[0]
|
|
285
|
+
return str(info["path"]), job_dir, int(info["bytes"])
|
|
286
|
+
except Exception:
|
|
287
|
+
shutil.rmtree(job_dir, ignore_errors=True)
|
|
288
|
+
raise
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def run_cursive_ocr(
|
|
292
|
+
img_path: str,
|
|
293
|
+
raw_len: int,
|
|
294
|
+
effort: str,
|
|
295
|
+
timeout_s: int,
|
|
296
|
+
cache_dir: str,
|
|
297
|
+
custom_prompt: str | None,
|
|
298
|
+
) -> tuple[str, dict[str, object]]:
|
|
299
|
+
import shutil
|
|
300
|
+
import subprocess
|
|
301
|
+
|
|
302
|
+
cli_name = resolve_vision_cli()
|
|
303
|
+
cli_bin = shutil.which(cli_name)
|
|
304
|
+
if not cli_bin:
|
|
305
|
+
raise RuntimeError(
|
|
306
|
+
f"Vision CLI '{cli_name}' not found on PATH. Install '{cli_name}' "
|
|
307
|
+
"or set KINLOOM_OCR_CLI to a compatible vision CLI executable."
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
model = os.environ.get("KINLOOM_OCR_MODEL", "").strip() or f"gemini-4-hydrogen-{effort}"
|
|
311
|
+
work_dir = os.path.join(cache_dir, ".work")
|
|
312
|
+
send_path, cleanup_dir, sent_bytes = prepare_cursive_image(img_path, raw_len, work_dir)
|
|
313
|
+
try:
|
|
314
|
+
prompt_template = custom_prompt or DEFAULT_CURSIVE_PROMPT
|
|
315
|
+
prompt = (
|
|
316
|
+
prompt_template.format(image_path=send_path)
|
|
317
|
+
if "{image_path}" in prompt_template
|
|
318
|
+
else f"Call read_file ONCE on {send_path}. {prompt_template}"
|
|
319
|
+
)
|
|
320
|
+
add_dir = os.path.dirname(send_path)
|
|
321
|
+
try:
|
|
322
|
+
proc = subprocess.run(
|
|
323
|
+
[
|
|
324
|
+
cli_bin,
|
|
325
|
+
"--model",
|
|
326
|
+
model,
|
|
327
|
+
"--dangerously-skip-permissions",
|
|
328
|
+
"--disable-slash-commands",
|
|
329
|
+
"--add-dir",
|
|
330
|
+
add_dir,
|
|
331
|
+
"--output-format",
|
|
332
|
+
"json",
|
|
333
|
+
"--print-timeout",
|
|
334
|
+
f"{timeout_s}s",
|
|
335
|
+
f"-p={prompt}",
|
|
336
|
+
],
|
|
337
|
+
cwd=add_dir,
|
|
338
|
+
capture_output=True,
|
|
339
|
+
text=True,
|
|
340
|
+
timeout=timeout_s + 15,
|
|
341
|
+
)
|
|
342
|
+
except subprocess.TimeoutExpired as exc:
|
|
343
|
+
raise RuntimeError(
|
|
344
|
+
f"{cli_name} timed out after {timeout_s}s on {os.path.basename(img_path)} "
|
|
345
|
+
f"(pass a higher --timeout to override)."
|
|
346
|
+
) from exc
|
|
347
|
+
if proc.returncode != 0:
|
|
348
|
+
detail = (proc.stderr or proc.stdout).strip()
|
|
349
|
+
raise RuntimeError(f"{cli_name} exited {proc.returncode}: {detail[:400]}")
|
|
350
|
+
try:
|
|
351
|
+
payload = json.loads(proc.stdout)
|
|
352
|
+
except json.JSONDecodeError as exc:
|
|
353
|
+
raise RuntimeError(f"{cli_name} returned non-JSON stdout: {proc.stdout[:300]}") from exc
|
|
354
|
+
if payload.get("status") != "SUCCESS":
|
|
355
|
+
raise RuntimeError(
|
|
356
|
+
f"{cli_name} returned status={payload.get('status')}: {str(payload)[:300]}"
|
|
357
|
+
)
|
|
358
|
+
text = str(payload.get("response") or "").strip()
|
|
359
|
+
if not text:
|
|
360
|
+
raise RuntimeError(f"{cli_name} returned an empty transcription response.")
|
|
361
|
+
usage = payload.get("usage") or {}
|
|
362
|
+
meta: dict[str, object] = {
|
|
363
|
+
"cli": cli_name,
|
|
364
|
+
"model": model,
|
|
365
|
+
"effort": effort,
|
|
366
|
+
"sent_bytes": sent_bytes,
|
|
367
|
+
"duration_seconds": payload.get("duration_seconds"),
|
|
368
|
+
"thinking_tokens": usage.get("thinking_tokens"),
|
|
369
|
+
"output_tokens": usage.get("output_tokens"),
|
|
370
|
+
}
|
|
371
|
+
return text, meta
|
|
372
|
+
finally:
|
|
373
|
+
if cleanup_dir is not None:
|
|
374
|
+
shutil.rmtree(cleanup_dir, ignore_errors=True)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def append_telemetry(
|
|
378
|
+
*,
|
|
379
|
+
mode: str,
|
|
380
|
+
duration_ms: float,
|
|
381
|
+
cache_hit: bool | None,
|
|
382
|
+
exit_code: int,
|
|
383
|
+
bytes_out: int,
|
|
384
|
+
) -> None:
|
|
385
|
+
sig_file = os.environ.get("KINLOOM_CACHE_HIT_FILE")
|
|
386
|
+
if sig_file and isinstance(cache_hit, bool):
|
|
387
|
+
try:
|
|
388
|
+
with open(sig_file, "w", encoding="utf-8") as sfh:
|
|
389
|
+
sfh.write("1" if cache_hit else "0")
|
|
390
|
+
except Exception:
|
|
391
|
+
pass
|
|
392
|
+
if (
|
|
393
|
+
os.environ.get("KINLOOM_TELEMETRY_PARENT") == "1"
|
|
394
|
+
or os.environ.get("KINLOOM_TELEMETRY_ACTIVE") == "1"
|
|
395
|
+
):
|
|
396
|
+
return
|
|
397
|
+
try:
|
|
398
|
+
from datetime import datetime, timezone
|
|
399
|
+
|
|
400
|
+
target = default_telemetry_file()
|
|
401
|
+
parent = os.path.dirname(os.path.abspath(target))
|
|
402
|
+
if parent:
|
|
403
|
+
os.makedirs(parent, exist_ok=True)
|
|
404
|
+
entry = {
|
|
405
|
+
"ts": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
406
|
+
"cmd": "cached-ocr.py",
|
|
407
|
+
"subcmd": f"ocr {mode}" if mode else "ocr",
|
|
408
|
+
"person_id": None,
|
|
409
|
+
"duration_ms": max(0, int(round(duration_ms))),
|
|
410
|
+
"cache_hit": cache_hit,
|
|
411
|
+
"exit_code": int(exit_code),
|
|
412
|
+
"bytes_out": max(0, int(bytes_out)),
|
|
413
|
+
}
|
|
414
|
+
with open(target, "a", encoding="utf-8") as fh:
|
|
415
|
+
fh.write(json.dumps(entry, separators=(",", ":")) + "\n")
|
|
416
|
+
except Exception:
|
|
417
|
+
pass
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def main(argv: list[str] | None = None) -> int:
|
|
421
|
+
t_start = time.perf_counter()
|
|
422
|
+
try:
|
|
423
|
+
opts = parse_args(sys.argv[1:] if argv is None else argv)
|
|
424
|
+
except ValueError as exc:
|
|
425
|
+
sys.stderr.write(f"Error: {exc}\n")
|
|
426
|
+
append_telemetry(
|
|
427
|
+
mode="",
|
|
428
|
+
duration_ms=(time.perf_counter() - t_start) * 1000.0,
|
|
429
|
+
cache_hit=None,
|
|
430
|
+
exit_code=2,
|
|
431
|
+
bytes_out=0,
|
|
432
|
+
)
|
|
433
|
+
return 2
|
|
434
|
+
|
|
435
|
+
img_path = os.path.abspath(str(opts["image"]))
|
|
436
|
+
mode = str(opts["mode"])
|
|
437
|
+
if not os.path.isfile(img_path):
|
|
438
|
+
sys.stderr.write(f"Error: image file not found: {img_path}\n")
|
|
439
|
+
append_telemetry(
|
|
440
|
+
mode=mode,
|
|
441
|
+
duration_ms=(time.perf_counter() - t_start) * 1000.0,
|
|
442
|
+
cache_hit=None,
|
|
443
|
+
exit_code=1,
|
|
444
|
+
bytes_out=0,
|
|
445
|
+
)
|
|
446
|
+
return 1
|
|
447
|
+
|
|
448
|
+
cache_dir = os.path.abspath(str(opts["cache_dir"]))
|
|
449
|
+
with open(img_path, "rb") as fh:
|
|
450
|
+
raw_bytes = fh.read()
|
|
451
|
+
sha256_hex = hashlib.sha256(raw_bytes).hexdigest()
|
|
452
|
+
|
|
453
|
+
psm = int(opts["psm"])
|
|
454
|
+
effort = str(opts["effort"])
|
|
455
|
+
custom_prompt = opts["prompt"] if isinstance(opts["prompt"], str) else None
|
|
456
|
+
slug = mode_slug(mode, psm, effort, custom_prompt)
|
|
457
|
+
cache_file = os.path.join(cache_dir, f"{sha256_hex}_{slug}.json")
|
|
458
|
+
|
|
459
|
+
if not opts["force"] and os.path.isfile(cache_file):
|
|
460
|
+
try:
|
|
461
|
+
with open(cache_file, "r", encoding="utf-8") as fh:
|
|
462
|
+
record = json.load(fh)
|
|
463
|
+
except (OSError, json.JSONDecodeError):
|
|
464
|
+
record = None
|
|
465
|
+
if isinstance(record, dict) and isinstance(record.get("text"), str):
|
|
466
|
+
lookup_ms = round((time.perf_counter() - t_start) * 1000.0, 2)
|
|
467
|
+
if opts["json"]:
|
|
468
|
+
out = {
|
|
469
|
+
**record,
|
|
470
|
+
"cached": True,
|
|
471
|
+
"cache_path": cache_file,
|
|
472
|
+
"lookup_ms": lookup_ms,
|
|
473
|
+
}
|
|
474
|
+
rendered = json.dumps(out, indent=2, ensure_ascii=False) + "\n"
|
|
475
|
+
else:
|
|
476
|
+
rendered = record["text"] + "\n"
|
|
477
|
+
sys.stdout.write(rendered)
|
|
478
|
+
append_telemetry(
|
|
479
|
+
mode=mode,
|
|
480
|
+
duration_ms=(time.perf_counter() - t_start) * 1000.0,
|
|
481
|
+
cache_hit=True,
|
|
482
|
+
exit_code=0,
|
|
483
|
+
bytes_out=len(rendered.encode("utf-8")),
|
|
484
|
+
)
|
|
485
|
+
return 0
|
|
486
|
+
|
|
487
|
+
from datetime import datetime, timezone
|
|
488
|
+
|
|
489
|
+
timeout_val = opts["timeout"]
|
|
490
|
+
timeout_s = (
|
|
491
|
+
int(timeout_val)
|
|
492
|
+
if timeout_val is not None
|
|
493
|
+
else (DEFAULT_PRINTED_TIMEOUT_S if mode == "printed" else DEFAULT_CURSIVE_TIMEOUT_S)
|
|
494
|
+
)
|
|
495
|
+
t_ocr = time.perf_counter()
|
|
496
|
+
try:
|
|
497
|
+
if mode == "printed":
|
|
498
|
+
text, meta = run_printed_ocr(img_path, psm=psm, timeout_s=timeout_s)
|
|
499
|
+
engine = "tesseract"
|
|
500
|
+
else:
|
|
501
|
+
text, meta = run_cursive_ocr(
|
|
502
|
+
img_path=img_path,
|
|
503
|
+
raw_len=len(raw_bytes),
|
|
504
|
+
effort=effort,
|
|
505
|
+
timeout_s=timeout_s,
|
|
506
|
+
cache_dir=cache_dir,
|
|
507
|
+
custom_prompt=custom_prompt,
|
|
508
|
+
)
|
|
509
|
+
engine = f"{meta.get('cli', resolve_vision_cli())}:{meta.get('model', '')}"
|
|
510
|
+
except Exception as exc:
|
|
511
|
+
sys.stderr.write(f"Error: {exc}\n")
|
|
512
|
+
append_telemetry(
|
|
513
|
+
mode=mode,
|
|
514
|
+
duration_ms=(time.perf_counter() - t_start) * 1000.0,
|
|
515
|
+
cache_hit=False,
|
|
516
|
+
exit_code=1,
|
|
517
|
+
bytes_out=0,
|
|
518
|
+
)
|
|
519
|
+
return 1
|
|
520
|
+
|
|
521
|
+
elapsed_ms = int(round((time.perf_counter() - t_ocr) * 1000.0))
|
|
522
|
+
record = {
|
|
523
|
+
"sha256": sha256_hex,
|
|
524
|
+
"mode": slug,
|
|
525
|
+
"engine": engine,
|
|
526
|
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
|
527
|
+
"elapsed_ms": elapsed_ms,
|
|
528
|
+
"text": text,
|
|
529
|
+
"source_hint": os.path.basename(img_path),
|
|
530
|
+
"meta": meta,
|
|
531
|
+
}
|
|
532
|
+
atomic_write_json(cache_file, record)
|
|
533
|
+
|
|
534
|
+
if opts["json"]:
|
|
535
|
+
out = {
|
|
536
|
+
**record,
|
|
537
|
+
"cached": False,
|
|
538
|
+
"cache_path": cache_file,
|
|
539
|
+
"lookup_ms": round((time.perf_counter() - t_start) * 1000.0, 2),
|
|
540
|
+
}
|
|
541
|
+
rendered = json.dumps(out, indent=2, ensure_ascii=False) + "\n"
|
|
542
|
+
else:
|
|
543
|
+
rendered = text + "\n"
|
|
544
|
+
sys.stdout.write(rendered)
|
|
545
|
+
append_telemetry(
|
|
546
|
+
mode=mode,
|
|
547
|
+
duration_ms=(time.perf_counter() - t_start) * 1000.0,
|
|
548
|
+
cache_hit=False,
|
|
549
|
+
exit_code=0,
|
|
550
|
+
bytes_out=len(rendered.encode("utf-8")),
|
|
551
|
+
)
|
|
552
|
+
return 0
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
if __name__ == "__main__":
|
|
556
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: ocr
|
|
3
|
+
description: Run content-addressed cached OCR on archival scans: fast printed-text OCR via tesseract or handwritten cursive transcription via a configured vision CLI, keyed by image SHA-256 and mode so repeated runs return instantly from disk.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Cached OCR (`kinloom ocr`)
|
|
7
|
+
|
|
8
|
+
Content-addressed OCR for genealogical scans. Each image is hashed by SHA-256 and cached on disk by hash and mode so repeated reads return immediately without re-running OCR or paying vision API cost twice.
|
|
9
|
+
|
|
10
|
+
## Printed text (`--mode printed`, default)
|
|
11
|
+
|
|
12
|
+
Uses local `tesseract` (default `--psm 6`, single uniform block of text). Every `tesseract` call forces `OMP_THREAD_LIMIT=1` and a hard per-image timeout (`--timeout`, default `30` seconds for printed text, `90` seconds for cursive vision OCR) so parallel runs fail fast instead of thrashing CPU cores:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
kinloom ocr ./scans/obituary-1912.jpg
|
|
16
|
+
kinloom ocr ./scans/city-directory-p44.jpg --psm 4 --json
|
|
17
|
+
kinloom ocr ./scans/obituary-1912.jpg --force
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Handwritten cursive (`--mode cursive`)
|
|
21
|
+
|
|
22
|
+
Automatically downsizes scans larger than 350 KB using the bundled `prep-scan` preview pipeline, then invokes the configured vision CLI (`KINLOOM_OCR_CLI`, default `agy`) to transcribe headers and rows verbatim while marking illegible text as `[?]`:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
kinloom ocr ./scans/census-1870-sheet4.jpg --mode cursive
|
|
26
|
+
kinloom ocr ./scans/deed-1848.jpg --mode cursive --effort medium --json
|
|
27
|
+
kinloom ocr ./scans/letter-1864.jpg --mode cursive --prompt "Transcribe this letter verbatim from {image_path}."
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Cache layout
|
|
31
|
+
|
|
32
|
+
Cached JSON records are written atomically to `<cache-dir>/<sha256>_<mode-slug>.json`, where `<cache-dir>` defaults to:
|
|
33
|
+
|
|
34
|
+
1. `--cache-dir <dir>`
|
|
35
|
+
2. `KINLOOM_OCR_CACHE_DIR`
|
|
36
|
+
3. `$XDG_CACHE_HOME/kinloom-ocr`
|
|
37
|
+
4. `~/.cache/kinloom-ocr`
|
|
38
|
+
|
|
39
|
+
Pass `--force` to recompute and overwrite an existing cache entry, or `--json` to inspect cache status, SHA-256 digest, engine metadata, and timing.
|
|
40
|
+
|
|
41
|
+
## Environment variables
|
|
42
|
+
|
|
43
|
+
- `KINLOOM_OCR_CACHE_DIR` (optional): overrides the default cache directory.
|
|
44
|
+
- `KINLOOM_OCR_CLI` (optional): vision CLI binary invoked in `--mode cursive` (default: `agy`).
|
|
45
|
+
- `KINLOOM_OCR_MODEL` (optional): overrides the model name passed to the vision CLI.
|
|
46
|
+
- `XDG_CACHE_HOME` (optional): standard cache base directory used when `KINLOOM_OCR_CACHE_DIR` is unset.
|
|
47
|
+
|
|
48
|
+
## Requirements
|
|
49
|
+
|
|
50
|
+
- Python 3.11+ standard library only for the wrapper itself.
|
|
51
|
+
- `tesseract` (`tesseract-ocr`) on `PATH` for `--mode printed`.
|
|
52
|
+
- Configured vision CLI (`KINLOOM_OCR_CLI`, default `agy`) on `PATH` for `--mode cursive` (plus `uv` or Pillow when oversized cursive scans need downsizing).
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: prep-scan
|
|
3
|
+
description: Prepare archival scans for inspection and publication: generate compact JPEG previews in parallel, rotate/crop/redact scans with automatic verification previews, stitch census sheet header strips, and render selective PDF pages via pdftoppm.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Scan Preparation (`kinloom prep-scan`)
|
|
7
|
+
|
|
8
|
+
Generate lightweight inspection previews, redacted archival crops, census header contact strips, and selective PDF page renders. The bundled Python script uses a PEP 723 `uv run --script` header (`pillow`, `httpx`), and `pdf-pages` uses `pdftoppm` from Poppler.
|
|
9
|
+
|
|
10
|
+
## Subcommands
|
|
11
|
+
|
|
12
|
+
### 1. Compact inspection previews (`preview`)
|
|
13
|
+
|
|
14
|
+
Resize and compress one or more large archival scans in parallel into compact JPEGs (default max width `1400px`, max size `280 KB`) for fast visual review:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
kinloom prep-scan preview ./raw/census-1880.tif ./raw/deed-1872.jpg --out-dir ./previews
|
|
18
|
+
kinloom prep-scan preview ./raw/*.jpg --out-dir ./previews --max-width 1600 --max-kb 250 --json
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### 2. Rotate, crop, and redact (`crop`)
|
|
22
|
+
|
|
23
|
+
Apply optional clockwise rotation (`90`, `180`, `270`), crop to `x0,y0,x1,y1`, draw solid black redaction boxes in cropped coordinates, write the archival output image, and automatically generate a compact verification preview:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
kinloom prep-scan crop ./raw/certificate.jpg ./media/certificate.jpg \
|
|
27
|
+
--rotate 90 \
|
|
28
|
+
--box 120,80,2400,3100 \
|
|
29
|
+
--redact 40,2100,900,2250 \
|
|
30
|
+
--preview-out ./previews/certificate.preview.jpg
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### 3. Census header or street contact strip (`sheet-strip`)
|
|
34
|
+
|
|
35
|
+
Slice the top or left band from local scans or remote image URLs in parallel and stitch them into a single labeled contact sheet for fast enumeration-district or street scanning:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
kinloom prep-scan sheet-strip ./sheets/ed-12-*.jpg --out ./strips/ed-12-headers.jpg --band top --band-pct 18
|
|
39
|
+
kinloom prep-scan sheet-strip ./sheets/ed-12-*.jpg --out ./strips/ed-12-streets.jpg --band left --band-pct 12 --max-kb 250
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### 4. Selective PDF page rendering (`pdf-pages`)
|
|
43
|
+
|
|
44
|
+
Render only the requested PDF page numbers via `pdftoppm`, build compact previews in parallel, and optionally emit a labeled contact strip:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
kinloom prep-scan pdf-pages ./archive/county-history.pdf --pages 1-4,18,42-45 --out-dir ./rendered --dpi 150
|
|
48
|
+
kinloom prep-scan pdf-pages ./archive/packet.pdf --pages 1-6 --out-dir ./rendered --strip ./rendered/contact.jpg --json
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Environment variables
|
|
52
|
+
|
|
53
|
+
- `KINLOOM_OCR_CACHE_DIR` (optional): overrides the default preview cache root (`$XDG_CACHE_HOME/kinloom-ocr` or `~/.cache/kinloom-ocr`).
|
|
54
|
+
- `XDG_CACHE_HOME` (optional): standard cache base directory used when `KINLOOM_OCR_CACHE_DIR` is unset.
|
|
55
|
+
|
|
56
|
+
## Requirements
|
|
57
|
+
|
|
58
|
+
- `uv` (or Python 3.11+ with `pillow`, plus `httpx` for URL inputs in `sheet-strip`).
|
|
59
|
+
- `pdftoppm` (`poppler-utils` on Linux or `poppler` on macOS) for `pdf-pages`.
|