Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
91 lines (74 loc) · 2.77 KB
/
Copy pathcli.py
File metadata and controls
91 lines (74 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python3
"""
cli.py
======
Command-line interface for the OCR engine.
Examples:
python cli.py scan.png
python cli.py document.pdf --lang eng --psm 6 -o out.txt
python cli.py photo.jpg --no-deskew --threshold otsu --min-conf 60
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from ocr_engine import OCREngine, PreprocessConfig
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
description="Extract text from images and PDFs using Tesseract OCR.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
p.add_argument("input", help="Path to an image or PDF file.")
p.add_argument("-o", "--output", help="Write extracted text to this file.")
p.add_argument("--lang", default="eng", help="Tesseract language code(s).")
p.add_argument("--psm", type=int, default=6, help="Page segmentation mode.")
p.add_argument("--oem", type=int, default=3, help="OCR engine mode.")
p.add_argument(
"--threshold", default="adaptive",
choices=["adaptive", "otsu", "none"],
help="Binarization method.",
)
p.add_argument("--no-deskew", action="store_true", help="Disable deskewing.")
p.add_argument("--no-denoise", action="store_true", help="Disable denoising.")
p.add_argument(
"--min-conf", type=float, default=0.0,
help="Warn if a page's mean confidence falls below this (0-100).",
)
return p
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
if not Path(args.input).exists():
print(f"error: file not found: {args.input}", file=sys.stderr)
return 1
config = PreprocessConfig(
threshold=args.threshold,
deskew=not args.no_deskew,
denoise=not args.no_denoise,
)
engine = OCREngine(
lang=args.lang, psm=args.psm, oem=args.oem, config=config
)
try:
results = engine.read(args.input)
except Exception as exc: # noqa: BLE001 — surface any failure to the user
print(f"error: {exc}", file=sys.stderr)
return 1
chunks: list[str] = []
for r in results:
header = f"----- Page {r.page} (confidence {r.mean_confidence}%) -----"
chunks.append(header + "\n" + r.text)
if r.mean_confidence < args.min_conf:
print(
f"warning: page {r.page} confidence "
f"{r.mean_confidence}% < {args.min_conf}%",
file=sys.stderr,
)
combined = "\n\n".join(chunks)
if args.output:
Path(args.output).write_text(combined, encoding="utf-8")
print(f"Wrote {len(results)} page(s) to {args.output}")
else:
print(combined)
return 0
if __name__ == "__main__":
raise SystemExit(main())