flake8 delinting

This commit is contained in:
James R. Barlow
2021-09-21 16:37:03 -07:00
parent 9559f76fae
commit c725bf79da
16 changed files with 47 additions and 34 deletions
-1
View File
@@ -20,7 +20,6 @@ from typing import List, Optional
from PIL import Image
from ocrmypdf.api import StrPath
from ocrmypdf.exceptions import (
MissingDependencyError,
SubprocessOutputError,
+2 -2
View File
@@ -96,12 +96,12 @@ def run(
try:
with Image.open(output_pnm) as imout:
imout.save(output_file, dpi=(dpi, dpi))
except (FileNotFoundError, OSError):
except OSError as e:
raise SubprocessOutputError(
"unpaper: failed to produce the expected output file. "
+ " Called with: "
+ str(args_unpaper)
) from None
) from e
def validate_custom_args(args: str) -> List[str]:
+2 -2
View File
@@ -399,7 +399,7 @@ def run_pipeline(options, *, plugin_manager, api=False):
return ExitCode.invalid_output_pdf
report_output_file_size(options, start_input_file, options.output_file)
except (KeyboardInterrupt if not api else NeverRaise) as e:
except (KeyboardInterrupt if not api else NeverRaise):
if options.verbose >= 1:
log.exception("KeyboardInterrupt")
else:
@@ -413,7 +413,7 @@ def run_pipeline(options, *, plugin_manager, api=False):
else:
log.error(type(e).__name__)
return e.exit_code
except (Exception if not api else NeverRaise) as e: # pylint: disable=broad-except
except (Exception if not api else NeverRaise): # pylint: disable=broad-except
log.exception("An exception occurred while executing the pipeline")
return ExitCode.other_error
finally:
+2 -7
View File
@@ -26,12 +26,7 @@ from ocrmypdf.exceptions import (
MissingDependencyError,
OutputFileAccessError,
)
from ocrmypdf.helpers import (
is_file_writable,
is_iterable_notstr,
monotonic,
safe_symlink,
)
from ocrmypdf.helpers import is_file_writable, monotonic, safe_symlink
from ocrmypdf.hocrtransform import HOCR_OK_LANGS
from ocrmypdf.subprocess import check_external_program
@@ -68,7 +63,7 @@ def check_options_languages(options, ocr_engine_languages):
missing_languages = options.languages - ocr_engine_languages
if missing_languages:
msg = (
f"OCR engine does not have language data for the following "
"OCR engine does not have language data for the following "
"requested languages: \n"
)
msg += '\n'.join(lang for lang in missing_languages)
+15 -4
View File
@@ -15,10 +15,7 @@ from pathlib import Path
from typing import AnyStr, BinaryIO, Iterable, Optional, Union
from warnings import warn
from ocrmypdf._logging import ( # pylint: disable=unused-import
PageNumberFilter,
TqdmConsole,
)
from ocrmypdf._logging import PageNumberFilter, TqdmConsole
from ocrmypdf._plugin_manager import get_plugin_manager
from ocrmypdf._sync import run_pipeline
from ocrmypdf._validation import check_options
@@ -338,3 +335,17 @@ def ocr( # pylint: disable=unused-argument
options = create_options(**create_options_kwargs)
check_options(options, plugin_manager)
return run_pipeline(options=options, plugin_manager=plugin_manager, api=True)
__all__ = [
'PageNumberFilter',
'TqdmConsole',
'Verbosity',
'check_options',
'configure_logging',
'create_options',
'get_parser',
'get_plugin_manager',
'ocr',
'run_pipeline',
]
+1 -1
View File
@@ -21,7 +21,7 @@ import sys
import threading
from contextlib import suppress
from multiprocessing.pool import Pool, ThreadPool
from typing import Callable, Iterable, Optional, Tuple, Type, Union
from typing import Callable, Iterable, Type, Union
from tqdm import tqdm
@@ -11,7 +11,6 @@ import os
from ocrmypdf import hookimpl
from ocrmypdf._exec import tesseract
from ocrmypdf.cli import numeric
from ocrmypdf.exceptions import MissingDependencyError
from ocrmypdf.helpers import clamp
from ocrmypdf.pluginspec import OcrEngine
from ocrmypdf.subprocess import check_external_program
+1 -1
View File
@@ -226,7 +226,7 @@ def check_pdf(input_file: Path) -> bool:
except (
# Workaround for a problematic pikepdf version
# pragma: no cover
getattr(pikepdf, 'ForeignObjectError')
pikepdf.ForeignObjectError
if pikepdf.__version__ == '2.1.0'
else NeverRaise
):
+4 -1
View File
@@ -533,12 +533,15 @@ def transcode_pngs(
_transcode_png(pike, filename, xref)
DEFAULT_EXECUTOR = SerialExecutor()
def optimize(
input_file: Path,
output_file: Path,
context,
save_settings,
executor: Executor = SerialExecutor(),
executor: Executor = DEFAULT_EXECUTOR,
) -> None:
options = context.options
if options.optimize == 0:
+6 -3
View File
@@ -9,7 +9,7 @@
import atexit
import logging
import re
from collections import defaultdict, namedtuple
from collections import defaultdict
from contextlib import ExitStack
from decimal import Decimal
from enum import Enum
@@ -449,7 +449,7 @@ def _image_xobjects(container) -> Iterator[Tuple[Object, str]]:
xobjs = resources['/XObject'].as_dict()
for xobj in xobjs:
candidate: Object = xobjs[xobj]
if not '/Subtype' in candidate:
if '/Subtype' not in candidate:
continue
if candidate['/Subtype'] == '/Image':
pdfimage = candidate
@@ -877,6 +877,9 @@ class PageInfo:
)
DEFAULT_EXECUTOR = SerialExecutor()
class PdfInfo:
"""Get summary information about a PDF"""
@@ -888,7 +891,7 @@ class PdfInfo:
progbar: bool = False,
max_workers: int = None,
check_pages=None,
executor: Executor = SerialExecutor(),
executor: Executor = DEFAULT_EXECUTOR,
):
self._infile = infile
if check_pages is None:
-1
View File
@@ -15,7 +15,6 @@ from collections.abc import Mapping
from contextlib import suppress
from distutils.version import LooseVersion, Version
from functools import lru_cache
from pathlib import Path
from subprocess import PIPE, STDOUT, CalledProcessError, CompletedProcess, Popen
from subprocess import run as subprocess_run
from typing import Callable, Optional, Type, Union
+5 -7
View File
@@ -9,9 +9,9 @@ import os
import shutil
import sys
from distutils.version import LooseVersion
from itertools import chain, filterfalse
from itertools import chain
from pathlib import Path
from typing import Any, Callable, Iterator, Optional, Tuple, TypeVar, cast
from typing import Any, Callable, Iterable, Iterator, Set, Tuple, TypeVar
try:
import winreg
@@ -137,14 +137,12 @@ def fix_windows_args(program, args, env):
return args
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
def unique_everseen(iterable: Iterable[T], key: Callable[[T], T]) -> Iterator[T]:
"List unique elements, preserving order."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen: Set[T] = set()
seen_add = seen.add
if key is None:
key = lambda x: x
for element in iterable:
k = key(element)
if k not in seen: