scanlayer 1.2.0__tar.gz → 1.3.0__tar.gz
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.
- {scanlayer-1.2.0/scanlayer.egg-info → scanlayer-1.3.0}/PKG-INFO +6 -2
- {scanlayer-1.2.0 → scanlayer-1.3.0}/README.md +5 -1
- {scanlayer-1.2.0 → scanlayer-1.3.0}/pyproject.toml +1 -1
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/__init__.py +1 -1
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/cli/parser.py +7 -2
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/cli/run.py +18 -5
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/config.py +6 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/main.py +118 -33
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/ocr/engine.py +169 -54
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/pdf/builder.py +80 -35
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/preprocessing/enhance.py +45 -4
- {scanlayer-1.2.0 → scanlayer-1.3.0/scanlayer.egg-info}/PKG-INFO +6 -2
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer.egg-info/SOURCES.txt +2 -0
- scanlayer-1.3.0/tests/test_cli_logging.py +46 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_config.py +6 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_merge_workers.py +2 -2
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_ocr_optimizations.py +136 -20
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_pdf_optimizations.py +78 -0
- scanlayer-1.3.0/tests/test_pdf_page_count.py +157 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_pdf_streaming.py +74 -2
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_preprocess_optimizations.py +33 -3
- {scanlayer-1.2.0 → scanlayer-1.3.0}/LICENSE.md +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/__main__.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/cli/__init__.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/cli/dry_run.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/fonts/DejaVuSans.ttf +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/layout/__init__.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/layout/columns.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/ocr/__init__.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/ocr/export.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/pdf/__init__.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/pdf/fonts.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/preprocessing/__init__.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/utils/__init__.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/utils/debug_image.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/utils/errors.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/utils/logger.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/utils/resources.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer/utils/validators.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer.egg-info/dependency_links.txt +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer.egg-info/entry_points.txt +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer.egg-info/requires.txt +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/scanlayer.egg-info/top_level.txt +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/setup.cfg +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_batch_parallel.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_batch_planning.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_benchmark_helpers.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_columns.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_dry_run.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_export.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_fonts.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_main_integration.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_pdf_builder.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_resources.py +0 -0
- {scanlayer-1.2.0 → scanlayer-1.3.0}/tests/test_validators.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: scanlayer
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.0
|
|
4
4
|
Summary: Image (scan/photo) to searchable PDF, or raw OCR export, via Tesseract.
|
|
5
5
|
Author: Hyacinthe-primus
|
|
6
6
|
Author-email: Hyacinthe-primus <hyacintheatho91@gmail.com>
|
|
@@ -38,7 +38,9 @@ Dynamic: license-file
|
|
|
38
38
|
export the raw OCR result as plain text, JSON, TSV, or hOCR. Use it as a
|
|
39
39
|
command-line tool or as a Python library; both are the same engine underneath.
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
<div align="center">
|
|
42
|
+
|
|
43
|
+
[](https://badge.fury.io/py/scanlayer)
|
|
42
44
|
[](https://codecov.io/gh/Hyacinthe-primus/scanlayer)
|
|
43
45
|
[](#)
|
|
44
46
|

|
|
@@ -46,6 +48,8 @@ command-line tool or as a Python library; both are the same engine underneath.
|
|
|
46
48
|
[](https://github.com/Hyacinthe-primus/scanlayer)
|
|
47
49
|
[](LICENSE.md)
|
|
48
50
|
|
|
51
|
+
</div>
|
|
52
|
+
|
|
49
53
|
---
|
|
50
54
|
|
|
51
55
|
## Documentation
|
|
@@ -8,7 +8,9 @@
|
|
|
8
8
|
export the raw OCR result as plain text, JSON, TSV, or hOCR. Use it as a
|
|
9
9
|
command-line tool or as a Python library; both are the same engine underneath.
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
<div align="center">
|
|
12
|
+
|
|
13
|
+
[](https://badge.fury.io/py/scanlayer)
|
|
12
14
|
[](https://codecov.io/gh/Hyacinthe-primus/scanlayer)
|
|
13
15
|
[](#)
|
|
14
16
|

|
|
@@ -16,6 +18,8 @@ command-line tool or as a Python library; both are the same engine underneath.
|
|
|
16
18
|
[](https://github.com/Hyacinthe-primus/scanlayer)
|
|
17
19
|
[](LICENSE.md)
|
|
18
20
|
|
|
21
|
+
</div>
|
|
22
|
+
|
|
19
23
|
---
|
|
20
24
|
|
|
21
25
|
## Documentation
|
|
@@ -145,11 +145,16 @@ def _build_parser() -> argparse.ArgumentParser:
|
|
|
145
145
|
ocr_group.add_argument(
|
|
146
146
|
"--whitelist", default=None,
|
|
147
147
|
help="Allowed characters for OCR, e.g. "
|
|
148
|
-
"'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'"
|
|
148
|
+
"'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Include a "
|
|
149
|
+
"space to preserve word boundaries; punctuation excluded "
|
|
150
|
+
"this way is left out of the word, not used to drop it.",
|
|
149
151
|
)
|
|
150
152
|
ocr_group.add_argument(
|
|
151
153
|
"--blacklist", default=None,
|
|
152
|
-
help="Forbidden characters for OCR, e.g. '|`~'"
|
|
154
|
+
help="Forbidden characters for OCR, e.g. '|`~'. A "
|
|
155
|
+
"punctuation-only blacklist keeps the affected word; an "
|
|
156
|
+
"alphanumeric blacklist can make Tesseract discard whole "
|
|
157
|
+
"words because their confidence drops to 0.",
|
|
153
158
|
)
|
|
154
159
|
ocr_group.add_argument(
|
|
155
160
|
"--font", default=None,
|
|
@@ -25,7 +25,23 @@ from scanlayer.main import (
|
|
|
25
25
|
convert_merge,
|
|
26
26
|
plan_batch,
|
|
27
27
|
)
|
|
28
|
-
from scanlayer.utils.logger import get_logger, log_error, log_warning
|
|
28
|
+
from scanlayer.utils.logger import get_logger, log_error, log_warning, set_log_level
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _configure_logging(verbose: bool, quiet: bool) -> None:
|
|
32
|
+
"""Apply CLI verbosity to loggers that already exist.
|
|
33
|
+
|
|
34
|
+
Module-level loggers are created at import time, before argv is parsed,
|
|
35
|
+
so setting the LOG_LEVEL environment variable alone does not change them.
|
|
36
|
+
"""
|
|
37
|
+
if verbose:
|
|
38
|
+
level = "DEBUG"
|
|
39
|
+
elif quiet:
|
|
40
|
+
level = "ERROR"
|
|
41
|
+
else:
|
|
42
|
+
return
|
|
43
|
+
os.environ["LOG_LEVEL"] = level
|
|
44
|
+
set_log_level(level)
|
|
29
45
|
|
|
30
46
|
|
|
31
47
|
def main(argv: list[str] = None) -> int:
|
|
@@ -33,10 +49,7 @@ def main(argv: list[str] = None) -> int:
|
|
|
33
49
|
parser = _build_parser()
|
|
34
50
|
args = parser.parse_args(argv)
|
|
35
51
|
|
|
36
|
-
|
|
37
|
-
os.environ["LOG_LEVEL"] = "DEBUG"
|
|
38
|
-
elif args.quiet:
|
|
39
|
-
os.environ["LOG_LEVEL"] = "ERROR"
|
|
52
|
+
_configure_logging(args.verbose, args.quiet)
|
|
40
53
|
|
|
41
54
|
log = get_logger("main")
|
|
42
55
|
|
|
@@ -133,6 +133,10 @@ UNSHARP_SIGMA = 1.2
|
|
|
133
133
|
PREPROCESS_TRY_ADAPTIVE_THRESHOLD = False
|
|
134
134
|
|
|
135
135
|
DENOISING_H = 10
|
|
136
|
+
# Non-local-means search window. OpenCV's default is 21; 11 is the
|
|
137
|
+
# conservative default here, and 7 is available for a larger speed win.
|
|
138
|
+
# Must be an odd integer >= 3.
|
|
139
|
+
DENOISING_SEARCH_WINDOW = 11
|
|
136
140
|
|
|
137
141
|
CLAHE_CLIP_LIMIT = 2.0
|
|
138
142
|
CLAHE_TILE_GRID = (8, 8)
|
|
@@ -180,6 +184,8 @@ _CONFIGURABLE_KEYS = {
|
|
|
180
184
|
"ocr_timeout_seconds": "OCR_TIMEOUT_SECONDS",
|
|
181
185
|
"osd_timeout_seconds": "OSD_TIMEOUT_SECONDS",
|
|
182
186
|
"ocr_max_concurrency": "OCR_MAX_CONCURRENCY",
|
|
187
|
+
"denoising_h": "DENOISING_H",
|
|
188
|
+
"denoising_search_window": "DENOISING_SEARCH_WINDOW",
|
|
183
189
|
"char_whitelist": "TESSERACT_CHAR_WHITELIST",
|
|
184
190
|
"char_blacklist": "TESSERACT_CHAR_BLACKLIST",
|
|
185
191
|
"jpeg_quality": "PDF_JPEG_QUALITY",
|
|
@@ -9,6 +9,8 @@ from __future__ import annotations
|
|
|
9
9
|
import glob
|
|
10
10
|
import os
|
|
11
11
|
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
12
14
|
import tempfile
|
|
13
15
|
import threading
|
|
14
16
|
import time
|
|
@@ -232,7 +234,30 @@ def _pdf_page_logical_path(
|
|
|
232
234
|
|
|
233
235
|
|
|
234
236
|
def _pdf_page_count(path: str) -> int:
|
|
235
|
-
"""Read PDF page count via
|
|
237
|
+
"""Read PDF page count via pypdf when available, else pdfinfo.
|
|
238
|
+
|
|
239
|
+
pypdf avoids a poppler process startup per PDF, but it is optional.
|
|
240
|
+
Any import, parsing, decryption, or page-count failure falls back to the
|
|
241
|
+
existing pdfinfo behavior so its validation and error contract remain
|
|
242
|
+
authoritative.
|
|
243
|
+
"""
|
|
244
|
+
try:
|
|
245
|
+
from pypdf import PdfReader
|
|
246
|
+
except ImportError:
|
|
247
|
+
PdfReader = None
|
|
248
|
+
|
|
249
|
+
if PdfReader is not None:
|
|
250
|
+
try:
|
|
251
|
+
with open(path, "rb") as stream:
|
|
252
|
+
pages = len(PdfReader(stream).pages)
|
|
253
|
+
except Exception:
|
|
254
|
+
# Do not hide cancellation/system-exit: those derive from
|
|
255
|
+
# BaseException, not Exception. Everything else falls back to
|
|
256
|
+
# the authoritative pdfinfo validation below.
|
|
257
|
+
pages = 0
|
|
258
|
+
if isinstance(pages, int) and not isinstance(pages, bool) and pages > 0:
|
|
259
|
+
return pages
|
|
260
|
+
|
|
236
261
|
try:
|
|
237
262
|
from pdf2image import pdfinfo_from_path
|
|
238
263
|
from pdf2image.exceptions import PDFInfoNotInstalledError
|
|
@@ -560,55 +585,115 @@ def _expand_pdf_input(
|
|
|
560
585
|
return out_paths
|
|
561
586
|
|
|
562
587
|
|
|
588
|
+
def _pdftoppm_subprocess_kwargs() -> dict:
|
|
589
|
+
"""Hide the poppler child console window on Windows."""
|
|
590
|
+
if sys.platform != "win32":
|
|
591
|
+
return {}
|
|
592
|
+
startupinfo = subprocess.STARTUPINFO()
|
|
593
|
+
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
|
594
|
+
startupinfo.wShowWindow = subprocess.SW_HIDE
|
|
595
|
+
return {"startupinfo": startupinfo}
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _run_pdftoppm(cmd: list[str]) -> subprocess.CompletedProcess:
|
|
599
|
+
"""Run one poppler rasterization command.
|
|
600
|
+
|
|
601
|
+
Kept as a separate seam so tests can replace the subprocess boundary
|
|
602
|
+
without patching global subprocess state.
|
|
603
|
+
"""
|
|
604
|
+
return subprocess.run(
|
|
605
|
+
cmd,
|
|
606
|
+
capture_output=True,
|
|
607
|
+
text=True,
|
|
608
|
+
encoding="utf-8",
|
|
609
|
+
errors="replace",
|
|
610
|
+
**_pdftoppm_subprocess_kwargs(),
|
|
611
|
+
)
|
|
612
|
+
|
|
613
|
+
|
|
563
614
|
def _rasterize_pdf_pages(
|
|
564
615
|
path: str, first_page: int, last_page: int,
|
|
565
616
|
dpi: Optional[int], tmp_dir: str,
|
|
566
617
|
) -> tuple[list[str], str]:
|
|
567
|
-
"""Rasterize a bounded page range into a unique per-chunk directory.
|
|
568
|
-
try:
|
|
569
|
-
from pdf2image import convert_from_path
|
|
570
|
-
from pdf2image.exceptions import PDFInfoNotInstalledError
|
|
571
|
-
except ImportError as exc:
|
|
572
|
-
raise DependencyError(
|
|
573
|
-
"PDF input requires the 'pdf2image' package: "
|
|
574
|
-
"pip install pdf2image"
|
|
575
|
-
) from exc
|
|
618
|
+
"""Rasterize a bounded page range into a unique per-chunk directory.
|
|
576
619
|
|
|
620
|
+
This invokes ``pdftoppm`` directly instead of going through
|
|
621
|
+
``pdf2image.convert_from_path``. The latter runs ``pdfinfo`` again for
|
|
622
|
+
every chunk and adds Python-level path handling, which dominated small
|
|
623
|
+
and medium PDF batches. Direct poppler output is byte-identical PPM.
|
|
624
|
+
"""
|
|
577
625
|
raster_dpi = dpi or config.DEFAULT_DPI
|
|
578
626
|
job_dir = tempfile.mkdtemp(prefix="scanlayer_pdf_page_", dir=tmp_dir)
|
|
627
|
+
prefix = os.path.join(job_dir, "page")
|
|
628
|
+
|
|
579
629
|
try:
|
|
580
|
-
|
|
630
|
+
executable = shutil.which("pdftoppm")
|
|
631
|
+
if not executable:
|
|
632
|
+
raise DependencyError(
|
|
633
|
+
"PDF input requires poppler-utils (the 'pdftoppm'/'pdfinfo' "
|
|
634
|
+
"binaries) on PATH. 'pip install pdf2image' alone is not "
|
|
635
|
+
"enough, poppler is a separate system package "
|
|
636
|
+
"(apt install poppler-utils / brew install poppler / "
|
|
637
|
+
"download poppler for Windows and add it to PATH)."
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
cmd = [
|
|
641
|
+
executable,
|
|
642
|
+
"-r", str(raster_dpi),
|
|
643
|
+
"-f", str(first_page),
|
|
644
|
+
"-l", str(last_page),
|
|
581
645
|
path,
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
646
|
+
prefix,
|
|
647
|
+
]
|
|
648
|
+
try:
|
|
649
|
+
proc = _run_pdftoppm(cmd)
|
|
650
|
+
except FileNotFoundError as exc:
|
|
651
|
+
raise DependencyError(
|
|
652
|
+
"PDF input requires poppler-utils (the 'pdftoppm'/'pdfinfo' "
|
|
653
|
+
"binaries) on PATH. 'pip install pdf2image' alone is not "
|
|
654
|
+
"enough, poppler is a separate system package "
|
|
655
|
+
"(apt install poppler-utils / brew install poppler / "
|
|
656
|
+
"download poppler for Windows and add it to PATH)."
|
|
657
|
+
) from exc
|
|
658
|
+
|
|
659
|
+
if proc.returncode != 0:
|
|
660
|
+
detail = (proc.stderr or proc.stdout or "").strip()
|
|
661
|
+
raise InputFileError(
|
|
662
|
+
f"'{path}' pages {first_page}-{last_page}: could not "
|
|
663
|
+
f"rasterize (pdftoppm exited {proc.returncode}"
|
|
664
|
+
+ (f": {detail}" if detail else "")
|
|
665
|
+
+ ")."
|
|
666
|
+
)
|
|
667
|
+
|
|
668
|
+
page_paths = glob.glob(prefix + "*.ppm")
|
|
669
|
+
|
|
670
|
+
def page_number(page_path: str) -> int:
|
|
671
|
+
stem = os.path.splitext(os.path.basename(page_path))[0]
|
|
672
|
+
try:
|
|
673
|
+
return int(stem.rsplit("-", 1)[1])
|
|
674
|
+
except (IndexError, ValueError):
|
|
675
|
+
return -1
|
|
676
|
+
|
|
677
|
+
page_paths.sort(key=page_number)
|
|
678
|
+
expected = list(range(first_page, last_page + 1))
|
|
679
|
+
if not page_paths or [page_number(p) for p in page_paths] != expected:
|
|
680
|
+
raise InputFileError(
|
|
681
|
+
f"'{path}' pages {first_page}-{last_page}: pdftoppm did not "
|
|
682
|
+
"produce the expected page files."
|
|
683
|
+
)
|
|
684
|
+
return page_paths, job_dir
|
|
685
|
+
except (DependencyError, InputFileError):
|
|
591
686
|
shutil.rmtree(job_dir, ignore_errors=True)
|
|
592
|
-
raise
|
|
593
|
-
"PDF input requires poppler-utils (the 'pdftoppm'/'pdfinfo' "
|
|
594
|
-
"binaries) on PATH. 'pip install pdf2image' alone is not "
|
|
595
|
-
"enough, poppler is a separate system package "
|
|
596
|
-
"(apt install poppler-utils / brew install poppler / "
|
|
597
|
-
"download poppler for Windows and add it to PATH)."
|
|
598
|
-
) from exc
|
|
687
|
+
raise
|
|
599
688
|
except Exception as exc:
|
|
600
689
|
shutil.rmtree(job_dir, ignore_errors=True)
|
|
601
690
|
raise InputFileError(
|
|
602
691
|
f"'{path}' pages {first_page}-{last_page}: could not rasterize "
|
|
603
692
|
f"({type(exc).__name__}: {exc})"
|
|
604
693
|
) from exc
|
|
605
|
-
|
|
606
|
-
if not page_paths:
|
|
694
|
+
except BaseException:
|
|
607
695
|
shutil.rmtree(job_dir, ignore_errors=True)
|
|
608
|
-
raise
|
|
609
|
-
f"'{path}' pages {first_page}-{last_page}: no rasterized pages."
|
|
610
|
-
)
|
|
611
|
-
return page_paths, job_dir
|
|
696
|
+
raise
|
|
612
697
|
|
|
613
698
|
|
|
614
699
|
def _rasterize_pdf_page(
|
|
@@ -7,7 +7,10 @@ confidence. Supports early-exit and parallel execution via threads.
|
|
|
7
7
|
|
|
8
8
|
from __future__ import annotations
|
|
9
9
|
|
|
10
|
+
import csv
|
|
10
11
|
import os
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
11
14
|
import tempfile
|
|
12
15
|
import threading
|
|
13
16
|
import time
|
|
@@ -96,25 +99,108 @@ def _is_printable(text: str) -> bool:
|
|
|
96
99
|
return True
|
|
97
100
|
|
|
98
101
|
|
|
99
|
-
def
|
|
100
|
-
|
|
102
|
+
def _tesseract_command(
|
|
103
|
+
ocr_path: str,
|
|
104
|
+
output_base: str,
|
|
105
|
+
lang: str,
|
|
101
106
|
psm: int,
|
|
102
107
|
effective_dpi: int,
|
|
103
108
|
char_whitelist: Optional[str],
|
|
104
109
|
char_blacklist: Optional[str],
|
|
105
|
-
) -> str:
|
|
106
|
-
"""
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
110
|
+
) -> list[str]:
|
|
111
|
+
"""Build the Tesseract argv list for one OCR pass.
|
|
112
|
+
|
|
113
|
+
Kept as a list rather than a shell-style config string: whitelist and
|
|
114
|
+
blacklist values can legitimately contain spaces (a space in a whitelist
|
|
115
|
+
preserves word boundaries). pytesseract splits its ``config=`` string with
|
|
116
|
+
``shlex`` and silently drops a trailing space, which merges whole lines
|
|
117
|
+
into zero-confidence tokens.
|
|
118
|
+
"""
|
|
119
|
+
cmd = [
|
|
120
|
+
config.TESSERACT_CMD,
|
|
121
|
+
ocr_path,
|
|
122
|
+
output_base,
|
|
123
|
+
"-l", lang,
|
|
124
|
+
"--psm", str(psm),
|
|
125
|
+
"--oem", str(config.TESSERACT_OEM),
|
|
126
|
+
"-c", f"user_defined_dpi={effective_dpi}",
|
|
127
|
+
]
|
|
128
|
+
if config.TESSDATA_DIR:
|
|
129
|
+
cmd.extend(["--tessdata-dir", config.TESSDATA_DIR])
|
|
113
130
|
if char_whitelist:
|
|
114
|
-
|
|
131
|
+
cmd.extend(["-c", f"tessedit_char_whitelist={char_whitelist}"])
|
|
115
132
|
if char_blacklist:
|
|
116
|
-
|
|
117
|
-
|
|
133
|
+
cmd.extend(["-c", f"tessedit_char_blacklist={char_blacklist}"])
|
|
134
|
+
cmd.extend(["-c", "tessedit_create_tsv=1"])
|
|
135
|
+
return cmd
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _subprocess_kwargs() -> dict:
|
|
139
|
+
"""Match pytesseract's hidden-console behavior on Windows."""
|
|
140
|
+
if sys.platform != "win32":
|
|
141
|
+
return {}
|
|
142
|
+
startupinfo = subprocess.STARTUPINFO()
|
|
143
|
+
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
|
144
|
+
startupinfo.wShowWindow = subprocess.SW_HIDE
|
|
145
|
+
return {"startupinfo": startupinfo}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _run_tesseract_tsv(
|
|
149
|
+
ocr_path: str,
|
|
150
|
+
lang: str,
|
|
151
|
+
psm: int,
|
|
152
|
+
effective_dpi: int,
|
|
153
|
+
char_whitelist: Optional[str],
|
|
154
|
+
char_blacklist: Optional[str],
|
|
155
|
+
) -> list[list[str]]:
|
|
156
|
+
"""Run Tesseract once and return its TSV rows, header excluded."""
|
|
157
|
+
fd, output_base = tempfile.mkstemp(prefix="scanlayer_tsv_")
|
|
158
|
+
os.close(fd)
|
|
159
|
+
os.unlink(output_base)
|
|
160
|
+
tsv_path = output_base + ".tsv"
|
|
161
|
+
try:
|
|
162
|
+
cmd = _tesseract_command(
|
|
163
|
+
ocr_path, output_base, lang, psm, effective_dpi,
|
|
164
|
+
char_whitelist, char_blacklist,
|
|
165
|
+
)
|
|
166
|
+
try:
|
|
167
|
+
proc = subprocess.run(
|
|
168
|
+
cmd,
|
|
169
|
+
capture_output=True,
|
|
170
|
+
text=True,
|
|
171
|
+
encoding="utf-8",
|
|
172
|
+
errors="replace",
|
|
173
|
+
timeout=config.OCR_TIMEOUT_SECONDS,
|
|
174
|
+
**_subprocess_kwargs(),
|
|
175
|
+
)
|
|
176
|
+
except FileNotFoundError as exc:
|
|
177
|
+
raise pytesseract.TesseractNotFoundError() from exc
|
|
178
|
+
except subprocess.TimeoutExpired as exc:
|
|
179
|
+
raise OCRProcessingError(
|
|
180
|
+
f"PSM {psm}: Tesseract timeout (> "
|
|
181
|
+
f"{config.OCR_TIMEOUT_SECONDS}s). Image likely too "
|
|
182
|
+
"large/noisy, or the Tesseract binary is stuck."
|
|
183
|
+
) from exc
|
|
184
|
+
|
|
185
|
+
if proc.returncode != 0:
|
|
186
|
+
message = (proc.stderr or proc.stdout or "").strip()
|
|
187
|
+
raise pytesseract.TesseractError(proc.returncode, message)
|
|
188
|
+
|
|
189
|
+
if not os.path.exists(tsv_path):
|
|
190
|
+
raise OCRProcessingError(
|
|
191
|
+
f"PSM {psm}: Tesseract exited successfully but produced no "
|
|
192
|
+
"TSV output."
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
with open(
|
|
196
|
+
tsv_path, "r", encoding="utf-8", errors="replace", newline="",
|
|
197
|
+
) as fh:
|
|
198
|
+
reader = csv.reader(fh, delimiter="\t", quoting=csv.QUOTE_NONE)
|
|
199
|
+
next(reader, None) # header
|
|
200
|
+
return [row for row in reader if len(row) >= 12]
|
|
201
|
+
finally:
|
|
202
|
+
_remove_temp_file(tsv_path)
|
|
203
|
+
_remove_temp_file(output_base + ".txt")
|
|
118
204
|
|
|
119
205
|
|
|
120
206
|
def tessdata_config() -> str:
|
|
@@ -127,10 +213,9 @@ def tessdata_config() -> str:
|
|
|
127
213
|
def _write_ocr_image(ocr_image: np.ndarray) -> str:
|
|
128
214
|
"""Encode the OCR image once to a temp BMP and return its path.
|
|
129
215
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
deleted by the caller as soon as all passes finish.
|
|
216
|
+
Re-encoding the same page for every PSM candidate is wasteful. BMP is
|
|
217
|
+
lossless and avoids PNG encoding/decoding overhead; the file is deleted
|
|
218
|
+
by the caller as soon as all passes finish.
|
|
134
219
|
"""
|
|
135
220
|
fd, path = tempfile.mkstemp(prefix="scanlayer_ocr_", suffix=".bmp")
|
|
136
221
|
os.close(fd)
|
|
@@ -164,11 +249,34 @@ def _remove_temp_file(path: Optional[str]) -> None:
|
|
|
164
249
|
)
|
|
165
250
|
|
|
166
251
|
|
|
252
|
+
def _keep_zero_confidence_word(
|
|
253
|
+
raw_text: str,
|
|
254
|
+
char_whitelist: Optional[str],
|
|
255
|
+
char_blacklist: Optional[str],
|
|
256
|
+
) -> bool:
|
|
257
|
+
"""Decide whether a confidence-0 word is still trustworthy.
|
|
258
|
+
|
|
259
|
+
Tesseract reports confidence 0 for words it had to constrain because of
|
|
260
|
+
``tessedit_char_whitelist``/``tessedit_char_blacklist``. For a whitelist,
|
|
261
|
+
the text is valid when every character is explicitly allowed. For a
|
|
262
|
+
blacklist made only of punctuation/symbols, Tesseract drops those
|
|
263
|
+
characters but leaves the rest of the word intact; for an alphanumeric
|
|
264
|
+
blacklist it may substitute other characters, so dropping is safer.
|
|
265
|
+
"""
|
|
266
|
+
if char_whitelist:
|
|
267
|
+
return all(ch in char_whitelist for ch in raw_text)
|
|
268
|
+
if char_blacklist:
|
|
269
|
+
return (
|
|
270
|
+
all(not ch.isalnum() for ch in char_blacklist)
|
|
271
|
+
and not any(ch in raw_text for ch in char_blacklist)
|
|
272
|
+
)
|
|
273
|
+
return False
|
|
274
|
+
|
|
275
|
+
|
|
167
276
|
def _run_ocr(
|
|
168
277
|
ocr_image: "str | np.ndarray",
|
|
169
278
|
lang: str,
|
|
170
279
|
psm: int,
|
|
171
|
-
tess_base: str,
|
|
172
280
|
effective_dpi: int,
|
|
173
281
|
char_whitelist: Optional[str],
|
|
174
282
|
char_blacklist: Optional[str],
|
|
@@ -176,34 +284,29 @@ def _run_ocr(
|
|
|
176
284
|
"""Run a single OCR pass with a given PSM. Raises on genuine failure.
|
|
177
285
|
|
|
178
286
|
``ocr_image`` is normally a pre-encoded file path; a NumPy array is still
|
|
179
|
-
accepted for internal compatibility, but then
|
|
287
|
+
accepted for internal compatibility, but then a temporary BMP is written.
|
|
180
288
|
"""
|
|
181
289
|
t0 = time.perf_counter()
|
|
182
290
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
291
|
+
cleanup_path = None
|
|
292
|
+
if isinstance(ocr_image, np.ndarray):
|
|
293
|
+
ocr_path = _write_ocr_image(ocr_image)
|
|
294
|
+
cleanup_path = ocr_path
|
|
295
|
+
else:
|
|
296
|
+
ocr_path = ocr_image
|
|
186
297
|
|
|
187
298
|
try:
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
timeout=config.OCR_TIMEOUT_SECONDS,
|
|
299
|
+
rows = _run_tesseract_tsv(
|
|
300
|
+
ocr_path, lang, psm, effective_dpi,
|
|
301
|
+
char_whitelist, char_blacklist,
|
|
192
302
|
)
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
raise
|
|
197
|
-
except RuntimeError as exc:
|
|
198
|
-
raise OCRProcessingError(
|
|
199
|
-
f"PSM {psm}: Tesseract timeout (> {config.OCR_TIMEOUT_SECONDS}s). "
|
|
200
|
-
"Image likely too large/noisy, or the Tesseract binary is stuck."
|
|
201
|
-
) from exc
|
|
303
|
+
finally:
|
|
304
|
+
if cleanup_path is not None:
|
|
305
|
+
_remove_temp_file(cleanup_path)
|
|
202
306
|
|
|
203
307
|
words: list[Word] = []
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
raw_text = data["text"][i].strip()
|
|
308
|
+
for row in rows:
|
|
309
|
+
raw_text = row[11].strip()
|
|
207
310
|
if not raw_text:
|
|
208
311
|
continue
|
|
209
312
|
|
|
@@ -212,31 +315,44 @@ def _run_ocr(
|
|
|
212
315
|
continue
|
|
213
316
|
|
|
214
317
|
try:
|
|
215
|
-
conf = float(
|
|
318
|
+
conf = float(row[10])
|
|
216
319
|
except (ValueError, TypeError):
|
|
217
320
|
conf = -1.0
|
|
218
321
|
|
|
219
322
|
if conf < config.MIN_WORD_CONFIDENCE:
|
|
220
|
-
|
|
323
|
+
if conf == 0 and _keep_zero_confidence_word(
|
|
324
|
+
raw_text, char_whitelist, char_blacklist,
|
|
325
|
+
):
|
|
326
|
+
log.debug(
|
|
327
|
+
f"PSM {psm}: keeping zero-confidence word constrained "
|
|
328
|
+
f"by a character filter: {raw_text!r}"
|
|
329
|
+
)
|
|
330
|
+
else:
|
|
331
|
+
continue
|
|
221
332
|
|
|
222
|
-
|
|
223
|
-
|
|
333
|
+
try:
|
|
334
|
+
left = float(row[6])
|
|
335
|
+
top = float(row[7])
|
|
336
|
+
width = float(row[8])
|
|
337
|
+
height = float(row[9])
|
|
338
|
+
except (ValueError, TypeError):
|
|
339
|
+
continue
|
|
224
340
|
if width <= 0 or height <= 0:
|
|
225
341
|
continue
|
|
226
342
|
|
|
227
343
|
try:
|
|
228
344
|
line_id = (
|
|
229
|
-
int(
|
|
230
|
-
+ int(
|
|
231
|
-
+ int(
|
|
345
|
+
int(row[2]) * 1_000_000
|
|
346
|
+
+ int(row[3]) * 1_000
|
|
347
|
+
+ int(row[4])
|
|
232
348
|
)
|
|
233
|
-
except (ValueError, TypeError,
|
|
349
|
+
except (ValueError, TypeError, IndexError):
|
|
234
350
|
line_id = -1
|
|
235
351
|
|
|
236
352
|
words.append(Word(
|
|
237
353
|
text=raw_text,
|
|
238
|
-
x=
|
|
239
|
-
y=
|
|
354
|
+
x=left,
|
|
355
|
+
y=top,
|
|
240
356
|
width=width,
|
|
241
357
|
height=height,
|
|
242
358
|
confidence=conf,
|
|
@@ -304,8 +420,8 @@ def extract_words(
|
|
|
304
420
|
"""Run OCR with automatic PSM selection.
|
|
305
421
|
|
|
306
422
|
The OCR image is encoded to one temporary file and reused by every PSM
|
|
307
|
-
pass. This removes the repeated ``Image.save()`` calls
|
|
308
|
-
|
|
423
|
+
pass. This removes the repeated ``Image.save()`` calls a per-pass temp
|
|
424
|
+
file would otherwise need.
|
|
309
425
|
|
|
310
426
|
ocr_slots, if given, is shared by concurrent callers (convert_merge()
|
|
311
427
|
processing several pages at once) and bounds how many Tesseract passes
|
|
@@ -319,7 +435,6 @@ def extract_words(
|
|
|
319
435
|
bl = char_blacklist if char_blacklist is not None else config.TESSERACT_CHAR_BLACKLIST
|
|
320
436
|
|
|
321
437
|
use_configured_tesseract()
|
|
322
|
-
tess_base = tessdata_config()
|
|
323
438
|
|
|
324
439
|
psm_candidates = list(config.TESSERACT_PSM_CANDIDATES)
|
|
325
440
|
if not psm_candidates:
|
|
@@ -344,7 +459,7 @@ def extract_words(
|
|
|
344
459
|
ocr_path = _write_ocr_image(ocr_image)
|
|
345
460
|
if len(psm_candidates) == 1:
|
|
346
461
|
attempt, error = _safe_run_ocr(
|
|
347
|
-
ocr_path, lang, psm_candidates[0],
|
|
462
|
+
ocr_path, lang, psm_candidates[0],
|
|
348
463
|
effective_dpi, wl, bl, psm=psm_candidates[0],
|
|
349
464
|
ocr_slots=slots,
|
|
350
465
|
)
|
|
@@ -363,7 +478,7 @@ def extract_words(
|
|
|
363
478
|
executor = ThreadPoolExecutor(max_workers=max_workers)
|
|
364
479
|
futures = {
|
|
365
480
|
executor.submit(
|
|
366
|
-
_safe_run_ocr, ocr_path, lang, psm,
|
|
481
|
+
_safe_run_ocr, ocr_path, lang, psm,
|
|
367
482
|
effective_dpi, wl, bl, psm=psm, ocr_slots=slots,
|
|
368
483
|
): psm
|
|
369
484
|
for psm in psm_candidates
|
|
@@ -409,7 +524,7 @@ def extract_words(
|
|
|
409
524
|
else:
|
|
410
525
|
for psm in psm_candidates:
|
|
411
526
|
attempt, error = _safe_run_ocr(
|
|
412
|
-
ocr_path, lang, psm,
|
|
527
|
+
ocr_path, lang, psm,
|
|
413
528
|
effective_dpi, wl, bl, psm=psm, ocr_slots=slots,
|
|
414
529
|
)
|
|
415
530
|
if attempt is not None:
|