@kinloom/cli 0.2.0 → 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 (80) hide show
  1. package/dist/assets/cached-ocr.py +346 -116
  2. package/dist/assets/ocr.md +25 -1
  3. package/dist/assets/prep-scan.md +42 -4
  4. package/dist/assets/prep-scan.py +432 -10
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +12 -3
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +299 -28
  7. package/dist/bundled-skills/archive-org/SKILL.md +40 -7
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +825 -128
  9. package/dist/bundled-skills/california-archives/SKILL.md +10 -0
  10. package/dist/bundled-skills/california-archives/scripts/ca-archives +281 -40
  11. package/dist/bundled-skills/chronicling-america/SKILL.md +26 -6
  12. package/dist/bundled-skills/chronicling-america/scripts/chronam +379 -76
  13. package/dist/bundled-skills/findagrave/SKILL.md +18 -5
  14. package/dist/bundled-skills/findagrave/scripts/findagrave +485 -40
  15. package/dist/bundled-skills/hathitrust/SKILL.md +9 -2
  16. package/dist/bundled-skills/hathitrust/scripts/hathi +197 -12
  17. package/dist/bundled-skills/kentucky-archives/SKILL.md +1 -0
  18. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +361 -73
  19. package/dist/bundled-skills/library-of-michigan/SKILL.md +9 -2
  20. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +190 -21
  21. package/dist/bundled-skills/missouri-archives/SKILL.md +9 -0
  22. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +284 -61
  23. package/dist/bundled-skills/nara-catalog-search/SKILL.md +12 -0
  24. package/dist/bundled-skills/nara-catalog-search/scripts/nara +586 -133
  25. package/dist/bundled-skills/new-jersey-archives/SKILL.md +18 -1
  26. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +329 -45
  27. package/dist/bundled-skills/openarchieven/SKILL.md +9 -2
  28. package/dist/bundled-skills/openarchieven/scripts/openarchieven +206 -14
  29. package/dist/bundled-skills/texas-archives/SKILL.md +9 -0
  30. package/dist/bundled-skills/texas-archives/scripts/texas-archives +245 -20
  31. package/dist/bundled-skills/uk-archives/SKILL.md +11 -2
  32. package/dist/bundled-skills/uk-archives/scripts/uk-archives +276 -36
  33. package/dist/bundled-skills/usgs-gnis/SKILL.md +12 -2
  34. package/dist/bundled-skills/usgs-gnis/scripts/gnis +210 -46
  35. package/dist/bundled-skills/virginia-archives/SKILL.md +42 -2
  36. package/dist/bundled-skills/virginia-archives/scripts/va-archives +616 -43
  37. package/dist/bundled-skills/wikitree/SKILL.md +7 -1
  38. package/dist/bundled-skills/wikitree/scripts/wikitree +260 -24
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +107 -2
  41. package/dist/cli.js.map +1 -1
  42. package/dist/client.d.ts.map +1 -1
  43. package/dist/client.js +30 -5
  44. package/dist/client.js.map +1 -1
  45. package/dist/commands/ops/audit.d.ts.map +1 -1
  46. package/dist/commands/ops/audit.js +5 -0
  47. package/dist/commands/ops/audit.js.map +1 -1
  48. package/dist/commands/ops/dates.d.ts +87 -0
  49. package/dist/commands/ops/dates.d.ts.map +1 -0
  50. package/dist/commands/ops/dates.js +228 -0
  51. package/dist/commands/ops/dates.js.map +1 -0
  52. package/dist/commands/ops/help.d.ts +3 -1
  53. package/dist/commands/ops/help.d.ts.map +1 -1
  54. package/dist/commands/ops/help.js +33 -0
  55. package/dist/commands/ops/help.js.map +1 -1
  56. package/dist/commands/ops/index.d.ts +3 -1
  57. package/dist/commands/ops/index.d.ts.map +1 -1
  58. package/dist/commands/ops/index.js +2 -0
  59. package/dist/commands/ops/index.js.map +1 -1
  60. package/dist/commands/ops/integrate.d.ts +5 -0
  61. package/dist/commands/ops/integrate.d.ts.map +1 -1
  62. package/dist/commands/ops/integrate.js +217 -26
  63. package/dist/commands/ops/integrate.js.map +1 -1
  64. package/dist/commands/ops/sync.d.ts +17 -0
  65. package/dist/commands/ops/sync.d.ts.map +1 -1
  66. package/dist/commands/ops/sync.js +173 -0
  67. package/dist/commands/ops/sync.js.map +1 -1
  68. package/dist/commands/ops/verify.d.ts +76 -0
  69. package/dist/commands/ops/verify.d.ts.map +1 -0
  70. package/dist/commands/ops/verify.js +325 -0
  71. package/dist/commands/ops/verify.js.map +1 -0
  72. package/dist/commands/records/index.d.ts +1 -1
  73. package/dist/commands/records/index.d.ts.map +1 -1
  74. package/dist/commands/records/index.js +1 -1
  75. package/dist/commands/records/index.js.map +1 -1
  76. package/dist/commands/records/runner.d.ts +2 -0
  77. package/dist/commands/records/runner.d.ts.map +1 -1
  78. package/dist/commands/records/runner.js +33 -2
  79. package/dist/commands/records/runner.js.map +1 -1
  80. package/package.json +2 -2
@@ -59,16 +59,19 @@ def print_usage() -> None:
59
59
  cache_default = default_cache_dir()
60
60
  cli_default = resolve_vision_cli()
61
61
  sys.stdout.write(
62
- "Usage: kinloom ocr <image> [options]\n\n"
62
+ "Usage: kinloom ocr <image> [image ...] [options]\n\n"
63
63
  "Options:\n"
64
64
  " --mode <printed|cursive> OCR mode (default: printed)\n"
65
65
  " --psm <int> Tesseract PSM for --mode printed (default: 6)\n"
66
66
  f" --effort <low|medium|high|xhigh> Reasoning effort for --mode cursive (default: {DEFAULT_CURSIVE_EFFORT})\n"
67
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"
68
+ f" --timeout <seconds> Per-image subprocess timeout (default: {DEFAULT_PRINTED_TIMEOUT_S} printed, {DEFAULT_CURSIVE_TIMEOUT_S} cursive)\n"
69
69
  " --prompt <text> Custom prompt for --mode cursive (supports {image_path})\n"
70
70
  " --force Bypass cache and recompute OCR\n"
71
- " --json Emit structured JSON output\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"
72
75
  " -h, --help Show this help message\n\n"
73
76
  "Environment:\n"
74
77
  f" KINLOOM_OCR_CACHE_DIR Override cache directory (default: {cache_default})\n"
@@ -78,8 +81,9 @@ def print_usage() -> None:
78
81
 
79
82
 
80
83
  def parse_args(argv: list[str]) -> dict[str, object]:
84
+ images: list[str] = []
81
85
  opts: dict[str, object] = {
82
- "image": None,
86
+ "images": images,
83
87
  "mode": "printed",
84
88
  "psm": 6,
85
89
  "effort": DEFAULT_CURSIVE_EFFORT,
@@ -88,6 +92,9 @@ def parse_args(argv: list[str]) -> dict[str, object]:
88
92
  "prompt": None,
89
93
  "force": False,
90
94
  "json": False,
95
+ "boxes": False,
96
+ "tsv": False,
97
+ "find": None,
91
98
  }
92
99
  i = 0
93
100
  n = len(argv)
@@ -100,10 +107,13 @@ def parse_args(argv: list[str]) -> dict[str, object]:
100
107
  opts["force"] = True
101
108
  i += 1
102
109
  continue
103
- if arg == "--json":
104
- opts["json"] = True
110
+ if arg in ("--json", "--boxes", "--tsv"):
111
+ opts[arg[2:]] = True
105
112
  i += 1
106
113
  continue
114
+ if arg == "--":
115
+ images.extend(argv[i + 1 :])
116
+ break
107
117
  if arg.startswith("--"):
108
118
  if "=" in arg:
109
119
  key, val = arg.split("=", 1)
@@ -138,18 +148,28 @@ def parse_args(argv: list[str]) -> dict[str, object]:
138
148
  opts["timeout"] = parsed_timeout
139
149
  elif key == "--prompt":
140
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
141
160
  else:
142
161
  raise ValueError(f"Unknown option: {key}")
143
162
  i += 1
144
163
  continue
145
- if opts["image"] is None:
146
- opts["image"] = arg
147
- i += 1
148
- continue
149
- raise ValueError(f"Unexpected positional argument: {arg}")
164
+ images.append(arg)
165
+ i += 1
150
166
 
151
- if not opts["image"]:
167
+ if not images:
152
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.")
153
173
  return opts
154
174
 
155
175
 
@@ -180,7 +200,9 @@ def atomic_write_json(dest: str, payload: dict[str, object]) -> None:
180
200
  raise
181
201
 
182
202
 
183
- def run_printed_ocr(img_path: str, psm: int, timeout_s: int) -> tuple[str, dict[str, object]]:
203
+ def run_printed_ocr(
204
+ img_path: str, psm: int, timeout_s: int, tsv: bool = False
205
+ ) -> tuple[str, dict[str, object]]:
184
206
  import shutil
185
207
  import subprocess
186
208
 
@@ -193,21 +215,8 @@ def run_printed_ocr(img_path: str, psm: int, timeout_s: int) -> tuple[str, dict[
193
215
  # Pin OpenMP to a single thread so parallel OCR calls cannot thrash CPU cores.
194
216
  tesseract_env = {**os.environ, "OMP_THREAD_LIMIT": "1"}
195
217
  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
- )
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
211
220
  try:
212
221
  proc = subprocess.run(
213
222
  cmd,
@@ -229,7 +238,202 @@ def run_printed_ocr(img_path: str, psm: int, timeout_s: int) -> tuple[str, dict[
229
238
  if proc.returncode != 0:
230
239
  detail = (proc.stderr or proc.stdout).strip()
231
240
  raise RuntimeError(f"tesseract exited {proc.returncode}: {detail[:300]}")
232
- return proc.stdout.strip(), {"psm": psm, "omp_thread_limit": 1, "timeout_s": timeout_s}
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
+ )
233
437
 
234
438
 
235
439
  def prepare_cursive_image(img_path: str, raw_len: int, work_dir: str) -> tuple[str, str | None, int]:
@@ -432,81 +636,100 @@ def main(argv: list[str] | None = None) -> int:
432
636
  )
433
637
  return 2
434
638
 
435
- img_path = os.path.abspath(str(opts["image"]))
639
+ raw_images = opts["images"]
640
+ assert isinstance(raw_images, list)
436
641
  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
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))
447
656
 
448
657
  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()
658
+ multi = len(resolved_images) > 1
452
659
 
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):
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] = []
460
664
  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)
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")
478
673
  append_telemetry(
479
- mode=mode,
674
+ mode=layout_mode,
480
675
  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")),
676
+ cache_hit=False,
677
+ exit_code=1,
678
+ bytes_out=0,
484
679
  )
485
- return 0
486
-
487
- from datetime import datetime, timezone
680
+ return 1
488
681
 
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"
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"
500
695
  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,
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"
508
711
  )
509
- engine = f"{meta.get('cli', resolve_vision_cli())}:{meta.get('model', '')}"
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)
510
733
  except Exception as exc:
511
734
  sys.stderr.write(f"Error: {exc}\n")
512
735
  append_telemetry(
@@ -518,34 +741,41 @@ def main(argv: list[str] | None = None) -> int:
518
741
  )
519
742
  return 1
520
743
 
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"
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
+ )
542
767
  else:
543
- rendered = text + "\n"
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
+
544
774
  sys.stdout.write(rendered)
545
775
  append_telemetry(
546
776
  mode=mode,
547
777
  duration_ms=(time.perf_counter() - t_start) * 1000.0,
548
- cache_hit=False,
778
+ cache_hit=bool(hits) and all(hits),
549
779
  exit_code=0,
550
780
  bytes_out=len(rendered.encode("utf-8")),
551
781
  )
@@ -17,6 +17,30 @@ kinloom ocr ./scans/city-directory-p44.jpg --psm 4 --json
17
17
  kinloom ocr ./scans/obituary-1912.jpg --force
18
18
  ```
19
19
 
20
+ ## Multi-file batches
21
+
22
+ Pass two or more image paths in one call instead of writing a shell `for` loop. Every image runs with the same `OMP_THREAD_LIMIT=1` pin, SHA-256 disk cache, and per-image `--timeout`. Single-image output is unchanged; multi-image runs print `=== <path> ===` sections in text or `--tsv` mode, and `{ files: [...], count, cache_hits }` in `--json`, `--boxes`, or `--find` mode:
23
+
24
+ ```bash
25
+ kinloom ocr ./scans/page-01.jpg ./scans/page-02.jpg ./scans/page-03.jpg
26
+ kinloom ocr ./scans/page-*.jpg --find 'probate|docket'
27
+ kinloom ocr ./scans/crop-1.jpg ./scans/crop-2.jpg --json
28
+ ```
29
+
30
+ ## Line boxes and raw TSV (`--boxes`, `--find`, `--tsv`)
31
+
32
+ Use these flags instead of ad-hoc `tesseract ... tsv` calls when you need pixel coordinates (printed mode only). They run the same hardened `tesseract` call (`OMP_THREAD_LIMIT=1`, `--timeout`, default `30` seconds).
33
+
34
+ - `--boxes` prints JSON: `{ sha256, psm, image_width, image_height, lines: [{ text, x0, y0, x1, y1, conf, page, block, par, line, words: [...] }], cached, cache_path }`. Words are grouped into lines by Tesseract `(block_num, par_num, line_num)`. `conf` is the mean word confidence.
35
+ - `--find <regex>` implies `--boxes` and keeps only lines whose text matches the regex (case-insensitive). Pass each `x0 y0 x1 y1` box to `kinloom prep-scan crop` or `kinloom prep-scan stitch`.
36
+ - `--tsv` prints the raw Tesseract TSV. You cannot combine it with `--boxes` or `--find`.
37
+
38
+ ```bash
39
+ kinloom ocr ./scans/county-history-p212.jpg --find 'probate|docket'
40
+ kinloom ocr ./scans/county-history-p212.jpg --boxes --psm 4
41
+ kinloom ocr ./scans/county-history-p212.jpg --tsv > p212.tsv
42
+ ```
43
+
20
44
  ## Handwritten cursive (`--mode cursive`)
21
45
 
22
46
  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 `[?]`:
@@ -29,7 +53,7 @@ kinloom ocr ./scans/letter-1864.jpg --mode cursive --prompt "Transcribe this let
29
53
 
30
54
  ## Cache layout
31
55
 
32
- Cached JSON records are written atomically to `<cache-dir>/<sha256>_<mode-slug>.json`, where `<cache-dir>` defaults to:
56
+ Cached JSON records are written atomically to `<cache-dir>/<sha256>_<mode-slug>.json`. Layout output uses separate files, so it never collides with plain-text OCR: `<sha256>_printed_psm<N>.tsv` (raw TSV) and `<sha256>_printed_psm<N>.boxes.json` (parsed boxes). `--find` filters the cached boxes, so a new regex on the same scan does not run `tesseract` again. `<cache-dir>` defaults to:
33
57
 
34
58
  1. `--cache-dir <dir>`
35
59
  2. `KINLOOM_OCR_CACHE_DIR`