Skip to content

Commit

Permalink
added more ruff rules (#145)
Browse files Browse the repository at this point in the history
Signed-off-by: Alexander Piskun <[email protected]>
  • Loading branch information
bigcat88 authored Sep 24, 2023
1 parent 0eb98b4 commit fadca53
Show file tree
Hide file tree
Showing 33 changed files with 186 additions and 195 deletions.
4 changes: 2 additions & 2 deletions .github/transform_to-pi_heif.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# This script transform project to `pi-heif` in place. Should be used only with GA Actions.
"""Script to transform the project to `pi-heif` in place. Should be used only with GA Actions."""

import os

Expand All @@ -22,7 +22,7 @@
files_list += [os.path.join(dir_name, x)]

for file_name in files_list:
with open(file_name, "r") as file:
with open(file_name) as file:
data = file.read()
modified_data = data.replace("pillow_heif", "pi_heif")
if modified_data != data:
Expand Down
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
All notable changes to this project will be documented in this file.

## [0.1x.x - 2023-0x-xx]
## [0.13.1 - 2023-10-0x]

### Changed

Expand Down
2 changes: 1 addition & 1 deletion benchmarks/benchmark_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def measure_decode(image, n_iterations, op_type: int):
cat_image_results = []
pug_image_results = []
large_image_results = []
for i, v in enumerate(VERSIONS):
for _, v in enumerate(VERSIONS):
run(f"{sys.executable} -m pip install pillow-heif=={v}".split(), check=True)
cat_image_results.append(measure_decode(cat_image_path, N_ITER_SMALL, operation_type))
pug_image_results.append(measure_decode(pug_image_path, N_ITER_SMALL, operation_type))
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/benchmark_encode.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def measure_encode(image, n_iterations):
la_image_results = []
l_image_results = []
pug_image_results = []
for i, v in enumerate(VERSIONS):
for _, v in enumerate(VERSIONS):
run(f"{sys.executable} -m pip install pillow-heif=={v}".split(), check=True)
sleep(N_ITER)
rgba_image_results.append(measure_encode("RGBA", N_ITER))
Expand Down
6 changes: 3 additions & 3 deletions benchmarks/measure_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@
pillow_heif.register_heif_opener()
start_time = perf_counter()
if int(sys.argv[3]) == PILLOW_LOAD:
for i in range(int(sys.argv[1])):
for _ in range(int(sys.argv[1])):
im = Image.open(sys.argv[2])
im.load()
elif int(sys.argv[3]) == NUMPY_BGR:
for i in range(int(sys.argv[1])):
for _ in range(int(sys.argv[1])):
if pillow_heif.__version__.startswith("0.1"):
im = pillow_heif.open_heif(sys.argv[2], bgr_mode=True, convert_hdr_to_8bit=False)
else:
im = pillow_heif.open_heif(sys.argv[2], convert_hdr_to_8bit=False)
im.convert_to("BGR" if im.bit_depth == 8 else "BGR;16")
np_array = np.asarray(im)
elif int(sys.argv[3]) == NUMPY_RGB:
for i in range(int(sys.argv[1])):
for _ in range(int(sys.argv[1])):
if pillow_heif.__version__.startswith("0.1"):
im = pillow_heif.open_heif(sys.argv[2], convert_hdr_to_8bit=False)
else:
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/measure_encode.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
else:
img = L_IMAGE
start_time = perf_counter()
for i in range(int(sys.argv[1])):
for _ in range(int(sys.argv[1])):
buf = BytesIO()
img.save(buf, format="HEIF")
total_time = perf_counter() - start_time
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
# -- Project information -----------------------------------------------------

project = "pillow-heif"
copyright = "2021-2022, Alexander Piskun and Contributors"
copyright = "2021-2022, Alexander Piskun and Contributors" # noqa
author = "Alexander Piskun and Contributors"

# The short X.Y version.
Expand Down
2 changes: 1 addition & 1 deletion examples/heif_dump_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
print("\tSize:", image.size)
print("\tData size:", len(image.data))
print("\tStride:", image.stride)
print("\tThumbnails:", [t for t in image.info["thumbnails"]])
print("\tThumbnails:", list(image.info["thumbnails"]))
if image.info.get("icc_profile", None) is not None:
if len(image.info["icc_profile"]):
icc_profile = BytesIO(image.info["icc_profile"])
Expand Down
4 changes: 2 additions & 2 deletions examples/pillow_dump_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
file = "../tests/images/heif_other/cat.hif"
print("Dumping info for file:", file)
heif_pillow = Image.open(file)
print("Number of images:", len([i for i in ImageSequence.Iterator(heif_pillow)]))
print("Number of images:", len(list(ImageSequence.Iterator(heif_pillow))))
print("Information about each image:")
for image in ImageSequence.Iterator(heif_pillow):
print("\tMode:", image.mode)
print("\tSize:", image.size)
print("\tThumbnails:", [t for t in image.info["thumbnails"]])
print("\tThumbnails:", list(image.info["thumbnails"]))
print("\tData size:", len(image.tobytes()))
if image.info.get("icc_profile", None) is not None:
if len(image.info["icc_profile"]):
Expand Down
2 changes: 1 addition & 1 deletion examples/pillow_enumerate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@
pillow_heif.register_heif_opener()
image_path = Path("images/heif_other/nokia/alpha.heic")
img = Image.open(image_path)
for i, frame in enumerate(ImageSequence.Iterator(img)):
for i, _frame in enumerate(ImageSequence.Iterator(img)):
img.show(title=f"Image index={i}")
11 changes: 5 additions & 6 deletions libheif/linux_build_libs.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""File containing code to build Linux libraries for LibHeif and the LibHeif itself."""

import sys
from os import chdir, environ, getcwd, getenv, makedirs, mkdir, path, remove
from platform import machine
Expand Down Expand Up @@ -42,7 +44,7 @@ def download_file(url: str, out_path: str) -> bool:
n_download_clients -= 1
break
if not n_download_clients:
raise EnvironmentError("Both curl and wget cannot be found.")
raise OSError("Both curl and wget cannot be found.")
return False


Expand All @@ -62,10 +64,7 @@ def tool_check_version(name: str, min_version: str) -> bool:
_ = run([name, "--version"], stdout=PIPE, stderr=DEVNULL, check=True)
except (CalledProcessError, FileNotFoundError):
return False
if name == "nasm":
_regexp = r"version\s*(\d+(\.\d+){2})"
else: # cmake
_regexp = r"(\d+(\.\d+){2})$"
_regexp = r"version\s*(\d+(\.\d+){2})" if name == "nasm" else r"(\d+(\.\d+){2})$" # cmake
m_groups = search(_regexp, _.stdout.decode("utf-8"), flags=MULTILINE + IGNORECASE)
if m_groups is None:
return False
Expand Down Expand Up @@ -146,7 +145,7 @@ def build_lib_linux(url: str, name: str, musl: bool = False):
run(f"patch -p 1 -i {patch_path}".split(), check=True)
else:
download_extract_to(url, _lib_path)
if name == "libde265":
if name == "libde265": # noqa
chdir(_lib_path)
# for patch in (
# "libde265/CVE-2022-1253.patch",
Expand Down
4 changes: 1 addition & 3 deletions pillow_heif/AvifImagePlugin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Import this file to auto register an AVIF plugin for Pillow.
"""
"""Import this file to auto register an AVIF plugin for Pillow."""

from .as_plugin import register_avif_opener

Expand Down
4 changes: 1 addition & 3 deletions pillow_heif/HeifImagePlugin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Import this file to auto register a HEIF plugin for Pillow.
"""
"""Import this file to auto register a HEIF plugin for Pillow."""

from .as_plugin import register_heif_opener

Expand Down
4 changes: 1 addition & 3 deletions pillow_heif/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Import all possible stuff that can be used.
"""
"""Provide all possible stuff that can be used."""


from . import options
Expand Down
6 changes: 2 additions & 4 deletions pillow_heif/_deffered_error.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
"""
DeferredError class taken from PIL._util.py file.
"""
"""DeferredError class taken from PIL._util.py file."""


class DeferredError: # pylint: disable=too-few-public-methods
"""Allow failing import for doc purposes, as C module will be not build at `.readthedocs`"""
"""Allows failing import for doc purposes, as C module will be not build during docs build."""

def __init__(self, ex):
self.ex = ex
Expand Down
17 changes: 8 additions & 9 deletions pillow_heif/_lib_info.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Functions to get versions of underlying libraries.
"""
"""Functions to get versions of underlying libraries."""

try:
import _pillow_heif
Expand All @@ -12,17 +10,18 @@

def libheif_version() -> str:
"""Returns ``libheif`` version."""

return _pillow_heif.lib_info["libheif"]


def libheif_info() -> dict:
"""Returns a dictionary with version information.
The keys `libheif`, `HEIF`, `AVIF` are always present, but values for `HEIF`/`AVIF` can be empty.
{'libheif': '1.14.2',
'HEIF': 'x265 HEVC encoder (3.4+31-6722fce1f)',
'AVIF': 'AOMedia Project AV1 Encoder 3.5.0'
}"""
The keys `libheif`, `HEIF`, `AVIF` are always present, but values for `HEIF`/`AVIF` can be empty.
{
'libheif': '1.14.2',
'HEIF': 'x265 HEVC encoder (3.4+31-6722fce1f)',
'AVIF': 'AOMedia Project AV1 Encoder 3.5.0'
}
"""
return _pillow_heif.lib_info
4 changes: 2 additions & 2 deletions pillow_heif/_version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
""" Version of pillow_heif"""
"""Version of pillow_heif/pi_heif."""

__version__ = "0.13.0"
__version__ = "0.13.1.dev0"
31 changes: 12 additions & 19 deletions pillow_heif/as_plugin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Plugins for Pillow library.
"""
"""Plugins for the Pillow library."""

from itertools import chain
from typing import Union
Expand Down Expand Up @@ -82,8 +80,8 @@ def load(self):
def getxmp(self) -> dict:
"""Returns a dictionary containing the XMP tags. Requires ``defusedxml`` to be installed.
:returns: XMP tags in a dictionary."""

:returns: XMP tags in a dictionary.
"""
if self.info.get("xmp", None):
xmp_data = self.info["xmp"].rsplit(b"\x00", 1)
if xmp_data[0]:
Expand All @@ -96,9 +94,8 @@ def seek(self, frame):
self.__frame = frame
self._init_from_heif_file(frame)
_exif = getattr(self, "_exif", None) # Pillow 9.2+ do no reload exif between frames.
if _exif is not None:
if getattr(_exif, "_loaded", None):
_exif._loaded = False # pylint: disable=protected-access
if _exif is not None and getattr(_exif, "_loaded", None):
_exif._loaded = False # pylint: disable=protected-access

def tell(self):
return self.__frame
Expand All @@ -110,14 +107,13 @@ def verify(self) -> None:
def n_frames(self) -> int:
"""Returns the number of available frames.
:returns: Frame number, starting with 0."""

:returns: Frame number, starting with 0.
"""
return len(self._heif_file) if self._heif_file else 1

@property
def is_animated(self) -> bool:
"""Returns ``True`` if this image contains more than one frame, or ``False`` otherwise."""

return self.n_frames > 1

def _seek_check(self, frame):
Expand All @@ -140,7 +136,7 @@ def _init_from_heif_file(self, img_index: int) -> None:
class HeifImageFile(_LibHeifImageFile):
"""Pillow plugin class type for a HEIF image format."""

format = "HEIF"
format = "HEIF" # noqa
format_description = "HEIF container"


Expand Down Expand Up @@ -177,7 +173,6 @@ def register_heif_opener(**kwargs) -> None:
:param kwargs: dictionary with values to set in options. See: :ref:`options`.
"""

__options_update(**kwargs)
Image.register_open(HeifImageFile.format, HeifImageFile, _is_supported_heif)
if _pillow_heif.lib_info["HEIF"]:
Expand All @@ -191,7 +186,7 @@ def register_heif_opener(**kwargs) -> None:
class AvifImageFile(_LibHeifImageFile):
"""Pillow plugin class type for an AVIF image format."""

format = "AVIF"
format = "AVIF" # noqa
format_description = "AVIF container"


Expand Down Expand Up @@ -220,9 +215,8 @@ def register_avif_opener(**kwargs) -> None:
:param kwargs: dictionary with values to set in options. See: :ref:`options`.
"""

if not _pillow_heif.lib_info["AVIF"]:
warn("This version of `pillow-heif` was built without AVIF support.")
warn("This version of `pillow-heif` was built without AVIF support.", stacklevel=1)
return
__options_update(**kwargs)
Image.register_open(AvifImageFile.format, AvifImageFile, _is_supported_avif)
Expand All @@ -235,8 +229,7 @@ def register_avif_opener(**kwargs) -> None:


def __options_update(**kwargs):
"""Internal function to set options from `register_avif_opener` and `register_heif_opener`"""

"""Internal function to set options from `register_avif_opener` and `register_heif_opener` methods."""
for k, v in kwargs.items():
if k == "thumbnails":
options.THUMBNAILS = v
Expand All @@ -253,7 +246,7 @@ def __options_update(**kwargs):
elif k == "save_nclx_profile":
options.SAVE_NCLX_PROFILE = v
else:
warn(f"Unknown option: {k}")
warn(f"Unknown option: {k}", stacklevel=1)


def __save_one(im, fp, compression_format: HeifCompressionFormat):
Expand Down
6 changes: 2 additions & 4 deletions pillow_heif/constants.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Enums from LibHeif that are used.
"""
"""Enums from LibHeif that are used."""

from enum import IntEnum

Expand Down Expand Up @@ -168,7 +166,7 @@ class HeifMatrixCoefficients(IntEnum):


class HeifDepthRepresentationType(IntEnum):
"""Possible values of ``HeifDepthImage.info['metadata']['representation_type']``"""
"""Possible values of the ``HeifDepthImage.info['metadata']['representation_type']``."""

UNIFORM_INVERSE_Z = 0
"""Unknown"""
Expand Down
Loading

0 comments on commit fadca53

Please sign in to comment.