@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.
Files changed (111) hide show
  1. package/dist/assets/cached-ocr.py +786 -0
  2. package/dist/assets/ocr.md +76 -0
  3. package/dist/assets/prep-scan.md +97 -0
  4. package/dist/assets/prep-scan.py +1313 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +162 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +130 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +129 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +154 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +488 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +30 -5
  50. package/dist/client.js.map +1 -1
  51. package/dist/commands/ops/audit.d.ts +138 -0
  52. package/dist/commands/ops/audit.d.ts.map +1 -0
  53. package/dist/commands/ops/audit.js +872 -0
  54. package/dist/commands/ops/audit.js.map +1 -0
  55. package/dist/commands/ops/context.d.ts +100 -0
  56. package/dist/commands/ops/context.d.ts.map +1 -0
  57. package/dist/commands/ops/context.js +917 -0
  58. package/dist/commands/ops/context.js.map +1 -0
  59. package/dist/commands/ops/dates.d.ts +87 -0
  60. package/dist/commands/ops/dates.d.ts.map +1 -0
  61. package/dist/commands/ops/dates.js +228 -0
  62. package/dist/commands/ops/dates.js.map +1 -0
  63. package/dist/commands/ops/help.d.ts +8 -0
  64. package/dist/commands/ops/help.d.ts.map +1 -0
  65. package/dist/commands/ops/help.js +107 -0
  66. package/dist/commands/ops/help.js.map +1 -0
  67. package/dist/commands/ops/index.d.ts +8 -0
  68. package/dist/commands/ops/index.d.ts.map +1 -0
  69. package/dist/commands/ops/index.js +8 -0
  70. package/dist/commands/ops/index.js.map +1 -0
  71. package/dist/commands/ops/integrate.d.ts +61 -0
  72. package/dist/commands/ops/integrate.d.ts.map +1 -0
  73. package/dist/commands/ops/integrate.js +1063 -0
  74. package/dist/commands/ops/integrate.js.map +1 -0
  75. package/dist/commands/ops/sync.d.ts +194 -0
  76. package/dist/commands/ops/sync.d.ts.map +1 -0
  77. package/dist/commands/ops/sync.js +1251 -0
  78. package/dist/commands/ops/sync.js.map +1 -0
  79. package/dist/commands/ops/telemetry.d.ts +79 -0
  80. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  81. package/dist/commands/ops/telemetry.js +249 -0
  82. package/dist/commands/ops/telemetry.js.map +1 -0
  83. package/dist/commands/ops/verify.d.ts +76 -0
  84. package/dist/commands/ops/verify.d.ts.map +1 -0
  85. package/dist/commands/ops/verify.js +325 -0
  86. package/dist/commands/ops/verify.js.map +1 -0
  87. package/dist/commands/records/help.d.ts +18 -0
  88. package/dist/commands/records/help.d.ts.map +1 -0
  89. package/dist/commands/records/help.js +174 -0
  90. package/dist/commands/records/help.js.map +1 -0
  91. package/dist/commands/records/index.d.ts +5 -0
  92. package/dist/commands/records/index.d.ts.map +1 -0
  93. package/dist/commands/records/index.js +5 -0
  94. package/dist/commands/records/index.js.map +1 -0
  95. package/dist/commands/records/registry.d.ts +32 -0
  96. package/dist/commands/records/registry.d.ts.map +1 -0
  97. package/dist/commands/records/registry.js +227 -0
  98. package/dist/commands/records/registry.js.map +1 -0
  99. package/dist/commands/records/resolve.d.ts +14 -0
  100. package/dist/commands/records/resolve.d.ts.map +1 -0
  101. package/dist/commands/records/resolve.js +61 -0
  102. package/dist/commands/records/resolve.js.map +1 -0
  103. package/dist/commands/records/runner.d.ts +27 -0
  104. package/dist/commands/records/runner.d.ts.map +1 -0
  105. package/dist/commands/records/runner.js +255 -0
  106. package/dist/commands/records/runner.js.map +1 -0
  107. package/dist/index.d.ts +2 -0
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +2 -0
  110. package/dist/index.js.map +1 -1
  111. package/package.json +3 -3
@@ -0,0 +1,786 @@
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> [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> Per-image 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 (or {files: [...]} for multiple images)\n"
72
+ " --boxes Emit JSON line/word pixel boxes (printed mode only)\n"
73
+ " --tsv Emit raw Tesseract TSV (printed mode only)\n"
74
+ " --find <regex> Case-insensitive line filter; implies --boxes\n"
75
+ " -h, --help Show this help message\n\n"
76
+ "Environment:\n"
77
+ f" KINLOOM_OCR_CACHE_DIR Override cache directory (default: {cache_default})\n"
78
+ f" KINLOOM_OCR_CLI Vision CLI executable for --mode cursive (default: {cli_default})\n"
79
+ " KINLOOM_OCR_MODEL Override model name passed to --mode cursive vision CLI\n"
80
+ )
81
+
82
+
83
+ def parse_args(argv: list[str]) -> dict[str, object]:
84
+ images: list[str] = []
85
+ opts: dict[str, object] = {
86
+ "images": images,
87
+ "mode": "printed",
88
+ "psm": 6,
89
+ "effort": DEFAULT_CURSIVE_EFFORT,
90
+ "cache_dir": default_cache_dir(),
91
+ "timeout": None,
92
+ "prompt": None,
93
+ "force": False,
94
+ "json": False,
95
+ "boxes": False,
96
+ "tsv": False,
97
+ "find": None,
98
+ }
99
+ i = 0
100
+ n = len(argv)
101
+ while i < n:
102
+ arg = argv[i]
103
+ if arg in ("-h", "--help"):
104
+ print_usage()
105
+ raise SystemExit(0)
106
+ if arg == "--force":
107
+ opts["force"] = True
108
+ i += 1
109
+ continue
110
+ if arg in ("--json", "--boxes", "--tsv"):
111
+ opts[arg[2:]] = True
112
+ i += 1
113
+ continue
114
+ if arg == "--":
115
+ images.extend(argv[i + 1 :])
116
+ break
117
+ if arg.startswith("--"):
118
+ if "=" in arg:
119
+ key, val = arg.split("=", 1)
120
+ else:
121
+ key = arg
122
+ if i + 1 >= n:
123
+ raise ValueError(f"Option {key} requires a value.")
124
+ i += 1
125
+ val = argv[i]
126
+ if key == "--mode":
127
+ if val not in VALID_MODES:
128
+ raise ValueError(
129
+ f"Invalid --mode '{val}': choose from {', '.join(VALID_MODES)}."
130
+ )
131
+ opts["mode"] = val
132
+ elif key == "--psm":
133
+ opts["psm"] = int(val)
134
+ elif key == "--effort":
135
+ if val not in VALID_EFFORTS:
136
+ raise ValueError(
137
+ f"Invalid --effort '{val}': choose from {', '.join(VALID_EFFORTS)}."
138
+ )
139
+ opts["effort"] = val
140
+ elif key == "--cache-dir":
141
+ opts["cache_dir"] = val
142
+ elif key == "--timeout":
143
+ parsed_timeout = int(val)
144
+ if parsed_timeout <= 0:
145
+ raise ValueError(
146
+ f"Invalid --timeout '{val}': must be a positive integer in seconds."
147
+ )
148
+ opts["timeout"] = parsed_timeout
149
+ elif key == "--prompt":
150
+ opts["prompt"] = val
151
+ elif key == "--find":
152
+ import re
153
+
154
+ try:
155
+ re.compile(val)
156
+ except re.error as exc:
157
+ raise ValueError(f"Invalid --find regex '{val}': {exc}") from exc
158
+ opts["find"] = val
159
+ opts["boxes"] = True
160
+ else:
161
+ raise ValueError(f"Unknown option: {key}")
162
+ i += 1
163
+ continue
164
+ images.append(arg)
165
+ i += 1
166
+
167
+ if not images:
168
+ raise ValueError("Missing required positional argument: <image>.")
169
+ if opts["boxes"] and opts["tsv"]:
170
+ raise ValueError("--tsv cannot be combined with --boxes or --find.")
171
+ if (opts["boxes"] or opts["tsv"]) and opts["mode"] != "printed":
172
+ raise ValueError("--boxes, --tsv, and --find require --mode printed.")
173
+ return opts
174
+
175
+
176
+ def mode_slug(mode: str, psm: int, effort: str, custom_prompt: str | None) -> str:
177
+ if mode == "printed":
178
+ return f"printed_psm{psm}"
179
+ base = f"cursive_hydrogen_{effort}"
180
+ if custom_prompt:
181
+ digest = hashlib.sha256(custom_prompt.encode("utf-8")).hexdigest()[:8]
182
+ return f"{base}_p{digest}"
183
+ return base
184
+
185
+
186
+ def atomic_write_json(dest: str, payload: dict[str, object]) -> None:
187
+ parent = os.path.dirname(dest)
188
+ os.makedirs(parent, exist_ok=True)
189
+ tmp = os.path.join(parent, f".{os.path.basename(dest)}.{os.getpid()}.{time.time_ns()}.tmp")
190
+ try:
191
+ with open(tmp, "w", encoding="utf-8") as fh:
192
+ fh.write(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
193
+ os.replace(tmp, dest)
194
+ except Exception:
195
+ if os.path.exists(tmp):
196
+ try:
197
+ os.unlink(tmp)
198
+ except OSError:
199
+ pass
200
+ raise
201
+
202
+
203
+ def run_printed_ocr(
204
+ img_path: str, psm: int, timeout_s: int, tsv: bool = False
205
+ ) -> tuple[str, dict[str, object]]:
206
+ import shutil
207
+ import subprocess
208
+
209
+ tesseract_bin = shutil.which("tesseract")
210
+ if not tesseract_bin:
211
+ raise RuntimeError(
212
+ "tesseract executable not found on PATH. Install tesseract-ocr "
213
+ "(for example `apt install tesseract-ocr` or `brew install tesseract`)."
214
+ )
215
+ # Pin OpenMP to a single thread so parallel OCR calls cannot thrash CPU cores.
216
+ tesseract_env = {**os.environ, "OMP_THREAD_LIMIT": "1"}
217
+ timeout_bin = shutil.which("timeout")
218
+ tess_cmd = [tesseract_bin, img_path, "stdout", "--psm", str(psm), *(["tsv"] if tsv else [])]
219
+ cmd = [timeout_bin, "-k", "2", str(timeout_s), *tess_cmd] if timeout_bin else tess_cmd
220
+ try:
221
+ proc = subprocess.run(
222
+ cmd,
223
+ capture_output=True,
224
+ text=True,
225
+ timeout=timeout_s + 3 if timeout_bin else timeout_s,
226
+ env=tesseract_env,
227
+ )
228
+ except subprocess.TimeoutExpired as exc:
229
+ raise RuntimeError(
230
+ f"tesseract timed out after {timeout_s}s on {os.path.basename(img_path)} "
231
+ f"(increase --timeout or use --mode cursive for handwritten pages)."
232
+ ) from exc
233
+ if timeout_bin and proc.returncode in (124, 137):
234
+ raise RuntimeError(
235
+ f"tesseract timed out after {timeout_s}s on {os.path.basename(img_path)} "
236
+ f"(increase --timeout or use --mode cursive for handwritten pages)."
237
+ )
238
+ if proc.returncode != 0:
239
+ detail = (proc.stderr or proc.stdout).strip()
240
+ raise RuntimeError(f"tesseract exited {proc.returncode}: {detail[:300]}")
241
+ out = proc.stdout if tsv else proc.stdout.strip()
242
+ return out, {"psm": psm, "omp_thread_limit": 1, "timeout_s": timeout_s}
243
+
244
+
245
+ def parse_tesseract_tsv(tsv: str) -> dict[str, object]:
246
+ """Group Tesseract TSV word rows into lines keyed by (page, block, par, line)."""
247
+ rows = [r.split("\t") for r in tsv.splitlines() if r.strip()]
248
+ if not rows or rows[0][:1] != ["level"]:
249
+ raise RuntimeError("tesseract TSV output is missing its header row.")
250
+ header = rows[0]
251
+ image_width = image_height = 0
252
+ lines: dict[tuple[int, int, int, int], dict[str, object]] = {}
253
+ for raw in rows[1:]:
254
+ if len(raw) < len(header) - 1:
255
+ continue
256
+ rec = dict(zip(header, raw + [""] * (len(header) - len(raw))))
257
+ level = int(rec["level"])
258
+ left, top = int(rec["left"]), int(rec["top"])
259
+ right, bottom = left + int(rec["width"]), top + int(rec["height"])
260
+ if level == 1:
261
+ image_width = max(image_width, right)
262
+ image_height = max(image_height, bottom)
263
+ continue
264
+ text = rec.get("text", "").strip()
265
+ if level != 5 or not text:
266
+ continue
267
+ conf = float(rec["conf"])
268
+ key = (int(rec["page_num"]), int(rec["block_num"]), int(rec["par_num"]), int(rec["line_num"]))
269
+ line = lines.setdefault(key, {"words": []})
270
+ line["words"].append( # type: ignore[union-attr]
271
+ {"text": text, "x0": left, "y0": top, "x1": right, "y1": bottom, "conf": conf}
272
+ )
273
+ out_lines: list[dict[str, object]] = []
274
+ for (page, block, par, line_num), line in lines.items():
275
+ words = line["words"]
276
+ assert isinstance(words, list)
277
+ confs = [w["conf"] for w in words if w["conf"] >= 0]
278
+ out_lines.append(
279
+ {
280
+ "text": " ".join(str(w["text"]) for w in words),
281
+ "x0": min(w["x0"] for w in words),
282
+ "y0": min(w["y0"] for w in words),
283
+ "x1": max(w["x1"] for w in words),
284
+ "y1": max(w["y1"] for w in words),
285
+ "conf": round(sum(confs) / len(confs), 2) if confs else -1.0,
286
+ "page": page,
287
+ "block": block,
288
+ "par": par,
289
+ "line": line_num,
290
+ "words": words,
291
+ }
292
+ )
293
+ return {"image_width": image_width, "image_height": image_height, "lines": out_lines}
294
+
295
+
296
+ def atomic_write_text(dest: str, text: str) -> None:
297
+ parent = os.path.dirname(dest)
298
+ os.makedirs(parent, exist_ok=True)
299
+ tmp = os.path.join(parent, f".{os.path.basename(dest)}.{os.getpid()}.{time.time_ns()}.tmp")
300
+ try:
301
+ with open(tmp, "w", encoding="utf-8") as fh:
302
+ fh.write(text)
303
+ os.replace(tmp, dest)
304
+ except Exception:
305
+ if os.path.exists(tmp):
306
+ os.unlink(tmp)
307
+ raise
308
+
309
+
310
+ def run_layout_data(
311
+ opts: dict[str, object], img_path: str, sha256_hex: str, cache_dir: str
312
+ ) -> tuple[str | dict[str, object], bool]:
313
+ """Return (tsv_text_or_boxes_dict, cache_hit) using separate layout cache files."""
314
+ import re
315
+
316
+ psm = int(opts["psm"])
317
+ base = os.path.join(cache_dir, f"{sha256_hex}_printed_psm{psm}")
318
+ tsv_path, boxes_path = f"{base}.tsv", f"{base}.boxes.json"
319
+ timeout_val = opts["timeout"]
320
+ timeout_s = int(timeout_val) if timeout_val is not None else DEFAULT_PRINTED_TIMEOUT_S
321
+ force = bool(opts["force"])
322
+
323
+ def load_tsv() -> tuple[str, bool]:
324
+ if not force and os.path.isfile(tsv_path):
325
+ with open(tsv_path, "r", encoding="utf-8") as fh:
326
+ return fh.read(), True
327
+ tsv, _ = run_printed_ocr(img_path, psm=psm, timeout_s=timeout_s, tsv=True)
328
+ atomic_write_text(tsv_path, tsv)
329
+ return tsv, False
330
+
331
+ if opts["tsv"]:
332
+ tsv, cached = load_tsv()
333
+ return (tsv if tsv.endswith("\n") else tsv + "\n"), cached
334
+
335
+ boxes: dict[str, object] | None = None
336
+ cached = False
337
+ if not force and os.path.isfile(boxes_path):
338
+ try:
339
+ with open(boxes_path, "r", encoding="utf-8") as fh:
340
+ boxes = json.load(fh)
341
+ cached = True
342
+ except (OSError, json.JSONDecodeError):
343
+ boxes = None
344
+ if boxes is None:
345
+ tsv, cached = load_tsv()
346
+ boxes = {"sha256": sha256_hex, "psm": psm, **parse_tesseract_tsv(tsv)}
347
+ atomic_write_json(boxes_path, boxes)
348
+ out: dict[str, object] = {**boxes, "cached": cached, "cache_path": boxes_path}
349
+ pattern = opts["find"]
350
+ if isinstance(pattern, str):
351
+ rx = re.compile(pattern, re.IGNORECASE)
352
+ lines = boxes.get("lines") or []
353
+ assert isinstance(lines, list)
354
+ out["find"] = pattern
355
+ out["lines"] = [ln for ln in lines if rx.search(str(ln.get("text", "")))]
356
+ return out, cached
357
+
358
+
359
+ def run_ocr_data(
360
+ opts: dict[str, object],
361
+ img_path: str,
362
+ raw_bytes: bytes,
363
+ sha256_hex: str,
364
+ cache_dir: str,
365
+ ) -> tuple[dict[str, object], bool]:
366
+ """Return (ocr_record_with_cache_meta, cache_hit) for one image."""
367
+ from datetime import datetime, timezone
368
+
369
+ t_item = time.perf_counter()
370
+ mode = str(opts["mode"])
371
+ psm = int(opts["psm"])
372
+ effort = str(opts["effort"])
373
+ custom_prompt = opts["prompt"] if isinstance(opts["prompt"], str) else None
374
+ slug = mode_slug(mode, psm, effort, custom_prompt)
375
+ cache_file = os.path.join(cache_dir, f"{sha256_hex}_{slug}.json")
376
+
377
+ if not opts["force"] and os.path.isfile(cache_file):
378
+ try:
379
+ with open(cache_file, "r", encoding="utf-8") as fh:
380
+ record = json.load(fh)
381
+ except (OSError, json.JSONDecodeError):
382
+ record = None
383
+ if isinstance(record, dict) and isinstance(record.get("text"), str):
384
+ lookup_ms = round((time.perf_counter() - t_item) * 1000.0, 2)
385
+ return (
386
+ {
387
+ **record,
388
+ "cached": True,
389
+ "cache_path": cache_file,
390
+ "lookup_ms": lookup_ms,
391
+ },
392
+ True,
393
+ )
394
+
395
+ timeout_val = opts["timeout"]
396
+ timeout_s = (
397
+ int(timeout_val)
398
+ if timeout_val is not None
399
+ else (DEFAULT_PRINTED_TIMEOUT_S if mode == "printed" else DEFAULT_CURSIVE_TIMEOUT_S)
400
+ )
401
+ t_ocr = time.perf_counter()
402
+ if mode == "printed":
403
+ text, meta = run_printed_ocr(img_path, psm=psm, timeout_s=timeout_s)
404
+ engine = "tesseract"
405
+ else:
406
+ text, meta = run_cursive_ocr(
407
+ img_path=img_path,
408
+ raw_len=len(raw_bytes),
409
+ effort=effort,
410
+ timeout_s=timeout_s,
411
+ cache_dir=cache_dir,
412
+ custom_prompt=custom_prompt,
413
+ )
414
+ engine = f"{meta.get('cli', resolve_vision_cli())}:{meta.get('model', '')}"
415
+
416
+ elapsed_ms = int(round((time.perf_counter() - t_ocr) * 1000.0))
417
+ record = {
418
+ "sha256": sha256_hex,
419
+ "mode": slug,
420
+ "engine": engine,
421
+ "created_at": datetime.now(timezone.utc).isoformat(),
422
+ "elapsed_ms": elapsed_ms,
423
+ "text": text,
424
+ "source_hint": os.path.basename(img_path),
425
+ "meta": meta,
426
+ }
427
+ atomic_write_json(cache_file, record)
428
+ return (
429
+ {
430
+ **record,
431
+ "cached": False,
432
+ "cache_path": cache_file,
433
+ "lookup_ms": round((time.perf_counter() - t_item) * 1000.0, 2),
434
+ },
435
+ False,
436
+ )
437
+
438
+
439
+ def prepare_cursive_image(img_path: str, raw_len: int, work_dir: str) -> tuple[str, str | None, int]:
440
+ if raw_len <= CURSIVE_MAX_INPUT_BYTES:
441
+ return img_path, None, raw_len
442
+
443
+ import shutil
444
+ import subprocess
445
+
446
+ prep_script = os.path.join(os.path.dirname(os.path.realpath(__file__)), "prep-scan.py")
447
+ if not os.path.isfile(prep_script):
448
+ raise RuntimeError(f"Companion script not found: {prep_script}")
449
+
450
+ uv_bin = shutil.which("uv")
451
+ prep_cmd = (
452
+ [uv_bin, "run", "--script", prep_script]
453
+ if uv_bin
454
+ else [sys.executable, prep_script]
455
+ )
456
+
457
+ os.makedirs(work_dir, exist_ok=True)
458
+ job_dir = os.path.join(work_dir, f"job_{os.getpid()}_{time.time_ns()}")
459
+ os.makedirs(job_dir, exist_ok=True)
460
+ child_env = {
461
+ **os.environ,
462
+ "KINLOOM_TELEMETRY_PARENT": "1",
463
+ "KINLOOM_TELEMETRY_ACTIVE": "1",
464
+ }
465
+ try:
466
+ proc = subprocess.run(
467
+ [
468
+ *prep_cmd,
469
+ "preview",
470
+ img_path,
471
+ "--out-dir",
472
+ job_dir,
473
+ "--max-width",
474
+ str(CURSIVE_TARGET_MAX_WIDTH),
475
+ "--max-kb",
476
+ str(CURSIVE_TARGET_KB),
477
+ "--json",
478
+ ],
479
+ capture_output=True,
480
+ text=True,
481
+ timeout=60,
482
+ env=child_env,
483
+ )
484
+ if proc.returncode != 0:
485
+ raise RuntimeError(
486
+ f"prep-scan.py failed ({proc.returncode}): {(proc.stderr or proc.stdout).strip()[:300]}"
487
+ )
488
+ info = json.loads(proc.stdout)[0]
489
+ return str(info["path"]), job_dir, int(info["bytes"])
490
+ except Exception:
491
+ shutil.rmtree(job_dir, ignore_errors=True)
492
+ raise
493
+
494
+
495
+ def run_cursive_ocr(
496
+ img_path: str,
497
+ raw_len: int,
498
+ effort: str,
499
+ timeout_s: int,
500
+ cache_dir: str,
501
+ custom_prompt: str | None,
502
+ ) -> tuple[str, dict[str, object]]:
503
+ import shutil
504
+ import subprocess
505
+
506
+ cli_name = resolve_vision_cli()
507
+ cli_bin = shutil.which(cli_name)
508
+ if not cli_bin:
509
+ raise RuntimeError(
510
+ f"Vision CLI '{cli_name}' not found on PATH. Install '{cli_name}' "
511
+ "or set KINLOOM_OCR_CLI to a compatible vision CLI executable."
512
+ )
513
+
514
+ model = os.environ.get("KINLOOM_OCR_MODEL", "").strip() or f"gemini-4-hydrogen-{effort}"
515
+ work_dir = os.path.join(cache_dir, ".work")
516
+ send_path, cleanup_dir, sent_bytes = prepare_cursive_image(img_path, raw_len, work_dir)
517
+ try:
518
+ prompt_template = custom_prompt or DEFAULT_CURSIVE_PROMPT
519
+ prompt = (
520
+ prompt_template.format(image_path=send_path)
521
+ if "{image_path}" in prompt_template
522
+ else f"Call read_file ONCE on {send_path}. {prompt_template}"
523
+ )
524
+ add_dir = os.path.dirname(send_path)
525
+ try:
526
+ proc = subprocess.run(
527
+ [
528
+ cli_bin,
529
+ "--model",
530
+ model,
531
+ "--dangerously-skip-permissions",
532
+ "--disable-slash-commands",
533
+ "--add-dir",
534
+ add_dir,
535
+ "--output-format",
536
+ "json",
537
+ "--print-timeout",
538
+ f"{timeout_s}s",
539
+ f"-p={prompt}",
540
+ ],
541
+ cwd=add_dir,
542
+ capture_output=True,
543
+ text=True,
544
+ timeout=timeout_s + 15,
545
+ )
546
+ except subprocess.TimeoutExpired as exc:
547
+ raise RuntimeError(
548
+ f"{cli_name} timed out after {timeout_s}s on {os.path.basename(img_path)} "
549
+ f"(pass a higher --timeout to override)."
550
+ ) from exc
551
+ if proc.returncode != 0:
552
+ detail = (proc.stderr or proc.stdout).strip()
553
+ raise RuntimeError(f"{cli_name} exited {proc.returncode}: {detail[:400]}")
554
+ try:
555
+ payload = json.loads(proc.stdout)
556
+ except json.JSONDecodeError as exc:
557
+ raise RuntimeError(f"{cli_name} returned non-JSON stdout: {proc.stdout[:300]}") from exc
558
+ if payload.get("status") != "SUCCESS":
559
+ raise RuntimeError(
560
+ f"{cli_name} returned status={payload.get('status')}: {str(payload)[:300]}"
561
+ )
562
+ text = str(payload.get("response") or "").strip()
563
+ if not text:
564
+ raise RuntimeError(f"{cli_name} returned an empty transcription response.")
565
+ usage = payload.get("usage") or {}
566
+ meta: dict[str, object] = {
567
+ "cli": cli_name,
568
+ "model": model,
569
+ "effort": effort,
570
+ "sent_bytes": sent_bytes,
571
+ "duration_seconds": payload.get("duration_seconds"),
572
+ "thinking_tokens": usage.get("thinking_tokens"),
573
+ "output_tokens": usage.get("output_tokens"),
574
+ }
575
+ return text, meta
576
+ finally:
577
+ if cleanup_dir is not None:
578
+ shutil.rmtree(cleanup_dir, ignore_errors=True)
579
+
580
+
581
+ def append_telemetry(
582
+ *,
583
+ mode: str,
584
+ duration_ms: float,
585
+ cache_hit: bool | None,
586
+ exit_code: int,
587
+ bytes_out: int,
588
+ ) -> None:
589
+ sig_file = os.environ.get("KINLOOM_CACHE_HIT_FILE")
590
+ if sig_file and isinstance(cache_hit, bool):
591
+ try:
592
+ with open(sig_file, "w", encoding="utf-8") as sfh:
593
+ sfh.write("1" if cache_hit else "0")
594
+ except Exception:
595
+ pass
596
+ if (
597
+ os.environ.get("KINLOOM_TELEMETRY_PARENT") == "1"
598
+ or os.environ.get("KINLOOM_TELEMETRY_ACTIVE") == "1"
599
+ ):
600
+ return
601
+ try:
602
+ from datetime import datetime, timezone
603
+
604
+ target = default_telemetry_file()
605
+ parent = os.path.dirname(os.path.abspath(target))
606
+ if parent:
607
+ os.makedirs(parent, exist_ok=True)
608
+ entry = {
609
+ "ts": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
610
+ "cmd": "cached-ocr.py",
611
+ "subcmd": f"ocr {mode}" if mode else "ocr",
612
+ "person_id": None,
613
+ "duration_ms": max(0, int(round(duration_ms))),
614
+ "cache_hit": cache_hit,
615
+ "exit_code": int(exit_code),
616
+ "bytes_out": max(0, int(bytes_out)),
617
+ }
618
+ with open(target, "a", encoding="utf-8") as fh:
619
+ fh.write(json.dumps(entry, separators=(",", ":")) + "\n")
620
+ except Exception:
621
+ pass
622
+
623
+
624
+ def main(argv: list[str] | None = None) -> int:
625
+ t_start = time.perf_counter()
626
+ try:
627
+ opts = parse_args(sys.argv[1:] if argv is None else argv)
628
+ except ValueError as exc:
629
+ sys.stderr.write(f"Error: {exc}\n")
630
+ append_telemetry(
631
+ mode="",
632
+ duration_ms=(time.perf_counter() - t_start) * 1000.0,
633
+ cache_hit=None,
634
+ exit_code=2,
635
+ bytes_out=0,
636
+ )
637
+ return 2
638
+
639
+ raw_images = opts["images"]
640
+ assert isinstance(raw_images, list)
641
+ mode = str(opts["mode"])
642
+ resolved_images: list[tuple[str, str]] = []
643
+ for raw_arg in raw_images:
644
+ img_path = os.path.abspath(str(raw_arg))
645
+ if not os.path.isfile(img_path):
646
+ sys.stderr.write(f"Error: image file not found: {img_path}\n")
647
+ append_telemetry(
648
+ mode=mode,
649
+ duration_ms=(time.perf_counter() - t_start) * 1000.0,
650
+ cache_hit=None,
651
+ exit_code=1,
652
+ bytes_out=0,
653
+ )
654
+ return 1
655
+ resolved_images.append((str(raw_arg), img_path))
656
+
657
+ cache_dir = os.path.abspath(str(opts["cache_dir"]))
658
+ multi = len(resolved_images) > 1
659
+
660
+ if opts["boxes"] or opts["tsv"]:
661
+ layout_mode = "tsv" if opts["tsv"] else "boxes"
662
+ layout_results: list[tuple[str, str, str | dict[str, object]]] = []
663
+ hits: list[bool] = []
664
+ try:
665
+ for raw_arg, img_path in resolved_images:
666
+ with open(img_path, "rb") as fh:
667
+ sha256_hex = hashlib.sha256(fh.read()).hexdigest()
668
+ data, cached = run_layout_data(opts, img_path, sha256_hex, cache_dir)
669
+ layout_results.append((raw_arg, img_path, data))
670
+ hits.append(cached)
671
+ except Exception as exc:
672
+ sys.stderr.write(f"Error: {exc}\n")
673
+ append_telemetry(
674
+ mode=layout_mode,
675
+ duration_ms=(time.perf_counter() - t_start) * 1000.0,
676
+ cache_hit=False,
677
+ exit_code=1,
678
+ bytes_out=0,
679
+ )
680
+ return 1
681
+
682
+ if not multi:
683
+ single_data = layout_results[0][2]
684
+ if opts["tsv"]:
685
+ assert isinstance(single_data, str)
686
+ rendered = single_data
687
+ else:
688
+ rendered = json.dumps(single_data, indent=2, ensure_ascii=False) + "\n"
689
+ elif opts["tsv"]:
690
+ sections = [
691
+ f"=== {raw_arg} ===\n{str(data).rstrip()}"
692
+ for raw_arg, _img_path, data in layout_results
693
+ ]
694
+ rendered = "\n\n".join(sections) + "\n"
695
+ else:
696
+ files_out = []
697
+ for raw_arg, img_path, data in layout_results:
698
+ assert isinstance(data, dict)
699
+ files_out.append({"file": raw_arg, "path": img_path, **data})
700
+ rendered = (
701
+ json.dumps(
702
+ {
703
+ "files": files_out,
704
+ "count": len(files_out),
705
+ "cache_hits": sum(1 for h in hits if h),
706
+ },
707
+ indent=2,
708
+ ensure_ascii=False,
709
+ )
710
+ + "\n"
711
+ )
712
+
713
+ sys.stdout.write(rendered)
714
+ append_telemetry(
715
+ mode=layout_mode,
716
+ duration_ms=(time.perf_counter() - t_start) * 1000.0,
717
+ cache_hit=bool(hits) and all(hits),
718
+ exit_code=0,
719
+ bytes_out=len(rendered.encode("utf-8")),
720
+ )
721
+ return 0
722
+
723
+ ocr_results: list[tuple[str, str, dict[str, object]]] = []
724
+ hits = []
725
+ try:
726
+ for raw_arg, img_path in resolved_images:
727
+ with open(img_path, "rb") as fh:
728
+ raw_bytes = fh.read()
729
+ sha256_hex = hashlib.sha256(raw_bytes).hexdigest()
730
+ record, cached = run_ocr_data(opts, img_path, raw_bytes, sha256_hex, cache_dir)
731
+ ocr_results.append((raw_arg, img_path, record))
732
+ hits.append(cached)
733
+ except Exception as exc:
734
+ sys.stderr.write(f"Error: {exc}\n")
735
+ append_telemetry(
736
+ mode=mode,
737
+ duration_ms=(time.perf_counter() - t_start) * 1000.0,
738
+ cache_hit=False,
739
+ exit_code=1,
740
+ bytes_out=0,
741
+ )
742
+ return 1
743
+
744
+ if not multi:
745
+ single_rec = ocr_results[0][2]
746
+ if opts["json"]:
747
+ rendered = json.dumps(single_rec, indent=2, ensure_ascii=False) + "\n"
748
+ else:
749
+ rendered = str(single_rec["text"]) + "\n"
750
+ elif opts["json"]:
751
+ files_out = [
752
+ {"file": raw_arg, "path": img_path, **rec}
753
+ for raw_arg, img_path, rec in ocr_results
754
+ ]
755
+ rendered = (
756
+ json.dumps(
757
+ {
758
+ "files": files_out,
759
+ "count": len(files_out),
760
+ "cache_hits": sum(1 for h in hits if h),
761
+ },
762
+ indent=2,
763
+ ensure_ascii=False,
764
+ )
765
+ + "\n"
766
+ )
767
+ else:
768
+ sections = [
769
+ f"=== {raw_arg} ===\n{rec['text']}"
770
+ for raw_arg, _img_path, rec in ocr_results
771
+ ]
772
+ rendered = "\n\n".join(sections) + "\n"
773
+
774
+ sys.stdout.write(rendered)
775
+ append_telemetry(
776
+ mode=mode,
777
+ duration_ms=(time.perf_counter() - t_start) * 1000.0,
778
+ cache_hit=bool(hits) and all(hits),
779
+ exit_code=0,
780
+ bytes_out=len(rendered.encode("utf-8")),
781
+ )
782
+ return 0
783
+
784
+
785
+ if __name__ == "__main__":
786
+ raise SystemExit(main())