scanlayer 1.2.1__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.
Files changed (55) hide show
  1. {scanlayer-1.2.1/scanlayer.egg-info → scanlayer-1.3.0}/PKG-INFO +6 -2
  2. {scanlayer-1.2.1 → scanlayer-1.3.0}/README.md +5 -1
  3. {scanlayer-1.2.1 → scanlayer-1.3.0}/pyproject.toml +1 -1
  4. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/__init__.py +1 -1
  5. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/config.py +6 -0
  6. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/main.py +118 -33
  7. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/pdf/builder.py +80 -35
  8. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/preprocessing/enhance.py +45 -4
  9. {scanlayer-1.2.1 → scanlayer-1.3.0/scanlayer.egg-info}/PKG-INFO +6 -2
  10. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer.egg-info/SOURCES.txt +1 -0
  11. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_config.py +6 -0
  12. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_ocr_optimizations.py +46 -0
  13. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_pdf_optimizations.py +78 -0
  14. scanlayer-1.3.0/tests/test_pdf_page_count.py +157 -0
  15. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_pdf_streaming.py +74 -2
  16. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_preprocess_optimizations.py +33 -3
  17. {scanlayer-1.2.1 → scanlayer-1.3.0}/LICENSE.md +0 -0
  18. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/__main__.py +0 -0
  19. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/cli/__init__.py +0 -0
  20. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/cli/dry_run.py +0 -0
  21. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/cli/parser.py +0 -0
  22. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/cli/run.py +0 -0
  23. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/fonts/DejaVuSans.ttf +0 -0
  24. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/layout/__init__.py +0 -0
  25. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/layout/columns.py +0 -0
  26. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/ocr/__init__.py +0 -0
  27. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/ocr/engine.py +0 -0
  28. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/ocr/export.py +0 -0
  29. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/pdf/__init__.py +0 -0
  30. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/pdf/fonts.py +0 -0
  31. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/preprocessing/__init__.py +0 -0
  32. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/utils/__init__.py +0 -0
  33. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/utils/debug_image.py +0 -0
  34. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/utils/errors.py +0 -0
  35. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/utils/logger.py +0 -0
  36. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/utils/resources.py +0 -0
  37. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer/utils/validators.py +0 -0
  38. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer.egg-info/dependency_links.txt +0 -0
  39. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer.egg-info/entry_points.txt +0 -0
  40. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer.egg-info/requires.txt +0 -0
  41. {scanlayer-1.2.1 → scanlayer-1.3.0}/scanlayer.egg-info/top_level.txt +0 -0
  42. {scanlayer-1.2.1 → scanlayer-1.3.0}/setup.cfg +0 -0
  43. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_batch_parallel.py +0 -0
  44. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_batch_planning.py +0 -0
  45. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_benchmark_helpers.py +0 -0
  46. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_cli_logging.py +0 -0
  47. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_columns.py +0 -0
  48. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_dry_run.py +0 -0
  49. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_export.py +0 -0
  50. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_fonts.py +0 -0
  51. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_main_integration.py +0 -0
  52. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_merge_workers.py +0 -0
  53. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_pdf_builder.py +0 -0
  54. {scanlayer-1.2.1 → scanlayer-1.3.0}/tests/test_resources.py +0 -0
  55. {scanlayer-1.2.1 → 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.2.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
- [![PyPI version](https://img.shields.io/badge/pypi-v1.2.1-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
41
+ <div align="center">
42
+
43
+ [![PyPI version](https://img.shields.io/badge/pypi-v1.3.0-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
42
44
  [![codecov](https://img.shields.io/codecov/c/github/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://codecov.io/gh/Hyacinthe-primus/scanlayer)
43
45
  [![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?style=for-the-badge)](#)
44
46
  ![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey?style=for-the-badge)
@@ -46,6 +48,8 @@ command-line tool or as a Python library; both are the same engine underneath.
46
48
  [![GitHub last commit](https://img.shields.io/github/last-commit/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://github.com/Hyacinthe-primus/scanlayer)
47
49
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](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
- [![PyPI version](https://img.shields.io/badge/pypi-v1.2.1-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
11
+ <div align="center">
12
+
13
+ [![PyPI version](https://img.shields.io/badge/pypi-v1.3.0-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
12
14
  [![codecov](https://img.shields.io/codecov/c/github/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://codecov.io/gh/Hyacinthe-primus/scanlayer)
13
15
  [![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?style=for-the-badge)](#)
14
16
  ![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey?style=for-the-badge)
@@ -16,6 +18,8 @@ command-line tool or as a Python library; both are the same engine underneath.
16
18
  [![GitHub last commit](https://img.shields.io/github/last-commit/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://github.com/Hyacinthe-primus/scanlayer)
17
19
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](LICENSE.md)
18
20
 
21
+ </div>
22
+
19
23
  ---
20
24
 
21
25
  ## Documentation
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scanlayer"
7
- version = "1.2.1"
7
+ version = "1.3.0"
8
8
  description = "Image (scan/photo) to searchable PDF, or raw OCR export, via Tesseract."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -29,4 +29,4 @@ __all__ = [
29
29
  "convert_merge",
30
30
  ]
31
31
 
32
- __version__ = "1.2.1"
32
+ __version__ = "1.3.0"
@@ -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 pdfinfo without rasterizing pages."""
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
- page_paths = convert_from_path(
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
- dpi=raster_dpi,
583
- first_page=first_page,
584
- last_page=last_page,
585
- output_folder=job_dir,
586
- fmt="ppm",
587
- paths_only=True,
588
- thread_count=1,
589
- )
590
- except PDFInfoNotInstalledError as exc:
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 DependencyError(
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 InputFileError(
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,8 +7,10 @@ Page sized to background image, background drawn with adaptive compression
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
- import io
11
10
  import os
11
+ import tempfile
12
+ import time
13
+ from contextlib import contextmanager
12
14
  from dataclasses import dataclass
13
15
  from typing import Optional
14
16
 
@@ -92,18 +94,23 @@ def _is_mostly_grayscale(image: Image.Image, threshold: float = None) -> bool:
92
94
  return fraction_colored < threshold
93
95
 
94
96
 
95
- def _is_mostly_binary(image: Image.Image) -> bool:
97
+ def _is_mostly_binary(
98
+ image: Image.Image, grayscale: Optional[Image.Image] = None,
99
+ ) -> bool:
96
100
  """Detect if an image is near-binary (black text on white background).
97
101
 
98
102
  For near-binary content, lossless flate is smaller than JPEG. PIL's
99
103
  histogram runs in C over the 8-bit data and gives exactly the same 8-bin
100
104
  extreme fraction as the previous float32 NumPy histogram, without a
101
105
  full-image float allocation.
106
+
107
+ ``grayscale`` may be supplied by a caller that already converted the
108
+ image, so the full-image conversion is not repeated.
102
109
  """
103
- if image.mode != "L":
104
- image = image.convert("L")
105
- hist = image.histogram()
106
- total = image.width * image.height
110
+ if grayscale is None:
111
+ grayscale = image if image.mode == "L" else image.convert("L")
112
+ hist = grayscale.histogram()
113
+ total = grayscale.width * grayscale.height
107
114
  if total == 0:
108
115
  return False
109
116
  # np.histogram(..., bins=8, range=(0, 256)) used bins 0 and 7.
@@ -116,18 +123,47 @@ def _is_mostly_binary(image: Image.Image) -> bool:
116
123
  return is_binary
117
124
 
118
125
 
119
- def _as_jpeg_reader(image: Image.Image, quality: int) -> ImageReader:
120
- """Encodes the image as JPEG in a memory buffer and returns an
121
- ImageReader for ReportLab."""
122
- buffer = io.BytesIO()
123
- image.convert("RGB").save(
124
- buffer, format="JPEG", quality=quality, optimize=True,
126
+
127
+ def _remove_temp_file(path: str) -> None:
128
+ """Remove a temporary PDF background, tolerating Windows file locks."""
129
+ last_error = None
130
+ for attempt in range(4):
131
+ try:
132
+ os.unlink(path)
133
+ return
134
+ except FileNotFoundError:
135
+ return
136
+ except OSError as exc:
137
+ last_error = exc
138
+ time.sleep(0.05 * (attempt + 1))
139
+ log_warning(
140
+ log,
141
+ f"Could not remove temporary PDF background {path}: {last_error}",
125
142
  )
126
- buffer.seek(0)
127
- return ImageReader(buffer)
128
143
 
129
144
 
130
- def _as_lossless_reader(image: Image.Image) -> ImageReader:
145
+ def _as_jpeg_file(image: Image.Image, quality: int) -> str:
146
+ """Encode the JPEG background to a temp file and return its path.
147
+
148
+ Passing a file path to ReportLab avoids the full raw-image decode/hash
149
+ performed for an in-memory ImageReader, and keeps the encoded bytes out
150
+ of the Python heap. The caller deletes the file after drawImage().
151
+ """
152
+ fd, path = tempfile.mkstemp(prefix="scanlayer_bg_", suffix=".jpg")
153
+ os.close(fd)
154
+ try:
155
+ image.convert("RGB").save(
156
+ path, format="JPEG", quality=quality, optimize=True,
157
+ )
158
+ except Exception:
159
+ _remove_temp_file(path)
160
+ raise
161
+ return path
162
+
163
+
164
+ def _as_lossless_reader(
165
+ image: Image.Image, grayscale: Optional[Image.Image] = None,
166
+ ) -> ImageReader:
131
167
  """Pass a PIL image directly to ReportLab for lossless flate embedding.
132
168
 
133
169
  ReportLab accepts RGB and L PIL images natively and flate-compresses the
@@ -135,7 +171,7 @@ def _as_lossless_reader(image: Image.Image) -> ImageReader:
135
171
  """
136
172
  if _is_mostly_grayscale(image):
137
173
  if image.mode != "L":
138
- image = image.convert("L")
174
+ image = grayscale if grayscale is not None else image.convert("L")
139
175
  log.info("Background compression: lossless grayscale (flate)")
140
176
  else:
141
177
  if image.mode != "RGB":
@@ -144,22 +180,31 @@ def _as_lossless_reader(image: Image.Image) -> ImageReader:
144
180
  return ImageReader(image)
145
181
 
146
182
 
147
- def _select_background_reader(
148
- image: Image.Image, jpeg_quality: int
149
- ) -> ImageReader:
150
- """Chooses the best compression strategy for the PDF background.
151
-
152
- 1. Near-binary -> direct lossless flate (L when grayscale, RGB otherwise).
153
- 2. Otherwise -> JPEG at the configured quality.
183
+ @contextmanager
184
+ def _background_for_pdf(
185
+ image: Image.Image, jpeg_quality: int,
186
+ ):
187
+ """Yield the ReportLab background argument and clean up its temp file.
154
188
 
155
- ASCII85 is intentionally left at ReportLab's process-global default.
156
- Disabling it would add a global side effect for other ReportLab users and
157
- concurrent PDF generation; the safe per-document API does not expose it.
189
+ Lossless pages keep the direct PIL ImageReader path. JPEG pages use a
190
+ file-backed DCT stream so ReportLab does not decode the image into a
191
+ second full-resolution RGB buffer.
158
192
  """
159
- if config.PDF_ADAPTIVE_COMPRESSION and _is_mostly_binary(image):
160
- return _as_lossless_reader(image)
193
+ if config.PDF_ADAPTIVE_COMPRESSION:
194
+ grayscale = image if image.mode == "L" else image.convert("L")
195
+ if _is_mostly_binary(image, grayscale=grayscale):
196
+ yield _as_lossless_reader(image, grayscale=grayscale)
197
+ return
198
+ # Release the grayscale buffer before JPEG encoding so the JPEG path
199
+ # never retains an extra full-resolution image.
200
+ del grayscale
201
+
161
202
  log.info(f"Background compression: JPEG q={jpeg_quality}")
162
- return _as_jpeg_reader(image, jpeg_quality)
203
+ path = _as_jpeg_file(image, jpeg_quality)
204
+ try:
205
+ yield path
206
+ finally:
207
+ _remove_temp_file(path)
163
208
 
164
209
 
165
210
  def _font_size_for_height(height_px: float, px_to_pt: float) -> float:
@@ -233,12 +278,12 @@ def _draw_page(
233
278
 
234
279
  c.setPageSize((page_width_pt, page_height_pt))
235
280
 
236
- bg_reader = _select_background_reader(background, jpeg_quality)
237
- c.drawImage(
238
- bg_reader, 0, 0,
239
- width=page_width_pt, height=page_height_pt,
240
- preserveAspectRatio=False,
241
- )
281
+ with _background_for_pdf(background, jpeg_quality) as bg_reader:
282
+ c.drawImage(
283
+ bg_reader, 0, 0,
284
+ width=page_width_pt, height=page_height_pt,
285
+ preserveAspectRatio=False,
286
+ )
242
287
 
243
288
  skipped = 0
244
289
  for word in words:
@@ -102,13 +102,19 @@ def _fix_gross_orientation(image: Image.Image) -> tuple[Image.Image, int]:
102
102
  use_configured_tesseract()
103
103
  osd_image = image
104
104
  owns_osd_image = False
105
- if max(image.size) > _OSD_THUMBNAIL_MAX_DIM:
106
- osd_image = image.copy()
105
+ if osd_image.mode != "L":
106
+ # OSD converts to grayscale internally. Do it here once so the
107
+ # thumbnail and the Tesseract child process handle one channel.
108
+ osd_image = osd_image.convert("L")
109
+ owns_osd_image = True
110
+ if max(osd_image.size) > _OSD_THUMBNAIL_MAX_DIM:
111
+ if not owns_osd_image:
112
+ osd_image = osd_image.copy()
113
+ owns_osd_image = True
107
114
  osd_image.thumbnail(
108
115
  (_OSD_THUMBNAIL_MAX_DIM, _OSD_THUMBNAIL_MAX_DIM),
109
116
  Image.Resampling.LANCZOS,
110
117
  )
111
- owns_osd_image = True
112
118
 
113
119
  rotate = 0
114
120
  confidence = 0.0
@@ -323,6 +329,41 @@ def _remove_shadows(gray: np.ndarray) -> np.ndarray:
323
329
  return cv2.divide(gray, background, scale=255)
324
330
 
325
331
 
332
+ def _denoise_ocr_image(gray: np.ndarray) -> np.ndarray:
333
+ """Apply non-local-means denoising with validated OpenCV parameters.
334
+
335
+ The search window is the dominant cost of this stage. It stays
336
+ configurable so the conservative default and the faster 7-pixel window
337
+ can be compared without changing the algorithm.
338
+ """
339
+ window = config.DENOISING_SEARCH_WINDOW
340
+ if isinstance(window, bool) or not isinstance(window, int):
341
+ raise ValueError(
342
+ "DENOISING_SEARCH_WINDOW must be an odd integer >= 3, "
343
+ f"got {window!r}."
344
+ )
345
+ if window < 3 or window % 2 == 0:
346
+ raise ValueError(
347
+ "DENOISING_SEARCH_WINDOW must be an odd integer >= 3, "
348
+ f"got {window!r}."
349
+ )
350
+ strength = config.DENOISING_H
351
+ if isinstance(strength, bool) or not isinstance(strength, (int, float)):
352
+ raise ValueError(
353
+ f"DENOISING_H must be a non-negative number, got {strength!r}."
354
+ )
355
+ if strength < 0:
356
+ raise ValueError(
357
+ f"DENOISING_H must be a non-negative number, got {strength!r}."
358
+ )
359
+ return cv2.fastNlMeansDenoising(
360
+ gray,
361
+ h=strength,
362
+ templateWindowSize=7,
363
+ searchWindowSize=window,
364
+ )
365
+
366
+
326
367
  def _sharpen(gray: np.ndarray) -> np.ndarray:
327
368
  """Light unsharp mask after denoising/CLAHE to recover edge definition."""
328
369
  amount = config.UNSHARP_AMOUNT
@@ -382,7 +423,7 @@ def _build_ocr_image(
382
423
 
383
424
  gray = _remove_shadows(gray)
384
425
 
385
- denoised = cv2.fastNlMeansDenoising(gray, h=config.DENOISING_H)
426
+ denoised = _denoise_ocr_image(gray)
386
427
 
387
428
  clahe = cv2.createCLAHE(
388
429
  clipLimit=config.CLAHE_CLIP_LIMIT,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scanlayer
3
- Version: 1.2.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
- [![PyPI version](https://img.shields.io/badge/pypi-v1.2.1-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
41
+ <div align="center">
42
+
43
+ [![PyPI version](https://img.shields.io/badge/pypi-v1.3.0-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
42
44
  [![codecov](https://img.shields.io/codecov/c/github/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://codecov.io/gh/Hyacinthe-primus/scanlayer)
43
45
  [![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?style=for-the-badge)](#)
44
46
  ![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey?style=for-the-badge)
@@ -46,6 +48,8 @@ command-line tool or as a Python library; both are the same engine underneath.
46
48
  [![GitHub last commit](https://img.shields.io/github/last-commit/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://github.com/Hyacinthe-primus/scanlayer)
47
49
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](LICENSE.md)
48
50
 
51
+ </div>
52
+
49
53
  ---
50
54
 
51
55
  ## Documentation
@@ -46,6 +46,7 @@ tests/test_merge_workers.py
46
46
  tests/test_ocr_optimizations.py
47
47
  tests/test_pdf_builder.py
48
48
  tests/test_pdf_optimizations.py
49
+ tests/test_pdf_page_count.py
49
50
  tests/test_pdf_streaming.py
50
51
  tests/test_preprocess_optimizations.py
51
52
  tests/test_resources.py
@@ -21,6 +21,12 @@ def test_configure_osd_timeout():
21
21
  assert config.get_settings()["osd_timeout_seconds"] == 12
22
22
 
23
23
 
24
+ def test_configure_denoising_search_window():
25
+ config.configure(denoising_search_window=7)
26
+ assert config.DENOISING_SEARCH_WINDOW == 7
27
+ assert config.get_settings()["denoising_search_window"] == 7
28
+
29
+
24
30
  def test_configure_unknown_key_raises():
25
31
  with pytest.raises(ValueError, match="unknown option"):
26
32
  config.configure(not_a_real_setting="x")
@@ -64,16 +64,61 @@ def test_osd_runs_on_capped_thumbnail(monkeypatch):
64
64
 
65
65
  def fake_osd(image, **kwargs):
66
66
  seen["size"] = image.size
67
+ seen["mode"] = image.mode
67
68
  return _osd()
68
69
 
69
70
  monkeypatch.setattr(enhance.pytesseract, "image_to_osd", fake_osd)
70
71
  enhance._fix_gross_orientation(Image.new("RGB", (3000, 2000), "white"))
71
72
 
72
73
  assert max(seen["size"]) <= enhance._OSD_THUMBNAIL_MAX_DIM
74
+ assert seen["mode"] == "L"
75
+
76
+
77
+ def test_osd_receives_grayscale_input(monkeypatch):
78
+ seen = {}
79
+
80
+ def fake_osd(image, **kwargs):
81
+ seen["mode"] = image.mode
82
+ return {
83
+ "rotate": 90,
84
+ "orientation_conf": 10.0,
85
+ "script": "Latin",
86
+ }
87
+
88
+ monkeypatch.setattr(enhance.pytesseract, "image_to_osd", fake_osd)
89
+ result, rotation = enhance._fix_gross_orientation(
90
+ Image.new("RGB", (300, 500), "white")
91
+ )
92
+
93
+ assert seen["mode"] == "L"
94
+ assert rotation == 90
95
+ assert result.size == (500, 300)
96
+
97
+
98
+ def test_exif_orientation_is_preserved_with_grayscale_osd(monkeypatch):
99
+ seen = {}
100
+
101
+ def fake_osd(image, **kwargs):
102
+ seen["mode"] = image.mode
103
+ return _osd(rotate=0)
104
+
105
+ monkeypatch.setattr(enhance.pytesseract, "image_to_osd", fake_osd)
106
+ image = Image.new("RGB", (100, 200), "white")
107
+ image.getexif()[0x0112] = 6
108
+
109
+ result = enhance.preprocess(image, dpi=300, orientation=None)
110
+
111
+ assert result.exif_orientation_applied == 6
112
+ assert result.gross_rotation_applied == 0
113
+ assert seen["mode"] == "L"
114
+ result.background.close()
73
115
 
74
116
 
75
117
  def test_osd_timeout_is_graceful(monkeypatch):
118
+ seen = {}
119
+
76
120
  def fake_osd(image, **kwargs):
121
+ seen["mode"] = image.mode
77
122
  raise RuntimeError("Tesseract process timeout")
78
123
 
79
124
  monkeypatch.setattr(enhance.pytesseract, "image_to_osd", fake_osd)
@@ -82,6 +127,7 @@ def test_osd_timeout_is_graceful(monkeypatch):
82
127
 
83
128
  assert result is image
84
129
  assert rotation == 0
130
+ assert seen["mode"] == "L"
85
131
 
86
132
 
87
133
  @pytest.mark.parametrize("rotate", [0, 90, 180, 270])
@@ -130,6 +130,12 @@ def test_binary_detection_matches_old_histogram_rule():
130
130
  assert _is_mostly_binary(image) is expected
131
131
 
132
132
 
133
+ def test_binary_detection_with_reused_grayscale_matches_default():
134
+ for image in (_binary_image(), _grayscale_image(), _color_image()):
135
+ grayscale = image if image.mode == "L" else image.convert("L")
136
+ assert _is_mostly_binary(image, grayscale=grayscale) == _is_mostly_binary(image)
137
+
138
+
133
139
  def test_grayscale_detection_falls_back_for_ambiguous_sample():
134
140
  # 3% colored pixels: sampled fraction is near the 2% threshold, so the
135
141
  # exact full-image calculation must decide (and return False).
@@ -213,3 +219,75 @@ def test_pdf_build_does_not_change_reportlab_ascii85_setting(tmp_path):
213
219
  _binary_image(), _text_words(), str(tmp_path / "global.pdf"), dpi=200,
214
220
  )
215
221
  assert rl_config.useA85 == before
222
+
223
+
224
+ def test_jpeg_background_temp_file_is_removed_after_build(tmp_path, monkeypatch):
225
+ from scanlayer.pdf import builder
226
+
227
+ paths = []
228
+ original = builder._as_jpeg_file
229
+
230
+ def tracked(image, quality):
231
+ path = original(image, quality)
232
+ paths.append(path)
233
+ return path
234
+
235
+ monkeypatch.setattr(builder, "_as_jpeg_file", tracked)
236
+ build_searchable_pdf(
237
+ _color_image(), _text_words(), str(tmp_path / "color.pdf"), dpi=200,
238
+ )
239
+
240
+ assert len(paths) == 1
241
+ assert not os.path.exists(paths[0])
242
+ assert str(tmp_path) not in paths[0]
243
+
244
+
245
+ def test_jpeg_background_temp_file_is_removed_on_draw_failure(monkeypatch):
246
+ from scanlayer.pdf import builder
247
+
248
+ paths = []
249
+ original = builder._as_jpeg_file
250
+
251
+ def tracked(image, quality):
252
+ path = original(image, quality)
253
+ paths.append(path)
254
+ return path
255
+
256
+ monkeypatch.setattr(builder, "_as_jpeg_file", tracked)
257
+
258
+ with pytest.raises(RuntimeError, match="draw failed"):
259
+ with builder._background_for_pdf(_color_image(), 82) as arg:
260
+ paths.append(arg)
261
+ raise RuntimeError("draw failed")
262
+
263
+ assert not os.path.exists(paths[0])
264
+
265
+
266
+ def test_concurrent_jpeg_background_files_are_unique(tmp_path, monkeypatch):
267
+ from scanlayer.pdf import builder
268
+
269
+ paths = []
270
+ original = builder._as_jpeg_file
271
+
272
+ def tracked(image, quality):
273
+ path = original(image, quality)
274
+ paths.append(path)
275
+ return path
276
+
277
+ monkeypatch.setattr(builder, "_as_jpeg_file", tracked)
278
+
279
+ from scanlayer.pdf.fonts import resolve_font
280
+ resolve_font("eng")
281
+
282
+ def build(index):
283
+ out = tmp_path / f"color_{index}.pdf"
284
+ build_searchable_pdf(_color_image(), _text_words(), str(out), dpi=200)
285
+ return out
286
+
287
+ with ThreadPoolExecutor(max_workers=4) as pool:
288
+ outputs = list(pool.map(build, range(4)))
289
+
290
+ assert len(paths) == 4
291
+ assert len(set(paths)) == 4
292
+ assert all(not os.path.exists(path) for path in paths)
293
+ assert all(path.exists() for path in outputs)
@@ -0,0 +1,157 @@
1
+ """Tests for optional pypdf page counting and the pdfinfo fallback."""
2
+
3
+ import shutil
4
+ import sys
5
+ import types
6
+
7
+ import pypdf
8
+ import pytest
9
+ from pypdf import PdfReader, PdfWriter
10
+ from reportlab.pdfgen import canvas
11
+
12
+ from scanlayer.main import BatchOptions, _pdf_page_count, plan_batch
13
+ from scanlayer.utils.validators import DependencyError, InputFileError
14
+
15
+
16
+ def _make_pdf(path, pages=1):
17
+ c = canvas.Canvas(str(path))
18
+ for index in range(pages):
19
+ c.drawString(30, 100, f"Page {index + 1}")
20
+ c.showPage()
21
+ c.save()
22
+ return str(path)
23
+
24
+
25
+ def test_valid_pdf_uses_pypdf_and_skips_pdfinfo(tmp_path, monkeypatch):
26
+ pdf = _make_pdf(tmp_path / "two.pdf", pages=2)
27
+
28
+ def fail_pdfinfo(*args, **kwargs):
29
+ raise AssertionError("pdfinfo should not be called when pypdf succeeds")
30
+
31
+ import pdf2image
32
+ monkeypatch.setattr(pdf2image, "pdfinfo_from_path", fail_pdfinfo)
33
+
34
+ assert _pdf_page_count(pdf) == 2
35
+ plan = plan_batch(
36
+ [pdf], str(tmp_path / "out"), BatchOptions(), tmp_dir=str(tmp_path / "tmp"),
37
+ )
38
+ assert [job.page_number for job in plan.jobs] == [1, 2]
39
+
40
+
41
+ def test_missing_pypdf_falls_back_to_pdfinfo(tmp_path, monkeypatch):
42
+ monkeypatch.setitem(sys.modules, "pypdf", None)
43
+ import pdf2image
44
+ monkeypatch.setattr(
45
+ pdf2image, "pdfinfo_from_path", lambda path: {"Pages": 3},
46
+ )
47
+
48
+ assert _pdf_page_count(str(tmp_path / "three.pdf")) == 3
49
+
50
+
51
+ def test_unexpected_pypdf_parse_failure_falls_back(tmp_path, monkeypatch):
52
+ def fail(path):
53
+ raise ValueError("bad PDF structure")
54
+
55
+ monkeypatch.setattr(pypdf, "PdfReader", fail)
56
+ import pdf2image
57
+ monkeypatch.setattr(
58
+ pdf2image, "pdfinfo_from_path", lambda path: {"Pages": 6},
59
+ )
60
+
61
+ assert _pdf_page_count(str(tmp_path / "six.pdf")) == 6
62
+
63
+
64
+ def test_pypdf_page_count_failure_falls_back(tmp_path, monkeypatch):
65
+ class BrokenReader:
66
+ def __init__(self, path):
67
+ pass
68
+
69
+ @property
70
+ def pages(self):
71
+ raise RuntimeError("cannot enumerate pages")
72
+
73
+ monkeypatch.setattr(pypdf, "PdfReader", BrokenReader)
74
+ import pdf2image
75
+ monkeypatch.setattr(
76
+ pdf2image, "pdfinfo_from_path", lambda path: {"Pages": 7},
77
+ )
78
+
79
+ assert _pdf_page_count(str(tmp_path / "seven.pdf")) == 7
80
+
81
+
82
+ def test_pypdf_decryption_failure_falls_back(tmp_path, monkeypatch):
83
+ def fail(path):
84
+ raise pypdf.errors.FileNotDecryptedError("encrypted")
85
+
86
+ monkeypatch.setattr(pypdf, "PdfReader", fail)
87
+ import pdf2image
88
+ monkeypatch.setattr(
89
+ pdf2image, "pdfinfo_from_path", lambda path: {"Pages": 5},
90
+ )
91
+
92
+ assert _pdf_page_count(str(tmp_path / "five.pdf")) == 5
93
+
94
+
95
+ def test_zero_page_count_is_not_accepted(tmp_path, monkeypatch):
96
+ monkeypatch.setattr(
97
+ pypdf, "PdfReader", lambda path: types.SimpleNamespace(pages=[]),
98
+ )
99
+ import pdf2image
100
+ monkeypatch.setattr(
101
+ pdf2image, "pdfinfo_from_path", lambda path: {"Pages": 0},
102
+ )
103
+
104
+ with pytest.raises(InputFileError, match="0 pages"):
105
+ _pdf_page_count(str(tmp_path / "zero.pdf"))
106
+
107
+
108
+ def test_pdfinfo_failure_preserves_input_error(tmp_path, monkeypatch):
109
+ monkeypatch.setitem(sys.modules, "pypdf", None)
110
+ import pdf2image
111
+
112
+ def fail(path):
113
+ raise RuntimeError("boom")
114
+
115
+ monkeypatch.setattr(pdf2image, "pdfinfo_from_path", fail)
116
+ with pytest.raises(InputFileError, match="could not read as a PDF"):
117
+ _pdf_page_count(str(tmp_path / "bad.pdf"))
118
+
119
+
120
+ def test_pdfinfo_missing_poppler_preserves_dependency_error(tmp_path, monkeypatch):
121
+ monkeypatch.setitem(sys.modules, "pypdf", None)
122
+ import pdf2image
123
+
124
+ def fail(path):
125
+ raise pdf2image.exceptions.PDFInfoNotInstalledError("no poppler")
126
+
127
+ monkeypatch.setattr(pdf2image, "pdfinfo_from_path", fail)
128
+ with pytest.raises(DependencyError, match="poppler"):
129
+ _pdf_page_count(str(tmp_path / "bad.pdf"))
130
+
131
+
132
+ @pytest.mark.skipif(
133
+ shutil.which("pdfinfo") is None,
134
+ reason="poppler pdfinfo is not installed",
135
+ )
136
+ def test_malformed_pdf_falls_back_to_pdfinfo_error(tmp_path):
137
+ path = tmp_path / "bad.pdf"
138
+ path.write_bytes(b"%PDF dummy")
139
+
140
+ with pytest.raises(InputFileError):
141
+ _pdf_page_count(str(path))
142
+
143
+
144
+ @pytest.mark.skipif(
145
+ shutil.which("pdfinfo") is None,
146
+ reason="poppler pdfinfo is not installed",
147
+ )
148
+ def test_encrypted_pdf_falls_back_to_pdfinfo_error(tmp_path):
149
+ plain = _make_pdf(tmp_path / "plain.pdf")
150
+ encrypted = tmp_path / "encrypted.pdf"
151
+ writer = PdfWriter()
152
+ writer.append(PdfReader(plain))
153
+ writer.encrypt("secret")
154
+ writer.write(str(encrypted))
155
+
156
+ with pytest.raises(InputFileError):
157
+ _pdf_page_count(str(encrypted))
@@ -1,6 +1,7 @@
1
1
  """Phase 5D-2 tests for incremental, one-page-at-a-time PDF input."""
2
2
 
3
3
  import os
4
+ import shutil
4
5
  import tempfile
5
6
  import threading
6
7
  import time
@@ -156,13 +157,84 @@ def test_rasterization_failure_cleans_owned_directory(monkeypatch, tmp_path):
156
157
  def fail(*args, **kwargs):
157
158
  raise RuntimeError("raster failed")
158
159
 
159
- import pdf2image
160
- monkeypatch.setattr(pdf2image, "convert_from_path", fail)
160
+ monkeypatch.setattr(main_module, "_run_pdftoppm", fail)
161
161
  with pytest.raises(InputFileError):
162
162
  _rasterize_pdf_page(pdf, 1, 300, str(target))
163
163
  assert list(target.iterdir()) == []
164
164
 
165
165
 
166
+ def test_rasterization_missing_poppler_cleans_directory(monkeypatch, tmp_path):
167
+ pdf = _dummy_pdf(tmp_path / "report.pdf")
168
+ target = tmp_path / "pages"
169
+ target.mkdir()
170
+ monkeypatch.setattr(main_module.shutil, "which", lambda name: None)
171
+
172
+ with pytest.raises(main_module.DependencyError):
173
+ _rasterize_pdf_page(pdf, 1, 300, str(target))
174
+ assert list(target.iterdir()) == []
175
+
176
+
177
+ def test_rasterization_interrupt_cleans_directory(monkeypatch, tmp_path):
178
+ pdf = _dummy_pdf(tmp_path / "report.pdf")
179
+ target = tmp_path / "pages"
180
+ target.mkdir()
181
+
182
+ def interrupt(cmd):
183
+ raise KeyboardInterrupt()
184
+
185
+ monkeypatch.setattr(main_module, "_run_pdftoppm", interrupt)
186
+ with pytest.raises(KeyboardInterrupt):
187
+ _rasterize_pdf_page(pdf, 1, 300, str(target))
188
+ assert list(target.iterdir()) == []
189
+
190
+
191
+ def test_rasterization_incomplete_output_cleans_directory(monkeypatch, tmp_path):
192
+ pdf = _dummy_pdf(tmp_path / "report.pdf")
193
+ target = tmp_path / "pages"
194
+ target.mkdir()
195
+
196
+ def incomplete(cmd):
197
+ with open(f"{cmd[-1]}-1.ppm", "wb") as fh:
198
+ fh.write(b"P6\n1 1\n255\n\x00\x00\x00")
199
+ return type(
200
+ "Completed", (), {"returncode": 0, "stdout": "", "stderr": ""},
201
+ )()
202
+
203
+ monkeypatch.setattr(main_module, "_run_pdftoppm", incomplete)
204
+ with pytest.raises(InputFileError, match="expected page files"):
205
+ main_module._rasterize_pdf_pages(pdf, 1, 2, 300, str(target))
206
+ assert list(target.iterdir()) == []
207
+
208
+
209
+ def test_rasterized_pages_are_sorted_numerically(monkeypatch, tmp_path):
210
+ pdf = _dummy_pdf(tmp_path / "report.pdf")
211
+ tmp_dir = tmp_path / "tmp"
212
+ tmp_dir.mkdir()
213
+ calls = []
214
+
215
+ def fake_run(cmd):
216
+ calls.append(cmd)
217
+ prefix = cmd[-1]
218
+ for page in (10, 2, 5, 3, 4, 6, 7, 8, 9):
219
+ with open(f"{prefix}-{page}.ppm", "wb") as fh:
220
+ fh.write(b"P6\n1 1\n255\n\x00\x00\x00")
221
+ return type(
222
+ "Completed", (), {"returncode": 0, "stdout": "", "stderr": ""},
223
+ )()
224
+
225
+ monkeypatch.setattr(main_module, "_run_pdftoppm", fake_run)
226
+ paths, job_dir = main_module._rasterize_pdf_pages(
227
+ pdf, 2, 10, 300, str(tmp_dir),
228
+ )
229
+
230
+ assert [os.path.basename(p) for p in paths] == [
231
+ f"page-{page}.ppm" for page in range(2, 11)
232
+ ]
233
+ assert calls[0][-1].endswith("page")
234
+ assert os.path.isdir(job_dir)
235
+ shutil.rmtree(job_dir, ignore_errors=True)
236
+
237
+
166
238
  def test_same_stem_pdfs_collide_before_execution(monkeypatch, tmp_path):
167
239
  a = tmp_path / "a"
168
240
  b = tmp_path / "b"
@@ -2,10 +2,37 @@
2
2
 
3
3
  import cv2
4
4
  import numpy as np
5
+ import pytest
5
6
 
7
+ from scanlayer import config
6
8
  from scanlayer.preprocessing import enhance
7
9
 
8
10
 
11
+ def test_denoise_uses_configured_search_window(monkeypatch):
12
+ seen = {}
13
+
14
+ def fake_denoise(gray, **kwargs):
15
+ seen.update(kwargs)
16
+ return gray
17
+
18
+ monkeypatch.setattr(enhance.cv2, "fastNlMeansDenoising", fake_denoise)
19
+ config.configure(denoising_search_window=7)
20
+
21
+ result = enhance._denoise_ocr_image(np.zeros((8, 8), dtype=np.uint8))
22
+
23
+ assert result.shape == (8, 8)
24
+ assert seen["searchWindowSize"] == 7
25
+ assert seen["templateWindowSize"] == 7
26
+ assert seen["h"] == config.DENOISING_H
27
+
28
+
29
+ @pytest.mark.parametrize("value", [4, 2, 0, -1, "7", True])
30
+ def test_denoise_rejects_invalid_search_window(monkeypatch, value):
31
+ monkeypatch.setattr(config, "DENOISING_SEARCH_WINDOW", value)
32
+ with pytest.raises(ValueError, match="odd integer"):
33
+ enhance._denoise_ocr_image(np.zeros((8, 8), dtype=np.uint8))
34
+
35
+
9
36
  def test_build_ocr_image_upscales_after_filters(monkeypatch):
10
37
  """A small image must be filtered at native size, then upscaled."""
11
38
  seen = {}
@@ -17,7 +44,8 @@ def test_build_ocr_image_upscales_after_filters(monkeypatch):
17
44
  monkeypatch.setattr(enhance, "_remove_shadows", fake_shadow)
18
45
  monkeypatch.setattr(enhance, "_sharpen", lambda gray: gray)
19
46
  monkeypatch.setattr(
20
- enhance.cv2, "fastNlMeansDenoising", lambda gray, h: gray,
47
+ enhance.cv2, "fastNlMeansDenoising",
48
+ lambda gray, h, **kwargs: gray,
21
49
  )
22
50
 
23
51
  image = np.full((200, 1200, 3), 240, dtype=np.uint8)
@@ -41,7 +69,8 @@ def test_build_ocr_image_keeps_resize_first_for_small_upscale(monkeypatch):
41
69
  monkeypatch.setattr(enhance, "_remove_shadows", fake_shadow)
42
70
  monkeypatch.setattr(enhance, "_sharpen", lambda gray: gray)
43
71
  monkeypatch.setattr(
44
- enhance.cv2, "fastNlMeansDenoising", lambda gray, h: gray,
72
+ enhance.cv2, "fastNlMeansDenoising",
73
+ lambda gray, h, **kwargs: gray,
45
74
  )
46
75
 
47
76
  image = np.full((200, 2480, 3), 240, dtype=np.uint8)
@@ -64,7 +93,8 @@ def test_build_ocr_image_downscales_before_filters(monkeypatch):
64
93
  monkeypatch.setattr(enhance, "_remove_shadows", fake_shadow)
65
94
  monkeypatch.setattr(enhance, "_sharpen", lambda gray: gray)
66
95
  monkeypatch.setattr(
67
- enhance.cv2, "fastNlMeansDenoising", lambda gray, h: gray,
96
+ enhance.cv2, "fastNlMeansDenoising",
97
+ lambda gray, h, **kwargs: gray,
68
98
  )
69
99
 
70
100
  image = np.full((400, 4000, 3), 240, dtype=np.uint8)
File without changes
File without changes
File without changes