scanlayer 1.2.0__tar.gz → 1.2.1__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 (54) hide show
  1. {scanlayer-1.2.0/scanlayer.egg-info → scanlayer-1.2.1}/PKG-INFO +2 -2
  2. {scanlayer-1.2.0 → scanlayer-1.2.1}/README.md +1 -1
  3. {scanlayer-1.2.0 → scanlayer-1.2.1}/pyproject.toml +1 -1
  4. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/__init__.py +1 -1
  5. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/cli/parser.py +7 -2
  6. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/cli/run.py +18 -5
  7. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/ocr/engine.py +169 -54
  8. {scanlayer-1.2.0 → scanlayer-1.2.1/scanlayer.egg-info}/PKG-INFO +2 -2
  9. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer.egg-info/SOURCES.txt +1 -0
  10. scanlayer-1.2.1/tests/test_cli_logging.py +46 -0
  11. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_merge_workers.py +2 -2
  12. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_ocr_optimizations.py +90 -20
  13. {scanlayer-1.2.0 → scanlayer-1.2.1}/LICENSE.md +0 -0
  14. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/__main__.py +0 -0
  15. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/cli/__init__.py +0 -0
  16. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/cli/dry_run.py +0 -0
  17. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/config.py +0 -0
  18. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/fonts/DejaVuSans.ttf +0 -0
  19. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/layout/__init__.py +0 -0
  20. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/layout/columns.py +0 -0
  21. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/main.py +0 -0
  22. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/ocr/__init__.py +0 -0
  23. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/ocr/export.py +0 -0
  24. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/pdf/__init__.py +0 -0
  25. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/pdf/builder.py +0 -0
  26. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/pdf/fonts.py +0 -0
  27. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/preprocessing/__init__.py +0 -0
  28. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/preprocessing/enhance.py +0 -0
  29. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/utils/__init__.py +0 -0
  30. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/utils/debug_image.py +0 -0
  31. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/utils/errors.py +0 -0
  32. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/utils/logger.py +0 -0
  33. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/utils/resources.py +0 -0
  34. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer/utils/validators.py +0 -0
  35. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer.egg-info/dependency_links.txt +0 -0
  36. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer.egg-info/entry_points.txt +0 -0
  37. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer.egg-info/requires.txt +0 -0
  38. {scanlayer-1.2.0 → scanlayer-1.2.1}/scanlayer.egg-info/top_level.txt +0 -0
  39. {scanlayer-1.2.0 → scanlayer-1.2.1}/setup.cfg +0 -0
  40. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_batch_parallel.py +0 -0
  41. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_batch_planning.py +0 -0
  42. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_benchmark_helpers.py +0 -0
  43. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_columns.py +0 -0
  44. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_config.py +0 -0
  45. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_dry_run.py +0 -0
  46. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_export.py +0 -0
  47. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_fonts.py +0 -0
  48. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_main_integration.py +0 -0
  49. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_pdf_builder.py +0 -0
  50. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_pdf_optimizations.py +0 -0
  51. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_pdf_streaming.py +0 -0
  52. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_preprocess_optimizations.py +0 -0
  53. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_resources.py +0 -0
  54. {scanlayer-1.2.0 → scanlayer-1.2.1}/tests/test_validators.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scanlayer
3
- Version: 1.2.0
3
+ Version: 1.2.1
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,7 @@ 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.0-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
41
+ [![PyPI version](https://img.shields.io/badge/pypi-v1.2.1-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
42
42
  [![codecov](https://img.shields.io/codecov/c/github/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://codecov.io/gh/Hyacinthe-primus/scanlayer)
43
43
  [![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?style=for-the-badge)](#)
44
44
  ![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey?style=for-the-badge)
@@ -8,7 +8,7 @@
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.0-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
11
+ [![PyPI version](https://img.shields.io/badge/pypi-v1.2.1-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
12
12
  [![codecov](https://img.shields.io/codecov/c/github/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://codecov.io/gh/Hyacinthe-primus/scanlayer)
13
13
  [![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?style=for-the-badge)](#)
14
14
  ![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey?style=for-the-badge)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scanlayer"
7
- version = "1.2.0"
7
+ version = "1.2.1"
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.0"
32
+ __version__ = "1.2.1"
@@ -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
- if args.verbose:
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
 
@@ -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 _build_tess_config(
100
- tess_base: str,
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
- """Builds the Tesseract CLI argument string from the given options."""
107
- parts: list[str] = []
108
- if tess_base:
109
- parts.append(tess_base)
110
- parts.append(f"--psm {psm}")
111
- parts.append(f"--oem {config.TESSERACT_OEM}")
112
- parts.append(f"-c user_defined_dpi={effective_dpi}")
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
- parts.append(f"-c tessedit_char_whitelist={char_whitelist}")
131
+ cmd.extend(["-c", f"tessedit_char_whitelist={char_whitelist}"])
115
132
  if char_blacklist:
116
- parts.append(f"-c tessedit_char_blacklist={char_blacklist}")
117
- return " ".join(parts)
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
- pytesseract writes a fresh temp image for every ``image_to_data()`` call.
131
- With several PSM candidates that re-encodes the same page repeatedly.
132
- BMP is lossless and avoids PNG encoding/decoding overhead; the file is
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 pytesseract re-encodes it.
287
+ accepted for internal compatibility, but then a temporary BMP is written.
180
288
  """
181
289
  t0 = time.perf_counter()
182
290
 
183
- tess_config = _build_tess_config(
184
- tess_base, psm, effective_dpi, char_whitelist, char_blacklist,
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
- data = pytesseract.image_to_data(
189
- ocr_image, lang=lang, config=tess_config,
190
- output_type=pytesseract.Output.DICT,
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
- except pytesseract.TesseractNotFoundError:
194
- raise
195
- except pytesseract.TesseractError:
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
- n = len(data["text"])
205
- for i in range(n):
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(data["conf"][i])
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
- continue
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
- width = float(data["width"][i])
223
- height = float(data["height"][i])
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(data["block_num"][i]) * 1_000_000
230
- + int(data["par_num"][i]) * 1_000
231
- + int(data["line_num"][i])
345
+ int(row[2]) * 1_000_000
346
+ + int(row[3]) * 1_000
347
+ + int(row[4])
232
348
  )
233
- except (ValueError, TypeError, KeyError):
349
+ except (ValueError, TypeError, IndexError):
234
350
  line_id = -1
235
351
 
236
352
  words.append(Word(
237
353
  text=raw_text,
238
- x=float(data["left"][i]),
239
- y=float(data["top"][i]),
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 pytesseract would
308
- otherwise perform for each ``image_to_data()`` invocation.
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], tess_base,
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, tess_base,
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, tess_base,
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:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scanlayer
3
- Version: 1.2.0
3
+ Version: 1.2.1
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,7 @@ 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.0-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
41
+ [![PyPI version](https://img.shields.io/badge/pypi-v1.2.1-blue?style=for-the-badge)](https://badge.fury.io/py/scanlayer)
42
42
  [![codecov](https://img.shields.io/codecov/c/github/Hyacinthe-primus/scanlayer?style=for-the-badge)](https://codecov.io/gh/Hyacinthe-primus/scanlayer)
43
43
  [![Python](https://img.shields.io/badge/python-3.9%2B-3776AB?style=for-the-badge)](#)
44
44
  ![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey?style=for-the-badge)
@@ -35,6 +35,7 @@ scanlayer/utils/validators.py
35
35
  tests/test_batch_parallel.py
36
36
  tests/test_batch_planning.py
37
37
  tests/test_benchmark_helpers.py
38
+ tests/test_cli_logging.py
38
39
  tests/test_columns.py
39
40
  tests/test_config.py
40
41
  tests/test_dry_run.py
@@ -0,0 +1,46 @@
1
+ """CLI verbosity flags must reach loggers created at import time."""
2
+
3
+ import logging
4
+
5
+ from scanlayer.cli import run
6
+ from scanlayer.utils import logger as logger_module
7
+ from scanlayer.utils.logger import get_logger
8
+
9
+
10
+ def _restore_levels(levels):
11
+ for logger, level in levels.items():
12
+ logger.setLevel(level)
13
+
14
+
15
+ def test_cli_verbose_updates_existing_loggers(monkeypatch):
16
+ logger = get_logger("tests.cli_verbosity")
17
+ levels = {item: item.level for item in logger_module._known_loggers}
18
+ monkeypatch.delenv("LOG_LEVEL", raising=False)
19
+ try:
20
+ run._configure_logging(verbose=True, quiet=False)
21
+ assert logger.level == logging.DEBUG
22
+ finally:
23
+ _restore_levels(levels)
24
+
25
+
26
+ def test_cli_quiet_updates_existing_loggers(monkeypatch):
27
+ logger = get_logger("tests.cli_verbosity")
28
+ levels = {item: item.level for item in logger_module._known_loggers}
29
+ monkeypatch.delenv("LOG_LEVEL", raising=False)
30
+ try:
31
+ run._configure_logging(verbose=False, quiet=True)
32
+ assert logger.level == logging.ERROR
33
+ finally:
34
+ _restore_levels(levels)
35
+
36
+
37
+ def test_cli_default_verbosity_leaves_existing_levels_alone(monkeypatch):
38
+ logger = get_logger("tests.cli_verbosity")
39
+ logger.setLevel(logging.INFO)
40
+ levels = {item: item.level for item in logger_module._known_loggers}
41
+ monkeypatch.setenv("LOG_LEVEL", "INFO")
42
+ try:
43
+ run._configure_logging(verbose=False, quiet=False)
44
+ assert logger.level == logging.INFO
45
+ finally:
46
+ _restore_levels(levels)
@@ -279,14 +279,14 @@ def test_slots_bound_concurrent_tesseract_passes_and_are_released(monkeypatch):
279
279
  slots = threading.BoundedSemaphore(2)
280
280
 
281
281
  def one(_):
282
- return engine._safe_run_ocr(None, "eng", 3, "", 300, None, None, psm=3, ocr_slots=slots)
282
+ return engine._safe_run_ocr(None, "eng", 3, 300, None, None, psm=3, ocr_slots=slots)
283
283
 
284
284
  with ThreadPoolExecutor(max_workers=6) as pool:
285
285
  list(pool.map(one, range(6)))
286
286
  assert state["max"] == 2
287
287
 
288
288
  failing = engine._safe_run_ocr(
289
- None, "eng", 3, "", 300, None, None, psm=3, ocr_slots=slots, fail=True,
289
+ None, "eng", 3, 300, None, None, psm=3, ocr_slots=slots, fail=True,
290
290
  )
291
291
  assert failing[0] is None
292
292
  assert sum(1 for _ in range(5) if slots.acquire(blocking=False)) == 2
@@ -19,18 +19,10 @@ def _osd(rotate=0, confidence=10.0):
19
19
  return {"rotate": rotate, "orientation_conf": confidence}
20
20
 
21
21
 
22
- def _fake_ocr_data():
23
- return {
24
- "text": ["word"],
25
- "conf": [90],
26
- "width": [10],
27
- "height": [10],
28
- "block_num": [1],
29
- "par_num": [1],
30
- "line_num": [1],
31
- "left": [0],
32
- "top": [0],
33
- }
22
+ def _fake_tsv_rows():
23
+ return [
24
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "90", "word"],
25
+ ]
34
26
 
35
27
 
36
28
  def test_osd_uses_configured_tesseract_before_call(monkeypatch):
@@ -135,6 +127,84 @@ def test_osd_detects_real_gross_orientation(rotate):
135
127
  assert applied == rotate
136
128
 
137
129
 
130
+ def test_tesseract_command_preserves_filter_spaces(monkeypatch):
131
+ monkeypatch.setattr(config, "TESSDATA_DIR", None)
132
+ whitelist = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "
133
+ blacklist = "|`~"
134
+ cmd = engine._tesseract_command(
135
+ "page.bmp", "out", "eng", 3, 300, whitelist, blacklist,
136
+ )
137
+
138
+ whitelist_arg = "tessedit_char_whitelist=" + whitelist
139
+ blacklist_arg = "tessedit_char_blacklist=" + blacklist
140
+ assert cmd[cmd.index(whitelist_arg) - 1] == "-c"
141
+ assert cmd[cmd.index(blacklist_arg) - 1] == "-c"
142
+ assert whitelist_arg.endswith(" ")
143
+
144
+
145
+ def test_zero_confidence_whitelist_words_are_kept_only_when_allowed(monkeypatch):
146
+ rows = [
147
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "0", "quartz"],
148
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "0", "quartz,"],
149
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "0", "bad1"],
150
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "95", "kept"],
151
+ ]
152
+ monkeypatch.setattr(engine, "_run_tesseract_tsv", lambda *a, **k: rows)
153
+
154
+ attempt = engine._run_ocr(
155
+ "fake.bmp", "eng", 3, 300,
156
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ", None,
157
+ )
158
+
159
+ assert [word.text for word in attempt.words] == ["quartz", "kept"]
160
+
161
+
162
+ def test_zero_confidence_blacklist_keeps_punctuation_only_words(monkeypatch):
163
+ rows = [
164
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "0", "quartz"],
165
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "95", "kept"],
166
+ ]
167
+ monkeypatch.setattr(engine, "_run_tesseract_tsv", lambda *a, **k: rows)
168
+
169
+ attempt = engine._run_ocr("fake.bmp", "eng", 3, 300, None, ".")
170
+
171
+ assert [word.text for word in attempt.words] == ["quartz", "kept"]
172
+
173
+
174
+ def test_zero_confidence_blacklist_drops_alphanumeric_words(monkeypatch):
175
+ rows = [
176
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "0", "gebra"],
177
+ ["1", "1", "1", "1", "1", "1", "0", "0", "10", "10", "95", "kept"],
178
+ ]
179
+ monkeypatch.setattr(engine, "_run_tesseract_tsv", lambda *a, **k: rows)
180
+
181
+ attempt = engine._run_ocr("fake.bmp", "eng", 3, 300, None, "z")
182
+
183
+ assert [word.text for word in attempt.words] == ["kept"]
184
+
185
+
186
+ @requires_tesseract
187
+ def test_whitelist_with_space_preserves_word_boundaries():
188
+ image = Image.new("RGB", (900, 220), "white")
189
+ draw = ImageDraw.Draw(image)
190
+ try:
191
+ from scanlayer.pdf.fonts import _UNICODE_TTF_PATH
192
+ font = ImageFont.truetype(_UNICODE_TTF_PATH, 48)
193
+ except OSError:
194
+ font = ImageFont.load_default()
195
+ draw.text((30, 70), "Hello World", fill="black", font=font)
196
+
197
+ config.configure(
198
+ psm_candidates=[6], psm_parallel=False, min_word_confidence=35,
199
+ )
200
+ result = engine.extract_words(
201
+ np.array(image.convert("L")), 1.0, 300, lang="eng",
202
+ char_whitelist="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ",
203
+ )
204
+
205
+ assert len(result.words) >= 2
206
+
207
+
138
208
  def test_extract_words_encodes_image_once_and_cleans_up(monkeypatch):
139
209
  created = []
140
210
  original_write = engine._write_ocr_image
@@ -147,11 +217,11 @@ def test_extract_words_encodes_image_once_and_cleans_up(monkeypatch):
147
217
  monkeypatch.setattr(engine, "_write_ocr_image", write)
148
218
  seen = []
149
219
 
150
- def fake_image_to_data(image, **kwargs):
220
+ def fake_tsv(image, *args, **kwargs):
151
221
  seen.append((image, os.path.exists(image)))
152
- return _fake_ocr_data()
222
+ return _fake_tsv_rows()
153
223
 
154
- monkeypatch.setattr(engine.pytesseract, "image_to_data", fake_image_to_data)
224
+ monkeypatch.setattr(engine, "_run_tesseract_tsv", fake_tsv)
155
225
  config.configure(
156
226
  psm_candidates=[3, 4, 6, 11], psm_parallel=False,
157
227
  min_word_confidence=0, psm_early_exit_confidence=100.0,
@@ -180,10 +250,10 @@ def test_extract_words_cleans_up_when_all_passes_fail(monkeypatch):
180
250
 
181
251
  monkeypatch.setattr(engine, "_write_ocr_image", write)
182
252
 
183
- def fail(image, **kwargs):
253
+ def fail(image, *args, **kwargs):
184
254
  raise engine.pytesseract.TesseractError(1, "boom")
185
255
 
186
- monkeypatch.setattr(engine.pytesseract, "image_to_data", fail)
256
+ monkeypatch.setattr(engine, "_run_tesseract_tsv", fail)
187
257
  config.configure(psm_candidates=[3, 4], psm_parallel=False)
188
258
 
189
259
  with pytest.raises(OCRProcessingError):
@@ -206,11 +276,11 @@ def test_extract_words_parallel_early_exit_cleans_up(monkeypatch):
206
276
 
207
277
  monkeypatch.setattr(engine, "_write_ocr_image", write)
208
278
 
209
- def slow_ok(image, **kwargs):
279
+ def slow_ok(image, *args, **kwargs):
210
280
  time.sleep(0.05)
211
- return _fake_ocr_data()
281
+ return _fake_tsv_rows()
212
282
 
213
- monkeypatch.setattr(engine.pytesseract, "image_to_data", slow_ok)
283
+ monkeypatch.setattr(engine, "_run_tesseract_tsv", slow_ok)
214
284
  config.configure(
215
285
  psm_candidates=[3, 4], psm_parallel=True,
216
286
  psm_max_workers=1, psm_early_exit_confidence=0.0,
File without changes
File without changes
File without changes
File without changes
File without changes