From 0a0756b33e3667a1c588c0d346af6aff83bb38fb Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Tue, 27 Jan 2026 15:28:27 -0800 Subject: [PATCH] Tidy long lines and unnested with blocks --- src/ocrmypdf/_exec/tesseract.py | 4 +- src/ocrmypdf/_progressbar.py | 10 +++- src/ocrmypdf/api.py | 9 ++- src/ocrmypdf/builtin_plugins/optimize.py | 3 +- src/ocrmypdf/builtin_plugins/tesseract_ocr.py | 18 +++--- tests/test_pdfa.py | 5 +- tests/test_pdfinfo.py | 5 +- tests/test_system_font_provider.py | 59 +++++++++++-------- tests/test_validation.py | 10 ++-- tests/test_verapdf.py | 10 ++-- tests/test_watcher.py | 5 +- 11 files changed, 76 insertions(+), 62 deletions(-) diff --git a/src/ocrmypdf/_exec/tesseract.py b/src/ocrmypdf/_exec/tesseract.py index 9dc29b05..d41a0af7 100644 --- a/src/ocrmypdf/_exec/tesseract.py +++ b/src/ocrmypdf/_exec/tesseract.py @@ -287,7 +287,9 @@ def tesseract_log_output(stream: bytes) -> None: lines = text.splitlines() for line in lines: - if line.startswith("Tesseract Open Source") or line.startswith("Warning in pixReadMem"): + if line.startswith( + ("Tesseract Open Source", "Warning in pixReadMem") + ): continue elif 'diacritics' in line: tlog.warning("lots of diacritics - possibly poor OCR") diff --git a/src/ocrmypdf/_progressbar.py b/src/ocrmypdf/_progressbar.py index a8a0e044..c5e33d56 100644 --- a/src/ocrmypdf/_progressbar.py +++ b/src/ocrmypdf/_progressbar.py @@ -48,7 +48,8 @@ class ProgressBar(Protocol): A brief description of the current step (e.g. "Scanning contents", "OCR", "PDF/A conversion"). OCRmyPDF updates this before each major step. unit (str | None): - A short label for the type of work being tracked (e.g. "page", "%", "image"). + A short label for the type of work being tracked + (e.g. "page", "%", "image"). disable (bool): If ``True``, progress updates are suppressed (no output). Defaults to ``False``. @@ -90,7 +91,7 @@ class ProgressBar(Protocol): def update(self, n=1, *, completed=None): if completed is not None: - # If 'completed' is given, you could set self.current = completed + # If 'completed' is given, set self.current # but let's just read it to show usage print(f"Absolute completion reported: {completed}") # Otherwise, we increment by 'n' @@ -98,7 +99,10 @@ class ProgressBar(Protocol): if not self.disable: if self.total: percent = (self.current / self.total) * 100 - print(f"{self.desc}: {self.current}/{self.total} ({percent:.1f}%)") + print( + f"{self.desc}: {self.current}" + f"/{self.total} ({percent:.1f}%)" + ) else: print(f"{self.desc}: {self.current} units done") diff --git a/src/ocrmypdf/api.py b/src/ocrmypdf/api.py index 32fe2939..350c064d 100644 --- a/src/ocrmypdf/api.py +++ b/src/ocrmypdf/api.py @@ -291,7 +291,8 @@ def create_options( Args: input_file: Input file path or file object. output_file: Output file path or file object. - parser: ArgumentParser object (kept for compatibility, may be used for plugin validation). + parser: ArgumentParser object (kept for compatibility, + may be used for plugin validation). **kwargs: Keyword arguments. Returns: @@ -564,7 +565,8 @@ def ocr( # noqa: D417 # New-style API: OcrOptions passed directly options = input_file_or_options - # Check for conflicting parameters (all should be None except plugins/plugin_manager) + # Check for conflicting parameters + # (all should be None except plugins/plugin_manager) _check_no_conflicting_ocr_params(locals(), kwargs) # plugins and plugin_manager can still be passed alongside OcrOptions @@ -641,7 +643,8 @@ def ocr( # noqa: D417 if 'verbose' in kwargs: warn( - "ocrmypdf.ocr(verbose=) is ignored. Use ocrmypdf.configure_logging()." + "ocrmypdf.ocr(verbose=) is ignored. " + "Use ocrmypdf.configure_logging()." ) # Warn about deprecated jbig2 options and remove from kwargs diff --git a/src/ocrmypdf/builtin_plugins/optimize.py b/src/ocrmypdf/builtin_plugins/optimize.py index 690a4e41..f9941b94 100644 --- a/src/ocrmypdf/builtin_plugins/optimize.py +++ b/src/ocrmypdf/builtin_plugins/optimize.py @@ -50,7 +50,8 @@ class OptimizeOptions(BaseModel): Args: parser: The argument parser to add arguments to - namespace: The namespace prefix for argument names (not used for optimize for backward compatibility) + namespace: The namespace prefix for argument names + (not used for optimize for backward compatibility) """ optimizing = parser.add_argument_group( "Optimization options", "Control how the PDF is optimized after OCR" diff --git a/src/ocrmypdf/builtin_plugins/tesseract_ocr.py b/src/ocrmypdf/builtin_plugins/tesseract_ocr.py index b44821a8..0df11606 100644 --- a/src/ocrmypdf/builtin_plugins/tesseract_ocr.py +++ b/src/ocrmypdf/builtin_plugins/tesseract_ocr.py @@ -199,13 +199,17 @@ class TesseractOptions(BaseModel): default=True, dest=f'{namespace}_downsample_large_images', help=( - "Downsample large images before OCR. Tesseract has an upper limit on the " - "size images it will support. If this argument is given, OCRmyPDF will " - "downsample large images to fit Tesseract. This may reduce OCR quality, " - "on large images the most desirable text is usually larger. If this " - "parameter is not supplied, Tesseract will error out and produce no OCR " - "on the page in question. This argument should be used with a high value " - f"of --{namespace}-timeout to ensure Tesseract has enough to time." + "Downsample large images before OCR. Tesseract has " + "an upper limit on the size images it will support." + " If this argument is given, OCRmyPDF will " + "downsample large images to fit Tesseract. This " + "may reduce OCR quality, on large images the most" + " desirable text is usually larger. If this " + "parameter is not supplied, Tesseract will error " + "out and produce no OCR on the page in question. " + "This argument should be used with a high value " + f"of --{namespace}-timeout to ensure Tesseract " + "has enough to time." ), ) diff --git a/tests/test_pdfa.py b/tests/test_pdfa.py index 0e33678c..9edd0654 100644 --- a/tests/test_pdfa.py +++ b/tests/test_pdfa.py @@ -36,6 +36,5 @@ def test_pdfa(resources, outpdf, optimize, pdfa_level): # we don't use it assert b'/ObjStm' not in outpdf.read_bytes() - with pikepdf.open(outpdf) as pdf: - with pdf.open_metadata() as m: - assert m.pdfa_status == f'{pdfa_level}B' + with pikepdf.open(outpdf) as pdf, pdf.open_metadata() as m: + assert m.pdfa_status == f'{pdfa_level}B' diff --git a/tests/test_pdfinfo.py b/tests/test_pdfinfo.py index db897ee5..1bb7a160 100644 --- a/tests/test_pdfinfo.py +++ b/tests/test_pdfinfo.py @@ -197,9 +197,8 @@ def test_stack_abuse(): _interpret_contents(stream) stream = pikepdf.Stream(p, b'q ' * 135) - with pytest.warns(UserWarning): - with pytest.raises(RuntimeError): - _interpret_contents(stream) + with pytest.warns(UserWarning), pytest.raises(RuntimeError): + _interpret_contents(stream) def test_pages_issue700(monkeypatch, resources): diff --git a/tests/test_system_font_provider.py b/tests/test_system_font_provider.py index 39830b47..31f35767 100644 --- a/tests/test_system_font_provider.py +++ b/tests/test_system_font_provider.py @@ -72,41 +72,50 @@ class TestSystemFontProviderDirectories: def test_windows_font_dirs_with_windir(self): """Test Windows font directory from WINDIR env var.""" provider = SystemFontProvider() - with patch.object(sys, 'platform', 'win32'): - with patch.dict('os.environ', {'WINDIR': r'D:\Windows'}): - provider._font_dirs = None # Reset cache - dirs = provider._get_font_dirs() - # Check that Fonts subdir of WINDIR is included - # Use str comparison to avoid Path normalization issues across platforms - dir_strs = [str(d) for d in dirs] - assert any('Fonts' in d for d in dir_strs) + with ( + patch.object(sys, 'platform', 'win32'), + patch.dict('os.environ', {'WINDIR': r'D:\Windows'}), + ): + provider._font_dirs = None # Reset cache + dirs = provider._get_font_dirs() + # Check that Fonts subdir of WINDIR is included + # Use str comparison to avoid Path normalization issues across platforms + dir_strs = [str(d) for d in dirs] + assert any('Fonts' in d for d in dir_strs) def test_windows_font_dirs_default(self): """Test Windows font directory with default path.""" provider = SystemFontProvider() - with patch.object(sys, 'platform', 'win32'): - with patch.dict('os.environ', {}, clear=True): - provider._font_dirs = None # Reset cache - dirs = provider._get_font_dirs() - # Check that Windows\Fonts is included (default fallback) - dir_strs = [str(d) for d in dirs] - assert any('Windows' in d and 'Fonts' in d for d in dir_strs) + with ( + patch.object(sys, 'platform', 'win32'), + patch.dict('os.environ', {}, clear=True), + ): + provider._font_dirs = None # Reset cache + dirs = provider._get_font_dirs() + # Check that Windows\Fonts is included (default fallback) + dir_strs = [str(d) for d in dirs] + assert any('Windows' in d and 'Fonts' in d for d in dir_strs) def test_windows_font_dirs_with_localappdata(self): """Test Windows user fonts directory from LOCALAPPDATA env var.""" provider = SystemFontProvider() - with patch.object(sys, 'platform', 'win32'): - with patch.dict( + with ( + patch.object(sys, 'platform', 'win32'), + patch.dict( 'os.environ', {'WINDIR': r'C:\Windows', 'LOCALAPPDATA': r'C:\Users\Test\AppData\Local'}, - ): - provider._font_dirs = None # Reset cache - dirs = provider._get_font_dirs() - dir_strs = [str(d) for d in dirs] - # Should have both system and user font directories - assert len(dirs) == 2 - assert any('Windows' in d and 'Fonts' in d for d in dir_strs) - assert any('AppData' in d and 'Local' in d and 'Fonts' in d for d in dir_strs) + ), + ): + provider._font_dirs = None # Reset cache + dirs = provider._get_font_dirs() + dir_strs = [str(d) for d in dirs] + # Should have both system and user font directories + assert len(dirs) == 2 + assert any('Windows' in d and 'Fonts' in d for d in dir_strs) + assert any( + 'AppData' in d and 'Local' in d and 'Fonts' in d + for d in dir_strs + ) def test_font_dirs_cached(self): """Test that font directories are cached.""" diff --git a/tests/test_validation.py b/tests/test_validation.py index 535f013f..4bd44f4b 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -50,9 +50,8 @@ def test_old_tesseract_error(): with patch( 'ocrmypdf._exec.tesseract.version', return_value=TesseractVersion('4.00.00alpha'), - ): - with pytest.raises(MissingDependencyError): - vd.check_options(*make_opts_pm(pdf_renderer='sandwich', language='eng')) + ), pytest.raises(MissingDependencyError): + vd.check_options(*make_opts_pm(pdf_renderer='sandwich', language='eng')) def test_tesseract_not_installed(caplog): @@ -105,9 +104,8 @@ def test_pillow_options(): def test_output_tty(): - with patch('sys.stdout.isatty', return_value=True): - with pytest.raises(BadArgsError): - vd.check_requested_output_file(make_opts(output_file='-')) + with patch('sys.stdout.isatty', return_value=True), pytest.raises(BadArgsError): + vd.check_requested_output_file(make_opts(output_file='-')) def test_report_file_size(tmp_path, caplog): diff --git a/tests/test_verapdf.py b/tests/test_verapdf.py index ee1a633f..e7562256 100644 --- a/tests/test_verapdf.py +++ b/tests/test_verapdf.py @@ -76,9 +76,8 @@ class TestAddPdfaMetadata: pdf.save(test_pdf) # Verify it persists after save - with pikepdf.open(test_pdf) as pdf: - with pdf.open_metadata() as meta: - assert meta.pdfa_status == '2B' + with pikepdf.open(test_pdf) as pdf, pdf.open_metadata() as meta: + assert meta.pdfa_status == '2B' class TestAddSrgbOutputIntent: @@ -141,9 +140,8 @@ class TestSpeculativePdfaConversion: output_pdf = tmp_path / f'output_{output_type}.pdf' speculative_pdfa_conversion(input_pdf, output_pdf, output_type) - with pikepdf.open(output_pdf) as pdf: - with pdf.open_metadata() as meta: - assert meta.pdfa_status == expected_status + with pikepdf.open(output_pdf) as pdf, pdf.open_metadata() as meta: + assert meta.pdfa_status == expected_status @pytest.mark.skipif(not verapdf.available(), reason='verapdf not installed') diff --git a/tests/test_watcher.py b/tests/test_watcher.py index 8cfcaf7e..321cf19f 100644 --- a/tests/test_watcher.py +++ b/tests/test_watcher.py @@ -22,10 +22,7 @@ def test_watcher(tmp_path, resources, year_month): processed_dir = tmp_path / 'processed' processed_dir.mkdir() - if year_month: - env_extra = {'OCR_OUTPUT_DIRECTORY_YEAR_MONTH': '1'} - else: - env_extra = {} + env_extra = {'OCR_OUTPUT_DIRECTORY_YEAR_MONTH': '1'} if year_month else {} proc = subprocess.Popen( [ sys.executable,