Tidy long lines and unnested with blocks

This commit is contained in:
James R. Barlow
2026-01-27 15:28:27 -08:00
parent c5d3ef4b17
commit 0a0756b33e
11 changed files with 76 additions and 62 deletions
+3 -1
View File
@@ -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")
+7 -3
View File
@@ -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")
+6 -3
View File
@@ -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
+2 -1
View File
@@ -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"
+11 -7
View File
@@ -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."
),
)
+2 -3
View File
@@ -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'
+2 -3
View File
@@ -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):
+34 -25
View File
@@ -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."""
+4 -6
View File
@@ -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):
+4 -6
View File
@@ -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')
+1 -4
View File
@@ -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,