Configure pylint in pyproject and delint

This commit is contained in:
James R. Barlow
2022-06-12 00:30:44 -07:00
parent d640c2ded3
commit b17fb61389
33 changed files with 323 additions and 157 deletions
+11 -21
View File
@@ -14,13 +14,12 @@ import sys
from io import BytesIO
from os import fspath
from pathlib import Path
from shutil import which
from subprocess import PIPE, CalledProcessError
from typing import Optional
from PIL import Image, UnidentifiedImageError
from ocrmypdf.exceptions import MissingDependencyError, SubprocessOutputError
from ocrmypdf.exceptions import SubprocessOutputError
from ocrmypdf.helpers import Resolution
from ocrmypdf.subprocess import get_version, run, run_polling_stderr
@@ -33,29 +32,18 @@ except AttributeError:
log = logging.getLogger(__name__)
missing_gs_error = """
---------------------------------------------------------------------
This error normally occurs when ocrmypdf find can't Ghostscript.
Please ensure Ghostscript is installed and its location is added to
the system PATH environment variable.
For details see:
https://ocrmypdf.readthedocs.io/en/latest/installation.html
---------------------------------------------------------------------
"""
# Most reliable what to get the bitness of Python interpreter, according to Python docs
_is_64bit = sys.maxsize > 2**32
_IS_64BIT = sys.maxsize > 2**32
_gswin = None
_GSWIN = None
if os.name == 'nt':
if _is_64bit:
_gswin = 'gswin64c'
if _IS_64BIT:
_GSWIN = 'gswin64c'
else:
_gswin = 'gswin32c'
_GSWIN = 'gswin32c'
GS = _gswin if _gswin else 'gs'
del _gswin
GS = _GSWIN if _GSWIN else 'gs'
del _GSWIN
def version():
@@ -126,7 +114,7 @@ def rasterize_pdf(
p = run(args_gs, stdout=PIPE, stderr=PIPE, check=True)
except CalledProcessError as e:
log.error(e.stderr.decode(errors='replace'))
raise SubprocessOutputError('Ghostscript rasterizing failed')
raise SubprocessOutputError('Ghostscript rasterizing failed') from e
else:
stderr = p.stderr.decode(errors='replace')
if _gs_error_reported(stderr):
@@ -156,6 +144,8 @@ def rasterize_pdf(
class GhostscriptFollower:
"""Parses the output of Ghostscript and uses it to update the progress bar."""
re_process = re.compile(r"Processing pages \d+ through (\d+).")
re_page = re.compile(r"Page (\d+)")
+8 -5
View File
@@ -13,7 +13,7 @@ from math import pi
from os import fspath
from pathlib import Path
from subprocess import PIPE, STDOUT, CalledProcessError, TimeoutExpired
from typing import Dict, Iterator, List, Optional
from typing import Dict, List, Optional
from packaging.version import Version
from PIL import Image
@@ -55,6 +55,8 @@ TESSERACT_THRESHOLDING_METHODS: Dict[str, int] = {
class TesseractLoggerAdapter(logging.LoggerAdapter):
"Prepend [tesseract] to messages emitted from tesseract"
def process(self, msg, kwargs):
kwargs['extra'] = self.extra
return f'[tesseract] {msg}', kwargs
@@ -105,6 +107,7 @@ TESSERACT_VERSION_PATTERN = r"""
class TesseractVersion(Version):
"Modify standard packaging.Version regex to support Tesseract idiosyncracies."
_regex = re.compile(
r"^\s*" + TESSERACT_VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE
)
@@ -169,14 +172,14 @@ def tess_base_args(langs: List[str], engine_mode: Optional[int]) -> List[str]:
def _parse_tesseract_output(binary_output: bytes) -> Dict[str, str]:
def g():
def gen():
for line in binary_output.decode().splitlines():
line = line.strip()
parts = line.split(':', maxsplit=2)
if len(parts) == 2:
yield parts[0].strip(), parts[1].strip()
return {k: v for k, v in g()}
return dict(gen())
def get_orientation(
@@ -205,10 +208,10 @@ def get_orientation(
osd = _parse_tesseract_output(p.stdout)
angle = int(osd.get('Orientation in degrees', 0))
oc = OrientationConfidence(
orient_conf = OrientationConfidence(
angle=angle, confidence=float(osd.get('Orientation confidence', 0))
)
return oc
return orient_conf
def get_deskew(
+14 -6
View File
@@ -30,12 +30,16 @@ if sys.version_info >= (3, 10):
else:
from tempfile import TemporaryDirectory as _TemporaryDirectory
# Consume the ignore_cleanup_errors kwarg in Python 3.9 and older, without acting
# on this keyword. Users who need this issue full resolved should upgrade to Python
# 3.10.
# See: https://github.com/python/cpython/pull/24793
class TemporaryDirectory(_TemporaryDirectory):
"""Shim to consume ignore_cleanup_errors kwarg on Python 3.9 and older.
The argument is consumed without action. If users are getting errors related
to temporary file cleanup, they should upgrade to Python 3.10 which properly
cleans up temporary directories on Windows.
See: https://github.com/python/cpython/pull/24793
"""
def __init__(self, ignore_cleanup_errors=False, **kwargs):
super().__init__(**kwargs)
@@ -50,6 +54,8 @@ log = logging.getLogger(__name__)
class UnpaperImageTooLargeError(Exception):
"""To capture details when an image is too large for unpaper."""
def __init__(
self,
w,
@@ -66,8 +72,10 @@ def version() -> str:
return get_version('unpaper')
SUFFIXES = {'1': '.pbm', 'L': '.pgm', 'RGB': '.ppm'}
def _convert_image(im: Image.Image) -> Tuple[Image.Image, bool, str]:
SUFFIXES = {'1': '.pbm', 'L': '.pgm', 'RGB': '.ppm'}
im_modified = False
if im.mode not in SUFFIXES: