From 37923ffe52be801077739effbd04dc5a59b849d9 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Wed, 14 Jul 2021 02:34:28 -0700 Subject: [PATCH] Work around Pillow 8.3.1 DPI changes Pillow decided against round-tripping DPI values. https://github.com/python-pillow/Pillow/pull/5476 Fixes #802 --- src/ocrmypdf/helpers.py | 23 +++++++++++++++++++++-- tests/test_ghostscript.py | 2 +- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/ocrmypdf/helpers.py b/src/ocrmypdf/helpers.py index d7080f345..916fb42cf 100644 --- a/src/ocrmypdf/helpers.py +++ b/src/ocrmypdf/helpers.py @@ -25,19 +25,31 @@ class Resolution(namedtuple('Resolution', ('x', 'y'))): - """The number of pixels per inch in each 2D direction.""" + """The number of pixels per inch in each 2D direction. + + Resolution objects are considered "equal" for == purposes if they are + equal to a reasonable tolerance. + """ __slots__ = () + # rel_tol after converting from dpi to pixels per meter and saving + # as integer with rounding, as many file formats + CONVERSION_ERROR = 0.002 + def round(self, ndigits: int): return Resolution(round(self.x, ndigits), round(self.y, ndigits)) def to_int(self): return Resolution(int(round(self.x)), int(round(self.y))) + @classmethod + def _isclose(cls, a, b): + return isclose(a, b, rel_tol=cls.CONVERSION_ERROR) + @property def is_square(self) -> bool: - return isclose(self.x, self.y, rel_tol=1e-3) + return self._isclose(self.x, self.y) @property def is_finite(self) -> bool: @@ -61,6 +73,13 @@ def __str__(self): def __repr__(self): # pragma: no cover return f"Resolution({self.x}x{self.y} dpi)" + def __eq__(self, other): + if isinstance(other, tuple) and len(other) == 2: + other = Resolution(*other) + if not isinstance(other, Resolution): + return NotImplemented + return self._isclose(self.x, other.x) and self._isclose(self.y, other.y) + class NeverRaise(Exception): """An exception that is never raised""" diff --git a/tests/test_ghostscript.py b/tests/test_ghostscript.py index 0907b8190..28ecfe269 100644 --- a/tests/test_ghostscript.py +++ b/tests/test_ghostscript.py @@ -72,7 +72,7 @@ def test_rasterize_rotated(francais, outdir, caplog): with Image.open(outdir / 'out.png') as im: assert im.size == (target_size[1], target_size[0]) - assert im.info['dpi'] == (forced_dpi[1], forced_dpi[0]) + assert im.info['dpi'] == forced_dpi.flip_axis() def test_gs_render_failure(resources, outpdf):