H", tag_data[:2])[0]):
+ ifd_tag, typ, count, data = struct.unpack(
+ ">HHL4s", tag_data[i * 12 + 2 : (i + 1) * 12 + 2]
+ )
+ if ifd_tag == 0x1101:
+ # CameraInfo
+ (offset,) = struct.unpack(">L", data)
+ self.fp.seek(offset)
+
+ camerainfo: dict[str, int | bytes] = {
+ "ModelID": self.fp.read(4)
+ }
+
+ self.fp.read(4)
+ # Seconds since 2000
+ camerainfo["TimeStamp"] = i32le(self.fp.read(12))
+
+ self.fp.read(4)
+ camerainfo["InternalSerialNumber"] = self.fp.read(4)
+
+ self.fp.read(12)
+ parallax = self.fp.read(4)
+ handler = ImageFileDirectory_v2._load_dispatch[
+ TiffTags.FLOAT
+ ][1]
+ camerainfo["Parallax"] = handler(
+ ImageFileDirectory_v2(), parallax, False
+ )[0]
+
+ self.fp.read(4)
+ camerainfo["Category"] = self.fp.read(2)
+
+ makernote = {0x1101: camerainfo}
+ self._ifds[tag] = makernote
+ else:
+ # Interop
+ ifd = self._get_ifd_dict(tag_data, tag)
+ if ifd is not None:
+ self._ifds[tag] = ifd
+ ifd = self._ifds.setdefault(tag, {})
+ if tag == ExifTags.IFD.Exif and self._hidden_data:
+ ifd = {
+ k: v
+ for (k, v) in ifd.items()
+ if k not in (ExifTags.IFD.Interop, ExifTags.IFD.MakerNote)
+ }
+ return ifd
+
+ def hide_offsets(self) -> None:
+ for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo):
+ if tag in self:
+ self._hidden_data[tag] = self[tag]
+ del self[tag]
+
+ def __str__(self) -> str:
+ if self._info is not None:
+ # Load all keys into self._data
+ for tag in self._info:
+ self[tag]
+
+ return str(self._data)
+
+ def __len__(self) -> int:
+ keys = set(self._data)
+ if self._info is not None:
+ keys.update(self._info)
+ return len(keys)
+
+ def __getitem__(self, tag: int) -> Any:
+ if self._info is not None and tag not in self._data and tag in self._info:
+ self._data[tag] = self._fixup(self._info[tag])
+ del self._info[tag]
+ return self._data[tag]
+
+ def __contains__(self, tag: object) -> bool:
+ return tag in self._data or (self._info is not None and tag in self._info)
+
+ def __setitem__(self, tag: int, value: Any) -> None:
+ if self._info is not None and tag in self._info:
+ del self._info[tag]
+ self._data[tag] = value
+
+ def __delitem__(self, tag: int) -> None:
+ if self._info is not None and tag in self._info:
+ del self._info[tag]
+ else:
+ del self._data[tag]
+ if tag in self._ifds:
+ del self._ifds[tag]
+
+ def __iter__(self) -> Iterator[int]:
+ keys = set(self._data)
+ if self._info is not None:
+ keys.update(self._info)
+ return iter(keys)
diff --git a/venv/Lib/site-packages/PIL/ImageChops.py b/venv/Lib/site-packages/PIL/ImageChops.py
new file mode 100644
index 0000000..29a5c99
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageChops.py
@@ -0,0 +1,311 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# standard channel operations
+#
+# History:
+# 1996-03-24 fl Created
+# 1996-08-13 fl Added logical operations (for "1" images)
+# 2000-10-12 fl Added offset method (from Image.py)
+#
+# Copyright (c) 1997-2000 by Secret Labs AB
+# Copyright (c) 1996-2000 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+
+from __future__ import annotations
+
+from . import Image
+
+
+def constant(image: Image.Image, value: int) -> Image.Image:
+ """Fill a channel with a given gray level.
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ return Image.new("L", image.size, value)
+
+
+def duplicate(image: Image.Image) -> Image.Image:
+ """Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ return image.copy()
+
+
+def invert(image: Image.Image) -> Image.Image:
+ """
+ Invert an image (channel). ::
+
+ out = MAX - image
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image.load()
+ return image._new(image.im.chop_invert())
+
+
+def lighter(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """
+ Compares the two images, pixel by pixel, and returns a new image containing
+ the lighter values. ::
+
+ out = max(image1, image2)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_lighter(image2.im))
+
+
+def darker(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """
+ Compares the two images, pixel by pixel, and returns a new image containing
+ the darker values. ::
+
+ out = min(image1, image2)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_darker(image2.im))
+
+
+def difference(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """
+ Returns the absolute value of the pixel-by-pixel difference between the two
+ images. ::
+
+ out = abs(image1 - image2)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_difference(image2.im))
+
+
+def multiply(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """
+ Superimposes two images on top of each other.
+
+ If you multiply an image with a solid black image, the result is black. If
+ you multiply with a solid white image, the image is unaffected. ::
+
+ out = image1 * image2 / MAX
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_multiply(image2.im))
+
+
+def screen(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """
+ Superimposes two inverted images on top of each other. ::
+
+ out = MAX - ((MAX - image1) * (MAX - image2) / MAX)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_screen(image2.im))
+
+
+def soft_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """
+ Superimposes two images on top of each other using the Soft Light algorithm
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_soft_light(image2.im))
+
+
+def hard_light(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """
+ Superimposes two images on top of each other using the Hard Light algorithm
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_hard_light(image2.im))
+
+
+def overlay(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """
+ Superimposes two images on top of each other using the Overlay algorithm
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_overlay(image2.im))
+
+
+def add(
+ image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
+) -> Image.Image:
+ """
+ Adds two images, dividing the result by scale and adding the
+ offset. If omitted, scale defaults to 1.0, and offset to 0.0. ::
+
+ out = ((image1 + image2) / scale + offset)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_add(image2.im, scale, offset))
+
+
+def subtract(
+ image1: Image.Image, image2: Image.Image, scale: float = 1.0, offset: float = 0
+) -> Image.Image:
+ """
+ Subtracts two images, dividing the result by scale and adding the offset.
+ If omitted, scale defaults to 1.0, and offset to 0.0. ::
+
+ out = ((image1 - image2) / scale + offset)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_subtract(image2.im, scale, offset))
+
+
+def add_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """Add two images, without clipping the result. ::
+
+ out = ((image1 + image2) % MAX)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_add_modulo(image2.im))
+
+
+def subtract_modulo(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """Subtract two images, without clipping the result. ::
+
+ out = ((image1 - image2) % MAX)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_subtract_modulo(image2.im))
+
+
+def logical_and(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """Logical AND between two images.
+
+ Both of the images must have mode "1". If you would like to perform a
+ logical AND on an image with a mode other than "1", try
+ :py:meth:`~PIL.ImageChops.multiply` instead, using a black-and-white mask
+ as the second image. ::
+
+ out = ((image1 and image2) % MAX)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_and(image2.im))
+
+
+def logical_or(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """Logical OR between two images.
+
+ Both of the images must have mode "1". ::
+
+ out = ((image1 or image2) % MAX)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_or(image2.im))
+
+
+def logical_xor(image1: Image.Image, image2: Image.Image) -> Image.Image:
+ """Logical XOR between two images.
+
+ Both of the images must have mode "1". ::
+
+ out = ((bool(image1) != bool(image2)) % MAX)
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ image1.load()
+ image2.load()
+ return image1._new(image1.im.chop_xor(image2.im))
+
+
+def blend(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image:
+ """Blend images using constant transparency weight. Alias for
+ :py:func:`PIL.Image.blend`.
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ return Image.blend(image1, image2, alpha)
+
+
+def composite(
+ image1: Image.Image, image2: Image.Image, mask: Image.Image
+) -> Image.Image:
+ """Create composite using transparency mask. Alias for
+ :py:func:`PIL.Image.composite`.
+
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ return Image.composite(image1, image2, mask)
+
+
+def offset(image: Image.Image, xoffset: int, yoffset: int | None = None) -> Image.Image:
+ """Returns a copy of the image where data has been offset by the given
+ distances. Data wraps around the edges. If ``yoffset`` is omitted, it
+ is assumed to be equal to ``xoffset``.
+
+ :param image: Input image.
+ :param xoffset: The horizontal distance.
+ :param yoffset: The vertical distance. If omitted, both
+ distances are set to the same value.
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+
+ if yoffset is None:
+ yoffset = xoffset
+ image.load()
+ return image._new(image.im.offset(xoffset, yoffset))
diff --git a/venv/Lib/site-packages/PIL/ImageCms.py b/venv/Lib/site-packages/PIL/ImageCms.py
new file mode 100644
index 0000000..513e28a
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageCms.py
@@ -0,0 +1,1076 @@
+# The Python Imaging Library.
+# $Id$
+
+# Optional color management support, based on Kevin Cazabon's PyCMS
+# library.
+
+# Originally released under LGPL. Graciously donated to PIL in
+# March 2009, for distribution under the standard PIL license
+
+# History:
+
+# 2009-03-08 fl Added to PIL.
+
+# Copyright (C) 2002-2003 Kevin Cazabon
+# Copyright (c) 2009 by Fredrik Lundh
+# Copyright (c) 2013 by Eric Soroos
+
+# See the README file for information on usage and redistribution. See
+# below for the original description.
+from __future__ import annotations
+
+import operator
+import sys
+from enum import IntEnum, IntFlag
+from functools import reduce
+from typing import Any, Literal, SupportsFloat, SupportsInt, Union
+
+from . import Image
+from ._deprecate import deprecate
+from ._typing import SupportsRead
+
+try:
+ from . import _imagingcms as core
+
+ _CmsProfileCompatible = Union[
+ str, SupportsRead[bytes], core.CmsProfile, "ImageCmsProfile"
+ ]
+except ImportError as ex:
+ # Allow error import for doc purposes, but error out when accessing
+ # anything in core.
+ from ._util import DeferredError
+
+ core = DeferredError.new(ex)
+
+_DESCRIPTION = """
+pyCMS
+
+ a Python / PIL interface to the littleCMS ICC Color Management System
+ Copyright (C) 2002-2003 Kevin Cazabon
+ kevin@cazabon.com
+ https://www.cazabon.com
+
+ pyCMS home page: https://www.cazabon.com/pyCMS
+ littleCMS home page: https://www.littlecms.com
+ (littleCMS is Copyright (C) 1998-2001 Marti Maria)
+
+ Originally released under LGPL. Graciously donated to PIL in
+ March 2009, for distribution under the standard PIL license
+
+ The pyCMS.py module provides a "clean" interface between Python/PIL and
+ pyCMSdll, taking care of some of the more complex handling of the direct
+ pyCMSdll functions, as well as error-checking and making sure that all
+ relevant data is kept together.
+
+ While it is possible to call pyCMSdll functions directly, it's not highly
+ recommended.
+
+ Version History:
+
+ 1.0.0 pil Oct 2013 Port to LCMS 2.
+
+ 0.1.0 pil mod March 10, 2009
+
+ Renamed display profile to proof profile. The proof
+ profile is the profile of the device that is being
+ simulated, not the profile of the device which is
+ actually used to display/print the final simulation
+ (that'd be the output profile) - also see LCMSAPI.txt
+ input colorspace -> using 'renderingIntent' -> proof
+ colorspace -> using 'proofRenderingIntent' -> output
+ colorspace
+
+ Added LCMS FLAGS support.
+ Added FLAGS["SOFTPROOFING"] as default flag for
+ buildProofTransform (otherwise the proof profile/intent
+ would be ignored).
+
+ 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
+
+ 0.0.2 alpha Jan 6, 2002
+
+ Added try/except statements around type() checks of
+ potential CObjects... Python won't let you use type()
+ on them, and raises a TypeError (stupid, if you ask
+ me!)
+
+ Added buildProofTransformFromOpenProfiles() function.
+ Additional fixes in DLL, see DLL code for details.
+
+ 0.0.1 alpha first public release, Dec. 26, 2002
+
+ Known to-do list with current version (of Python interface, not pyCMSdll):
+
+ none
+
+"""
+
+_VERSION = "1.0.0 pil"
+
+
+# --------------------------------------------------------------------.
+
+
+#
+# intent/direction values
+
+
+class Intent(IntEnum):
+ PERCEPTUAL = 0
+ RELATIVE_COLORIMETRIC = 1
+ SATURATION = 2
+ ABSOLUTE_COLORIMETRIC = 3
+
+
+class Direction(IntEnum):
+ INPUT = 0
+ OUTPUT = 1
+ PROOF = 2
+
+
+#
+# flags
+
+
+class Flags(IntFlag):
+ """Flags and documentation are taken from ``lcms2.h``."""
+
+ NONE = 0
+ NOCACHE = 0x0040
+ """Inhibit 1-pixel cache"""
+ NOOPTIMIZE = 0x0100
+ """Inhibit optimizations"""
+ NULLTRANSFORM = 0x0200
+ """Don't transform anyway"""
+ GAMUTCHECK = 0x1000
+ """Out of Gamut alarm"""
+ SOFTPROOFING = 0x4000
+ """Do softproofing"""
+ BLACKPOINTCOMPENSATION = 0x2000
+ NOWHITEONWHITEFIXUP = 0x0004
+ """Don't fix scum dot"""
+ HIGHRESPRECALC = 0x0400
+ """Use more memory to give better accuracy"""
+ LOWRESPRECALC = 0x0800
+ """Use less memory to minimize resources"""
+ # this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
+ USE_8BITS_DEVICELINK = 0x0008
+ """Create 8 bits devicelinks"""
+ GUESSDEVICECLASS = 0x0020
+ """Guess device class (for ``transform2devicelink``)"""
+ KEEP_SEQUENCE = 0x0080
+ """Keep profile sequence for devicelink creation"""
+ FORCE_CLUT = 0x0002
+ """Force CLUT optimization"""
+ CLUT_POST_LINEARIZATION = 0x0001
+ """create postlinearization tables if possible"""
+ CLUT_PRE_LINEARIZATION = 0x0010
+ """create prelinearization tables if possible"""
+ NONEGATIVES = 0x8000
+ """Prevent negative numbers in floating point transforms"""
+ COPY_ALPHA = 0x04000000
+ """Alpha channels are copied on ``cmsDoTransform()``"""
+ NODEFAULTRESOURCEDEF = 0x01000000
+
+ _GRIDPOINTS_1 = 1 << 16
+ _GRIDPOINTS_2 = 2 << 16
+ _GRIDPOINTS_4 = 4 << 16
+ _GRIDPOINTS_8 = 8 << 16
+ _GRIDPOINTS_16 = 16 << 16
+ _GRIDPOINTS_32 = 32 << 16
+ _GRIDPOINTS_64 = 64 << 16
+ _GRIDPOINTS_128 = 128 << 16
+
+ @staticmethod
+ def GRIDPOINTS(n: int) -> Flags:
+ """
+ Fine-tune control over number of gridpoints
+
+ :param n: :py:class:`int` in range ``0 <= n <= 255``
+ """
+ return Flags.NONE | ((n & 0xFF) << 16)
+
+
+_MAX_FLAG = reduce(operator.or_, Flags)
+
+
+_FLAGS = {
+ "MATRIXINPUT": 1,
+ "MATRIXOUTPUT": 2,
+ "MATRIXONLY": (1 | 2),
+ "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
+ # Don't create prelinearization tables on precalculated transforms
+ # (internal use):
+ "NOPRELINEARIZATION": 16,
+ "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
+ "NOTCACHE": 64, # Inhibit 1-pixel cache
+ "NOTPRECALC": 256,
+ "NULLTRANSFORM": 512, # Don't transform anyway
+ "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
+ "LOWRESPRECALC": 2048, # Use less memory to minimize resources
+ "WHITEBLACKCOMPENSATION": 8192,
+ "BLACKPOINTCOMPENSATION": 8192,
+ "GAMUTCHECK": 4096, # Out of Gamut alarm
+ "SOFTPROOFING": 16384, # Do softproofing
+ "PRESERVEBLACK": 32768, # Black preservation
+ "NODEFAULTRESOURCEDEF": 16777216, # CRD special
+ "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
+}
+
+
+# --------------------------------------------------------------------.
+# Experimental PIL-level API
+# --------------------------------------------------------------------.
+
+##
+# Profile.
+
+
+class ImageCmsProfile:
+ def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
+ """
+ :param profile: Either a string representing a filename,
+ a file like object containing a profile or a
+ low-level profile object
+
+ """
+ self.filename: str | None = None
+
+ if isinstance(profile, str):
+ if sys.platform == "win32":
+ profile_bytes_path = profile.encode()
+ try:
+ profile_bytes_path.decode("ascii")
+ except UnicodeDecodeError:
+ with open(profile, "rb") as f:
+ self.profile = core.profile_frombytes(f.read())
+ return
+ self.filename = profile
+ self.profile = core.profile_open(profile)
+ elif hasattr(profile, "read"):
+ self.profile = core.profile_frombytes(profile.read())
+ elif isinstance(profile, core.CmsProfile):
+ self.profile = profile
+ else:
+ msg = "Invalid type for Profile" # type: ignore[unreachable]
+ raise TypeError(msg)
+
+ def __getattr__(self, name: str) -> Any:
+ if name in ("product_name", "product_info"):
+ deprecate(f"ImageCms.ImageCmsProfile.{name}", 13)
+ return None
+ msg = f"'{self.__class__.__name__}' object has no attribute '{name}'"
+ raise AttributeError(msg)
+
+ def tobytes(self) -> bytes:
+ """
+ Returns the profile in a format suitable for embedding in
+ saved images.
+
+ :returns: a bytes object containing the ICC profile.
+ """
+
+ return core.profile_tobytes(self.profile)
+
+
+class ImageCmsTransform(Image.ImagePointHandler):
+ """
+ Transform. This can be used with the procedural API, or with the standard
+ :py:func:`~PIL.Image.Image.point` method.
+
+ Will return the output profile in the ``output.info['icc_profile']``.
+ """
+
+ def __init__(
+ self,
+ input: ImageCmsProfile,
+ output: ImageCmsProfile,
+ input_mode: str,
+ output_mode: str,
+ intent: Intent = Intent.PERCEPTUAL,
+ proof: ImageCmsProfile | None = None,
+ proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
+ flags: Flags = Flags.NONE,
+ ):
+ if proof is None:
+ self.transform = core.buildTransform(
+ input.profile, output.profile, input_mode, output_mode, intent, flags
+ )
+ else:
+ self.transform = core.buildProofTransform(
+ input.profile,
+ output.profile,
+ proof.profile,
+ input_mode,
+ output_mode,
+ intent,
+ proof_intent,
+ flags,
+ )
+ # Note: inputMode and outputMode are for pyCMS compatibility only
+ self.input_mode = self.inputMode = input_mode
+ self.output_mode = self.outputMode = output_mode
+
+ self.output_profile = output
+
+ def point(self, im: Image.Image) -> Image.Image:
+ return self.apply(im)
+
+ def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
+ if imOut is None:
+ imOut = Image.new(self.output_mode, im.size, None)
+ self.transform.apply(im.getim(), imOut.getim())
+ imOut.info["icc_profile"] = self.output_profile.tobytes()
+ return imOut
+
+ def apply_in_place(self, im: Image.Image) -> Image.Image:
+ if im.mode != self.output_mode:
+ msg = "mode mismatch"
+ raise ValueError(msg) # wrong output mode
+ self.transform.apply(im.getim(), im.getim())
+ im.info["icc_profile"] = self.output_profile.tobytes()
+ return im
+
+
+def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
+ """
+ (experimental) Fetches the profile for the current display device.
+
+ :returns: ``None`` if the profile is not known.
+ """
+
+ if sys.platform != "win32":
+ return None
+
+ from . import ImageWin # type: ignore[unused-ignore, unreachable]
+
+ if isinstance(handle, ImageWin.HDC):
+ profile = core.get_display_profile_win32(int(handle), 1)
+ else:
+ profile = core.get_display_profile_win32(int(handle or 0))
+ if profile is None:
+ return None
+ return ImageCmsProfile(profile)
+
+
+# --------------------------------------------------------------------.
+# pyCMS compatible layer
+# --------------------------------------------------------------------.
+
+
+class PyCMSError(Exception):
+ """(pyCMS) Exception class.
+ This is used for all errors in the pyCMS API."""
+
+ pass
+
+
+def profileToProfile(
+ im: Image.Image,
+ inputProfile: _CmsProfileCompatible,
+ outputProfile: _CmsProfileCompatible,
+ renderingIntent: Intent = Intent.PERCEPTUAL,
+ outputMode: str | None = None,
+ inPlace: bool = False,
+ flags: Flags = Flags.NONE,
+) -> Image.Image | None:
+ """
+ (pyCMS) Applies an ICC transformation to a given image, mapping from
+ ``inputProfile`` to ``outputProfile``.
+
+ If the input or output profiles specified are not valid filenames, a
+ :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
+ ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
+ If an error occurs during application of the profiles,
+ a :exc:`PyCMSError` will be raised.
+ If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
+ a :exc:`PyCMSError` will be raised.
+
+ This function applies an ICC transformation to im from ``inputProfile``'s
+ color space to ``outputProfile``'s color space using the specified rendering
+ intent to decide how to handle out-of-gamut colors.
+
+ ``outputMode`` can be used to specify that a color mode conversion is to
+ be done using these profiles, but the specified profiles must be able
+ to handle that mode. I.e., if converting im from RGB to CMYK using
+ profiles, the input profile must handle RGB data, and the output
+ profile must handle CMYK data.
+
+ :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
+ or Image.open(...), etc.)
+ :param inputProfile: String, as a valid filename path to the ICC input
+ profile you wish to use for this image, or a profile object
+ :param outputProfile: String, as a valid filename path to the ICC output
+ profile you wish to use for this image, or a profile object
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
+ wish to use for the transform
+
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
+ ImageCms.Intent.SATURATION = 2
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
+
+ see the pyCMS documentation for details on rendering intents and what
+ they do.
+ :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
+ "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
+ MUST be the same mode as the input, or omitted completely. If
+ omitted, the outputMode will be the same as the mode of the input
+ image (im.mode)
+ :param inPlace: Boolean. If ``True``, the original image is modified in-place,
+ and ``None`` is returned. If ``False`` (default), a new
+ :py:class:`~PIL.Image.Image` object is returned with the transform applied.
+ :param flags: Integer (0-...) specifying additional flags
+ :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
+ the value of ``inPlace``
+ :exception PyCMSError:
+ """
+
+ if outputMode is None:
+ outputMode = im.mode
+
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
+ msg = "renderingIntent must be an integer between 0 and 3"
+ raise PyCMSError(msg)
+
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
+ raise PyCMSError(msg)
+
+ try:
+ if not isinstance(inputProfile, ImageCmsProfile):
+ inputProfile = ImageCmsProfile(inputProfile)
+ if not isinstance(outputProfile, ImageCmsProfile):
+ outputProfile = ImageCmsProfile(outputProfile)
+ transform = ImageCmsTransform(
+ inputProfile,
+ outputProfile,
+ im.mode,
+ outputMode,
+ renderingIntent,
+ flags=flags,
+ )
+ if inPlace:
+ transform.apply_in_place(im)
+ imOut = None
+ else:
+ imOut = transform.apply(im)
+ except (OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+ return imOut
+
+
+def getOpenProfile(
+ profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
+) -> ImageCmsProfile:
+ """
+ (pyCMS) Opens an ICC profile file.
+
+ The PyCMSProfile object can be passed back into pyCMS for use in creating
+ transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
+
+ If ``profileFilename`` is not a valid filename for an ICC profile,
+ a :exc:`PyCMSError` will be raised.
+
+ :param profileFilename: String, as a valid filename path to the ICC profile
+ you wish to open, or a file-like object.
+ :returns: A CmsProfile class object.
+ :exception PyCMSError:
+ """
+
+ try:
+ return ImageCmsProfile(profileFilename)
+ except (OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def buildTransform(
+ inputProfile: _CmsProfileCompatible,
+ outputProfile: _CmsProfileCompatible,
+ inMode: str,
+ outMode: str,
+ renderingIntent: Intent = Intent.PERCEPTUAL,
+ flags: Flags = Flags.NONE,
+) -> ImageCmsTransform:
+ """
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
+ ``outputProfile``. Use applyTransform to apply the transform to a given
+ image.
+
+ If the input or output profiles specified are not valid filenames, a
+ :exc:`PyCMSError` will be raised. If an error occurs during creation
+ of the transform, a :exc:`PyCMSError` will be raised.
+
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
+
+ This function builds and returns an ICC transform from the ``inputProfile``
+ to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
+ with out-of-gamut colors. It will ONLY work for converting images that
+ are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
+ i.e. "RGB", "RGBA", "CMYK", etc.).
+
+ Building the transform is a fair part of the overhead in
+ ImageCms.profileToProfile(), so if you're planning on converting multiple
+ images using the same input/output settings, this can save you time.
+ Once you have a transform object, it can be used with
+ ImageCms.applyProfile() to convert images without the need to re-compute
+ the lookup table for the transform.
+
+ The reason pyCMS returns a class object rather than a handle directly
+ to the transform is that it needs to keep track of the PIL input/output
+ modes that the transform is meant for. These attributes are stored in
+ the ``inMode`` and ``outMode`` attributes of the object (which can be
+ manually overridden if you really want to, but I don't know of any
+ time that would be of use, or would even work).
+
+ :param inputProfile: String, as a valid filename path to the ICC input
+ profile you wish to use for this transform, or a profile object
+ :param outputProfile: String, as a valid filename path to the ICC output
+ profile you wish to use for this transform, or a profile object
+ :param inMode: String, as a valid PIL mode that the appropriate profile
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
+ :param outMode: String, as a valid PIL mode that the appropriate profile
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
+ wish to use for the transform
+
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
+ ImageCms.Intent.SATURATION = 2
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
+
+ see the pyCMS documentation for details on rendering intents and what
+ they do.
+ :param flags: Integer (0-...) specifying additional flags
+ :returns: A CmsTransform class object.
+ :exception PyCMSError:
+ """
+
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
+ msg = "renderingIntent must be an integer between 0 and 3"
+ raise PyCMSError(msg)
+
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
+ raise PyCMSError(msg)
+
+ try:
+ if not isinstance(inputProfile, ImageCmsProfile):
+ inputProfile = ImageCmsProfile(inputProfile)
+ if not isinstance(outputProfile, ImageCmsProfile):
+ outputProfile = ImageCmsProfile(outputProfile)
+ return ImageCmsTransform(
+ inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
+ )
+ except (OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def buildProofTransform(
+ inputProfile: _CmsProfileCompatible,
+ outputProfile: _CmsProfileCompatible,
+ proofProfile: _CmsProfileCompatible,
+ inMode: str,
+ outMode: str,
+ renderingIntent: Intent = Intent.PERCEPTUAL,
+ proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
+ flags: Flags = Flags.SOFTPROOFING,
+) -> ImageCmsTransform:
+ """
+ (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
+ ``outputProfile``, but tries to simulate the result that would be
+ obtained on the ``proofProfile`` device.
+
+ If the input, output, or proof profiles specified are not valid
+ filenames, a :exc:`PyCMSError` will be raised.
+
+ If an error occurs during creation of the transform,
+ a :exc:`PyCMSError` will be raised.
+
+ If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
+ (or by pyCMS), a :exc:`PyCMSError` will be raised.
+
+ This function builds and returns an ICC transform from the ``inputProfile``
+ to the ``outputProfile``, but tries to simulate the result that would be
+ obtained on the ``proofProfile`` device using ``renderingIntent`` and
+ ``proofRenderingIntent`` to determine what to do with out-of-gamut
+ colors. This is known as "soft-proofing". It will ONLY work for
+ converting images that are in ``inMode`` to images that are in outMode
+ color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
+
+ Usage of the resulting transform object is exactly the same as with
+ ImageCms.buildTransform().
+
+ Proof profiling is generally used when using an output device to get a
+ good idea of what the final printed/displayed image would look like on
+ the ``proofProfile`` device when it's quicker and easier to use the
+ output device for judging color. Generally, this means that the
+ output device is a monitor, or a dye-sub printer (etc.), and the simulated
+ device is something more expensive, complicated, or time consuming
+ (making it difficult to make a real print for color judgement purposes).
+
+ Soft-proofing basically functions by adjusting the colors on the
+ output device to match the colors of the device being simulated. However,
+ when the simulated device has a much wider gamut than the output
+ device, you may obtain marginal results.
+
+ :param inputProfile: String, as a valid filename path to the ICC input
+ profile you wish to use for this transform, or a profile object
+ :param outputProfile: String, as a valid filename path to the ICC output
+ (monitor, usually) profile you wish to use for this transform, or a
+ profile object
+ :param proofProfile: String, as a valid filename path to the ICC proof
+ profile you wish to use for this transform, or a profile object
+ :param inMode: String, as a valid PIL mode that the appropriate profile
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
+ :param outMode: String, as a valid PIL mode that the appropriate profile
+ also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
+ :param renderingIntent: Integer (0-3) specifying the rendering intent you
+ wish to use for the input->proof (simulated) transform
+
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
+ ImageCms.Intent.SATURATION = 2
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
+
+ see the pyCMS documentation for details on rendering intents and what
+ they do.
+ :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
+ you wish to use for proof->output transform
+
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
+ ImageCms.Intent.SATURATION = 2
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
+
+ see the pyCMS documentation for details on rendering intents and what
+ they do.
+ :param flags: Integer (0-...) specifying additional flags
+ :returns: A CmsTransform class object.
+ :exception PyCMSError:
+ """
+
+ if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
+ msg = "renderingIntent must be an integer between 0 and 3"
+ raise PyCMSError(msg)
+
+ if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
+ msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
+ raise PyCMSError(msg)
+
+ try:
+ if not isinstance(inputProfile, ImageCmsProfile):
+ inputProfile = ImageCmsProfile(inputProfile)
+ if not isinstance(outputProfile, ImageCmsProfile):
+ outputProfile = ImageCmsProfile(outputProfile)
+ if not isinstance(proofProfile, ImageCmsProfile):
+ proofProfile = ImageCmsProfile(proofProfile)
+ return ImageCmsTransform(
+ inputProfile,
+ outputProfile,
+ inMode,
+ outMode,
+ renderingIntent,
+ proofProfile,
+ proofRenderingIntent,
+ flags,
+ )
+ except (OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+buildTransformFromOpenProfiles = buildTransform
+buildProofTransformFromOpenProfiles = buildProofTransform
+
+
+def applyTransform(
+ im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
+) -> Image.Image | None:
+ """
+ (pyCMS) Applies a transform to a given image.
+
+ If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
+
+ If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
+ :exc:`PyCMSError` is raised.
+
+ If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
+ supported by pyCMSdll or the profiles you used for the transform, a
+ :exc:`PyCMSError` is raised.
+
+ If an error occurs while the transform is being applied,
+ a :exc:`PyCMSError` is raised.
+
+ This function applies a pre-calculated transform (from
+ ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
+ to an image. The transform can be used for multiple images, saving
+ considerable calculation time if doing the same conversion multiple times.
+
+ If you want to modify im in-place instead of receiving a new image as
+ the return value, set ``inPlace`` to ``True``. This can only be done if
+ ``transform.input_mode`` and ``transform.output_mode`` are the same, because we
+ can't change the mode in-place (the buffer sizes for some modes are
+ different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
+ object of the same dimensions in mode ``transform.output_mode``.
+
+ :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
+ as the ``input_mode`` supported by the transform.
+ :param transform: A valid CmsTransform class object
+ :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
+ returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
+ transform applied is returned (and ``im`` is not changed). The default is
+ ``False``.
+ :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
+ depending on the value of ``inPlace``. The profile will be returned in
+ the image's ``info['icc_profile']``.
+ :exception PyCMSError:
+ """
+
+ try:
+ if inPlace:
+ transform.apply_in_place(im)
+ imOut = None
+ else:
+ imOut = transform.apply(im)
+ except (TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+ return imOut
+
+
+def createProfile(
+ colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
+) -> core.CmsProfile:
+ """
+ (pyCMS) Creates a profile.
+
+ If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
+ a :exc:`PyCMSError` is raised.
+
+ If using LAB and ``colorTemp`` is not a positive integer,
+ a :exc:`PyCMSError` is raised.
+
+ If an error occurs while creating the profile,
+ a :exc:`PyCMSError` is raised.
+
+ Use this function to create common profiles on-the-fly instead of
+ having to supply a profile on disk and knowing the path to it. It
+ returns a normal CmsProfile object that can be passed to
+ ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
+ to images.
+
+ :param colorSpace: String, the color space of the profile you wish to
+ create.
+ Currently only "LAB", "XYZ", and "sRGB" are supported.
+ :param colorTemp: Positive number for the white point for the profile, in
+ degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
+ illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
+ profiles, and is ignored for XYZ and sRGB.
+ :returns: A CmsProfile class object
+ :exception PyCMSError:
+ """
+
+ if colorSpace not in ["LAB", "XYZ", "sRGB"]:
+ msg = (
+ f"Color space not supported for on-the-fly profile creation ({colorSpace})"
+ )
+ raise PyCMSError(msg)
+
+ if colorSpace == "LAB":
+ try:
+ colorTemp = float(colorTemp)
+ except (TypeError, ValueError) as e:
+ msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
+ raise PyCMSError(msg) from e
+
+ try:
+ return core.createProfile(colorSpace, colorTemp)
+ except (TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def getProfileName(profile: _CmsProfileCompatible) -> str:
+ """
+
+ (pyCMS) Gets the internal product name for the given profile.
+
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
+ a :exc:`PyCMSError` is raised If an error occurs while trying
+ to obtain the name tag, a :exc:`PyCMSError` is raised.
+
+ Use this function to obtain the INTERNAL name of the profile (stored
+ in an ICC tag in the profile itself), usually the one used when the
+ profile was originally created. Sometimes this tag also contains
+ additional information supplied by the creator.
+
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
+ filename of an ICC profile.
+ :returns: A string containing the internal name of the profile as stored
+ in an ICC tag.
+ :exception PyCMSError:
+ """
+
+ try:
+ # add an extra newline to preserve pyCMS compatibility
+ if not isinstance(profile, ImageCmsProfile):
+ profile = ImageCmsProfile(profile)
+ # do it in python, not c.
+ # // name was "%s - %s" (model, manufacturer) || Description ,
+ # // but if the Model and Manufacturer were the same or the model
+ # // was long, Just the model, in 1.x
+ model = profile.profile.model
+ manufacturer = profile.profile.manufacturer
+
+ if not (model or manufacturer):
+ return (profile.profile.profile_description or "") + "\n"
+ if not manufacturer or (model and len(model) > 30):
+ return f"{model}\n"
+ return f"{model} - {manufacturer}\n"
+
+ except (AttributeError, OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def getProfileInfo(profile: _CmsProfileCompatible) -> str:
+ """
+ (pyCMS) Gets the internal product information for the given profile.
+
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile,
+ a :exc:`PyCMSError` is raised.
+
+ If an error occurs while trying to obtain the info tag,
+ a :exc:`PyCMSError` is raised.
+
+ Use this function to obtain the information stored in the profile's
+ info tag. This often contains details about the profile, and how it
+ was created, as supplied by the creator.
+
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
+ filename of an ICC profile.
+ :returns: A string containing the internal profile information stored in
+ an ICC tag.
+ :exception PyCMSError:
+ """
+
+ try:
+ if not isinstance(profile, ImageCmsProfile):
+ profile = ImageCmsProfile(profile)
+ # add an extra newline to preserve pyCMS compatibility
+ # Python, not C. the white point bits weren't working well,
+ # so skipping.
+ # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
+ description = profile.profile.profile_description
+ cpright = profile.profile.copyright
+ elements = [element for element in (description, cpright) if element]
+ return "\r\n\r\n".join(elements) + "\r\n\r\n"
+
+ except (AttributeError, OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
+ """
+ (pyCMS) Gets the copyright for the given profile.
+
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ :exc:`PyCMSError` is raised.
+
+ If an error occurs while trying to obtain the copyright tag,
+ a :exc:`PyCMSError` is raised.
+
+ Use this function to obtain the information stored in the profile's
+ copyright tag.
+
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
+ filename of an ICC profile.
+ :returns: A string containing the internal profile information stored in
+ an ICC tag.
+ :exception PyCMSError:
+ """
+ try:
+ # add an extra newline to preserve pyCMS compatibility
+ if not isinstance(profile, ImageCmsProfile):
+ profile = ImageCmsProfile(profile)
+ return (profile.profile.copyright or "") + "\n"
+ except (AttributeError, OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
+ """
+ (pyCMS) Gets the manufacturer for the given profile.
+
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ :exc:`PyCMSError` is raised.
+
+ If an error occurs while trying to obtain the manufacturer tag, a
+ :exc:`PyCMSError` is raised.
+
+ Use this function to obtain the information stored in the profile's
+ manufacturer tag.
+
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
+ filename of an ICC profile.
+ :returns: A string containing the internal profile information stored in
+ an ICC tag.
+ :exception PyCMSError:
+ """
+ try:
+ # add an extra newline to preserve pyCMS compatibility
+ if not isinstance(profile, ImageCmsProfile):
+ profile = ImageCmsProfile(profile)
+ return (profile.profile.manufacturer or "") + "\n"
+ except (AttributeError, OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def getProfileModel(profile: _CmsProfileCompatible) -> str:
+ """
+ (pyCMS) Gets the model for the given profile.
+
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ :exc:`PyCMSError` is raised.
+
+ If an error occurs while trying to obtain the model tag,
+ a :exc:`PyCMSError` is raised.
+
+ Use this function to obtain the information stored in the profile's
+ model tag.
+
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
+ filename of an ICC profile.
+ :returns: A string containing the internal profile information stored in
+ an ICC tag.
+ :exception PyCMSError:
+ """
+
+ try:
+ # add an extra newline to preserve pyCMS compatibility
+ if not isinstance(profile, ImageCmsProfile):
+ profile = ImageCmsProfile(profile)
+ return (profile.profile.model or "") + "\n"
+ except (AttributeError, OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def getProfileDescription(profile: _CmsProfileCompatible) -> str:
+ """
+ (pyCMS) Gets the description for the given profile.
+
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ :exc:`PyCMSError` is raised.
+
+ If an error occurs while trying to obtain the description tag,
+ a :exc:`PyCMSError` is raised.
+
+ Use this function to obtain the information stored in the profile's
+ description tag.
+
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
+ filename of an ICC profile.
+ :returns: A string containing the internal profile information stored in an
+ ICC tag.
+ :exception PyCMSError:
+ """
+
+ try:
+ # add an extra newline to preserve pyCMS compatibility
+ if not isinstance(profile, ImageCmsProfile):
+ profile = ImageCmsProfile(profile)
+ return (profile.profile.profile_description or "") + "\n"
+ except (AttributeError, OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
+ """
+ (pyCMS) Gets the default intent name for the given profile.
+
+ If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
+ :exc:`PyCMSError` is raised.
+
+ If an error occurs while trying to obtain the default intent, a
+ :exc:`PyCMSError` is raised.
+
+ Use this function to determine the default (and usually best optimized)
+ rendering intent for this profile. Most profiles support multiple
+ rendering intents, but are intended mostly for one type of conversion.
+ If you wish to use a different intent than returned, use
+ ImageCms.isIntentSupported() to verify it will work first.
+
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
+ filename of an ICC profile.
+ :returns: Integer 0-3 specifying the default rendering intent for this
+ profile.
+
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
+ ImageCms.Intent.SATURATION = 2
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
+
+ see the pyCMS documentation for details on rendering intents and what
+ they do.
+ :exception PyCMSError:
+ """
+
+ try:
+ if not isinstance(profile, ImageCmsProfile):
+ profile = ImageCmsProfile(profile)
+ return profile.profile.rendering_intent
+ except (AttributeError, OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
+
+
+def isIntentSupported(
+ profile: _CmsProfileCompatible, intent: Intent, direction: Direction
+) -> Literal[-1, 1]:
+ """
+ (pyCMS) Checks if a given intent is supported.
+
+ Use this function to verify that you can use your desired
+ ``intent`` with ``profile``, and that ``profile`` can be used for the
+ input/output/proof profile as you desire.
+
+ Some profiles are created specifically for one "direction", can cannot
+ be used for others. Some profiles can only be used for certain
+ rendering intents, so it's best to either verify this before trying
+ to create a transform with them (using this function), or catch the
+ potential :exc:`PyCMSError` that will occur if they don't
+ support the modes you select.
+
+ :param profile: EITHER a valid CmsProfile object, OR a string of the
+ filename of an ICC profile.
+ :param intent: Integer (0-3) specifying the rendering intent you wish to
+ use with this profile
+
+ ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
+ ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
+ ImageCms.Intent.SATURATION = 2
+ ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
+
+ see the pyCMS documentation for details on rendering intents and what
+ they do.
+ :param direction: Integer specifying if the profile is to be used for
+ input, output, or proof
+
+ INPUT = 0 (or use ImageCms.Direction.INPUT)
+ OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
+ PROOF = 2 (or use ImageCms.Direction.PROOF)
+
+ :returns: 1 if the intent/direction are supported, -1 if they are not.
+ :exception PyCMSError:
+ """
+
+ try:
+ if not isinstance(profile, ImageCmsProfile):
+ profile = ImageCmsProfile(profile)
+ # FIXME: I get different results for the same data w. different
+ # compilers. Bug in LittleCMS or in the binding?
+ if profile.profile.is_intent_supported(intent, direction):
+ return 1
+ else:
+ return -1
+ except (AttributeError, OSError, TypeError, ValueError) as v:
+ raise PyCMSError(v) from v
diff --git a/venv/Lib/site-packages/PIL/ImageColor.py b/venv/Lib/site-packages/PIL/ImageColor.py
new file mode 100644
index 0000000..9a15a8e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageColor.py
@@ -0,0 +1,320 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# map CSS3-style colour description strings to RGB
+#
+# History:
+# 2002-10-24 fl Added support for CSS-style color strings
+# 2002-12-15 fl Added RGBA support
+# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
+# 2004-07-19 fl Fixed gray/grey spelling issues
+# 2009-03-05 fl Fixed rounding error in grayscale calculation
+#
+# Copyright (c) 2002-2004 by Secret Labs AB
+# Copyright (c) 2002-2004 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import re
+from functools import lru_cache
+
+from . import Image
+
+
+@lru_cache
+def getrgb(color: str) -> tuple[int, int, int] | tuple[int, int, int, int]:
+ """
+ Convert a color string to an RGB or RGBA tuple. If the string cannot be
+ parsed, this function raises a :py:exc:`ValueError` exception.
+
+ .. versionadded:: 1.1.4
+
+ :param color: A color string
+ :return: ``(red, green, blue[, alpha])``
+ """
+ if len(color) > 100:
+ msg = "color specifier is too long"
+ raise ValueError(msg)
+ color = color.lower()
+
+ rgb = colormap.get(color, None)
+ if rgb:
+ if isinstance(rgb, tuple):
+ return rgb
+ rgb_tuple = getrgb(rgb)
+ assert len(rgb_tuple) == 3
+ colormap[color] = rgb_tuple
+ return rgb_tuple
+
+ # check for known string formats
+ if re.match("#[a-f0-9]{3}$", color):
+ return int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)
+
+ if re.match("#[a-f0-9]{4}$", color):
+ return (
+ int(color[1] * 2, 16),
+ int(color[2] * 2, 16),
+ int(color[3] * 2, 16),
+ int(color[4] * 2, 16),
+ )
+
+ if re.match("#[a-f0-9]{6}$", color):
+ return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)
+
+ if re.match("#[a-f0-9]{8}$", color):
+ return (
+ int(color[1:3], 16),
+ int(color[3:5], 16),
+ int(color[5:7], 16),
+ int(color[7:9], 16),
+ )
+
+ m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
+ if m:
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
+
+ m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)
+ if m:
+ return (
+ int((int(m.group(1)) * 255) / 100.0 + 0.5),
+ int((int(m.group(2)) * 255) / 100.0 + 0.5),
+ int((int(m.group(3)) * 255) / 100.0 + 0.5),
+ )
+
+ m = re.match(
+ r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
+ )
+ if m:
+ from colorsys import hls_to_rgb
+
+ rgb_floats = hls_to_rgb(
+ float(m.group(1)) / 360.0,
+ float(m.group(3)) / 100.0,
+ float(m.group(2)) / 100.0,
+ )
+ return (
+ int(rgb_floats[0] * 255 + 0.5),
+ int(rgb_floats[1] * 255 + 0.5),
+ int(rgb_floats[2] * 255 + 0.5),
+ )
+
+ m = re.match(
+ r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color
+ )
+ if m:
+ from colorsys import hsv_to_rgb
+
+ rgb_floats = hsv_to_rgb(
+ float(m.group(1)) / 360.0,
+ float(m.group(2)) / 100.0,
+ float(m.group(3)) / 100.0,
+ )
+ return (
+ int(rgb_floats[0] * 255 + 0.5),
+ int(rgb_floats[1] * 255 + 0.5),
+ int(rgb_floats[2] * 255 + 0.5),
+ )
+
+ m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)
+ if m:
+ return int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
+ msg = f"unknown color specifier: {repr(color)}"
+ raise ValueError(msg)
+
+
+@lru_cache
+def getcolor(color: str, mode: str) -> int | tuple[int, ...]:
+ """
+ Same as :py:func:`~PIL.ImageColor.getrgb` for most modes. However, if
+ ``mode`` is HSV, converts the RGB value to a HSV value, or if ``mode`` is
+ not color or a palette image, converts the RGB value to a grayscale value.
+ If the string cannot be parsed, this function raises a :py:exc:`ValueError`
+ exception.
+
+ .. versionadded:: 1.1.4
+
+ :param color: A color string
+ :param mode: Convert result to this mode
+ :return: ``graylevel, (graylevel, alpha) or (red, green, blue[, alpha])``
+ """
+ # same as getrgb, but converts the result to the given mode
+ rgb, alpha = getrgb(color), 255
+ if len(rgb) == 4:
+ alpha = rgb[3]
+ rgb = rgb[:3]
+
+ if mode == "HSV":
+ from colorsys import rgb_to_hsv
+
+ r, g, b = rgb
+ h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
+ return int(h * 255), int(s * 255), int(v * 255)
+ elif Image.getmodebase(mode) == "L":
+ r, g, b = rgb
+ # ITU-R Recommendation 601-2 for nonlinear RGB
+ # scaled to 24 bits to match the convert's implementation.
+ graylevel = (r * 19595 + g * 38470 + b * 7471 + 0x8000) >> 16
+ if mode[-1] == "A":
+ return graylevel, alpha
+ return graylevel
+ elif mode[-1] == "A":
+ return rgb + (alpha,)
+ return rgb
+
+
+colormap: dict[str, str | tuple[int, int, int]] = {
+ # X11 colour table from https://drafts.csswg.org/css-color-4/, with
+ # gray/grey spelling issues fixed. This is a superset of HTML 4.0
+ # colour names used in CSS 1.
+ "aliceblue": "#f0f8ff",
+ "antiquewhite": "#faebd7",
+ "aqua": "#00ffff",
+ "aquamarine": "#7fffd4",
+ "azure": "#f0ffff",
+ "beige": "#f5f5dc",
+ "bisque": "#ffe4c4",
+ "black": "#000000",
+ "blanchedalmond": "#ffebcd",
+ "blue": "#0000ff",
+ "blueviolet": "#8a2be2",
+ "brown": "#a52a2a",
+ "burlywood": "#deb887",
+ "cadetblue": "#5f9ea0",
+ "chartreuse": "#7fff00",
+ "chocolate": "#d2691e",
+ "coral": "#ff7f50",
+ "cornflowerblue": "#6495ed",
+ "cornsilk": "#fff8dc",
+ "crimson": "#dc143c",
+ "cyan": "#00ffff",
+ "darkblue": "#00008b",
+ "darkcyan": "#008b8b",
+ "darkgoldenrod": "#b8860b",
+ "darkgray": "#a9a9a9",
+ "darkgrey": "#a9a9a9",
+ "darkgreen": "#006400",
+ "darkkhaki": "#bdb76b",
+ "darkmagenta": "#8b008b",
+ "darkolivegreen": "#556b2f",
+ "darkorange": "#ff8c00",
+ "darkorchid": "#9932cc",
+ "darkred": "#8b0000",
+ "darksalmon": "#e9967a",
+ "darkseagreen": "#8fbc8f",
+ "darkslateblue": "#483d8b",
+ "darkslategray": "#2f4f4f",
+ "darkslategrey": "#2f4f4f",
+ "darkturquoise": "#00ced1",
+ "darkviolet": "#9400d3",
+ "deeppink": "#ff1493",
+ "deepskyblue": "#00bfff",
+ "dimgray": "#696969",
+ "dimgrey": "#696969",
+ "dodgerblue": "#1e90ff",
+ "firebrick": "#b22222",
+ "floralwhite": "#fffaf0",
+ "forestgreen": "#228b22",
+ "fuchsia": "#ff00ff",
+ "gainsboro": "#dcdcdc",
+ "ghostwhite": "#f8f8ff",
+ "gold": "#ffd700",
+ "goldenrod": "#daa520",
+ "gray": "#808080",
+ "grey": "#808080",
+ "green": "#008000",
+ "greenyellow": "#adff2f",
+ "honeydew": "#f0fff0",
+ "hotpink": "#ff69b4",
+ "indianred": "#cd5c5c",
+ "indigo": "#4b0082",
+ "ivory": "#fffff0",
+ "khaki": "#f0e68c",
+ "lavender": "#e6e6fa",
+ "lavenderblush": "#fff0f5",
+ "lawngreen": "#7cfc00",
+ "lemonchiffon": "#fffacd",
+ "lightblue": "#add8e6",
+ "lightcoral": "#f08080",
+ "lightcyan": "#e0ffff",
+ "lightgoldenrodyellow": "#fafad2",
+ "lightgreen": "#90ee90",
+ "lightgray": "#d3d3d3",
+ "lightgrey": "#d3d3d3",
+ "lightpink": "#ffb6c1",
+ "lightsalmon": "#ffa07a",
+ "lightseagreen": "#20b2aa",
+ "lightskyblue": "#87cefa",
+ "lightslategray": "#778899",
+ "lightslategrey": "#778899",
+ "lightsteelblue": "#b0c4de",
+ "lightyellow": "#ffffe0",
+ "lime": "#00ff00",
+ "limegreen": "#32cd32",
+ "linen": "#faf0e6",
+ "magenta": "#ff00ff",
+ "maroon": "#800000",
+ "mediumaquamarine": "#66cdaa",
+ "mediumblue": "#0000cd",
+ "mediumorchid": "#ba55d3",
+ "mediumpurple": "#9370db",
+ "mediumseagreen": "#3cb371",
+ "mediumslateblue": "#7b68ee",
+ "mediumspringgreen": "#00fa9a",
+ "mediumturquoise": "#48d1cc",
+ "mediumvioletred": "#c71585",
+ "midnightblue": "#191970",
+ "mintcream": "#f5fffa",
+ "mistyrose": "#ffe4e1",
+ "moccasin": "#ffe4b5",
+ "navajowhite": "#ffdead",
+ "navy": "#000080",
+ "oldlace": "#fdf5e6",
+ "olive": "#808000",
+ "olivedrab": "#6b8e23",
+ "orange": "#ffa500",
+ "orangered": "#ff4500",
+ "orchid": "#da70d6",
+ "palegoldenrod": "#eee8aa",
+ "palegreen": "#98fb98",
+ "paleturquoise": "#afeeee",
+ "palevioletred": "#db7093",
+ "papayawhip": "#ffefd5",
+ "peachpuff": "#ffdab9",
+ "peru": "#cd853f",
+ "pink": "#ffc0cb",
+ "plum": "#dda0dd",
+ "powderblue": "#b0e0e6",
+ "purple": "#800080",
+ "rebeccapurple": "#663399",
+ "red": "#ff0000",
+ "rosybrown": "#bc8f8f",
+ "royalblue": "#4169e1",
+ "saddlebrown": "#8b4513",
+ "salmon": "#fa8072",
+ "sandybrown": "#f4a460",
+ "seagreen": "#2e8b57",
+ "seashell": "#fff5ee",
+ "sienna": "#a0522d",
+ "silver": "#c0c0c0",
+ "skyblue": "#87ceeb",
+ "slateblue": "#6a5acd",
+ "slategray": "#708090",
+ "slategrey": "#708090",
+ "snow": "#fffafa",
+ "springgreen": "#00ff7f",
+ "steelblue": "#4682b4",
+ "tan": "#d2b48c",
+ "teal": "#008080",
+ "thistle": "#d8bfd8",
+ "tomato": "#ff6347",
+ "turquoise": "#40e0d0",
+ "violet": "#ee82ee",
+ "wheat": "#f5deb3",
+ "white": "#ffffff",
+ "whitesmoke": "#f5f5f5",
+ "yellow": "#ffff00",
+ "yellowgreen": "#9acd32",
+}
diff --git a/venv/Lib/site-packages/PIL/ImageDraw.py b/venv/Lib/site-packages/PIL/ImageDraw.py
new file mode 100644
index 0000000..8bcf2d8
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageDraw.py
@@ -0,0 +1,1036 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# drawing interface operations
+#
+# History:
+# 1996-04-13 fl Created (experimental)
+# 1996-08-07 fl Filled polygons, ellipses.
+# 1996-08-13 fl Added text support
+# 1998-06-28 fl Handle I and F images
+# 1998-12-29 fl Added arc; use arc primitive to draw ellipses
+# 1999-01-10 fl Added shape stuff (experimental)
+# 1999-02-06 fl Added bitmap support
+# 1999-02-11 fl Changed all primitives to take options
+# 1999-02-20 fl Fixed backwards compatibility
+# 2000-10-12 fl Copy on write, when necessary
+# 2001-02-18 fl Use default ink for bitmap/text also in fill mode
+# 2002-10-24 fl Added support for CSS-style color strings
+# 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing
+# 2002-12-11 fl Refactored low-level drawing API (work in progress)
+# 2004-08-26 fl Made Draw() a factory function, added getdraw() support
+# 2004-09-04 fl Added width support to line primitive
+# 2004-09-10 fl Added font mode handling
+# 2006-06-19 fl Added font bearing support (getmask2)
+#
+# Copyright (c) 1997-2006 by Secret Labs AB
+# Copyright (c) 1996-2006 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import math
+import struct
+from collections.abc import Sequence
+from typing import cast
+
+from . import Image, ImageColor, ImageText
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from types import ModuleType
+ from typing import Any, AnyStr
+
+ from . import ImageDraw2, ImageFont
+ from ._typing import Coords, _Ink
+
+# experimental access to the outline API
+Outline: Callable[[], Image.core._Outline] = Image.core.outline
+
+"""
+A simple 2D drawing interface for PIL images.
+
+Application code should use the Draw factory, instead of
+directly.
+"""
+
+
+class ImageDraw:
+ font: (
+ ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont | None
+ ) = None
+
+ def __init__(self, im: Image.Image, mode: str | None = None) -> None:
+ """
+ Create a drawing instance.
+
+ :param im: The image to draw in.
+ :param mode: Optional mode to use for color values. For RGB
+ images, this argument can be RGB or RGBA (to blend the
+ drawing into the image). For all other modes, this argument
+ must be the same as the image mode. If omitted, the mode
+ defaults to the mode of the image.
+ """
+ im._ensure_mutable()
+ blend = 0
+ if mode is None:
+ mode = im.mode
+ if mode != im.mode:
+ if mode == "RGBA" and im.mode == "RGB":
+ blend = 1
+ else:
+ msg = "mode mismatch"
+ raise ValueError(msg)
+ if mode == "P":
+ self.palette = im.palette
+ else:
+ self.palette = None
+ self._image = im
+ self.im = im.im
+ self.draw = Image.core.draw(self.im, blend)
+ self.mode = mode
+ if mode in ("I", "F"):
+ self.ink = self.draw.draw_ink(1)
+ else:
+ self.ink = self.draw.draw_ink(-1)
+ if mode in ("1", "P", "I", "F"):
+ # FIXME: fix Fill2 to properly support matte for I+F images
+ self.fontmode = "1"
+ else:
+ self.fontmode = "L" # aliasing is okay for other modes
+ self.fill = False
+
+ def getfont(
+ self,
+ ) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
+ """
+ Get the current default font.
+
+ To set the default font for this ImageDraw instance::
+
+ from PIL import ImageDraw, ImageFont
+ draw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
+
+ To set the default font for all future ImageDraw instances::
+
+ from PIL import ImageDraw, ImageFont
+ ImageDraw.ImageDraw.font = ImageFont.truetype("Tests/fonts/FreeMono.ttf")
+
+ If the current default font is ``None``,
+ it is initialized with ``ImageFont.load_default()``.
+
+ :returns: An image font."""
+ if not self.font:
+ # FIXME: should add a font repository
+ from . import ImageFont
+
+ self.font = ImageFont.load_default()
+ return self.font
+
+ def _getfont(
+ self, font_size: float | None
+ ) -> ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont:
+ if font_size is not None:
+ from . import ImageFont
+
+ return ImageFont.load_default(font_size)
+ else:
+ return self.getfont()
+
+ def _getink(
+ self, ink: _Ink | None, fill: _Ink | None = None
+ ) -> tuple[int | None, int | None]:
+ result_ink = None
+ result_fill = None
+ if ink is None and fill is None:
+ if self.fill:
+ result_fill = self.ink
+ else:
+ result_ink = self.ink
+ else:
+ if ink is not None:
+ if isinstance(ink, str):
+ ink = ImageColor.getcolor(ink, self.mode)
+ if self.palette and isinstance(ink, tuple):
+ ink = self.palette.getcolor(ink, self._image)
+ result_ink = self.draw.draw_ink(ink)
+ if fill is not None:
+ if isinstance(fill, str):
+ fill = ImageColor.getcolor(fill, self.mode)
+ if self.palette and isinstance(fill, tuple):
+ fill = self.palette.getcolor(fill, self._image)
+ result_fill = self.draw.draw_ink(fill)
+ return result_ink, result_fill
+
+ def arc(
+ self,
+ xy: Coords,
+ start: float,
+ end: float,
+ fill: _Ink | None = None,
+ width: int = 1,
+ ) -> None:
+ """Draw an arc."""
+ ink, fill = self._getink(fill)
+ if ink is not None:
+ self.draw.draw_arc(xy, start, end, ink, width)
+
+ def bitmap(
+ self, xy: Sequence[int], bitmap: Image.Image, fill: _Ink | None = None
+ ) -> None:
+ """Draw a bitmap."""
+ bitmap.load()
+ ink, fill = self._getink(fill)
+ if ink is None:
+ ink = fill
+ if ink is not None:
+ self.draw.draw_bitmap(xy, bitmap.im, ink)
+
+ def chord(
+ self,
+ xy: Coords,
+ start: float,
+ end: float,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ width: int = 1,
+ ) -> None:
+ """Draw a chord."""
+ ink, fill_ink = self._getink(outline, fill)
+ if fill_ink is not None:
+ self.draw.draw_chord(xy, start, end, fill_ink, 1)
+ if ink is not None and ink != fill_ink and width != 0:
+ self.draw.draw_chord(xy, start, end, ink, 0, width)
+
+ def ellipse(
+ self,
+ xy: Coords,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ width: int = 1,
+ ) -> None:
+ """Draw an ellipse."""
+ ink, fill_ink = self._getink(outline, fill)
+ if fill_ink is not None:
+ self.draw.draw_ellipse(xy, fill_ink, 1)
+ if ink is not None and ink != fill_ink and width != 0:
+ self.draw.draw_ellipse(xy, ink, 0, width)
+
+ def circle(
+ self,
+ xy: Sequence[float],
+ radius: float,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ width: int = 1,
+ ) -> None:
+ """Draw a circle given center coordinates and a radius."""
+ ellipse_xy = (xy[0] - radius, xy[1] - radius, xy[0] + radius, xy[1] + radius)
+ self.ellipse(ellipse_xy, fill, outline, width)
+
+ def line(
+ self,
+ xy: Coords,
+ fill: _Ink | None = None,
+ width: int = 0,
+ joint: str | None = None,
+ ) -> None:
+ """Draw a line, or a connected sequence of line segments."""
+ ink = self._getink(fill)[0]
+ if ink is not None:
+ self.draw.draw_lines(xy, ink, width)
+ if joint == "curve" and width > 4:
+ points: Sequence[Sequence[float]]
+ if isinstance(xy[0], (list, tuple)):
+ points = cast(Sequence[Sequence[float]], xy)
+ else:
+ points = [
+ cast(Sequence[float], tuple(xy[i : i + 2]))
+ for i in range(0, len(xy), 2)
+ ]
+ for i in range(1, len(points) - 1):
+ point = points[i]
+ angles = [
+ math.degrees(math.atan2(end[0] - start[0], start[1] - end[1]))
+ % 360
+ for start, end in (
+ (points[i - 1], point),
+ (point, points[i + 1]),
+ )
+ ]
+ if angles[0] == angles[1]:
+ # This is a straight line, so no joint is required
+ continue
+
+ def coord_at_angle(
+ coord: Sequence[float], angle: float
+ ) -> tuple[float, ...]:
+ x, y = coord
+ angle -= 90
+ distance = width / 2 - 1
+ return tuple(
+ p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
+ for p, p_d in (
+ (x, distance * math.cos(math.radians(angle))),
+ (y, distance * math.sin(math.radians(angle))),
+ )
+ )
+
+ flipped = (
+ angles[1] > angles[0] and angles[1] - 180 > angles[0]
+ ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0])
+ coords = [
+ (point[0] - width / 2 + 1, point[1] - width / 2 + 1),
+ (point[0] + width / 2 - 1, point[1] + width / 2 - 1),
+ ]
+ if flipped:
+ start, end = (angles[1] + 90, angles[0] + 90)
+ else:
+ start, end = (angles[0] - 90, angles[1] - 90)
+ self.pieslice(coords, start - 90, end - 90, fill)
+
+ if width > 8:
+ # Cover potential gaps between the line and the joint
+ if flipped:
+ gap_coords = [
+ coord_at_angle(point, angles[0] + 90),
+ point,
+ coord_at_angle(point, angles[1] + 90),
+ ]
+ else:
+ gap_coords = [
+ coord_at_angle(point, angles[0] - 90),
+ point,
+ coord_at_angle(point, angles[1] - 90),
+ ]
+ self.line(gap_coords, fill, width=3)
+
+ def shape(
+ self,
+ shape: Image.core._Outline,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ ) -> None:
+ """(Experimental) Draw a shape."""
+ shape.close()
+ ink, fill_ink = self._getink(outline, fill)
+ if fill_ink is not None:
+ self.draw.draw_outline(shape, fill_ink, 1)
+ if ink is not None and ink != fill_ink:
+ self.draw.draw_outline(shape, ink, 0)
+
+ def pieslice(
+ self,
+ xy: Coords,
+ start: float,
+ end: float,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ width: int = 1,
+ ) -> None:
+ """Draw a pieslice."""
+ ink, fill_ink = self._getink(outline, fill)
+ if fill_ink is not None:
+ self.draw.draw_pieslice(xy, start, end, fill_ink, 1)
+ if ink is not None and ink != fill_ink and width != 0:
+ self.draw.draw_pieslice(xy, start, end, ink, 0, width)
+
+ def point(self, xy: Coords, fill: _Ink | None = None) -> None:
+ """Draw one or more individual pixels."""
+ ink, fill = self._getink(fill)
+ if ink is not None:
+ self.draw.draw_points(xy, ink)
+
+ def polygon(
+ self,
+ xy: Coords,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ width: int = 1,
+ ) -> None:
+ """Draw a polygon."""
+ ink, fill_ink = self._getink(outline, fill)
+ if fill_ink is not None:
+ self.draw.draw_polygon(xy, fill_ink, 1)
+ if ink is not None and ink != fill_ink and width != 0:
+ if width == 1:
+ self.draw.draw_polygon(xy, ink, 0, width)
+ elif self.im is not None:
+ # To avoid expanding the polygon outwards,
+ # use the fill as a mask
+ mask = Image.new("1", self.im.size)
+ mask_ink = self._getink(1)[0]
+ draw = Draw(mask)
+ draw.draw.draw_polygon(xy, mask_ink, 1)
+
+ self.draw.draw_polygon(xy, ink, 0, width * 2 - 1, mask.im)
+
+ def regular_polygon(
+ self,
+ bounding_circle: Sequence[Sequence[float] | float],
+ n_sides: int,
+ rotation: float = 0,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ width: int = 1,
+ ) -> None:
+ """Draw a regular polygon."""
+ xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation)
+ self.polygon(xy, fill, outline, width)
+
+ def rectangle(
+ self,
+ xy: Coords,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ width: int = 1,
+ ) -> None:
+ """Draw a rectangle."""
+ ink, fill_ink = self._getink(outline, fill)
+ if fill_ink is not None:
+ self.draw.draw_rectangle(xy, fill_ink, 1)
+ if ink is not None and ink != fill_ink and width != 0:
+ self.draw.draw_rectangle(xy, ink, 0, width)
+
+ def rounded_rectangle(
+ self,
+ xy: Coords,
+ radius: float = 0,
+ fill: _Ink | None = None,
+ outline: _Ink | None = None,
+ width: int = 1,
+ *,
+ corners: tuple[bool, bool, bool, bool] | None = None,
+ ) -> None:
+ """Draw a rounded rectangle."""
+ if isinstance(xy[0], (list, tuple)):
+ (x0, y0), (x1, y1) = cast(Sequence[Sequence[float]], xy)
+ else:
+ x0, y0, x1, y1 = cast(Sequence[float], xy)
+ if x1 < x0:
+ msg = "x1 must be greater than or equal to x0"
+ raise ValueError(msg)
+ if y1 < y0:
+ msg = "y1 must be greater than or equal to y0"
+ raise ValueError(msg)
+ if corners is None:
+ corners = (True, True, True, True)
+
+ d = radius * 2
+
+ x0 = round(x0)
+ y0 = round(y0)
+ x1 = round(x1)
+ y1 = round(y1)
+ full_x, full_y = False, False
+ if all(corners):
+ full_x = d >= x1 - x0 - 1
+ if full_x:
+ # The two left and two right corners are joined
+ d = x1 - x0
+ full_y = d >= y1 - y0 - 1
+ if full_y:
+ # The two top and two bottom corners are joined
+ d = y1 - y0
+ if full_x and full_y:
+ # If all corners are joined, that is a circle
+ return self.ellipse(xy, fill, outline, width)
+
+ if d == 0 or not any(corners):
+ # If the corners have no curve,
+ # or there are no corners,
+ # that is a rectangle
+ return self.rectangle(xy, fill, outline, width)
+
+ r = int(d // 2)
+ ink, fill_ink = self._getink(outline, fill)
+
+ def draw_corners(pieslice: bool) -> None:
+ parts: tuple[tuple[tuple[float, float, float, float], int, int], ...]
+ if full_x:
+ # Draw top and bottom halves
+ parts = (
+ ((x0, y0, x0 + d, y0 + d), 180, 360),
+ ((x0, y1 - d, x0 + d, y1), 0, 180),
+ )
+ elif full_y:
+ # Draw left and right halves
+ parts = (
+ ((x0, y0, x0 + d, y0 + d), 90, 270),
+ ((x1 - d, y0, x1, y0 + d), 270, 90),
+ )
+ else:
+ # Draw four separate corners
+ parts = tuple(
+ part
+ for i, part in enumerate(
+ (
+ ((x0, y0, x0 + d, y0 + d), 180, 270),
+ ((x1 - d, y0, x1, y0 + d), 270, 360),
+ ((x1 - d, y1 - d, x1, y1), 0, 90),
+ ((x0, y1 - d, x0 + d, y1), 90, 180),
+ )
+ )
+ if corners[i]
+ )
+ for part in parts:
+ if pieslice:
+ self.draw.draw_pieslice(*(part + (fill_ink, 1)))
+ else:
+ self.draw.draw_arc(*(part + (ink, width)))
+
+ if fill_ink is not None:
+ draw_corners(True)
+
+ if full_x:
+ self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill_ink, 1)
+ elif x1 - r - 1 > x0 + r + 1:
+ self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill_ink, 1)
+ if not full_x and not full_y:
+ left = [x0, y0, x0 + r, y1]
+ if corners[0]:
+ left[1] += r + 1
+ if corners[3]:
+ left[3] -= r + 1
+ self.draw.draw_rectangle(left, fill_ink, 1)
+
+ right = [x1 - r, y0, x1, y1]
+ if corners[1]:
+ right[1] += r + 1
+ if corners[2]:
+ right[3] -= r + 1
+ self.draw.draw_rectangle(right, fill_ink, 1)
+ if ink is not None and ink != fill_ink and width != 0:
+ draw_corners(False)
+
+ if not full_x:
+ top = [x0, y0, x1, y0 + width - 1]
+ if corners[0]:
+ top[0] += r + 1
+ if corners[1]:
+ top[2] -= r + 1
+ self.draw.draw_rectangle(top, ink, 1)
+
+ bottom = [x0, y1 - width + 1, x1, y1]
+ if corners[3]:
+ bottom[0] += r + 1
+ if corners[2]:
+ bottom[2] -= r + 1
+ self.draw.draw_rectangle(bottom, ink, 1)
+ if not full_y:
+ left = [x0, y0, x0 + width - 1, y1]
+ if corners[0]:
+ left[1] += r + 1
+ if corners[3]:
+ left[3] -= r + 1
+ self.draw.draw_rectangle(left, ink, 1)
+
+ right = [x1 - width + 1, y0, x1, y1]
+ if corners[1]:
+ right[1] += r + 1
+ if corners[2]:
+ right[3] -= r + 1
+ self.draw.draw_rectangle(right, ink, 1)
+
+ def text(
+ self,
+ xy: tuple[float, float],
+ text: AnyStr | ImageText.Text,
+ fill: _Ink | None = None,
+ font: (
+ ImageFont.ImageFont
+ | ImageFont.FreeTypeFont
+ | ImageFont.TransposedFont
+ | None
+ ) = None,
+ anchor: str | None = None,
+ spacing: float = 4,
+ align: str = "left",
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ stroke_width: float = 0,
+ stroke_fill: _Ink | None = None,
+ embedded_color: bool = False,
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ """Draw text."""
+ if isinstance(text, ImageText.Text):
+ image_text = text
+ else:
+ if font is None:
+ font = self._getfont(kwargs.get("font_size"))
+ image_text = ImageText.Text(
+ text, font, self.mode, spacing, direction, features, language
+ )
+ if embedded_color:
+ image_text.embed_color()
+ if stroke_width:
+ image_text.stroke(stroke_width, stroke_fill)
+
+ def getink(fill: _Ink | None) -> int:
+ ink, fill_ink = self._getink(fill)
+ if ink is None:
+ assert fill_ink is not None
+ return fill_ink
+ return ink
+
+ ink = getink(fill)
+ if ink is None:
+ return
+
+ stroke_ink = None
+ if image_text.stroke_width:
+ stroke_ink = (
+ getink(image_text.stroke_fill)
+ if image_text.stroke_fill is not None
+ else ink
+ )
+
+ for xy, anchor, line in image_text._split(xy, anchor, align):
+
+ def draw_text(ink: int, stroke_width: float = 0) -> None:
+ mode = self.fontmode
+ if stroke_width == 0 and embedded_color:
+ mode = "RGBA"
+ coord = []
+ for i in range(2):
+ coord.append(int(xy[i]))
+ start = (math.modf(xy[0])[0], math.modf(xy[1])[0])
+ try:
+ mask, offset = image_text.font.getmask2( # type: ignore[union-attr,misc]
+ line,
+ mode,
+ direction=direction,
+ features=features,
+ language=language,
+ stroke_width=stroke_width,
+ stroke_filled=True,
+ anchor=anchor,
+ ink=ink,
+ start=start,
+ *args,
+ **kwargs,
+ )
+ coord = [coord[0] + offset[0], coord[1] + offset[1]]
+ except AttributeError:
+ try:
+ mask = image_text.font.getmask( # type: ignore[misc]
+ line,
+ mode,
+ direction,
+ features,
+ language,
+ stroke_width,
+ anchor,
+ ink,
+ start=start,
+ *args,
+ **kwargs,
+ )
+ except TypeError:
+ mask = image_text.font.getmask(line)
+ if mode == "RGBA":
+ # image_text.font.getmask2(mode="RGBA")
+ # returns color in RGB bands and mask in A
+ # extract mask and set text alpha
+ color, mask = mask, mask.getband(3)
+ ink_alpha = struct.pack("i", ink)[3]
+ color.fillband(3, ink_alpha)
+ x, y = coord
+ if self.im is not None:
+ self.im.paste(
+ color, (x, y, x + mask.size[0], y + mask.size[1]), mask
+ )
+ else:
+ self.draw.draw_bitmap(coord, mask, ink)
+
+ if stroke_ink is not None:
+ # Draw stroked text
+ draw_text(stroke_ink, image_text.stroke_width)
+
+ # Draw normal text
+ if ink != stroke_ink:
+ draw_text(ink)
+ else:
+ # Only draw normal text
+ draw_text(ink)
+
+ def multiline_text(
+ self,
+ xy: tuple[float, float],
+ text: AnyStr,
+ fill: _Ink | None = None,
+ font: (
+ ImageFont.ImageFont
+ | ImageFont.FreeTypeFont
+ | ImageFont.TransposedFont
+ | None
+ ) = None,
+ anchor: str | None = None,
+ spacing: float = 4,
+ align: str = "left",
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ stroke_width: float = 0,
+ stroke_fill: _Ink | None = None,
+ embedded_color: bool = False,
+ *,
+ font_size: float | None = None,
+ ) -> None:
+ return self.text(
+ xy,
+ text,
+ fill,
+ font,
+ anchor,
+ spacing,
+ align,
+ direction,
+ features,
+ language,
+ stroke_width,
+ stroke_fill,
+ embedded_color,
+ font_size=font_size,
+ )
+
+ def textlength(
+ self,
+ text: AnyStr,
+ font: (
+ ImageFont.ImageFont
+ | ImageFont.FreeTypeFont
+ | ImageFont.TransposedFont
+ | None
+ ) = None,
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ embedded_color: bool = False,
+ *,
+ font_size: float | None = None,
+ ) -> float:
+ """Get the length of a given string, in pixels with 1/64 precision."""
+ if font is None:
+ font = self._getfont(font_size)
+ image_text = ImageText.Text(
+ text,
+ font,
+ self.mode,
+ direction=direction,
+ features=features,
+ language=language,
+ )
+ if embedded_color:
+ image_text.embed_color()
+ return image_text.get_length()
+
+ def textbbox(
+ self,
+ xy: tuple[float, float],
+ text: AnyStr,
+ font: (
+ ImageFont.ImageFont
+ | ImageFont.FreeTypeFont
+ | ImageFont.TransposedFont
+ | None
+ ) = None,
+ anchor: str | None = None,
+ spacing: float = 4,
+ align: str = "left",
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ stroke_width: float = 0,
+ embedded_color: bool = False,
+ *,
+ font_size: float | None = None,
+ ) -> tuple[float, float, float, float]:
+ """Get the bounding box of a given string, in pixels."""
+ if font is None:
+ font = self._getfont(font_size)
+ image_text = ImageText.Text(
+ text, font, self.mode, spacing, direction, features, language
+ )
+ if embedded_color:
+ image_text.embed_color()
+ if stroke_width:
+ image_text.stroke(stroke_width)
+ return image_text.get_bbox(xy, anchor, align)
+
+ def multiline_textbbox(
+ self,
+ xy: tuple[float, float],
+ text: AnyStr,
+ font: (
+ ImageFont.ImageFont
+ | ImageFont.FreeTypeFont
+ | ImageFont.TransposedFont
+ | None
+ ) = None,
+ anchor: str | None = None,
+ spacing: float = 4,
+ align: str = "left",
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ stroke_width: float = 0,
+ embedded_color: bool = False,
+ *,
+ font_size: float | None = None,
+ ) -> tuple[float, float, float, float]:
+ return self.textbbox(
+ xy,
+ text,
+ font,
+ anchor,
+ spacing,
+ align,
+ direction,
+ features,
+ language,
+ stroke_width,
+ embedded_color,
+ font_size=font_size,
+ )
+
+
+def Draw(im: Image.Image, mode: str | None = None) -> ImageDraw:
+ """
+ A simple 2D drawing interface for PIL images.
+
+ :param im: The image to draw in.
+ :param mode: Optional mode to use for color values. For RGB
+ images, this argument can be RGB or RGBA (to blend the
+ drawing into the image). For all other modes, this argument
+ must be the same as the image mode. If omitted, the mode
+ defaults to the mode of the image.
+ """
+ try:
+ return getattr(im, "getdraw")(mode)
+ except AttributeError:
+ return ImageDraw(im, mode)
+
+
+def getdraw(im: Image.Image | None = None) -> tuple[ImageDraw2.Draw | None, ModuleType]:
+ """
+ :param im: The image to draw in.
+ :returns: A (drawing context, drawing resource factory) tuple.
+ """
+ from . import ImageDraw2
+
+ draw = ImageDraw2.Draw(im) if im is not None else None
+ return draw, ImageDraw2
+
+
+def floodfill(
+ image: Image.Image,
+ xy: tuple[int, int],
+ value: float | tuple[int, ...],
+ border: float | tuple[int, ...] | None = None,
+ thresh: float = 0,
+) -> None:
+ """
+ .. warning:: This method is experimental.
+
+ Fills a bounded region with a given color.
+
+ :param image: Target image.
+ :param xy: Seed position (a 2-item coordinate tuple). See
+ :ref:`coordinate-system`.
+ :param value: Fill color.
+ :param border: Optional border value. If given, the region consists of
+ pixels with a color different from the border color. If not given,
+ the region consists of pixels having the same color as the seed
+ pixel.
+ :param thresh: Optional threshold value which specifies a maximum
+ tolerable difference of a pixel value from the 'background' in
+ order for it to be replaced. Useful for filling regions of
+ non-homogeneous, but similar, colors.
+ """
+ # based on an implementation by Eric S. Raymond
+ # amended by yo1995 @20180806
+ pixel = image.load()
+ assert pixel is not None
+ x, y = xy
+ try:
+ background = pixel[x, y]
+ if _color_diff(value, background) <= thresh:
+ return # seed point already has fill color
+ pixel[x, y] = value
+ except (ValueError, IndexError):
+ return # seed point outside image
+ edge = {(x, y)}
+ # use a set to keep record of current and previous edge pixels
+ # to reduce memory consumption
+ full_edge = set()
+ while edge:
+ new_edge = set()
+ for x, y in edge: # 4 adjacent method
+ for s, t in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
+ # If already processed, or if a coordinate is negative, skip
+ if (s, t) in full_edge or s < 0 or t < 0:
+ continue
+ try:
+ p = pixel[s, t]
+ except (ValueError, IndexError):
+ pass
+ else:
+ full_edge.add((s, t))
+ if border is None:
+ fill = _color_diff(p, background) <= thresh
+ else:
+ fill = p not in (value, border)
+ if fill:
+ pixel[s, t] = value
+ new_edge.add((s, t))
+ full_edge = edge # discard pixels processed
+ edge = new_edge
+
+
+def _compute_regular_polygon_vertices(
+ bounding_circle: Sequence[Sequence[float] | float], n_sides: int, rotation: float
+) -> list[tuple[float, float]]:
+ """
+ Generate a list of vertices for a 2D regular polygon.
+
+ :param bounding_circle: The bounding circle is a sequence defined
+ by a point and radius. The polygon is inscribed in this circle.
+ (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``)
+ :param n_sides: Number of sides
+ (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon)
+ :param rotation: Apply an arbitrary rotation to the polygon
+ (e.g. ``rotation=90``, applies a 90 degree rotation)
+ :return: List of regular polygon vertices
+ (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``)
+
+ How are the vertices computed?
+ 1. Compute the following variables
+ - theta: Angle between the apothem & the nearest polygon vertex
+ - side_length: Length of each polygon edge
+ - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle)
+ - polygon_radius: Polygon radius (last element of bounding_circle)
+ - angles: Location of each polygon vertex in polar grid
+ (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0])
+
+ 2. For each angle in angles, get the polygon vertex at that angle
+ The vertex is computed using the equation below.
+ X= xcos(φ) + ysin(φ)
+ Y= −xsin(φ) + ycos(φ)
+
+ Note:
+ φ = angle in degrees
+ x = 0
+ y = polygon_radius
+
+ The formula above assumes rotation around the origin.
+ In our case, we are rotating around the centroid.
+ To account for this, we use the formula below
+ X = xcos(φ) + ysin(φ) + centroid_x
+ Y = −xsin(φ) + ycos(φ) + centroid_y
+ """
+ # 1. Error Handling
+ # 1.1 Check `n_sides` has an appropriate value
+ if not isinstance(n_sides, int):
+ msg = "n_sides should be an int" # type: ignore[unreachable]
+ raise TypeError(msg)
+ if n_sides < 3:
+ msg = "n_sides should be an int > 2"
+ raise ValueError(msg)
+
+ # 1.2 Check `bounding_circle` has an appropriate value
+ if not isinstance(bounding_circle, (list, tuple)):
+ msg = "bounding_circle should be a sequence"
+ raise TypeError(msg)
+
+ if len(bounding_circle) == 3:
+ if not all(isinstance(i, (int, float)) for i in bounding_circle):
+ msg = "bounding_circle should only contain numeric data"
+ raise ValueError(msg)
+
+ *centroid, polygon_radius = cast(list[float], list(bounding_circle))
+ elif len(bounding_circle) == 2 and isinstance(bounding_circle[0], (list, tuple)):
+ if not all(
+ isinstance(i, (int, float)) for i in bounding_circle[0]
+ ) or not isinstance(bounding_circle[1], (int, float)):
+ msg = "bounding_circle should only contain numeric data"
+ raise ValueError(msg)
+
+ if len(bounding_circle[0]) != 2:
+ msg = "bounding_circle centre should contain 2D coordinates (e.g. (x, y))"
+ raise ValueError(msg)
+
+ centroid = cast(list[float], list(bounding_circle[0]))
+ polygon_radius = cast(float, bounding_circle[1])
+ else:
+ msg = (
+ "bounding_circle should contain 2D coordinates "
+ "and a radius (e.g. (x, y, r) or ((x, y), r) )"
+ )
+ raise ValueError(msg)
+
+ if polygon_radius <= 0:
+ msg = "bounding_circle radius should be > 0"
+ raise ValueError(msg)
+
+ # 1.3 Check `rotation` has an appropriate value
+ if not isinstance(rotation, (int, float)):
+ msg = "rotation should be an int or float" # type: ignore[unreachable]
+ raise ValueError(msg)
+
+ # 2. Define Helper Functions
+ def _apply_rotation(point: list[float], degrees: float) -> tuple[float, float]:
+ return (
+ round(
+ point[0] * math.cos(math.radians(360 - degrees))
+ - point[1] * math.sin(math.radians(360 - degrees))
+ + centroid[0],
+ 2,
+ ),
+ round(
+ point[1] * math.cos(math.radians(360 - degrees))
+ + point[0] * math.sin(math.radians(360 - degrees))
+ + centroid[1],
+ 2,
+ ),
+ )
+
+ def _compute_polygon_vertex(angle: float) -> tuple[float, float]:
+ start_point = [polygon_radius, 0]
+ return _apply_rotation(start_point, angle)
+
+ def _get_angles(n_sides: int, rotation: float) -> list[float]:
+ angles = []
+ degrees = 360 / n_sides
+ # Start with the bottom left polygon vertex
+ current_angle = (270 - 0.5 * degrees) + rotation
+ for _ in range(n_sides):
+ angles.append(current_angle)
+ current_angle += degrees
+ if current_angle > 360:
+ current_angle -= 360
+ return angles
+
+ # 3. Variable Declarations
+ angles = _get_angles(n_sides, rotation)
+
+ # 4. Compute Vertices
+ return [_compute_polygon_vertex(angle) for angle in angles]
+
+
+def _color_diff(
+ color1: float | tuple[int, ...], color2: float | tuple[int, ...]
+) -> float:
+ """
+ Uses 1-norm distance to calculate difference between two values.
+ """
+ first = color1 if isinstance(color1, tuple) else (color1,)
+ second = color2 if isinstance(color2, tuple) else (color2,)
+
+ return sum(abs(first[i] - second[i]) for i in range(len(second)))
diff --git a/venv/Lib/site-packages/PIL/ImageDraw2.py b/venv/Lib/site-packages/PIL/ImageDraw2.py
new file mode 100644
index 0000000..3d68658
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageDraw2.py
@@ -0,0 +1,243 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# WCK-style drawing interface operations
+#
+# History:
+# 2003-12-07 fl created
+# 2005-05-15 fl updated; added to PIL as ImageDraw2
+# 2005-05-15 fl added text support
+# 2005-05-20 fl added arc/chord/pieslice support
+#
+# Copyright (c) 2003-2005 by Secret Labs AB
+# Copyright (c) 2003-2005 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+
+
+"""
+(Experimental) WCK-style drawing interface operations
+
+.. seealso:: :py:mod:`PIL.ImageDraw`
+"""
+from __future__ import annotations
+
+from typing import Any, AnyStr, BinaryIO
+
+from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
+from ._typing import Coords, StrOrBytesPath
+
+
+class Pen:
+ """Stores an outline color and width."""
+
+ def __init__(self, color: str, width: int = 1, opacity: int = 255) -> None:
+ self.color = ImageColor.getrgb(color)
+ self.width = width
+
+
+class Brush:
+ """Stores a fill color"""
+
+ def __init__(self, color: str, opacity: int = 255) -> None:
+ self.color = ImageColor.getrgb(color)
+
+
+class Font:
+ """Stores a TrueType font and color"""
+
+ def __init__(
+ self, color: str, file: StrOrBytesPath | BinaryIO, size: float = 12
+ ) -> None:
+ # FIXME: add support for bitmap fonts
+ self.color = ImageColor.getrgb(color)
+ self.font = ImageFont.truetype(file, size)
+
+
+class Draw:
+ """
+ (Experimental) WCK-style drawing interface
+ """
+
+ def __init__(
+ self,
+ image: Image.Image | str,
+ size: tuple[int, int] | list[int] | None = None,
+ color: float | tuple[float, ...] | str | None = None,
+ ) -> None:
+ if isinstance(image, str):
+ if size is None:
+ msg = "If image argument is mode string, size must be a list or tuple"
+ raise ValueError(msg)
+ image = Image.new(image, size, color)
+ self.draw = ImageDraw.Draw(image)
+ self.image = image
+ self.transform: tuple[float, float, float, float, float, float] | None = None
+
+ def flush(self) -> Image.Image:
+ return self.image
+
+ def render(
+ self,
+ op: str,
+ xy: Coords,
+ pen: Pen | Brush | None,
+ brush: Brush | Pen | None = None,
+ **kwargs: Any,
+ ) -> None:
+ # handle color arguments
+ outline = fill = None
+ width = 1
+ if isinstance(pen, Pen):
+ outline = pen.color
+ width = pen.width
+ elif isinstance(brush, Pen):
+ outline = brush.color
+ width = brush.width
+ if isinstance(brush, Brush):
+ fill = brush.color
+ elif isinstance(pen, Brush):
+ fill = pen.color
+ # handle transformation
+ if self.transform:
+ path = ImagePath.Path(xy)
+ path.transform(self.transform)
+ xy = path
+ # render the item
+ if op in ("arc", "line"):
+ kwargs.setdefault("fill", outline)
+ else:
+ kwargs.setdefault("fill", fill)
+ kwargs.setdefault("outline", outline)
+ if op == "line":
+ kwargs.setdefault("width", width)
+ getattr(self.draw, op)(xy, **kwargs)
+
+ def settransform(self, offset: tuple[float, float]) -> None:
+ """Sets a transformation offset."""
+ (xoffset, yoffset) = offset
+ self.transform = (1, 0, xoffset, 0, 1, yoffset)
+
+ def arc(
+ self,
+ xy: Coords,
+ pen: Pen | Brush | None,
+ start: float,
+ end: float,
+ *options: Any,
+ ) -> None:
+ """
+ Draws an arc (a portion of a circle outline) between the start and end
+ angles, inside the given bounding box.
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
+ """
+ self.render("arc", xy, pen, *options, start=start, end=end)
+
+ def chord(
+ self,
+ xy: Coords,
+ pen: Pen | Brush | None,
+ start: float,
+ end: float,
+ *options: Any,
+ ) -> None:
+ """
+ Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
+ with a straight line.
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
+ """
+ self.render("chord", xy, pen, *options, start=start, end=end)
+
+ def ellipse(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
+ """
+ Draws an ellipse inside the given bounding box.
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
+ """
+ self.render("ellipse", xy, pen, *options)
+
+ def line(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
+ """
+ Draws a line between the coordinates in the ``xy`` list.
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
+ """
+ self.render("line", xy, pen, *options)
+
+ def pieslice(
+ self,
+ xy: Coords,
+ pen: Pen | Brush | None,
+ start: float,
+ end: float,
+ *options: Any,
+ ) -> None:
+ """
+ Same as arc, but also draws straight lines between the end points and the
+ center of the bounding box.
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
+ """
+ self.render("pieslice", xy, pen, *options, start=start, end=end)
+
+ def polygon(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
+ """
+ Draws a polygon.
+
+ The polygon outline consists of straight lines between the given
+ coordinates, plus a straight line between the last and the first
+ coordinate.
+
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
+ """
+ self.render("polygon", xy, pen, *options)
+
+ def rectangle(self, xy: Coords, pen: Pen | Brush | None, *options: Any) -> None:
+ """
+ Draws a rectangle.
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
+ """
+ self.render("rectangle", xy, pen, *options)
+
+ def text(self, xy: tuple[float, float], text: AnyStr, font: Font) -> None:
+ """
+ Draws the string at the given position.
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
+ """
+ if self.transform:
+ path = ImagePath.Path(xy)
+ path.transform(self.transform)
+ xy = path
+ self.draw.text(xy, text, font=font.font, fill=font.color)
+
+ def textbbox(
+ self, xy: tuple[float, float], text: AnyStr, font: Font
+ ) -> tuple[float, float, float, float]:
+ """
+ Returns bounding box (in pixels) of given text.
+
+ :return: ``(left, top, right, bottom)`` bounding box
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textbbox`
+ """
+ if self.transform:
+ path = ImagePath.Path(xy)
+ path.transform(self.transform)
+ xy = path
+ return self.draw.textbbox(xy, text, font=font.font)
+
+ def textlength(self, text: AnyStr, font: Font) -> float:
+ """
+ Returns length (in pixels) of given text.
+ This is the amount by which following text should be offset.
+
+ .. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textlength`
+ """
+ return self.draw.textlength(text, font=font.font)
diff --git a/venv/Lib/site-packages/PIL/ImageEnhance.py b/venv/Lib/site-packages/PIL/ImageEnhance.py
new file mode 100644
index 0000000..0e7e6dd
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageEnhance.py
@@ -0,0 +1,113 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# image enhancement classes
+#
+# For a background, see "Image Processing By Interpolation and
+# Extrapolation", Paul Haeberli and Douglas Voorhies. Available
+# at http://www.graficaobscura.com/interp/index.html
+#
+# History:
+# 1996-03-23 fl Created
+# 2009-06-16 fl Fixed mean calculation
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1996.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from . import Image, ImageFilter, ImageStat
+
+
+class _Enhance:
+ image: Image.Image
+ degenerate: Image.Image
+
+ def enhance(self, factor: float) -> Image.Image:
+ """
+ Returns an enhanced image.
+
+ :param factor: A floating point value controlling the enhancement.
+ Factor 1.0 always returns a copy of the original image,
+ lower factors mean less color (brightness, contrast,
+ etc), and higher values more. There are no restrictions
+ on this value.
+ :rtype: :py:class:`~PIL.Image.Image`
+ """
+ return Image.blend(self.degenerate, self.image, factor)
+
+
+class Color(_Enhance):
+ """Adjust image color balance.
+
+ This class can be used to adjust the colour balance of an image, in
+ a manner similar to the controls on a colour TV set. An enhancement
+ factor of 0.0 gives a black and white image. A factor of 1.0 gives
+ the original image.
+ """
+
+ def __init__(self, image: Image.Image) -> None:
+ self.image = image
+ self.intermediate_mode = "L"
+ if "A" in image.getbands():
+ self.intermediate_mode = "LA"
+
+ if self.intermediate_mode != image.mode:
+ image = image.convert(self.intermediate_mode).convert(image.mode)
+ self.degenerate = image
+
+
+class Contrast(_Enhance):
+ """Adjust image contrast.
+
+ This class can be used to control the contrast of an image, similar
+ to the contrast control on a TV set. An enhancement factor of 0.0
+ gives a solid gray image. A factor of 1.0 gives the original image.
+ """
+
+ def __init__(self, image: Image.Image) -> None:
+ self.image = image
+ if image.mode != "L":
+ image = image.convert("L")
+ mean = int(ImageStat.Stat(image).mean[0] + 0.5)
+ self.degenerate = Image.new("L", image.size, mean)
+ if self.degenerate.mode != self.image.mode:
+ self.degenerate = self.degenerate.convert(self.image.mode)
+
+ if "A" in self.image.getbands():
+ self.degenerate.putalpha(self.image.getchannel("A"))
+
+
+class Brightness(_Enhance):
+ """Adjust image brightness.
+
+ This class can be used to control the brightness of an image. An
+ enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
+ original image.
+ """
+
+ def __init__(self, image: Image.Image) -> None:
+ self.image = image
+ self.degenerate = Image.new(image.mode, image.size, 0)
+
+ if "A" in image.getbands():
+ self.degenerate.putalpha(image.getchannel("A"))
+
+
+class Sharpness(_Enhance):
+ """Adjust image sharpness.
+
+ This class can be used to adjust the sharpness of an image. An
+ enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
+ original image, and a factor of 2.0 gives a sharpened image.
+ """
+
+ def __init__(self, image: Image.Image) -> None:
+ self.image = image
+ self.degenerate = image.filter(ImageFilter.SMOOTH)
+
+ if "A" in image.getbands():
+ self.degenerate.putalpha(image.getchannel("A"))
diff --git a/venv/Lib/site-packages/PIL/ImageFile.py b/venv/Lib/site-packages/PIL/ImageFile.py
new file mode 100644
index 0000000..3390dfa
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageFile.py
@@ -0,0 +1,938 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# base class for image file handlers
+#
+# history:
+# 1995-09-09 fl Created
+# 1996-03-11 fl Fixed load mechanism.
+# 1996-04-15 fl Added pcx/xbm decoders.
+# 1996-04-30 fl Added encoders.
+# 1996-12-14 fl Added load helpers
+# 1997-01-11 fl Use encode_to_file where possible
+# 1997-08-27 fl Flush output in _save
+# 1998-03-05 fl Use memory mapping for some modes
+# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
+# 1999-05-31 fl Added image parser
+# 2000-10-12 fl Set readonly flag on memory-mapped images
+# 2002-03-20 fl Use better messages for common decoder errors
+# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
+# 2003-10-30 fl Added StubImageFile class
+# 2004-02-25 fl Made incremental parser more robust
+#
+# Copyright (c) 1997-2004 by Secret Labs AB
+# Copyright (c) 1995-2004 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import abc
+import io
+import itertools
+import logging
+import os
+import struct
+from typing import IO, Any, NamedTuple, cast
+
+from . import ExifTags, Image
+from ._util import DeferredError, is_path
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from ._typing import StrOrBytesPath
+
+logger = logging.getLogger(__name__)
+
+MAXBLOCK = 65536
+"""
+By default, Pillow processes image data in blocks. This helps to prevent excessive use
+of resources. Codecs may disable this behaviour with ``_pulls_fd`` or ``_pushes_fd``.
+
+When reading an image, this is the number of bytes to read at once.
+
+When writing an image, this is the number of bytes to write at once.
+If the image width times 4 is greater, then that will be used instead.
+Plugins may also set a greater number.
+
+User code may set this to another number.
+"""
+
+SAFEBLOCK = 1024 * 1024
+
+LOAD_TRUNCATED_IMAGES = False
+"""Whether or not to load truncated image files. User code may change this."""
+
+ERRORS = {
+ -1: "image buffer overrun error",
+ -2: "decoding error",
+ -3: "unknown error",
+ -8: "bad configuration",
+ -9: "out of memory error",
+}
+"""
+Dict of known error codes returned from :meth:`.PyDecoder.decode`,
+:meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and
+:meth:`.PyEncoder.encode_to_file`.
+"""
+
+
+#
+# --------------------------------------------------------------------
+# Helpers
+
+
+def _get_oserror(error: int, *, encoder: bool) -> OSError:
+ try:
+ msg = Image.core.getcodecstatus(error)
+ except AttributeError:
+ msg = ERRORS.get(error)
+ if not msg:
+ msg = f"{'encoder' if encoder else 'decoder'} error {error}"
+ msg += f" when {'writing' if encoder else 'reading'} image file"
+ return OSError(msg)
+
+
+def _tilesort(t: _Tile) -> int:
+ # sort on offset
+ return t[2]
+
+
+class _Tile(NamedTuple):
+ codec_name: str
+ extents: tuple[int, int, int, int] | None
+ offset: int = 0
+ args: tuple[Any, ...] | str | None = None
+
+
+#
+# --------------------------------------------------------------------
+# ImageFile base class
+
+
+class ImageFile(Image.Image):
+ """Base class for image file format handlers."""
+
+ def __init__(
+ self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None
+ ) -> None:
+ super().__init__()
+
+ self._min_frame = 0
+
+ self.custom_mimetype: str | None = None
+
+ self.tile: list[_Tile] = []
+ """ A list of tile descriptors """
+
+ self.readonly = 1 # until we know better
+
+ self.decoderconfig: tuple[Any, ...] = ()
+ self.decodermaxblock = MAXBLOCK
+
+ self.fp: IO[bytes] | None
+ self._fp: IO[bytes] | DeferredError
+ if is_path(fp):
+ # filename
+ self.fp = open(fp, "rb")
+ self.filename = os.fspath(fp)
+ self._exclusive_fp = True
+ else:
+ # stream
+ self.fp = cast(IO[bytes], fp)
+ self.filename = filename if filename is not None else ""
+ # can be overridden
+ self._exclusive_fp = False
+
+ try:
+ try:
+ self._open()
+ except (
+ IndexError, # end of data
+ TypeError, # end of data (ord)
+ KeyError, # unsupported mode
+ EOFError, # got header but not the first frame
+ struct.error,
+ ) as v:
+ raise SyntaxError(v) from v
+
+ if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:
+ msg = "not identified by this driver"
+ raise SyntaxError(msg)
+ except BaseException:
+ # close the file only if we have opened it this constructor
+ if self._exclusive_fp:
+ self.fp.close()
+ raise
+
+ def _open(self) -> None:
+ pass
+
+ # Context manager support
+ def __enter__(self) -> ImageFile:
+ return self
+
+ def _close_fp(self) -> None:
+ if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError):
+ if self._fp != self.fp:
+ self._fp.close()
+ self._fp = DeferredError(ValueError("Operation on closed image"))
+ if self.fp:
+ self.fp.close()
+
+ def __exit__(self, *args: object) -> None:
+ if getattr(self, "_exclusive_fp", False):
+ self._close_fp()
+ self.fp = None
+
+ def close(self) -> None:
+ """
+ Closes the file pointer, if possible.
+
+ This operation will destroy the image core and release its memory.
+ The image data will be unusable afterward.
+
+ This function is required to close images that have multiple frames or
+ have not had their file read and closed by the
+ :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
+ more information.
+ """
+ try:
+ self._close_fp()
+ self.fp = None
+ except Exception as msg:
+ logger.debug("Error closing: %s", msg)
+
+ super().close()
+
+ def get_child_images(self) -> list[ImageFile]:
+ child_images = []
+ exif = self.getexif()
+ ifds = []
+ if ExifTags.Base.SubIFDs in exif:
+ subifd_offsets = exif[ExifTags.Base.SubIFDs]
+ if subifd_offsets:
+ if not isinstance(subifd_offsets, tuple):
+ subifd_offsets = (subifd_offsets,)
+ for subifd_offset in subifd_offsets:
+ ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))
+ ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
+ if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):
+ assert exif._info is not None
+ ifds.append((ifd1, exif._info.next))
+
+ offset = None
+ for ifd, ifd_offset in ifds:
+ assert self.fp is not None
+ current_offset = self.fp.tell()
+ if offset is None:
+ offset = current_offset
+
+ fp = self.fp
+ if ifd is not None:
+ thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset)
+ if thumbnail_offset is not None:
+ thumbnail_offset += getattr(self, "_exif_offset", 0)
+ self.fp.seek(thumbnail_offset)
+
+ length = ifd.get(ExifTags.Base.JpegIFByteCount)
+ assert isinstance(length, int)
+ data = self.fp.read(length)
+ fp = io.BytesIO(data)
+
+ with Image.open(fp) as im:
+ from . import TiffImagePlugin
+
+ if thumbnail_offset is None and isinstance(
+ im, TiffImagePlugin.TiffImageFile
+ ):
+ im._frame_pos = [ifd_offset]
+ im._seek(0)
+ im.load()
+ child_images.append(im)
+
+ if offset is not None:
+ assert self.fp is not None
+ self.fp.seek(offset)
+ return child_images
+
+ def get_format_mimetype(self) -> str | None:
+ if self.custom_mimetype:
+ return self.custom_mimetype
+ if self.format is not None:
+ return Image.MIME.get(self.format.upper())
+ return None
+
+ def __getstate__(self) -> list[Any]:
+ return super().__getstate__() + [self.filename]
+
+ def __setstate__(self, state: list[Any]) -> None:
+ self.tile = []
+ if len(state) > 5:
+ self.filename = state[5]
+ super().__setstate__(state)
+
+ def verify(self) -> None:
+ """Check file integrity"""
+
+ # raise exception if something's wrong. must be called
+ # directly after open, and closes file when finished.
+ if self._exclusive_fp and self.fp:
+ self.fp.close()
+ self.fp = None
+
+ def load(self) -> Image.core.PixelAccess | None:
+ """Load image data based on tile list"""
+
+ if not self.tile and self._im is None:
+ msg = "cannot load this image"
+ raise OSError(msg)
+
+ pixel = Image.Image.load(self)
+ if not self.tile:
+ return pixel
+
+ self.map: mmap.mmap | None = None
+ use_mmap = self.filename and len(self.tile) == 1
+
+ assert self.fp is not None
+ readonly = 0
+
+ # look for read/seek overrides
+ if hasattr(self, "load_read"):
+ read = self.load_read
+ # don't use mmap if there are custom read/seek functions
+ use_mmap = False
+ else:
+ read = self.fp.read
+
+ if hasattr(self, "load_seek"):
+ seek = self.load_seek
+ use_mmap = False
+ else:
+ seek = self.fp.seek
+
+ if use_mmap:
+ # try memory mapping
+ decoder_name, extents, offset, args = self.tile[0]
+ if isinstance(args, str):
+ args = (args, 0, 1)
+ if (
+ decoder_name == "raw"
+ and isinstance(args, tuple)
+ and len(args) >= 3
+ and args[0] == self.mode
+ and args[0] in Image._MAPMODES
+ ):
+ if offset < 0:
+ msg = "Tile offset cannot be negative"
+ raise ValueError(msg)
+ try:
+ # use mmap, if possible
+ import mmap
+
+ with open(self.filename) as fp:
+ self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
+ if offset + self.size[1] * args[1] > self.map.size():
+ msg = "buffer is not large enough"
+ raise OSError(msg)
+ self.im = Image.core.map_buffer(
+ self.map, self.size, decoder_name, offset, args
+ )
+ readonly = 1
+ # After trashing self.im,
+ # we might need to reload the palette data.
+ if self.palette:
+ self.palette.dirty = 1
+ except (AttributeError, OSError, ImportError):
+ self.map = None
+
+ self.load_prepare()
+ err_code = -3 # initialize to unknown error
+ if not self.map:
+ # sort tiles in file order
+ self.tile.sort(key=_tilesort)
+
+ # FIXME: This is a hack to handle TIFF's JpegTables tag.
+ prefix = getattr(self, "tile_prefix", b"")
+
+ # Remove consecutive duplicates that only differ by their offset
+ self.tile = [
+ list(tiles)[-1]
+ for _, tiles in itertools.groupby(
+ self.tile, lambda tile: (tile[0], tile[1], tile[3])
+ )
+ ]
+ for i, (decoder_name, extents, offset, args) in enumerate(self.tile):
+ seek(offset)
+ decoder = Image._getdecoder(
+ self.mode, decoder_name, args, self.decoderconfig
+ )
+ try:
+ decoder.setimage(self.im, extents)
+ if decoder.pulls_fd:
+ decoder.setfd(self.fp)
+ err_code = decoder.decode(b"")[1]
+ else:
+ b = prefix
+ while True:
+ read_bytes = self.decodermaxblock
+ if i + 1 < len(self.tile):
+ next_offset = self.tile[i + 1].offset
+ if next_offset > offset:
+ read_bytes = next_offset - offset
+ try:
+ s = read(read_bytes)
+ except (IndexError, struct.error) as e:
+ # truncated png/gif
+ if LOAD_TRUNCATED_IMAGES:
+ break
+ else:
+ msg = "image file is truncated"
+ raise OSError(msg) from e
+
+ if not s: # truncated jpeg
+ if LOAD_TRUNCATED_IMAGES:
+ break
+ else:
+ msg = (
+ "image file is truncated "
+ f"({len(b)} bytes not processed)"
+ )
+ raise OSError(msg)
+
+ b = b + s
+ n, err_code = decoder.decode(b)
+ if n < 0:
+ break
+ b = b[n:]
+ finally:
+ # Need to cleanup here to prevent leaks
+ decoder.cleanup()
+
+ self.tile = []
+ self.readonly = readonly
+
+ self.load_end()
+
+ if self._exclusive_fp and self._close_exclusive_fp_after_loading:
+ self.fp.close()
+ self.fp = None
+
+ if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
+ # still raised if decoder fails to return anything
+ raise _get_oserror(err_code, encoder=False)
+
+ return Image.Image.load(self)
+
+ def load_prepare(self) -> None:
+ # create image memory if necessary
+ if self._im is None:
+ self.im = Image.core.new(self.mode, self.size)
+ # create palette (optional)
+ if self.mode == "P":
+ Image.Image.load(self)
+
+ def load_end(self) -> None:
+ # may be overridden
+ pass
+
+ # may be defined for contained formats
+ # def load_seek(self, pos: int) -> None:
+ # pass
+
+ # may be defined for blocked formats (e.g. PNG)
+ # def load_read(self, read_bytes: int) -> bytes:
+ # pass
+
+ def _seek_check(self, frame: int) -> bool:
+ if (
+ frame < self._min_frame
+ # Only check upper limit on frames if additional seek operations
+ # are not required to do so
+ or (
+ not (hasattr(self, "_n_frames") and self._n_frames is None)
+ and frame >= getattr(self, "n_frames") + self._min_frame
+ )
+ ):
+ msg = "attempt to seek outside sequence"
+ raise EOFError(msg)
+
+ return self.tell() != frame
+
+
+class StubHandler(abc.ABC):
+ def open(self, im: StubImageFile) -> None:
+ pass
+
+ @abc.abstractmethod
+ def load(self, im: StubImageFile) -> Image.Image:
+ pass
+
+
+class StubImageFile(ImageFile, metaclass=abc.ABCMeta):
+ """
+ Base class for stub image loaders.
+
+ A stub loader is an image loader that can identify files of a
+ certain format, but relies on external code to load the file.
+ """
+
+ @abc.abstractmethod
+ def _open(self) -> None:
+ pass
+
+ def load(self) -> Image.core.PixelAccess | None:
+ loader = self._load()
+ if loader is None:
+ msg = f"cannot find loader for this {self.format} file"
+ raise OSError(msg)
+ image = loader.load(self)
+ assert image is not None
+ # become the other object (!)
+ self.__class__ = image.__class__ # type: ignore[assignment]
+ self.__dict__ = image.__dict__
+ return image.load()
+
+ @abc.abstractmethod
+ def _load(self) -> StubHandler | None:
+ """(Hook) Find actual image loader."""
+ pass
+
+
+class Parser:
+ """
+ Incremental image parser. This class implements the standard
+ feed/close consumer interface.
+ """
+
+ incremental = None
+ image: Image.Image | None = None
+ data: bytes | None = None
+ decoder: Image.core.ImagingDecoder | PyDecoder | None = None
+ offset = 0
+ finished = 0
+
+ def reset(self) -> None:
+ """
+ (Consumer) Reset the parser. Note that you can only call this
+ method immediately after you've created a parser; parser
+ instances cannot be reused.
+ """
+ assert self.data is None, "cannot reuse parsers"
+
+ def feed(self, data: bytes) -> None:
+ """
+ (Consumer) Feed data to the parser.
+
+ :param data: A string buffer.
+ :exception OSError: If the parser failed to parse the image file.
+ """
+ # collect data
+
+ if self.finished:
+ return
+
+ if self.data is None:
+ self.data = data
+ else:
+ self.data = self.data + data
+
+ # parse what we have
+ if self.decoder:
+ if self.offset > 0:
+ # skip header
+ skip = min(len(self.data), self.offset)
+ self.data = self.data[skip:]
+ self.offset = self.offset - skip
+ if self.offset > 0 or not self.data:
+ return
+
+ n, e = self.decoder.decode(self.data)
+
+ if n < 0:
+ # end of stream
+ self.data = None
+ self.finished = 1
+ if e < 0:
+ # decoding error
+ self.image = None
+ raise _get_oserror(e, encoder=False)
+ else:
+ # end of image
+ return
+ self.data = self.data[n:]
+
+ elif self.image:
+ # if we end up here with no decoder, this file cannot
+ # be incrementally parsed. wait until we've gotten all
+ # available data
+ pass
+
+ else:
+ # attempt to open this file
+ try:
+ with io.BytesIO(self.data) as fp:
+ im = Image.open(fp)
+ except OSError:
+ pass # not enough data
+ else:
+ flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
+ if flag or len(im.tile) != 1:
+ # custom load code, or multiple tiles
+ self.decode = None
+ else:
+ # initialize decoder
+ im.load_prepare()
+ d, e, o, a = im.tile[0]
+ im.tile = []
+ self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)
+ self.decoder.setimage(im.im, e)
+
+ # calculate decoder offset
+ self.offset = o
+ if self.offset <= len(self.data):
+ self.data = self.data[self.offset :]
+ self.offset = 0
+
+ self.image = im
+
+ def __enter__(self) -> Parser:
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ self.close()
+
+ def close(self) -> Image.Image:
+ """
+ (Consumer) Close the stream.
+
+ :returns: An image object.
+ :exception OSError: If the parser failed to parse the image file either
+ because it cannot be identified or cannot be
+ decoded.
+ """
+ # finish decoding
+ if self.decoder:
+ # get rid of what's left in the buffers
+ self.feed(b"")
+ self.data = self.decoder = None
+ if not self.finished:
+ msg = "image was incomplete"
+ raise OSError(msg)
+ if not self.image:
+ msg = "cannot parse this image"
+ raise OSError(msg)
+ if self.data:
+ # incremental parsing not possible; reopen the file
+ # not that we have all data
+ with io.BytesIO(self.data) as fp:
+ try:
+ self.image = Image.open(fp)
+ finally:
+ self.image.load()
+ return self.image
+
+
+# --------------------------------------------------------------------
+
+
+def _save(im: Image.Image, fp: IO[bytes], tile: list[_Tile], bufsize: int = 0) -> None:
+ """Helper to save image based on tile list
+
+ :param im: Image object.
+ :param fp: File object.
+ :param tile: Tile list.
+ :param bufsize: Optional buffer size
+ """
+
+ im.load()
+ if not hasattr(im, "encoderconfig"):
+ im.encoderconfig = ()
+ tile.sort(key=_tilesort)
+ # FIXME: make MAXBLOCK a configuration parameter
+ # It would be great if we could have the encoder specify what it needs
+ # But, it would need at least the image size in most cases. RawEncode is
+ # a tricky case.
+ bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
+ try:
+ fh = fp.fileno()
+ fp.flush()
+ _encode_tile(im, fp, tile, bufsize, fh)
+ except (AttributeError, io.UnsupportedOperation) as exc:
+ _encode_tile(im, fp, tile, bufsize, None, exc)
+ if hasattr(fp, "flush"):
+ fp.flush()
+
+
+def _encode_tile(
+ im: Image.Image,
+ fp: IO[bytes],
+ tile: list[_Tile],
+ bufsize: int,
+ fh: int | None,
+ exc: BaseException | None = None,
+) -> None:
+ for encoder_name, extents, offset, args in tile:
+ if offset > 0:
+ fp.seek(offset)
+ encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)
+ try:
+ encoder.setimage(im.im, extents)
+ if encoder.pushes_fd:
+ encoder.setfd(fp)
+ errcode = encoder.encode_to_pyfd()[1]
+ else:
+ if exc:
+ # compress to Python file-compatible object
+ while True:
+ errcode, data = encoder.encode(bufsize)[1:]
+ fp.write(data)
+ if errcode:
+ break
+ else:
+ # slight speedup: compress to real file object
+ assert fh is not None
+ errcode = encoder.encode_to_file(fh, bufsize)
+ if errcode < 0:
+ raise _get_oserror(errcode, encoder=True) from exc
+ finally:
+ encoder.cleanup()
+
+
+def _safe_read(fp: IO[bytes], size: int) -> bytes:
+ """
+ Reads large blocks in a safe way. Unlike fp.read(n), this function
+ doesn't trust the user. If the requested size is larger than
+ SAFEBLOCK, the file is read block by block.
+
+ :param fp: File handle. Must implement a read method.
+ :param size: Number of bytes to read.
+ :returns: A string containing size bytes of data.
+
+ Raises an OSError if the file is truncated and the read cannot be completed
+
+ """
+ if size <= 0:
+ return b""
+ if size <= SAFEBLOCK:
+ data = fp.read(size)
+ if len(data) < size:
+ msg = "Truncated File Read"
+ raise OSError(msg)
+ return data
+ blocks: list[bytes] = []
+ remaining_size = size
+ while remaining_size > 0:
+ block = fp.read(min(remaining_size, SAFEBLOCK))
+ if not block:
+ break
+ blocks.append(block)
+ remaining_size -= len(block)
+ if sum(len(block) for block in blocks) < size:
+ msg = "Truncated File Read"
+ raise OSError(msg)
+ return b"".join(blocks)
+
+
+class PyCodecState:
+ def __init__(self) -> None:
+ self.xsize = 0
+ self.ysize = 0
+ self.xoff = 0
+ self.yoff = 0
+
+ def extents(self) -> tuple[int, int, int, int]:
+ return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize
+
+
+class PyCodec:
+ fd: IO[bytes] | None
+
+ def __init__(self, mode: str, *args: Any) -> None:
+ self.im: Image.core.ImagingCore | None = None
+ self.state = PyCodecState()
+ self.fd = None
+ self.mode = mode
+ self.init(args)
+
+ def init(self, args: tuple[Any, ...]) -> None:
+ """
+ Override to perform codec specific initialization
+
+ :param args: Tuple of arg items from the tile entry
+ :returns: None
+ """
+ self.args = args
+
+ def cleanup(self) -> None:
+ """
+ Override to perform codec specific cleanup
+
+ :returns: None
+ """
+ pass
+
+ def setfd(self, fd: IO[bytes]) -> None:
+ """
+ Called from ImageFile to set the Python file-like object
+
+ :param fd: A Python file-like object
+ :returns: None
+ """
+ self.fd = fd
+
+ def setimage(
+ self,
+ im: Image.core.ImagingCore,
+ extents: tuple[int, int, int, int] | None = None,
+ ) -> None:
+ """
+ Called from ImageFile to set the core output image for the codec
+
+ :param im: A core image object
+ :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
+ for this tile
+ :returns: None
+ """
+
+ # following c code
+ self.im = im
+
+ if extents:
+ (x0, y0, x1, y1) = extents
+ else:
+ (x0, y0, x1, y1) = (0, 0, 0, 0)
+
+ if x0 == 0 and x1 == 0:
+ self.state.xsize, self.state.ysize = self.im.size
+ else:
+ self.state.xoff = x0
+ self.state.yoff = y0
+ self.state.xsize = x1 - x0
+ self.state.ysize = y1 - y0
+
+ if self.state.xsize <= 0 or self.state.ysize <= 0:
+ msg = "Size cannot be negative"
+ raise ValueError(msg)
+
+ if (
+ self.state.xsize + self.state.xoff > self.im.size[0]
+ or self.state.ysize + self.state.yoff > self.im.size[1]
+ ):
+ msg = "Tile cannot extend outside image"
+ raise ValueError(msg)
+
+
+class PyDecoder(PyCodec):
+ """
+ Python implementation of a format decoder. Override this class and
+ add the decoding logic in the :meth:`decode` method.
+
+ See :ref:`Writing Your Own File Codec in Python`
+ """
+
+ _pulls_fd = False
+
+ @property
+ def pulls_fd(self) -> bool:
+ return self._pulls_fd
+
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+ """
+ Override to perform the decoding process.
+
+ :param buffer: A bytes object with the data to be decoded.
+ :returns: A tuple of ``(bytes consumed, errcode)``.
+ If finished with decoding return -1 for the bytes consumed.
+ Err codes are from :data:`.ImageFile.ERRORS`.
+ """
+ msg = "unavailable in base decoder"
+ raise NotImplementedError(msg)
+
+ def set_as_raw(
+ self, data: bytes, rawmode: str | None = None, extra: tuple[Any, ...] = ()
+ ) -> None:
+ """
+ Convenience method to set the internal image from a stream of raw data
+
+ :param data: Bytes to be set
+ :param rawmode: The rawmode to be used for the decoder.
+ If not specified, it will default to the mode of the image
+ :param extra: Extra arguments for the decoder.
+ :returns: None
+ """
+
+ if not rawmode:
+ rawmode = self.mode
+ d = Image._getdecoder(self.mode, "raw", rawmode, extra)
+ assert self.im is not None
+ d.setimage(self.im, self.state.extents())
+ s = d.decode(data)
+
+ if s[0] >= 0:
+ msg = "not enough image data"
+ raise ValueError(msg)
+ if s[1] != 0:
+ msg = "cannot decode image data"
+ raise ValueError(msg)
+
+
+class PyEncoder(PyCodec):
+ """
+ Python implementation of a format encoder. Override this class and
+ add the decoding logic in the :meth:`encode` method.
+
+ See :ref:`Writing Your Own File Codec in Python`
+ """
+
+ _pushes_fd = False
+
+ @property
+ def pushes_fd(self) -> bool:
+ return self._pushes_fd
+
+ def encode(self, bufsize: int) -> tuple[int, int, bytes]:
+ """
+ Override to perform the encoding process.
+
+ :param bufsize: Buffer size.
+ :returns: A tuple of ``(bytes encoded, errcode, bytes)``.
+ If finished with encoding return 1 for the error code.
+ Err codes are from :data:`.ImageFile.ERRORS`.
+ """
+ msg = "unavailable in base encoder"
+ raise NotImplementedError(msg)
+
+ def encode_to_pyfd(self) -> tuple[int, int]:
+ """
+ If ``pushes_fd`` is ``True``, then this method will be used,
+ and ``encode()`` will only be called once.
+
+ :returns: A tuple of ``(bytes consumed, errcode)``.
+ Err codes are from :data:`.ImageFile.ERRORS`.
+ """
+ if not self.pushes_fd:
+ return 0, -8 # bad configuration
+ bytes_consumed, errcode, data = self.encode(0)
+ if data:
+ assert self.fd is not None
+ self.fd.write(data)
+ return bytes_consumed, errcode
+
+ def encode_to_file(self, fh: int, bufsize: int) -> int:
+ """
+ :param fh: File handle.
+ :param bufsize: Buffer size.
+
+ :returns: If finished successfully, return 0.
+ Otherwise, return an error code. Err codes are from
+ :data:`.ImageFile.ERRORS`.
+ """
+ errcode = 0
+ while errcode == 0:
+ status, errcode, buf = self.encode(bufsize)
+ if status > 0:
+ os.write(fh, buf[status:])
+ return errcode
diff --git a/venv/Lib/site-packages/PIL/ImageFilter.py b/venv/Lib/site-packages/PIL/ImageFilter.py
new file mode 100644
index 0000000..9326eee
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageFilter.py
@@ -0,0 +1,607 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# standard filters
+#
+# History:
+# 1995-11-27 fl Created
+# 2002-06-08 fl Added rank and mode filters
+# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
+#
+# Copyright (c) 1997-2003 by Secret Labs AB.
+# Copyright (c) 1995-2002 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import abc
+import functools
+from collections.abc import Sequence
+from typing import cast
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from types import ModuleType
+ from typing import Any
+
+ from . import _imaging
+ from ._typing import NumpyArray
+
+
+class Filter(abc.ABC):
+ @abc.abstractmethod
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
+ pass
+
+
+class MultibandFilter(Filter):
+ pass
+
+
+class BuiltinFilter(MultibandFilter):
+ filterargs: tuple[Any, ...]
+
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
+ if image.mode == "P":
+ msg = "cannot filter palette images"
+ raise ValueError(msg)
+ return image.filter(*self.filterargs)
+
+
+class Kernel(BuiltinFilter):
+ """
+ Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
+ point kernels.
+
+ Kernels can only be applied to "L" and "RGB" images.
+
+ :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
+ :param kernel: A sequence containing kernel weights. The kernel will be flipped
+ vertically before being applied to the image.
+ :param scale: Scale factor. If given, the result for each pixel is divided by this
+ value. The default is the sum of the kernel weights.
+ :param offset: Offset. If given, this value is added to the result, after it has
+ been divided by the scale factor.
+ """
+
+ name = "Kernel"
+
+ def __init__(
+ self,
+ size: tuple[int, int],
+ kernel: Sequence[float],
+ scale: float | None = None,
+ offset: float = 0,
+ ) -> None:
+ if scale is None:
+ # default scale is sum of kernel
+ scale = functools.reduce(lambda a, b: a + b, kernel)
+ if size[0] * size[1] != len(kernel):
+ msg = "not enough coefficients in kernel"
+ raise ValueError(msg)
+ self.filterargs = size, scale, offset, kernel
+
+
+class RankFilter(Filter):
+ """
+ Create a rank filter. The rank filter sorts all pixels in
+ a window of the given size, and returns the ``rank``'th value.
+
+ :param size: The kernel size, in pixels.
+ :param rank: What pixel value to pick. Use 0 for a min filter,
+ ``size * size / 2`` for a median filter, ``size * size - 1``
+ for a max filter, etc.
+ """
+
+ name = "Rank"
+
+ def __init__(self, size: int, rank: int) -> None:
+ self.size = size
+ self.rank = rank
+
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
+ if image.mode == "P":
+ msg = "cannot filter palette images"
+ raise ValueError(msg)
+ image = image.expand(self.size // 2, self.size // 2)
+ return image.rankfilter(self.size, self.rank)
+
+
+class MedianFilter(RankFilter):
+ """
+ Create a median filter. Picks the median pixel value in a window with the
+ given size.
+
+ :param size: The kernel size, in pixels.
+ """
+
+ name = "Median"
+
+ def __init__(self, size: int = 3) -> None:
+ self.size = size
+ self.rank = size * size // 2
+
+
+class MinFilter(RankFilter):
+ """
+ Create a min filter. Picks the lowest pixel value in a window with the
+ given size.
+
+ :param size: The kernel size, in pixels.
+ """
+
+ name = "Min"
+
+ def __init__(self, size: int = 3) -> None:
+ self.size = size
+ self.rank = 0
+
+
+class MaxFilter(RankFilter):
+ """
+ Create a max filter. Picks the largest pixel value in a window with the
+ given size.
+
+ :param size: The kernel size, in pixels.
+ """
+
+ name = "Max"
+
+ def __init__(self, size: int = 3) -> None:
+ self.size = size
+ self.rank = size * size - 1
+
+
+class ModeFilter(Filter):
+ """
+ Create a mode filter. Picks the most frequent pixel value in a box with the
+ given size. Pixel values that occur only once or twice are ignored; if no
+ pixel value occurs more than twice, the original pixel value is preserved.
+
+ :param size: The kernel size, in pixels.
+ """
+
+ name = "Mode"
+
+ def __init__(self, size: int = 3) -> None:
+ self.size = size
+
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
+ return image.modefilter(self.size)
+
+
+class GaussianBlur(MultibandFilter):
+ """Blurs the image with a sequence of extended box filters, which
+ approximates a Gaussian kernel. For details on accuracy see
+
+
+ :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two
+ numbers for x and y, or a single number for both.
+ """
+
+ name = "GaussianBlur"
+
+ def __init__(self, radius: float | Sequence[float] = 2) -> None:
+ self.radius = radius
+
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
+ xy = self.radius
+ if isinstance(xy, (int, float)):
+ xy = (xy, xy)
+ if xy == (0, 0):
+ return image.copy()
+ return image.gaussian_blur(xy)
+
+
+class BoxBlur(MultibandFilter):
+ """Blurs the image by setting each pixel to the average value of the pixels
+ in a square box extending radius pixels in each direction.
+ Supports float radius of arbitrary size. Uses an optimized implementation
+ which runs in linear time relative to the size of the image
+ for any radius value.
+
+ :param radius: Size of the box in a direction. Either a sequence of two numbers for
+ x and y, or a single number for both.
+
+ Radius 0 does not blur, returns an identical image.
+ Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
+ """
+
+ name = "BoxBlur"
+
+ def __init__(self, radius: float | Sequence[float]) -> None:
+ xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)
+ if xy[0] < 0 or xy[1] < 0:
+ msg = "radius must be >= 0"
+ raise ValueError(msg)
+ self.radius = radius
+
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
+ xy = self.radius
+ if isinstance(xy, (int, float)):
+ xy = (xy, xy)
+ if xy == (0, 0):
+ return image.copy()
+ return image.box_blur(xy)
+
+
+class UnsharpMask(MultibandFilter):
+ """Unsharp mask filter.
+
+ See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
+ the parameters.
+
+ :param radius: Blur Radius
+ :param percent: Unsharp strength, in percent
+ :param threshold: Threshold controls the minimum brightness change that
+ will be sharpened
+
+ .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
+
+ """
+
+ name = "UnsharpMask"
+
+ def __init__(
+ self, radius: float = 2, percent: int = 150, threshold: int = 3
+ ) -> None:
+ self.radius = radius
+ self.percent = percent
+ self.threshold = threshold
+
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
+ return image.unsharp_mask(self.radius, self.percent, self.threshold)
+
+
+class BLUR(BuiltinFilter):
+ name = "Blur"
+ # fmt: off
+ filterargs = (5, 5), 16, 0, (
+ 1, 1, 1, 1, 1,
+ 1, 0, 0, 0, 1,
+ 1, 0, 0, 0, 1,
+ 1, 0, 0, 0, 1,
+ 1, 1, 1, 1, 1,
+ )
+ # fmt: on
+
+
+class CONTOUR(BuiltinFilter):
+ name = "Contour"
+ # fmt: off
+ filterargs = (3, 3), 1, 255, (
+ -1, -1, -1,
+ -1, 8, -1,
+ -1, -1, -1,
+ )
+ # fmt: on
+
+
+class DETAIL(BuiltinFilter):
+ name = "Detail"
+ # fmt: off
+ filterargs = (3, 3), 6, 0, (
+ 0, -1, 0,
+ -1, 10, -1,
+ 0, -1, 0,
+ )
+ # fmt: on
+
+
+class EDGE_ENHANCE(BuiltinFilter):
+ name = "Edge-enhance"
+ # fmt: off
+ filterargs = (3, 3), 2, 0, (
+ -1, -1, -1,
+ -1, 10, -1,
+ -1, -1, -1,
+ )
+ # fmt: on
+
+
+class EDGE_ENHANCE_MORE(BuiltinFilter):
+ name = "Edge-enhance More"
+ # fmt: off
+ filterargs = (3, 3), 1, 0, (
+ -1, -1, -1,
+ -1, 9, -1,
+ -1, -1, -1,
+ )
+ # fmt: on
+
+
+class EMBOSS(BuiltinFilter):
+ name = "Emboss"
+ # fmt: off
+ filterargs = (3, 3), 1, 128, (
+ -1, 0, 0,
+ 0, 1, 0,
+ 0, 0, 0,
+ )
+ # fmt: on
+
+
+class FIND_EDGES(BuiltinFilter):
+ name = "Find Edges"
+ # fmt: off
+ filterargs = (3, 3), 1, 0, (
+ -1, -1, -1,
+ -1, 8, -1,
+ -1, -1, -1,
+ )
+ # fmt: on
+
+
+class SHARPEN(BuiltinFilter):
+ name = "Sharpen"
+ # fmt: off
+ filterargs = (3, 3), 16, 0, (
+ -2, -2, -2,
+ -2, 32, -2,
+ -2, -2, -2,
+ )
+ # fmt: on
+
+
+class SMOOTH(BuiltinFilter):
+ name = "Smooth"
+ # fmt: off
+ filterargs = (3, 3), 13, 0, (
+ 1, 1, 1,
+ 1, 5, 1,
+ 1, 1, 1,
+ )
+ # fmt: on
+
+
+class SMOOTH_MORE(BuiltinFilter):
+ name = "Smooth More"
+ # fmt: off
+ filterargs = (5, 5), 100, 0, (
+ 1, 1, 1, 1, 1,
+ 1, 5, 5, 5, 1,
+ 1, 5, 44, 5, 1,
+ 1, 5, 5, 5, 1,
+ 1, 1, 1, 1, 1,
+ )
+ # fmt: on
+
+
+class Color3DLUT(MultibandFilter):
+ """Three-dimensional color lookup table.
+
+ Transforms 3-channel pixels using the values of the channels as coordinates
+ in the 3D lookup table and interpolating the nearest elements.
+
+ This method allows you to apply almost any color transformation
+ in constant time by using pre-calculated decimated tables.
+
+ .. versionadded:: 5.2.0
+
+ :param size: Size of the table. One int or tuple of (int, int, int).
+ Minimal size in any dimension is 2, maximum is 65.
+ :param table: Flat lookup table. A list of ``channels * size**3``
+ float elements or a list of ``size**3`` channels-sized
+ tuples with floats. Channels are changed first,
+ then first dimension, then second, then third.
+ Value 0.0 corresponds lowest value of output, 1.0 highest.
+ :param channels: Number of channels in the table. Could be 3 or 4.
+ Default is 3.
+ :param target_mode: A mode for the result image. Should have not less
+ than ``channels`` channels. Default is ``None``,
+ which means that mode wouldn't be changed.
+ """
+
+ name = "Color 3D LUT"
+
+ def __init__(
+ self,
+ size: int | tuple[int, int, int],
+ table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,
+ channels: int = 3,
+ target_mode: str | None = None,
+ **kwargs: bool,
+ ) -> None:
+ if channels not in (3, 4):
+ msg = "Only 3 or 4 output channels are supported"
+ raise ValueError(msg)
+ self.size = size = self._check_size(size)
+ self.channels = channels
+ self.mode = target_mode
+
+ # Hidden flag `_copy_table=False` could be used to avoid extra copying
+ # of the table if the table is specially made for the constructor.
+ copy_table = kwargs.get("_copy_table", True)
+ items = size[0] * size[1] * size[2]
+ wrong_size = False
+
+ numpy: ModuleType | None = None
+ if hasattr(table, "shape"):
+ try:
+ import numpy
+ except ImportError:
+ pass
+
+ if numpy and isinstance(table, numpy.ndarray):
+ numpy_table: NumpyArray = table
+ if copy_table:
+ numpy_table = numpy_table.copy()
+
+ if numpy_table.shape in [
+ (items * channels,),
+ (items, channels),
+ (size[2], size[1], size[0], channels),
+ ]:
+ table = numpy_table.reshape(items * channels)
+ else:
+ wrong_size = True
+
+ else:
+ if copy_table:
+ table = list(table)
+
+ # Convert to a flat list
+ if table and isinstance(table[0], (list, tuple)):
+ raw_table = cast(Sequence[Sequence[int]], table)
+ flat_table: list[int] = []
+ for pixel in raw_table:
+ if len(pixel) != channels:
+ msg = (
+ "The elements of the table should "
+ f"have a length of {channels}."
+ )
+ raise ValueError(msg)
+ flat_table.extend(pixel)
+ table = flat_table
+
+ if wrong_size or len(table) != items * channels:
+ msg = (
+ "The table should have either channels * size**3 float items "
+ "or size**3 items of channels-sized tuples with floats. "
+ f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "
+ f"Actual length: {len(table)}"
+ )
+ raise ValueError(msg)
+ self.table = table
+
+ @staticmethod
+ def _check_size(size: Any) -> tuple[int, int, int]:
+ try:
+ _, _, _ = size
+ except ValueError as e:
+ msg = "Size should be either an integer or a tuple of three integers."
+ raise ValueError(msg) from e
+ except TypeError:
+ size = (size, size, size)
+ size = tuple(int(x) for x in size)
+ for size_1d in size:
+ if not 2 <= size_1d <= 65:
+ msg = "Size should be in [2, 65] range."
+ raise ValueError(msg)
+ return size
+
+ @classmethod
+ def generate(
+ cls,
+ size: int | tuple[int, int, int],
+ callback: Callable[[float, float, float], tuple[float, ...]],
+ channels: int = 3,
+ target_mode: str | None = None,
+ ) -> Color3DLUT:
+ """Generates new LUT using provided callback.
+
+ :param size: Size of the table. Passed to the constructor.
+ :param callback: Function with three parameters which correspond
+ three color channels. Will be called ``size**3``
+ times with values from 0.0 to 1.0 and should return
+ a tuple with ``channels`` elements.
+ :param channels: The number of channels which should return callback.
+ :param target_mode: Passed to the constructor of the resulting
+ lookup table.
+ """
+ size_1d, size_2d, size_3d = cls._check_size(size)
+ if channels not in (3, 4):
+ msg = "Only 3 or 4 output channels are supported"
+ raise ValueError(msg)
+
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)
+ idx_out = 0
+ for b in range(size_3d):
+ for g in range(size_2d):
+ for r in range(size_1d):
+ table[idx_out : idx_out + channels] = callback(
+ r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)
+ )
+ idx_out += channels
+
+ return cls(
+ (size_1d, size_2d, size_3d),
+ table,
+ channels=channels,
+ target_mode=target_mode,
+ _copy_table=False,
+ )
+
+ def transform(
+ self,
+ callback: Callable[..., tuple[float, ...]],
+ with_normals: bool = False,
+ channels: int | None = None,
+ target_mode: str | None = None,
+ ) -> Color3DLUT:
+ """Transforms the table values using provided callback and returns
+ a new LUT with altered values.
+
+ :param callback: A function which takes old lookup table values
+ and returns a new set of values. The number
+ of arguments which function should take is
+ ``self.channels`` or ``3 + self.channels``
+ if ``with_normals`` flag is set.
+ Should return a tuple of ``self.channels`` or
+ ``channels`` elements if it is set.
+ :param with_normals: If true, ``callback`` will be called with
+ coordinates in the color cube as the first
+ three arguments. Otherwise, ``callback``
+ will be called only with actual color values.
+ :param channels: The number of channels in the resulting lookup table.
+ :param target_mode: Passed to the constructor of the resulting
+ lookup table.
+ """
+ if channels not in (None, 3, 4):
+ msg = "Only 3 or 4 output channels are supported"
+ raise ValueError(msg)
+ ch_in = self.channels
+ ch_out = channels or ch_in
+ size_1d, size_2d, size_3d = self.size
+
+ table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out)
+ idx_in = 0
+ idx_out = 0
+ for b in range(size_3d):
+ for g in range(size_2d):
+ for r in range(size_1d):
+ values = self.table[idx_in : idx_in + ch_in]
+ if with_normals:
+ values = callback(
+ r / (size_1d - 1),
+ g / (size_2d - 1),
+ b / (size_3d - 1),
+ *values,
+ )
+ else:
+ values = callback(*values)
+ table[idx_out : idx_out + ch_out] = values
+ idx_in += ch_in
+ idx_out += ch_out
+
+ return type(self)(
+ self.size,
+ table,
+ channels=ch_out,
+ target_mode=target_mode or self.mode,
+ _copy_table=False,
+ )
+
+ def __repr__(self) -> str:
+ r = [
+ f"{self.__class__.__name__} from {self.table.__class__.__name__}",
+ "size={:d}x{:d}x{:d}".format(*self.size),
+ f"channels={self.channels:d}",
+ ]
+ if self.mode:
+ r.append(f"target_mode={self.mode}")
+ return "<{}>".format(" ".join(r))
+
+ def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:
+ from . import Image
+
+ return image.color_lut_3d(
+ self.mode or image.mode,
+ Image.Resampling.BILINEAR,
+ self.channels,
+ self.size,
+ self.table,
+ )
diff --git a/venv/Lib/site-packages/PIL/ImageFont.py b/venv/Lib/site-packages/PIL/ImageFont.py
new file mode 100644
index 0000000..d11f7bf
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageFont.py
@@ -0,0 +1,1320 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# PIL raster font management
+#
+# History:
+# 1996-08-07 fl created (experimental)
+# 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3
+# 1999-02-06 fl rewrote most font management stuff in C
+# 1999-03-17 fl take pth files into account in load_path (from Richard Jones)
+# 2001-02-17 fl added freetype support
+# 2001-05-09 fl added TransposedFont wrapper class
+# 2002-03-04 fl make sure we have a "L" or "1" font
+# 2002-12-04 fl skip non-directory entries in the system path
+# 2003-04-29 fl add embedded default font
+# 2003-09-27 fl added support for truetype charmap encodings
+#
+# Todo:
+# Adapt to PILFONT2 format (16-bit fonts, compressed, single file)
+#
+# Copyright (c) 1997-2003 by Secret Labs AB
+# Copyright (c) 1996-2003 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+
+from __future__ import annotations
+
+import base64
+import os
+import sys
+import warnings
+from enum import IntEnum
+from io import BytesIO
+from types import ModuleType
+from typing import IO, Any, BinaryIO, TypedDict, cast
+
+from . import Image
+from ._typing import StrOrBytesPath
+from ._util import DeferredError, is_path
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from . import ImageFile
+ from ._imaging import ImagingFont
+ from ._imagingft import Font
+
+
+class Axis(TypedDict):
+ minimum: int | None
+ default: int | None
+ maximum: int | None
+ name: bytes | None
+
+
+class Layout(IntEnum):
+ BASIC = 0
+ RAQM = 1
+
+
+MAX_STRING_LENGTH = 1_000_000
+
+
+core: ModuleType | DeferredError
+try:
+ from . import _imagingft as core
+except ImportError as ex:
+ core = DeferredError.new(ex)
+
+
+def _string_length_check(text: str | bytes | bytearray) -> None:
+ if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:
+ msg = "too many characters in string"
+ raise ValueError(msg)
+
+
+# FIXME: add support for pilfont2 format (see FontFile.py)
+
+# --------------------------------------------------------------------
+# Font metrics format:
+# "PILfont" LF
+# fontdescriptor LF
+# (optional) key=value... LF
+# "DATA" LF
+# binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)
+#
+# To place a character, cut out srcbox and paste at dstbox,
+# relative to the character position. Then move the character
+# position according to dx, dy.
+# --------------------------------------------------------------------
+
+
+class ImageFont:
+ """PIL font wrapper"""
+
+ font: ImagingFont
+
+ def _load_pilfont(self, filename: str) -> None:
+ with open(filename, "rb") as fp:
+ image: ImageFile.ImageFile | None = None
+ root = os.path.splitext(filename)[0]
+
+ for ext in (".png", ".gif", ".pbm"):
+ if image:
+ image.close()
+ try:
+ fullname = root + ext
+ image = Image.open(fullname)
+ except Exception:
+ pass
+ else:
+ if image and image.mode in ("1", "L"):
+ break
+ else:
+ if image:
+ image.close()
+
+ msg = f"cannot find glyph data file {root}.{{gif|pbm|png}}"
+ raise OSError(msg)
+
+ self.file = fullname
+
+ self._load_pilfont_data(fp, image)
+ image.close()
+
+ def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
+ # check image
+ if image.mode not in ("1", "L"):
+ image.close()
+
+ msg = "invalid font image mode"
+ raise TypeError(msg)
+
+ # read PILfont header
+ if file.read(8) != b"PILfont\n":
+ image.close()
+
+ msg = "Not a PILfont file"
+ raise SyntaxError(msg)
+ file.readline()
+ self.info = [] # FIXME: should be a dictionary
+ while True:
+ s = file.readline()
+ if not s or s == b"DATA\n":
+ break
+ self.info.append(s)
+
+ # read PILfont metrics
+ data = file.read(256 * 20)
+
+ image.load()
+
+ self.font = Image.core.font(image.im, data)
+
+ def getmask(
+ self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any
+ ) -> Image.core.ImagingCore:
+ """
+ Create a bitmap for the text.
+
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
+ maximum value of 255. Otherwise, it should have mode ``1``.
+
+ :param text: Text to render.
+ :param mode: Used by some graphics drivers to indicate what mode the
+ driver prefers; if empty, the renderer may return either
+ mode. Note that the mode is always a string, to simplify
+ C-level implementations.
+
+ .. versionadded:: 1.1.5
+
+ :return: An internal PIL storage memory instance as defined by the
+ :py:mod:`PIL.Image.core` interface module.
+ """
+ _string_length_check(text)
+ Image._decompression_bomb_check(self.font.getsize(text))
+ return self.font.getmask(text, mode)
+
+ def getbbox(
+ self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
+ ) -> tuple[int, int, int, int]:
+ """
+ Returns bounding box (in pixels) of given text.
+
+ .. versionadded:: 9.2.0
+
+ :param text: Text to render.
+
+ :return: ``(left, top, right, bottom)`` bounding box
+ """
+ _string_length_check(text)
+ width, height = self.font.getsize(text)
+ return 0, 0, width, height
+
+ def getlength(
+ self, text: str | bytes | bytearray, *args: Any, **kwargs: Any
+ ) -> int:
+ """
+ Returns length (in pixels) of given text.
+ This is the amount by which following text should be offset.
+
+ .. versionadded:: 9.2.0
+ """
+ _string_length_check(text)
+ width, height = self.font.getsize(text)
+ return width
+
+
+##
+# Wrapper for FreeType fonts. Application code should use the
+# truetype factory function to create font objects.
+
+
+class FreeTypeFont:
+ """FreeType font wrapper (requires _imagingft service)"""
+
+ font: Font
+ font_bytes: bytes
+
+ def __init__(
+ self,
+ font: StrOrBytesPath | BinaryIO,
+ size: float = 10,
+ index: int = 0,
+ encoding: str = "",
+ layout_engine: Layout | None = None,
+ ) -> None:
+ # FIXME: use service provider instead
+
+ if isinstance(core, DeferredError):
+ raise core.ex
+
+ if size <= 0:
+ msg = f"font size must be greater than 0, not {size}"
+ raise ValueError(msg)
+
+ self.path = font
+ self.size = size
+ self.index = index
+ self.encoding = encoding
+
+ if layout_engine not in (Layout.BASIC, Layout.RAQM):
+ layout_engine = Layout.BASIC
+ if core.HAVE_RAQM:
+ layout_engine = Layout.RAQM
+ elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:
+ warnings.warn(
+ "Raqm layout was requested, but Raqm is not available. "
+ "Falling back to basic layout."
+ )
+ layout_engine = Layout.BASIC
+
+ self.layout_engine = layout_engine
+
+ def load_from_bytes(f: IO[bytes]) -> None:
+ self.font_bytes = f.read()
+ self.font = core.getfont(
+ "", size, index, encoding, self.font_bytes, layout_engine
+ )
+
+ if is_path(font):
+ font = os.fspath(font)
+ if sys.platform == "win32":
+ font_bytes_path = font if isinstance(font, bytes) else font.encode()
+ try:
+ font_bytes_path.decode("ascii")
+ except UnicodeDecodeError:
+ # FreeType cannot load fonts with non-ASCII characters on Windows
+ # So load it into memory first
+ with open(font, "rb") as f:
+ load_from_bytes(f)
+ return
+ self.font = core.getfont(
+ font, size, index, encoding, layout_engine=layout_engine
+ )
+ else:
+ load_from_bytes(cast(IO[bytes], font))
+
+ def __getstate__(self) -> list[Any]:
+ return [self.path, self.size, self.index, self.encoding, self.layout_engine]
+
+ def __setstate__(self, state: list[Any]) -> None:
+ path, size, index, encoding, layout_engine = state
+ FreeTypeFont.__init__(self, path, size, index, encoding, layout_engine)
+
+ def getname(self) -> tuple[str | None, str | None]:
+ """
+ :return: A tuple of the font family (e.g. Helvetica) and the font style
+ (e.g. Bold)
+ """
+ return self.font.family, self.font.style
+
+ def getmetrics(self) -> tuple[int, int]:
+ """
+ :return: A tuple of the font ascent (the distance from the baseline to
+ the highest outline point) and descent (the distance from the
+ baseline to the lowest outline point, a negative value)
+ """
+ return self.font.ascent, self.font.descent
+
+ def getlength(
+ self,
+ text: str | bytes,
+ mode: str = "",
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ ) -> float:
+ """
+ Returns length (in pixels with 1/64 precision) of given text when rendered
+ in font with provided direction, features, and language.
+
+ This is the amount by which following text should be offset.
+ Text bounding box may extend past the length in some fonts,
+ e.g. when using italics or accents.
+
+ The result is returned as a float; it is a whole number if using basic layout.
+
+ Note that the sum of two lengths may not equal the length of a concatenated
+ string due to kerning. If you need to adjust for kerning, include the following
+ character and subtract its length.
+
+ For example, instead of ::
+
+ hello = font.getlength("Hello")
+ world = font.getlength("World")
+ hello_world = hello + world # not adjusted for kerning
+ assert hello_world == font.getlength("HelloWorld") # may fail
+
+ use ::
+
+ hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning
+ world = font.getlength("World")
+ hello_world = hello + world # adjusted for kerning
+ assert hello_world == font.getlength("HelloWorld") # True
+
+ or disable kerning with (requires libraqm) ::
+
+ hello = draw.textlength("Hello", font, features=["-kern"])
+ world = draw.textlength("World", font, features=["-kern"])
+ hello_world = hello + world # kerning is disabled, no need to adjust
+ assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])
+
+ .. versionadded:: 8.0.0
+
+ :param text: Text to measure.
+ :param mode: Used by some graphics drivers to indicate what mode the
+ driver prefers; if empty, the renderer may return either
+ mode. Note that the mode is always a string, to simplify
+ C-level implementations.
+
+ :param direction: Direction of the text. It can be 'rtl' (right to
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
+ Requires libraqm.
+
+ :param features: A list of OpenType font features to be used during text
+ layout. This is usually used to turn on optional
+ font features that are not enabled by default,
+ for example 'dlig' or 'ss01', but can be also
+ used to turn off default font features for
+ example '-liga' to disable ligatures or '-kern'
+ to disable kerning. To get all supported
+ features, see
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
+ Requires libraqm.
+
+ :param language: Language of the text. Different languages may use
+ different glyph shapes or ligatures. This parameter tells
+ the font which language the text is in, and to apply the
+ correct substitutions as appropriate, if available.
+ It should be a `BCP 47 language code
+ `_
+ Requires libraqm.
+
+ :return: Either width for horizontal text, or height for vertical text.
+ """
+ _string_length_check(text)
+ return self.font.getlength(text, mode, direction, features, language) / 64
+
+ def getbbox(
+ self,
+ text: str | bytes,
+ mode: str = "",
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ stroke_width: float = 0,
+ anchor: str | None = None,
+ ) -> tuple[float, float, float, float]:
+ """
+ Returns bounding box (in pixels) of given text relative to given anchor
+ when rendered in font with provided direction, features, and language.
+
+ Use :py:meth:`getlength()` to get the offset of following text with
+ 1/64 pixel precision. The bounding box includes extra margins for
+ some fonts, e.g. italics or accents.
+
+ .. versionadded:: 8.0.0
+
+ :param text: Text to render.
+ :param mode: Used by some graphics drivers to indicate what mode the
+ driver prefers; if empty, the renderer may return either
+ mode. Note that the mode is always a string, to simplify
+ C-level implementations.
+
+ :param direction: Direction of the text. It can be 'rtl' (right to
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
+ Requires libraqm.
+
+ :param features: A list of OpenType font features to be used during text
+ layout. This is usually used to turn on optional
+ font features that are not enabled by default,
+ for example 'dlig' or 'ss01', but can be also
+ used to turn off default font features for
+ example '-liga' to disable ligatures or '-kern'
+ to disable kerning. To get all supported
+ features, see
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
+ Requires libraqm.
+
+ :param language: Language of the text. Different languages may use
+ different glyph shapes or ligatures. This parameter tells
+ the font which language the text is in, and to apply the
+ correct substitutions as appropriate, if available.
+ It should be a `BCP 47 language code
+ `_
+ Requires libraqm.
+
+ :param stroke_width: The width of the text stroke.
+
+ :param anchor: The text anchor alignment. Determines the relative location of
+ the anchor to the text. The default alignment is top left,
+ specifically ``la`` for horizontal text and ``lt`` for
+ vertical text. See :ref:`text-anchors` for details.
+
+ :return: ``(left, top, right, bottom)`` bounding box
+ """
+ _string_length_check(text)
+ size, offset = self.font.getsize(
+ text, mode, direction, features, language, anchor
+ )
+ left, top = offset[0] - stroke_width, offset[1] - stroke_width
+ width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width
+ return left, top, left + width, top + height
+
+ def getmask(
+ self,
+ text: str | bytes,
+ mode: str = "",
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ stroke_width: float = 0,
+ anchor: str | None = None,
+ ink: int = 0,
+ start: tuple[float, float] | None = None,
+ ) -> Image.core.ImagingCore:
+ """
+ Create a bitmap for the text.
+
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
+ maximum value of 255. If the font has embedded color data, the bitmap
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
+
+ :param text: Text to render.
+ :param mode: Used by some graphics drivers to indicate what mode the
+ driver prefers; if empty, the renderer may return either
+ mode. Note that the mode is always a string, to simplify
+ C-level implementations.
+
+ .. versionadded:: 1.1.5
+
+ :param direction: Direction of the text. It can be 'rtl' (right to
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
+ Requires libraqm.
+
+ .. versionadded:: 4.2.0
+
+ :param features: A list of OpenType font features to be used during text
+ layout. This is usually used to turn on optional
+ font features that are not enabled by default,
+ for example 'dlig' or 'ss01', but can be also
+ used to turn off default font features for
+ example '-liga' to disable ligatures or '-kern'
+ to disable kerning. To get all supported
+ features, see
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
+ Requires libraqm.
+
+ .. versionadded:: 4.2.0
+
+ :param language: Language of the text. Different languages may use
+ different glyph shapes or ligatures. This parameter tells
+ the font which language the text is in, and to apply the
+ correct substitutions as appropriate, if available.
+ It should be a `BCP 47 language code
+ `_
+ Requires libraqm.
+
+ .. versionadded:: 6.0.0
+
+ :param stroke_width: The width of the text stroke.
+
+ .. versionadded:: 6.2.0
+
+ :param anchor: The text anchor alignment. Determines the relative location of
+ the anchor to the text. The default alignment is top left,
+ specifically ``la`` for horizontal text and ``lt`` for
+ vertical text. See :ref:`text-anchors` for details.
+
+ .. versionadded:: 8.0.0
+
+ :param ink: Foreground ink for rendering in RGBA mode.
+
+ .. versionadded:: 8.0.0
+
+ :param start: Tuple of horizontal and vertical offset, as text may render
+ differently when starting at fractional coordinates.
+
+ .. versionadded:: 9.4.0
+
+ :return: An internal PIL storage memory instance as defined by the
+ :py:mod:`PIL.Image.core` interface module.
+ """
+ return self.getmask2(
+ text,
+ mode,
+ direction=direction,
+ features=features,
+ language=language,
+ stroke_width=stroke_width,
+ anchor=anchor,
+ ink=ink,
+ start=start,
+ )[0]
+
+ def getmask2(
+ self,
+ text: str | bytes,
+ mode: str = "",
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ stroke_width: float = 0,
+ anchor: str | None = None,
+ ink: int = 0,
+ start: tuple[float, float] | None = None,
+ *args: Any,
+ **kwargs: Any,
+ ) -> tuple[Image.core.ImagingCore, tuple[int, int]]:
+ """
+ Create a bitmap for the text.
+
+ If the font uses antialiasing, the bitmap should have mode ``L`` and use a
+ maximum value of 255. If the font has embedded color data, the bitmap
+ should have mode ``RGBA``. Otherwise, it should have mode ``1``.
+
+ :param text: Text to render.
+ :param mode: Used by some graphics drivers to indicate what mode the
+ driver prefers; if empty, the renderer may return either
+ mode. Note that the mode is always a string, to simplify
+ C-level implementations.
+
+ .. versionadded:: 1.1.5
+
+ :param direction: Direction of the text. It can be 'rtl' (right to
+ left), 'ltr' (left to right) or 'ttb' (top to bottom).
+ Requires libraqm.
+
+ .. versionadded:: 4.2.0
+
+ :param features: A list of OpenType font features to be used during text
+ layout. This is usually used to turn on optional
+ font features that are not enabled by default,
+ for example 'dlig' or 'ss01', but can be also
+ used to turn off default font features for
+ example '-liga' to disable ligatures or '-kern'
+ to disable kerning. To get all supported
+ features, see
+ https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
+ Requires libraqm.
+
+ .. versionadded:: 4.2.0
+
+ :param language: Language of the text. Different languages may use
+ different glyph shapes or ligatures. This parameter tells
+ the font which language the text is in, and to apply the
+ correct substitutions as appropriate, if available.
+ It should be a `BCP 47 language code
+ `_
+ Requires libraqm.
+
+ .. versionadded:: 6.0.0
+
+ :param stroke_width: The width of the text stroke.
+
+ .. versionadded:: 6.2.0
+
+ :param anchor: The text anchor alignment. Determines the relative location of
+ the anchor to the text. The default alignment is top left,
+ specifically ``la`` for horizontal text and ``lt`` for
+ vertical text. See :ref:`text-anchors` for details.
+
+ .. versionadded:: 8.0.0
+
+ :param ink: Foreground ink for rendering in RGBA mode.
+
+ .. versionadded:: 8.0.0
+
+ :param start: Tuple of horizontal and vertical offset, as text may render
+ differently when starting at fractional coordinates.
+
+ .. versionadded:: 9.4.0
+
+ :return: A tuple of an internal PIL storage memory instance as defined by the
+ :py:mod:`PIL.Image.core` interface module, and the text offset, the
+ gap between the starting coordinate and the first marking
+ """
+ _string_length_check(text)
+ if start is None:
+ start = (0, 0)
+
+ def fill(width: int, height: int) -> Image.core.ImagingCore:
+ size = (width, height)
+ Image._decompression_bomb_check(size)
+ return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)
+
+ return self.font.render(
+ text,
+ fill,
+ mode,
+ direction,
+ features,
+ language,
+ stroke_width,
+ kwargs.get("stroke_filled", False),
+ anchor,
+ ink,
+ start,
+ )
+
+ def font_variant(
+ self,
+ font: StrOrBytesPath | BinaryIO | None = None,
+ size: float | None = None,
+ index: int | None = None,
+ encoding: str | None = None,
+ layout_engine: Layout | None = None,
+ ) -> FreeTypeFont:
+ """
+ Create a copy of this FreeTypeFont object,
+ using any specified arguments to override the settings.
+
+ Parameters are identical to the parameters used to initialize this
+ object.
+
+ :return: A FreeTypeFont object.
+ """
+ if font is None:
+ try:
+ font = BytesIO(self.font_bytes)
+ except AttributeError:
+ font = self.path
+ return FreeTypeFont(
+ font=font,
+ size=self.size if size is None else size,
+ index=self.index if index is None else index,
+ encoding=self.encoding if encoding is None else encoding,
+ layout_engine=layout_engine or self.layout_engine,
+ )
+
+ def get_variation_names(self) -> list[bytes]:
+ """
+ :returns: A list of the named styles in a variation font.
+ :exception OSError: If the font is not a variation font.
+ """
+ names = []
+ for name in self.font.getvarnames():
+ name = name.replace(b"\x00", b"")
+ if name not in names:
+ names.append(name)
+ return names
+
+ def set_variation_by_name(self, name: str | bytes) -> None:
+ """
+ :param name: The name of the style.
+ :exception OSError: If the font is not a variation font.
+ """
+ names = self.get_variation_names()
+ if not isinstance(name, bytes):
+ name = name.encode()
+ index = names.index(name) + 1
+
+ if index == getattr(self, "_last_variation_index", None):
+ # When the same name is set twice in a row,
+ # there is an 'unknown freetype error'
+ # https://savannah.nongnu.org/bugs/?56186
+ return
+ self._last_variation_index = index
+
+ self.font.setvarname(index)
+
+ def get_variation_axes(self) -> list[Axis]:
+ """
+ :returns: A list of the axes in a variation font.
+ :exception OSError: If the font is not a variation font.
+ """
+ axes = self.font.getvaraxes()
+ for axis in axes:
+ if axis["name"]:
+ axis["name"] = axis["name"].replace(b"\x00", b"")
+ return axes
+
+ def set_variation_by_axes(self, axes: list[float]) -> None:
+ """
+ :param axes: A list of values for each axis.
+ :exception OSError: If the font is not a variation font.
+ """
+ self.font.setvaraxes(axes)
+
+
+class TransposedFont:
+ """Wrapper for writing rotated or mirrored text"""
+
+ def __init__(
+ self, font: ImageFont | FreeTypeFont, orientation: Image.Transpose | None = None
+ ):
+ """
+ Wrapper that creates a transposed font from any existing font
+ object.
+
+ :param font: A font object.
+ :param orientation: An optional orientation. If given, this should
+ be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,
+ Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or
+ Image.Transpose.ROTATE_270.
+ """
+ self.font = font
+ self.orientation = orientation # any 'transpose' argument, or None
+
+ def getmask(
+ self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any
+ ) -> Image.core.ImagingCore:
+ im = self.font.getmask(text, mode, *args, **kwargs)
+ if self.orientation is not None:
+ return im.transpose(self.orientation)
+ return im
+
+ def getbbox(
+ self, text: str | bytes, *args: Any, **kwargs: Any
+ ) -> tuple[int, int, float, float]:
+ # TransposedFont doesn't support getmask2, move top-left point to (0, 0)
+ # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont
+ left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)
+ width = right - left
+ height = bottom - top
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
+ return 0, 0, height, width
+ return 0, 0, width, height
+
+ def getlength(self, text: str | bytes, *args: Any, **kwargs: Any) -> float:
+ if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):
+ msg = "text length is undefined for text rotated by 90 or 270 degrees"
+ raise ValueError(msg)
+ return self.font.getlength(text, *args, **kwargs)
+
+
+def load(filename: str) -> ImageFont:
+ """
+ Load a font file. This function loads a font object from the given
+ bitmap font file, and returns the corresponding font object. For loading TrueType
+ or OpenType fonts instead, see :py:func:`~PIL.ImageFont.truetype`.
+
+ :param filename: Name of font file.
+ :return: A font object.
+ :exception OSError: If the file could not be read.
+ """
+ f = ImageFont()
+ f._load_pilfont(filename)
+ return f
+
+
+def truetype(
+ font: StrOrBytesPath | BinaryIO,
+ size: float = 10,
+ index: int = 0,
+ encoding: str = "",
+ layout_engine: Layout | None = None,
+) -> FreeTypeFont:
+ """
+ Load a TrueType or OpenType font from a file or file-like object,
+ and create a font object. This function loads a font object from the given
+ file or file-like object, and creates a font object for a font of the given
+ size. For loading bitmap fonts instead, see :py:func:`~PIL.ImageFont.load`
+ and :py:func:`~PIL.ImageFont.load_path`.
+
+ Pillow uses FreeType to open font files. On Windows, be aware that FreeType
+ will keep the file open as long as the FreeTypeFont object exists. Windows
+ limits the number of files that can be open in C at once to 512, so if many
+ fonts are opened simultaneously and that limit is approached, an
+ ``OSError`` may be thrown, reporting that FreeType "cannot open resource".
+ A workaround would be to copy the file(s) into memory, and open that instead.
+
+ This function requires the _imagingft service.
+
+ :param font: A filename or file-like object containing a TrueType font.
+ If the file is not found in this filename, the loader may also
+ search in other directories, such as:
+
+ * The :file:`fonts/` directory on Windows,
+ * :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/`
+ and :file:`~/Library/Fonts/` on macOS.
+ * :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`,
+ and :file:`/usr/share/fonts` on Linux; or those specified by
+ the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables
+ for user-installed and system-wide fonts, respectively.
+
+ :param size: The requested size, in pixels.
+ :param index: Which font face to load (default is first available face).
+ :param encoding: Which font encoding to use (default is Unicode). Possible
+ encodings include (see the FreeType documentation for more
+ information):
+
+ * "unic" (Unicode)
+ * "symb" (Microsoft Symbol)
+ * "ADOB" (Adobe Standard)
+ * "ADBE" (Adobe Expert)
+ * "ADBC" (Adobe Custom)
+ * "armn" (Apple Roman)
+ * "sjis" (Shift JIS)
+ * "gb " (PRC)
+ * "big5"
+ * "wans" (Extended Wansung)
+ * "joha" (Johab)
+ * "lat1" (Latin-1)
+
+ This specifies the character set to use. It does not alter the
+ encoding of any text provided in subsequent operations.
+ :param layout_engine: Which layout engine to use, if available:
+ :attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.
+ If it is available, Raqm layout will be used by default.
+ Otherwise, basic layout will be used.
+
+ Raqm layout is recommended for all non-English text. If Raqm layout
+ is not required, basic layout will have better performance.
+
+ You can check support for Raqm layout using
+ :py:func:`PIL.features.check_feature` with ``feature="raqm"``.
+
+ .. versionadded:: 4.2.0
+ :return: A font object.
+ :exception OSError: If the file could not be read.
+ :exception ValueError: If the font size is not greater than zero.
+ """
+
+ def freetype(font: StrOrBytesPath | BinaryIO) -> FreeTypeFont:
+ return FreeTypeFont(font, size, index, encoding, layout_engine)
+
+ try:
+ return freetype(font)
+ except OSError:
+ if not is_path(font):
+ raise
+ ttf_filename = os.path.basename(font)
+
+ dirs = []
+ if sys.platform == "win32":
+ # check the windows font repository
+ # NOTE: must use uppercase WINDIR, to work around bugs in
+ # 1.5.2's os.environ.get()
+ windir = os.environ.get("WINDIR")
+ if windir:
+ dirs.append(os.path.join(windir, "fonts"))
+ elif sys.platform in ("linux", "linux2"):
+ data_home = os.environ.get("XDG_DATA_HOME")
+ if not data_home:
+ # The freedesktop spec defines the following default directory for
+ # when XDG_DATA_HOME is unset or empty. This user-level directory
+ # takes precedence over system-level directories.
+ data_home = os.path.expanduser("~/.local/share")
+ xdg_dirs = [data_home]
+
+ data_dirs = os.environ.get("XDG_DATA_DIRS")
+ if not data_dirs:
+ # Similarly, defaults are defined for the system-level directories
+ data_dirs = "/usr/local/share:/usr/share"
+ xdg_dirs += data_dirs.split(":")
+
+ dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs]
+ elif sys.platform == "darwin":
+ dirs += [
+ "/Library/Fonts",
+ "/System/Library/Fonts",
+ os.path.expanduser("~/Library/Fonts"),
+ ]
+
+ ext = os.path.splitext(ttf_filename)[1]
+ first_font_with_a_different_extension = None
+ for directory in dirs:
+ for walkroot, walkdir, walkfilenames in os.walk(directory):
+ for walkfilename in walkfilenames:
+ if ext and walkfilename == ttf_filename:
+ return freetype(os.path.join(walkroot, walkfilename))
+ elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:
+ fontpath = os.path.join(walkroot, walkfilename)
+ if os.path.splitext(fontpath)[1] == ".ttf":
+ return freetype(fontpath)
+ if not ext and first_font_with_a_different_extension is None:
+ first_font_with_a_different_extension = fontpath
+ if first_font_with_a_different_extension:
+ return freetype(first_font_with_a_different_extension)
+ raise
+
+
+def load_path(filename: str | bytes) -> ImageFont:
+ """
+ Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
+ bitmap font along the Python path.
+
+ :param filename: Name of font file.
+ :return: A font object.
+ :exception OSError: If the file could not be read.
+ """
+ if not isinstance(filename, str):
+ filename = filename.decode("utf-8")
+ for directory in sys.path:
+ try:
+ return load(os.path.join(directory, filename))
+ except OSError:
+ pass
+ msg = f'cannot find font file "{filename}" in sys.path'
+ if os.path.exists(filename):
+ msg += f', did you mean ImageFont.load("{filename}") instead?'
+
+ raise OSError(msg)
+
+
+def load_default_imagefont() -> ImageFont:
+ f = ImageFont()
+ f._load_pilfont_data(
+ # courB08
+ BytesIO(
+ base64.b64decode(
+ b"""
+UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA
+BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL
+AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA
+AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB
+ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A
+BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB
+//kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA
+AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH
+AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
+ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
+AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
+/gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
+AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
+AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
+AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
+BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
+AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
+2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
+AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
++gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
+////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
+BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
+AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
+AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
+AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
+BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
+//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
+AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
+AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
+mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
+AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
+AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
+AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
+Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB
+//sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA
+AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ
+AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
+DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
+AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
++wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
+AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
+///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
+AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
+BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
+Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
+eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
+AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
++gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
+////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
+BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
+AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
+AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
+Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
+Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
+//cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
+AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
+AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
+LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
+AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
+AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
+AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
+AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
+AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
+EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
+AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
+pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
+AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
++QAGAAIAzgAKANUAEw==
+"""
+ )
+ ),
+ Image.open(
+ BytesIO(
+ base64.b64decode(
+ b"""
+iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
+Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
+M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
+LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
+IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
+Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
+NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx
+in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9
+SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY
+AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt
+y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG
+ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY
+lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H
+/Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3
+AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47
+c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/
+/yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw
+pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv
+oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR
+evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
+AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
+Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
+w7IkEbzhVQAAAABJRU5ErkJggg==
+"""
+ )
+ )
+ ),
+ )
+ return f
+
+
+def load_default(size: float | None = None) -> FreeTypeFont | ImageFont:
+ """If FreeType support is available, load a version of Aileron Regular,
+ https://dotcolon.net/fonts/aileron, with a more limited character set.
+
+ Otherwise, load a "better than nothing" font.
+
+ .. versionadded:: 1.1.4
+
+ :param size: The font size of Aileron Regular.
+
+ .. versionadded:: 10.1.0
+
+ :return: A font object.
+ """
+ if isinstance(core, ModuleType) or size is not None:
+ return truetype(
+ BytesIO(
+ base64.b64decode(
+ b"""
+AAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA
+AduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA
+MAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh
+tdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk
+OAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889QALA+gAAAAA0Bqf2QAAAADhCh2h/
+2r/LgOxAyAAAAAIAAIAAAAAAAAAAQAAA8r/GgAAA7j/av9qA7EAAQAAAAAAAAAAAAAAAAAAAHQAAQ
+AAAHQAQwAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAADAfoBkAAFAAgCigJYAAAASwKKAlgAAAFeADI
+BPgAAAAAFAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABVS1dOAEAAIPsCAwL/GgDIA8oA5iAAAJMAAAAA
+AhICsgAAACAAAwH0AAAAAAAAAU0AAADYAAAA8gA5AVMAVgJEAEYCRAA1AuQAKQKOAEAAsAArATsAZ
+AE7AB4CMABVAkQAUADc/+EBEgAgANwAJQEv//sCRAApAkQAggJEADwCRAAtAkQAIQJEADkCRAArAk
+QAMgJEACwCRAAxANwAJQDc/+ECRABnAkQAUAJEAEQB8wAjA1QANgJ/AB0CcwBkArsALwLFAGQCSwB
+kAjcAZALGAC8C2gBkAQgAZAIgADcCYQBkAj8AZANiAGQCzgBkAuEALwJWAGQC3QAvAmsAZAJJADQC
+ZAAiAqoAXgJuACADuAAaAnEAGQJFABMCTwAuATMAYgEv//sBJwAiAkQAUAH0ADIBLAApAhMAJAJjA
+EoCEQAeAmcAHgIlAB4BIgAVAmcAHgJRAEoA7gA+AOn/8wIKAEoA9wBGA1cASgJRAEoCSgAeAmMASg
+JnAB4BSgBKAcsAGAE5ABQCUABCAgIAAQMRAAEB4v/6AgEAAQHOABQBLwBAAPoAYAEvACECRABNA0Y
+AJAItAHgBKgAcAkQAUAEsAHQAygAgAi0AOQD3ADYA9wAWAaEANgGhABYCbAAlAYMAeAGDADkA6/9q
+AhsAFAIKABUB/QAVAAAAAwAAAAMAAAAcAAEAAAAAAKQAAwABAAAAHAAEAIgAAAAeABAAAwAOAH4Aq
+QCrALEAtAC3ALsgGSAdICYgOiBEISL7Av//AAAAIACpAKsAsAC0ALcAuyAYIBwgJiA5IEQhIvsB//
+//4/+5/7j/tP+y/7D/reBR4E/gR+A14CzfTwVxAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAEGAAABAAAAAAAAAAECAAAAAgAAAAAAAAAAAAAAAAAAAAEAAAMEBQYHCAkKCwwNDg8QERIT
+FBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMT
+U5PUFFSU1RVVldYWVpbXF1eX2BhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAA
+AAAAAAYnFmAAAAAABlAAAAAAAAAAAAAAAAAAAAAAAAAAAAY2htAAAAAAAAAABrbGlqAAAAAHAAbm9
+ycwBnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmACYAJgAmAD4AUgCCAMoBCgFO
+AVwBcgGIAaYBvAHKAdYB6AH2AgwCIAJKAogCpgLWAw4DIgNkA5wDugPUA+gD/AQQBEYEogS8BPoFJ
+gVSBWoFgAWwBcoF1gX6BhQGJAZMBmgGiga0BuIHGgdUB2YHkAeiB8AH3AfyCAoIHAgqCDoITghcCG
+oIogjSCPoJKglYCXwJwgnqCgIKKApACl4Klgq8CtwLDAs8C1YLjAuyC9oL7gwMDCYMSAxgDKAMrAz
+qDQoNTA1mDYQNoA2uDcAN2g3oDfYODA4iDkoOXA5sDnoOnA7EDvwAAAAFAAAAAAH0ArwAAwAGAAkA
+DAAPAAAxESERAxMhExcRASELARETAfT6qv6syKr+jgFUqsiqArz9RAGLAP/+1P8B/v3VAP8BLP4CA
+P8AAgA5//IAuQKyAAMACwAANyMDMwIyFhQGIiY0oE4MZk84JCQ4JLQB/v3AJDgkJDgAAgBWAeUBPA
+LfAAMABwAAEyMnMxcjJzOmRgpagkYKWgHl+vr6AAAAAAIARgAAAf4CsgAbAB8AAAEHMxUjByM3Iwc
+jNyM1MzcjNTM3MwczNzMHMxUrAQczAZgdZXEvOi9bLzovWmYdZXEvOi9bLzovWp9bHlsBn4w429vb
+2ziMONvb29s4jAAAAAMANf+mAg4DDAAfACYALAAAJRQGBxUjNS4BJzMeARcRLgE0Njc1MxUeARcjJ
+icVHgEBFBYXNQ4BExU+ATU0Ag5xWDpgcgRcBz41Xl9oVTpVYwpcC1ttXP6cLTQuM5szOrVRZwlOTQ
+ZqVzZECAEAGlukZAlOTQdrUG8O7iNlAQgxNhDlCDj+8/YGOjReAAAAAAUAKf/yArsCvAAHAAsAFQA
+dACcAABIyFhQGIiY0EyMBMwQiBhUUFjI2NTQSMhYUBiImNDYiBhUUFjI2NTR5iFBQiFCVVwHAV/5c
+OiMjOiPmiFBQiFCxOiMjOiMCvFaSVlaS/ZoCsjIzMC80NC8w/uNWklZWkhozMC80NC8wAAAAAgBA/
+/ICbgLAACIALgAAARUjEQYjIiY1NDY3LgE1NDYzMhcVJiMiBhUUFhcWOwE1MxUFFBYzMjc1IyIHDg
+ECbmBcYYOOVkg7R4hsQjY4Q0RNRD4SLDxW/pJUXzksPCkUUk0BgUb+zBVUZ0BkDw5RO1huCkULQzp
+COAMBcHDHRz0J/AIHRQAAAAEAKwHlAIUC3wADAAATIycze0YKWgHl+gAAAAABAGT/sAEXAwwACQAA
+EzMGEBcjLgE0Nt06dXU6OUBAAwzG/jDGVePs4wAAAAEAHv+wANEDDAAJAAATMx4BFAYHIzYQHjo5Q
+EA5OnUDDFXj7ONVxgHQAAAAAQBVAFIB2wHbAA4AAAE3FwcXBycHJzcnNxcnMwEtmxOfcTJjYzJxnx
+ObCj4BKD07KYolmZkliik7PbMAAQBQAFUB9AIlAAsAAAEjFSM1IzUzNTMVMwH0tTq1tTq1AR/Kyjj
+OzgAAAAAB/+H/iACMAGQABAAANwcjNzOMWlFOXVrS3AAAAQAgAP8A8gE3AAMAABMjNTPy0tIA/zgA
+AQAl//IApQByAAcAADYyFhQGIiY0STgkJDgkciQ4JCQ4AAAAAf/7/+IBNALQAAMAABcjEzM5Pvs+H
+gLuAAAAAAIAKf/yAhsCwAADAAcAABIgECA2IBAgKQHy/g5gATL+zgLA/TJEAkYAAAAAAQCCAAABlg
+KyAAgAAAERIxEHNTc2MwGWVr6SIygCsv1OAldxW1sWAAEAPAAAAg4CwAAZAAA3IRUhNRM+ATU0JiM
+iDwEjNz4BMzIWFRQGB7kBUv4x+kI2QTt+EAFWAQp8aGVtSl5GRjEA/0RVLzlLmAoKa3FsUkNxXQAA
+AAEALf/yAhYCwAAqAAABHgEVFAYjIi8BMxceATMyNjU0KwE1MzI2NTQmIyIGDwEjNz4BMzIWFRQGA
+YxBSZJo2RUBVgEHV0JBUaQREUBUQzc5TQcBVgEKfGhfcEMBbxJbQl1x0AoKRkZHPn9GSD80QUVCCg
+pfbGBPOlgAAAACACEAAAIkArIACgAPAAAlIxUjNSE1ATMRMyMRBg8BAiRXVv6qAVZWV60dHLCurq4
+rAdn+QgFLMibzAAABADn/8gIZArIAHQAAATIWFRQGIyIvATMXFjMyNjU0JiMiByMTIRUhBzc2ATNv
+d5Fl1RQBVgIad0VSTkVhL1IwAYj+vh8rMAHHgGdtgcUKCoFXTU5bYgGRRvAuHQAAAAACACv/8gITA
+sAAFwAjAAABMhYVFAYjIhE0NjMyFh8BIycmIyIDNzYTMjY1NCYjIgYVFBYBLmp7imr0l3RZdAgBXA
+IYZ5wKJzU6QVNJSz5SUAHSgWltiQFGxcNlVQoKdv7sPiz+ZF1LTmJbU0lhAAAAAQAyAAACGgKyAAY
+AAAEVASMBITUCGv6oXAFL/oECsij9dgJsRgAAAAMALP/xAhgCwAAWACAALAAAAR4BFRQGIyImNTQ2
+Ny4BNTQ2MhYVFAYmIgYVFBYyNjU0AzI2NTQmIyIGFRQWAZQ5S5BmbIpPOjA7ecp5P2F8Q0J8RIVJS
+0pLTEtOAW0TXTxpZ2ZqPF0SE1A3VWVlVTdQ/UU0N0RENzT9/ko+Ok1NOj1LAAIAMf/yAhkCwAAXAC
+MAAAEyERQGIyImLwEzFxYzMhMHBiMiJjU0NhMyNjU0JiMiBhUUFgEl9Jd0WXQIAVwCGGecCic1SWp
+7imo+UlBAQVNJAsD+usXDZVUKCnYBFD4sgWltif5kW1NJYV1LTmIAAAACACX/8gClAiAABwAPAAAS
+MhYUBiImNBIyFhQGIiY0STgkJDgkJDgkJDgkAiAkOCQkOP52JDgkJDgAAAAC/+H/iAClAiAABwAMA
+AASMhYUBiImNBMHIzczSTgkJDgkaFpSTl4CICQ4JCQ4/mba5gAAAQBnAB4B+AH0AAYAAAENARUlNS
+UB+P6qAVb+bwGRAbCmpkbJRMkAAAIAUAC7AfQBuwADAAcAAAEhNSERITUhAfT+XAGk/lwBpAGDOP8
+AOAABAEQAHgHVAfQABgAAARUFNS0BNQHV/m8BVv6qAStEyUSmpkYAAAAAAgAj//IB1ALAABgAIAAA
+ATIWFRQHDgEHIz4BNz4BNTQmIyIGByM+ARIyFhQGIiY0AQRibmktIAJWBSEqNig+NTlHBFoDezQ4J
+CQ4JALAZ1BjaS03JS1DMD5LLDQ/SUVgcv2yJDgkJDgAAAAAAgA2/5gDFgKYADYAQgAAAQMGFRQzMj
+Y1NCYjIg4CFRQWMzI2NxcGIyImNTQ+AjMyFhUUBiMiJwcGIyImNTQ2MzIfATcHNzYmIyIGFRQzMjY
+Cej8EJjJJlnBAfGQ+oHtAhjUYg5OPx0h2k06Os3xRWQsVLjY5VHtdPBwJETcJDyUoOkZEJz8B0f74
+EQ8kZl6EkTFZjVOLlyknMVm1pmCiaTq4lX6CSCknTVRmmR8wPdYnQzxuSWVGAAIAHQAAAncCsgAHA
+AoAACUjByMTMxMjATMDAcj+UVz4dO5d/sjPZPT0ArL9TgE6ATQAAAADAGQAAAJMArIAEAAbACcAAA
+EeARUUBgcGKwERMzIXFhUUJRUzMjc2NTQnJiMTPgE1NCcmKwEVMzIBvkdHZkwiNt7LOSGq/oeFHBt
+hahIlSTM+cB8Yj5UWAW8QT0VYYgwFArIEF5Fv1eMED2NfDAL93AU+N24PBP0AAAAAAQAv//ICjwLA
+ABsAAAEyFh8BIycmIyIGFRQWMzI/ATMHDgEjIiY1NDYBdX+PCwFWAiKiaHx5ZaIiAlYBCpWBk6a0A
+sCAagoKpqN/gaOmCgplhcicn8sAAAIAZAAAAp8CsgAMABkAAAEeARUUBgcGKwERMzITPgE1NCYnJi
+sBETMyAY59lJp8IzXN0jUVWmdjWRs5d3I4Aq4QqJWUug8EArL9mQ+PeHGHDgX92gAAAAABAGQAAAI
+vArIACwAAJRUhESEVIRUhFSEVAi/+NQHB/pUBTf6zRkYCskbwRvAAAAABAGQAAAIlArIACQAAExUh
+FSERIxEhFboBQ/69VgHBAmzwRv7KArJGAAAAAAEAL//yAo8CwAAfAAABMxEjNQcGIyImNTQ2MzIWH
+wEjJyYjIgYVFBYzMjY1IwGP90wfPnWTprSSf48LAVYCIqJofHllVG+hAU3+s3hARsicn8uAagoKpq
+N/gaN1XAAAAAEAZAAAAowCsgALAAABESMRIREjETMRIRECjFb+hFZWAXwCsv1OAS7+0gKy/sQBPAA
+AAAABAGQAAAC6ArIAAwAAMyMRM7pWVgKyAAABADf/8gHoArIAEwAAAREUBw4BIyImLwEzFxYzMjc2
+NREB6AIFcGpgbQIBVgIHfXQKAQKy/lYxIltob2EpKYyEFD0BpwAAAAABAGQAAAJ0ArIACwAACQEjA
+wcVIxEzEQEzATsBJ3ntQlZWAVVlAWH+nwEnR+ACsv6RAW8AAQBkAAACLwKyAAUAACUVIREzEQIv/j
+VWRkYCsv2UAAABAGQAAAMUArIAFAAAAREjETQ3BgcDIwMmJxYVESMRMxsBAxRWAiMxemx8NxsCVo7
+MywKy/U4BY7ZLco7+nAFmoFxLtP6dArL9lwJpAAAAAAEAZAAAAoACsgANAAAhIwEWFREjETMBJjUR
+MwKAhP67A1aEAUUDVAJeeov+pwKy/aJ5jAFZAAAAAgAv//ICuwLAAAkAEwAAEiAWFRQGICY1NBIyN
+jU0JiIGFRTbATSsrP7MrNrYenrYegLAxaKhxsahov47nIeIm5uIhwACAGQAAAJHArIADgAYAAABHg
+EVFAYHBisBESMRMzITNjQnJisBETMyAZRUX2VOHzuAVtY7GlxcGDWIiDUCrgtnVlVpCgT+5gKy/rU
+V1BUF/vgAAAACAC//zAK9AsAAEgAcAAAlFhcHJiMiBwYjIiY1NDYgFhUUJRQWMjY1NCYiBgI9PUMx
+UDcfKh8omqysATSs/dR62Hp62HpICTg7NgkHxqGixcWitbWHnJyHiJubAAIAZAAAAlgCsgAXACMAA
+CUWFyMmJyYnJisBESMRMzIXHgEVFAYHFiUzMjc+ATU0JyYrAQIqDCJfGQwNWhAhglbiOx9QXEY1Tv
+6bhDATMj1lGSyMtYgtOXR0BwH+1wKyBApbU0BSESRAAgVAOGoQBAABADT/8gIoAsAAJQAAATIWFyM
+uASMiBhUUFhceARUUBiMiJiczHgEzMjY1NCYnLgE1NDYBOmd2ClwGS0E6SUNRdW+HZnKKC1wPWkQ9
+Uk1cZGuEAsBwXUJHNjQ3OhIbZVZZbm5kREo+NT5DFRdYUFdrAAAAAAEAIgAAAmQCsgAHAAABIxEjE
+SM1IQJk9lb2AkICbP2UAmxGAAEAXv/yAmQCsgAXAAABERQHDgEiJicmNREzERQXHgEyNjc2NRECZA
+IIgfCBCAJWAgZYmlgGAgKy/k0qFFxzc1wUKgGz/lUrEkRQUEQSKwGrAAAAAAEAIAAAAnoCsgAGAAA
+hIwMzGwEzAYJ07l3N1FwCsv2PAnEAAAEAGgAAA7ECsgAMAAABAyMLASMDMxsBMxsBA7HAcZyicrZi
+kaB0nJkCsv1OAlP9rQKy/ZsCW/2kAmYAAAEAGQAAAm8CsgALAAAhCwEjEwMzGwEzAxMCCsrEY/bkY
+re+Y/D6AST+3AFcAVb+5gEa/q3+oQAAAQATAAACUQKyAAgAAAERIxEDMxsBMwFdVvRjwLphARD+8A
+EQAaL+sQFPAAABAC4AAAI5ArIACQAAJRUhNQEhNSEVAQI5/fUBof57Aen+YUZGQgIqRkX92QAAAAA
+BAGL/sAEFAwwABwAAARUjETMVIxEBBWlpowMMOP0UOANcAAAB//v/4gE0AtAAAwAABSMDMwE0Pvs+
+HgLuAAAAAQAi/7AAxQMMAAcAABcjNTMRIzUzxaNpaaNQOALsOAABAFAA1wH0AmgABgAAJQsBIxMzE
+wGwjY1GsESw1wFZ/qcBkf5vAAAAAQAy/6oBwv/iAAMAAAUhNSEBwv5wAZBWOAAAAAEAKQJEALYCsg
+ADAAATIycztjhVUAJEbgAAAAACACT/8gHQAiAAHQAlAAAhJwcGIyImNTQ2OwE1NCcmIyIHIz4BMzI
+XFh0BFBcnMjY9ASYVFAF6CR0wVUtgkJoiAgdgaQlaBm1Zrg4DCuQ9R+5MOSFQR1tbDiwUUXBUXowf
+J8c9SjRORzYSgVwAAAAAAgBK//ICRQLfABEAHgAAATIWFRQGIyImLwEVIxEzETc2EzI2NTQmIyIGH
+QEUFgFUcYCVbiNJEyNWVigySElcU01JXmECIJd4i5QTEDRJAt/+3jkq/hRuZV55ZWsdX14AAQAe//
+IB9wIgABgAAAEyFhcjJiMiBhUUFjMyNjczDgEjIiY1NDYBF152DFocbEJXU0A1Rw1aE3pbaoKQAiB
+oWH5qZm1tPDlaXYuLgZcAAAACAB7/8gIZAt8AEQAeAAABESM1BwYjIiY1NDYzMhYfAREDMjY9ATQm
+IyIGFRQWAhlWKDJacYCVbiNJEyOnSV5hQUlcUwLf/SFVOSqXeIuUExA0ARb9VWVrHV9ebmVeeQACA
+B7/8gH9AiAAFQAbAAABFAchHgEzMjY3Mw4BIyImNTQ2MzIWJyIGByEmAf0C/oAGUkA1SwlaD4FXbI
+WObmt45UBVBwEqDQEYFhNjWD84W16Oh3+akU9aU60AAAEAFQAAARoC8gAWAAATBh0BMxUjESMRIzU
+zNTQ3PgEzMhcVJqcDbW1WOTkDB0k8Hx5oAngVITRC/jQBzEIsJRs5PwVHEwAAAAIAHv8uAhkCIAAi
+AC8AAAERFAcOASMiLwEzFx4BMzI2NzY9AQcGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZAQSEd
+NwRAVcBBU5DTlUDASgyWnGAlW4jSRMjp0leYUFJXFMCEv5wSh1zeq8KCTI8VU0ZIQk5Kpd4i5QTED
+RJ/iJlax1fXm5lXnkAAQBKAAACCgLkABcAAAEWFREjETQnLgEHDgEdASMRMxE3NjMyFgIIAlYCBDs
+6RVRWViE5UVViAYUbQP7WASQxGzI7AQJyf+kC5P7TPSxUAAACAD4AAACsAsAABwALAAASMhYUBiIm
+NBMjETNeLiAgLiBiVlYCwCAuICAu/WACEgAC//P/LgCnAsAABwAVAAASMhYUBiImNBcRFAcGIyInN
+RY3NjURWS4gIC4gYgMLcRwNSgYCAsAgLiAgLo79wCUbZAJGBzMOHgJEAAAAAQBKAAACCALfAAsAAC
+EnBxUjETMREzMHEwGTwTJWVvdu9/rgN6kC3/4oAQv6/ugAAQBG//wA3gLfAA8AABMRFBceATcVBiM
+iJicmNRGcAQIcIxkkKi4CAQLf/bkhERoSBD4EJC8SNAJKAAAAAQBKAAADEAIgACQAAAEWFREjETQn
+JiMiFREjETQnJiMiFREjETMVNzYzMhYXNzYzMhYDCwVWBAxedFYEDF50VlYiJko7ThAvJkpEVAGfI
+jn+vAEcQyRZ1v76ARxDJFnW/voCEk08HzYtRB9HAAAAAAEASgAAAgoCIAAWAAABFhURIxE0JyYjIg
+YdASMRMxU3NjMyFgIIAlYCCXBEVVZWITlRVWIBhRtA/tYBJDEbbHR/6QISWz0sVAAAAAACAB7/8gI
+sAiAABwARAAASIBYUBiAmNBIyNjU0JiIGFRSlAQCHh/8Ah7ieWlqeWgIgn/Cfn/D+s3ZfYHV1YF8A
+AgBK/zwCRQIgABEAHgAAATIWFRQGIyImLwERIxEzFTc2EzI2NTQmIyIGHQEUFgFUcYCVbiNJEyNWV
+igySElcU01JXmECIJd4i5QTEDT+8wLWVTkq/hRuZV55ZWsdX14AAgAe/zwCGQIgABEAHgAAAREjEQ
+cGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZVigyWnGAlW4jSRMjp0leYUFJXFMCEv0qARk5Kpd
+4i5QTEDRJ/iJlax1fXm5lXnkAAQBKAAABPgIeAA0AAAEyFxUmBhURIxEzFTc2ARoWDkdXVlYwIwIe
+B0EFVlf+0gISU0cYAAEAGP/yAa0CIAAjAAATMhYXIyYjIgYVFBYXHgEVFAYjIiYnMxYzMjY1NCYnL
+gE1NDbkV2MJWhNdKy04PF1XbVhWbgxaE2ktOjlEUllkAiBaS2MrJCUoEBlPQkhOVFZoKCUmLhIWSE
+BIUwAAAAEAFP/4ARQCiQAXAAATERQXHgE3FQYjIiYnJjURIzUzNTMVMxWxAQMmMx8qMjMEAUdHVmM
+BzP7PGw4mFgY/BSwxDjQBNUJ7e0IAAAABAEL/8gICAhIAFwAAAREjNQcGIyImJyY1ETMRFBceATMy
+Nj0BAgJWITlRT2EKBVYEBkA1RFECEv3uWj4qTToiOQE+/tIlJC43c4DpAAAAAAEAAQAAAfwCEgAGA
+AABAyMDMxsBAfzJaclfop8CEv3uAhL+LQHTAAABAAEAAAMLAhIADAAAAQMjCwEjAzMbATMbAQMLqW
+Z2dmapY3t0a3Z7AhL97gG+/kICEv5AAcD+QwG9AAAB//oAAAHWAhIACwAAARMjJwcjEwMzFzczARq
+8ZIuKY763ZoWFYwEO/vLV1QEMAQbNzQAAAQAB/y4B+wISABEAAAEDDgEjIic1FjMyNj8BAzMbAQH7
+2iFZQB8NDRIpNhQH02GenQIS/cFVUAJGASozEwIt/i4B0gABABQAAAGxAg4ACQAAJRUhNQEhNSEVA
+QGx/mMBNP7iAYL+zkREQgGIREX+ewAAAAABAED/sAEOAwwALAAAASMiBhUUFxYVFAYHHgEVFAcGFR
+QWOwEVIyImNTQ3NjU0JzU2NTQnJjU0NjsBAQ4MKiMLDS4pKS4NCyMqDAtERAwLUlILDERECwLUGBk
+WTlsgKzUFBTcrIFtOFhkYOC87GFVMIkUIOAhFIkxVGDsvAAAAAAEAYP84AJoDIAADAAAXIxEzmjo6
+yAPoAAEAIf+wAO8DDAAsAAATFQYVFBcWFRQGKwE1MzI2NTQnJjU0NjcuATU0NzY1NCYrATUzMhYVF
+AcGFRTvUgsMREQLDCojCw0uKSkuDQsjKgwLREQMCwF6OAhFIkxVGDsvOBgZFk5bICs1BQU3KyBbTh
+YZGDgvOxhVTCJFAAABAE0A3wH2AWQAEwAAATMUIyImJyYjIhUjNDMyFhcWMzIBvjhuGywtQR0xOG4
+bLC1BHTEBZIURGCNMhREYIwAAAwAk/94DIgLoAAcAEQApAAAAIBYQBiAmECQgBhUUFiA2NTQlMhYX
+IyYjIgYUFjMyNjczDgEjIiY1NDYBAQFE3d3+vN0CB/7wubkBELn+xVBnD1wSWDo+QTcqOQZcEmZWX
+HN2Aujg/rbg4AFKpr+Mjb6+jYxbWEldV5ZZNShLVn5na34AAgB4AFIB9AGeAAUACwAAAQcXIyc3Mw
+cXIyc3AUqJiUmJifOJiUmJiQGepqampqampqYAAAIAHAHSAQ4CwAAHAA8AABIyFhQGIiY0NiIGFBY
+yNjRgakREakSTNCEhNCECwEJqQkJqCiM4IyM4AAAAAAIAUAAAAfQCCwALAA8AAAEzFSMVIzUjNTM1
+MxMhNSEBP7W1OrW1OrX+XAGkAVs4tLQ4sP31OAAAAQB0AkQBAQKyAAMAABMjNzOsOD1QAkRuAAAAA
+AEAIADsAKoBdgAHAAASMhYUBiImNEg6KCg6KAF2KDooKDoAAAIAOQBSAbUBngAFAAsAACUHIzcnMw
+UHIzcnMwELiUmJiUkBM4lJiYlJ+KampqampqYAAAABADYB5QDhAt8ABAAAEzczByM2Xk1OXQHv8Po
+AAQAWAeUAwQLfAAQAABMHIzczwV5NTl0C1fD6AAIANgHlAYsC3wAEAAkAABM3MwcjPwEzByM2Xk1O
+XapeTU5dAe/w+grw+gAAAgAWAeUBawLfAAQACQAAEwcjNzMXByM3M8FeTU5dql5NTl0C1fD6CvD6A
+AADACX/8gI1AHIABwAPABcAADYyFhQGIiY0NjIWFAYiJjQ2MhYUBiImNEk4JCQ4JOw4JCQ4JOw4JC
+Q4JHIkOCQkOCQkOCQkOCQkOCQkOAAAAAEAeABSAUoBngAFAAABBxcjJzcBSomJSYmJAZ6mpqamAAA
+AAAEAOQBSAQsBngAFAAAlByM3JzMBC4lJiYlJ+KampgAAAf9qAAABgQKyAAMAACsBATM/VwHAVwKy
+AAAAAAIAFAHIAdwClAAHABQAABMVIxUjNSM1BRUjNwcjJxcjNTMXN9pKMkoByDICKzQqATJLKysCl
+CmjoykBy46KiY3Lm5sAAQAVAAABvALyABgAAAERIxEjESMRIzUzNTQ3NjMyFxUmBgcGHQEBvFbCVj
+k5AxHHHx5iVgcDAg798gHM/jQBzEIOJRuWBUcIJDAVIRYAAAABABX//AHkAvIAJQAAJR4BNxUGIyI
+mJyY1ESYjIgcGHQEzFSMRIxEjNTM1NDc2MzIXERQBowIcIxkkKi4CAR4nXgwDbW1WLy8DEbNdOmYa
+EQQ/BCQvEjQCFQZWFSEWQv40AcxCDiUblhP9uSEAAAAAAAAWAQ4AAQAAAAAAAAATACgAAQAAAAAAA
+QAHAEwAAQAAAAAAAgAHAGQAAQAAAAAAAwAaAKIAAQAAAAAABAAHAM0AAQAAAAAABQA8AU8AAQAAAA
+AABgAPAawAAQAAAAAACAALAdQAAQAAAAAACQALAfgAAQAAAAAACwAXAjQAAQAAAAAADAAXAnwAAwA
+BBAkAAAAmAAAAAwABBAkAAQAOADwAAwABBAkAAgAOAFQAAwABBAkAAwA0AGwAAwABBAkABAAOAL0A
+AwABBAkABQB4ANUAAwABBAkABgAeAYwAAwABBAkACAAWAbwAAwABBAkACQAWAeAAAwABBAkACwAuA
+gQAAwABBAkADAAuAkwATgBvACAAUgBpAGcAaAB0AHMAIABSAGUAcwBlAHIAdgBlAGQALgAATm8gUm
+lnaHRzIFJlc2VydmVkLgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAUgBlAGcAdQBsAGEAcgAAUmV
+ndWxhcgAAMQAuADEAMAAyADsAVQBLAFcATgA7AEEAaQBsAGUAcgBvAG4ALQBSAGUAZwB1AGwAYQBy
+AAAxLjEwMjtVS1dOO0FpbGVyb24tUmVndWxhcgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAVgBlA
+HIAcwBpAG8AbgAgADEALgAxADAAMgA7AFAAUwAgADAAMAAxAC4AMQAwADIAOwBoAG8AdABjAG8Abg
+B2ACAAMQAuADAALgA3ADAAOwBtAGEAawBlAG8AdABmAC4AbABpAGIAMgAuADUALgA1ADgAMwAyADk
+AAFZlcnNpb24gMS4xMDI7UFMgMDAxLjEwMjtob3Rjb252IDEuMC43MDttYWtlb3RmLmxpYjIuNS41
+ODMyOQAAQQBpAGwAZQByAG8AbgAtAFIAZQBnAHUAbABhAHIAAEFpbGVyb24tUmVndWxhcgAAUwBvA
+HIAYQAgAFMAYQBnAGEAbgBvAABTb3JhIFNhZ2FubwAAUwBvAHIAYQAgAFMAYQBnAGEAbgBvAABTb3
+JhIFNhZ2FubwAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBsAG8AbgAuAG4AZQB0AAB
+odHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBs
+AG8AbgAuAG4AZQB0AABodHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAAAACAAAAAAAA/4MAMgAAAAAAA
+AAAAAAAAAAAAAAAAAAAAHQAAAABAAIAAwAEAAUABgAHAAgACQAKAAsADAANAA4ADwAQABEAEgATAB
+QAFQAWABcAGAAZABoAGwAcAB0AHgAfACAAIQAiACMAJAAlACYAJwAoACkAKgArACwALQAuAC8AMAA
+xADIAMwA0ADUANgA3ADgAOQA6ADsAPAA9AD4APwBAAEEAQgBDAEQARQBGAEcASABJAEoASwBMAE0A
+TgBPAFAAUQBSAFMAVABVAFYAVwBYAFkAWgBbAFwAXQBeAF8AYABhAIsAqQCDAJMAjQDDAKoAtgC3A
+LQAtQCrAL4AvwC8AIwAwADBAAAAAAAB//8AAgABAAAADAAAABwAAAACAAIAAwBxAAEAcgBzAAIABA
+AAAAIAAAABAAAACgBMAGYAAkRGTFQADmxhdG4AGgAEAAAAAP//AAEAAAAWAANDQVQgAB5NT0wgABZ
+ST00gABYAAP//AAEAAAAA//8AAgAAAAEAAmxpZ2EADmxvY2wAFAAAAAEAAQAAAAEAAAACAAYAEAAG
+AAAAAgASADQABAAAAAEATAADAAAAAgAQABYAAQAcAAAAAQABAE8AAQABAGcAAQABAE8AAwAAAAIAE
+AAWAAEAHAAAAAEAAQAvAAEAAQBnAAEAAQAvAAEAGgABAAgAAgAGAAwAcwACAE8AcgACAEwAAQABAE
+kAAAABAAAACgBGAGAAAkRGTFQADmxhdG4AHAAEAAAAAP//AAIAAAABABYAA0NBVCAAFk1PTCAAFlJ
+PTSAAFgAA//8AAgAAAAEAAmNwc3AADmtlcm4AFAAAAAEAAAAAAAEAAQACAAYADgABAAAAAQASAAIA
+AAACAB4ANgABAAoABQAFAAoAAgABACQAPQAAAAEAEgAEAAAAAQAMAAEAOP/nAAEAAQAkAAIGigAEA
+AAFJAXKABoAGQAA//gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAD/sv+4/+z/7v/MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAD/xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/9T/6AAAAAD/8QAA
+ABD/vQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/7gAAAAAAAAAAAAAAAAAA//MAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAP/5AAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/gAAD/4AAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//L/9AAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAA/+gAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/zAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/mAAAAAAAAAAAAAAAAAAD
+/4gAA//AAAAAA//YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/+AAAAAAAAP/OAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zv/qAAAAAP/0AAAACAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/ZAAD/egAA/1kAAAAA/5D/rgAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAD/9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAD/8AAA/7b/8P+wAAD/8P/E/98AAAAA/8P/+P/0//oAAAAAAAAAAAAA//gA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+AAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/w//C/9MAAP/SAAD/9wAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAD/yAAA/+kAAAAA//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/9wAAAAD//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAP/2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAP/cAAAAAAAAAAAAAAAA/7YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAP/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/6AAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAkAFAAEAAAAAQACwAAABcA
+BgAAAAAAAAAIAA4AAAAAAAsAEgAAAAAAAAATABkAAwANAAAAAQAJAAAAAAAAAAAAAAAAAAAAGAAAA
+AAABwAAAAAAAAAAAAAAFQAFAAAAAAAYABgAAAAUAAAACgAAAAwAAgAPABEAFgAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAEAEQBdAAYAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAcAAAAAAAAABwAAAAAACAAAAAAAAAAAAAcAAAAHAAAAEwAJ
+ABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA
+gAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC
+YAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA
+AAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==
+"""
+ )
+ ),
+ 10 if size is None else size,
+ layout_engine=Layout.BASIC,
+ )
+ return load_default_imagefont()
diff --git a/venv/Lib/site-packages/PIL/ImageGrab.py b/venv/Lib/site-packages/PIL/ImageGrab.py
new file mode 100644
index 0000000..4228078
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageGrab.py
@@ -0,0 +1,224 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# screen grabber
+#
+# History:
+# 2001-04-26 fl created
+# 2001-09-17 fl use builtin driver, if present
+# 2002-11-19 fl added grabclipboard support
+#
+# Copyright (c) 2001-2002 by Secret Labs AB
+# Copyright (c) 2001-2002 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import io
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+
+from . import Image
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from . import ImageWin
+
+
+def grab(
+ bbox: tuple[int, int, int, int] | None = None,
+ include_layered_windows: bool = False,
+ all_screens: bool = False,
+ xdisplay: str | None = None,
+ window: int | ImageWin.HWND | None = None,
+) -> Image.Image:
+ im: Image.Image
+ if xdisplay is None:
+ if sys.platform == "darwin":
+ fh, filepath = tempfile.mkstemp(".png")
+ os.close(fh)
+ args = ["screencapture"]
+ if window:
+ args += ["-l", str(window)]
+ elif bbox:
+ left, top, right, bottom = bbox
+ args += ["-R", f"{left},{top},{right-left},{bottom-top}"]
+ subprocess.call(args + ["-x", filepath])
+ im = Image.open(filepath)
+ im.load()
+ os.unlink(filepath)
+ if bbox:
+ if window:
+ # Determine if the window was in Retina mode or not
+ # by capturing it without the shadow,
+ # and checking how different the width is
+ fh, filepath = tempfile.mkstemp(".png")
+ os.close(fh)
+ subprocess.call(
+ ["screencapture", "-l", str(window), "-o", "-x", filepath]
+ )
+ with Image.open(filepath) as im_no_shadow:
+ retina = im.width - im_no_shadow.width > 100
+ os.unlink(filepath)
+
+ # Since screencapture's -R does not work with -l,
+ # crop the image manually
+ if retina:
+ left, top, right, bottom = bbox
+ im_cropped = im.resize(
+ (right - left, bottom - top),
+ box=tuple(coord * 2 for coord in bbox),
+ )
+ else:
+ im_cropped = im.crop(bbox)
+ im.close()
+ return im_cropped
+ else:
+ im_resized = im.resize((right - left, bottom - top))
+ im.close()
+ return im_resized
+ return im
+ elif sys.platform == "win32":
+ if window is not None:
+ all_screens = -1
+ offset, size, data = Image.core.grabscreen_win32(
+ include_layered_windows,
+ all_screens,
+ int(window) if window is not None else 0,
+ )
+ im = Image.frombytes(
+ "RGB",
+ size,
+ data,
+ # RGB, 32-bit line padding, origin lower left corner
+ "raw",
+ "BGR",
+ (size[0] * 3 + 3) & -4,
+ -1,
+ )
+ if bbox:
+ x0, y0 = offset
+ left, top, right, bottom = bbox
+ im = im.crop((left - x0, top - y0, right - x0, bottom - y0))
+ return im
+ # Cast to Optional[str] needed for Windows and macOS.
+ display_name: str | None = xdisplay
+ try:
+ if not Image.core.HAVE_XCB:
+ msg = "Pillow was built without XCB support"
+ raise OSError(msg)
+ size, data = Image.core.grabscreen_x11(display_name)
+ except OSError:
+ if display_name is None and sys.platform not in ("darwin", "win32"):
+ if shutil.which("gnome-screenshot"):
+ args = ["gnome-screenshot", "-f"]
+ elif shutil.which("grim"):
+ args = ["grim"]
+ elif shutil.which("spectacle"):
+ args = ["spectacle", "-n", "-b", "-f", "-o"]
+ else:
+ raise
+ fh, filepath = tempfile.mkstemp(".png")
+ os.close(fh)
+ subprocess.call(args + [filepath])
+ im = Image.open(filepath)
+ im.load()
+ os.unlink(filepath)
+ if bbox:
+ im_cropped = im.crop(bbox)
+ im.close()
+ return im_cropped
+ return im
+ else:
+ raise
+ else:
+ im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)
+ if bbox:
+ im = im.crop(bbox)
+ return im
+
+
+def grabclipboard() -> Image.Image | list[str] | None:
+ if sys.platform == "darwin":
+ p = subprocess.run(
+ ["osascript", "-e", "get the clipboard as «class PNGf»"],
+ capture_output=True,
+ )
+ if p.returncode != 0:
+ return None
+
+ import binascii
+
+ data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3]))
+ return Image.open(data)
+ elif sys.platform == "win32":
+ fmt, data = Image.core.grabclipboard_win32()
+ if fmt == "file": # CF_HDROP
+ import struct
+
+ o = struct.unpack_from("I", data)[0]
+ if data[16] == 0:
+ files = data[o:].decode("mbcs").split("\0")
+ else:
+ files = data[o:].decode("utf-16le").split("\0")
+ return files[: files.index("")]
+ if isinstance(data, bytes):
+ data = io.BytesIO(data)
+ if fmt == "png":
+ from . import PngImagePlugin
+
+ return PngImagePlugin.PngImageFile(data)
+ elif fmt == "DIB":
+ from . import BmpImagePlugin
+
+ return BmpImagePlugin.DibImageFile(data)
+ return None
+ else:
+ if os.getenv("WAYLAND_DISPLAY"):
+ session_type = "wayland"
+ elif os.getenv("DISPLAY"):
+ session_type = "x11"
+ else: # Session type check failed
+ session_type = None
+
+ if shutil.which("wl-paste") and session_type in ("wayland", None):
+ args = ["wl-paste", "-t", "image"]
+ elif shutil.which("xclip") and session_type in ("x11", None):
+ args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]
+ else:
+ msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"
+ raise NotImplementedError(msg)
+
+ p = subprocess.run(args, capture_output=True)
+ if p.returncode != 0:
+ err = p.stderr
+ for silent_error in [
+ # wl-paste, when the clipboard is empty
+ b"Nothing is copied",
+ # Ubuntu/Debian wl-paste, when the clipboard is empty
+ b"No selection",
+ # Ubuntu/Debian wl-paste, when an image isn't available
+ b"No suitable type of content copied",
+ # wl-paste or Ubuntu/Debian xclip, when an image isn't available
+ b" not available",
+ # xclip, when an image isn't available
+ b"cannot convert ",
+ # xclip, when the clipboard isn't initialized
+ b"xclip: Error: There is no owner for the ",
+ ]:
+ if silent_error in err:
+ return None
+ msg = f"{args[0]} error"
+ if err:
+ msg += f": {err.strip().decode()}"
+ raise ChildProcessError(msg)
+
+ data = io.BytesIO(p.stdout)
+ im = Image.open(data)
+ im.load()
+ return im
diff --git a/venv/Lib/site-packages/PIL/ImageMath.py b/venv/Lib/site-packages/PIL/ImageMath.py
new file mode 100644
index 0000000..dfdc50c
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageMath.py
@@ -0,0 +1,314 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# a simple math add-on for the Python Imaging Library
+#
+# History:
+# 1999-02-15 fl Original PIL Plus release
+# 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6
+# 2005-09-12 fl Fixed int() and float() for Python 2.4.1
+#
+# Copyright (c) 1999-2005 by Secret Labs AB
+# Copyright (c) 2005 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import builtins
+
+from . import Image, _imagingmath
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from types import CodeType
+ from typing import Any
+
+
+class _Operand:
+ """Wraps an image operand, providing standard operators"""
+
+ def __init__(self, im: Image.Image):
+ self.im = im
+
+ def __fixup(self, im1: _Operand | float) -> Image.Image:
+ # convert image to suitable mode
+ if isinstance(im1, _Operand):
+ # argument was an image.
+ if im1.im.mode in ("1", "L"):
+ return im1.im.convert("I")
+ elif im1.im.mode in ("I", "F"):
+ return im1.im
+ else:
+ msg = f"unsupported mode: {im1.im.mode}"
+ raise ValueError(msg)
+ else:
+ # argument was a constant
+ if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
+ return Image.new("I", self.im.size, im1)
+ else:
+ return Image.new("F", self.im.size, im1)
+
+ def apply(
+ self,
+ op: str,
+ im1: _Operand | float,
+ im2: _Operand | float | None = None,
+ mode: str | None = None,
+ ) -> _Operand:
+ im_1 = self.__fixup(im1)
+ if im2 is None:
+ # unary operation
+ out = Image.new(mode or im_1.mode, im_1.size, None)
+ try:
+ op = getattr(_imagingmath, f"{op}_{im_1.mode}")
+ except AttributeError as e:
+ msg = f"bad operand type for '{op}'"
+ raise TypeError(msg) from e
+ _imagingmath.unop(op, out.getim(), im_1.getim())
+ else:
+ # binary operation
+ im_2 = self.__fixup(im2)
+ if im_1.mode != im_2.mode:
+ # convert both arguments to floating point
+ if im_1.mode != "F":
+ im_1 = im_1.convert("F")
+ if im_2.mode != "F":
+ im_2 = im_2.convert("F")
+ if im_1.size != im_2.size:
+ # crop both arguments to a common size
+ size = (
+ min(im_1.size[0], im_2.size[0]),
+ min(im_1.size[1], im_2.size[1]),
+ )
+ if im_1.size != size:
+ im_1 = im_1.crop((0, 0) + size)
+ if im_2.size != size:
+ im_2 = im_2.crop((0, 0) + size)
+ out = Image.new(mode or im_1.mode, im_1.size, None)
+ try:
+ op = getattr(_imagingmath, f"{op}_{im_1.mode}")
+ except AttributeError as e:
+ msg = f"bad operand type for '{op}'"
+ raise TypeError(msg) from e
+ _imagingmath.binop(op, out.getim(), im_1.getim(), im_2.getim())
+ return _Operand(out)
+
+ # unary operators
+ def __bool__(self) -> bool:
+ # an image is "true" if it contains at least one non-zero pixel
+ return self.im.getbbox() is not None
+
+ def __abs__(self) -> _Operand:
+ return self.apply("abs", self)
+
+ def __pos__(self) -> _Operand:
+ return self
+
+ def __neg__(self) -> _Operand:
+ return self.apply("neg", self)
+
+ # binary operators
+ def __add__(self, other: _Operand | float) -> _Operand:
+ return self.apply("add", self, other)
+
+ def __radd__(self, other: _Operand | float) -> _Operand:
+ return self.apply("add", other, self)
+
+ def __sub__(self, other: _Operand | float) -> _Operand:
+ return self.apply("sub", self, other)
+
+ def __rsub__(self, other: _Operand | float) -> _Operand:
+ return self.apply("sub", other, self)
+
+ def __mul__(self, other: _Operand | float) -> _Operand:
+ return self.apply("mul", self, other)
+
+ def __rmul__(self, other: _Operand | float) -> _Operand:
+ return self.apply("mul", other, self)
+
+ def __truediv__(self, other: _Operand | float) -> _Operand:
+ return self.apply("div", self, other)
+
+ def __rtruediv__(self, other: _Operand | float) -> _Operand:
+ return self.apply("div", other, self)
+
+ def __mod__(self, other: _Operand | float) -> _Operand:
+ return self.apply("mod", self, other)
+
+ def __rmod__(self, other: _Operand | float) -> _Operand:
+ return self.apply("mod", other, self)
+
+ def __pow__(self, other: _Operand | float) -> _Operand:
+ return self.apply("pow", self, other)
+
+ def __rpow__(self, other: _Operand | float) -> _Operand:
+ return self.apply("pow", other, self)
+
+ # bitwise
+ def __invert__(self) -> _Operand:
+ return self.apply("invert", self)
+
+ def __and__(self, other: _Operand | float) -> _Operand:
+ return self.apply("and", self, other)
+
+ def __rand__(self, other: _Operand | float) -> _Operand:
+ return self.apply("and", other, self)
+
+ def __or__(self, other: _Operand | float) -> _Operand:
+ return self.apply("or", self, other)
+
+ def __ror__(self, other: _Operand | float) -> _Operand:
+ return self.apply("or", other, self)
+
+ def __xor__(self, other: _Operand | float) -> _Operand:
+ return self.apply("xor", self, other)
+
+ def __rxor__(self, other: _Operand | float) -> _Operand:
+ return self.apply("xor", other, self)
+
+ def __lshift__(self, other: _Operand | float) -> _Operand:
+ return self.apply("lshift", self, other)
+
+ def __rshift__(self, other: _Operand | float) -> _Operand:
+ return self.apply("rshift", self, other)
+
+ # logical
+ def __eq__(self, other: _Operand | float) -> _Operand: # type: ignore[override]
+ return self.apply("eq", self, other)
+
+ def __ne__(self, other: _Operand | float) -> _Operand: # type: ignore[override]
+ return self.apply("ne", self, other)
+
+ def __lt__(self, other: _Operand | float) -> _Operand:
+ return self.apply("lt", self, other)
+
+ def __le__(self, other: _Operand | float) -> _Operand:
+ return self.apply("le", self, other)
+
+ def __gt__(self, other: _Operand | float) -> _Operand:
+ return self.apply("gt", self, other)
+
+ def __ge__(self, other: _Operand | float) -> _Operand:
+ return self.apply("ge", self, other)
+
+
+# conversions
+def imagemath_int(self: _Operand) -> _Operand:
+ return _Operand(self.im.convert("I"))
+
+
+def imagemath_float(self: _Operand) -> _Operand:
+ return _Operand(self.im.convert("F"))
+
+
+# logical
+def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:
+ return self.apply("eq", self, other, mode="I")
+
+
+def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:
+ return self.apply("ne", self, other, mode="I")
+
+
+def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:
+ return self.apply("min", self, other)
+
+
+def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:
+ return self.apply("max", self, other)
+
+
+def imagemath_convert(self: _Operand, mode: str) -> _Operand:
+ return _Operand(self.im.convert(mode))
+
+
+ops = {
+ "int": imagemath_int,
+ "float": imagemath_float,
+ "equal": imagemath_equal,
+ "notequal": imagemath_notequal,
+ "min": imagemath_min,
+ "max": imagemath_max,
+ "convert": imagemath_convert,
+}
+
+
+def lambda_eval(expression: Callable[[dict[str, Any]], Any], **kw: Any) -> Any:
+ """
+ Returns the result of an image function.
+
+ :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
+ images, use the :py:meth:`~PIL.Image.Image.split` method or
+ :py:func:`~PIL.Image.merge` function.
+
+ :param expression: A function that receives a dictionary.
+ :param **kw: Values to add to the function's dictionary.
+ :return: The expression result. This is usually an image object, but can
+ also be an integer, a floating point value, or a pixel tuple,
+ depending on the expression.
+ """
+
+ args: dict[str, Any] = ops.copy()
+ args.update(kw)
+ for k, v in args.items():
+ if isinstance(v, Image.Image):
+ args[k] = _Operand(v)
+
+ out = expression(args)
+ try:
+ return out.im
+ except AttributeError:
+ return out
+
+
+def unsafe_eval(expression: str, **kw: Any) -> Any:
+ """
+ Evaluates an image expression. This uses Python's ``eval()`` function to process
+ the expression string, and carries the security risks of doing so. It is not
+ recommended to process expressions without considering this.
+ :py:meth:`~lambda_eval` is a more secure alternative.
+
+ :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
+ images, use the :py:meth:`~PIL.Image.Image.split` method or
+ :py:func:`~PIL.Image.merge` function.
+
+ :param expression: A string containing a Python-style expression.
+ :param **kw: Values to add to the evaluation context.
+ :return: The evaluated expression. This is usually an image object, but can
+ also be an integer, a floating point value, or a pixel tuple,
+ depending on the expression.
+ """
+
+ # build execution namespace
+ args: dict[str, Any] = ops.copy()
+ for k in kw:
+ if "__" in k or hasattr(builtins, k):
+ msg = f"'{k}' not allowed"
+ raise ValueError(msg)
+
+ args.update(kw)
+ for k, v in args.items():
+ if isinstance(v, Image.Image):
+ args[k] = _Operand(v)
+
+ compiled_code = compile(expression, "", "eval")
+
+ def scan(code: CodeType) -> None:
+ for const in code.co_consts:
+ if type(const) is type(compiled_code):
+ scan(const)
+
+ for name in code.co_names:
+ if name not in args and name != "abs":
+ msg = f"'{name}' not allowed"
+ raise ValueError(msg)
+
+ scan(compiled_code)
+ out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
+ try:
+ return out.im
+ except AttributeError:
+ return out
diff --git a/venv/Lib/site-packages/PIL/ImageMode.py b/venv/Lib/site-packages/PIL/ImageMode.py
new file mode 100644
index 0000000..b7c6c86
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageMode.py
@@ -0,0 +1,85 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# standard mode descriptors
+#
+# History:
+# 2006-03-20 fl Added
+#
+# Copyright (c) 2006 by Secret Labs AB.
+# Copyright (c) 2006 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import sys
+from functools import lru_cache
+from typing import NamedTuple
+
+
+class ModeDescriptor(NamedTuple):
+ """Wrapper for mode strings."""
+
+ mode: str
+ bands: tuple[str, ...]
+ basemode: str
+ basetype: str
+ typestr: str
+
+ def __str__(self) -> str:
+ return self.mode
+
+
+@lru_cache
+def getmode(mode: str) -> ModeDescriptor:
+ """Gets a mode descriptor for the given mode."""
+ endian = "<" if sys.byteorder == "little" else ">"
+
+ modes = {
+ # core modes
+ # Bits need to be extended to bytes
+ "1": ("L", "L", ("1",), "|b1"),
+ "L": ("L", "L", ("L",), "|u1"),
+ "I": ("L", "I", ("I",), f"{endian}i4"),
+ "F": ("L", "F", ("F",), f"{endian}f4"),
+ "P": ("P", "L", ("P",), "|u1"),
+ "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),
+ "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),
+ "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),
+ "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),
+ "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),
+ # UNDONE - unsigned |u1i1i1
+ "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),
+ "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),
+ # extra experimental modes
+ "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),
+ "LA": ("L", "L", ("L", "A"), "|u1"),
+ "La": ("L", "L", ("L", "a"), "|u1"),
+ "PA": ("RGB", "L", ("P", "A"), "|u1"),
+ }
+ if mode in modes:
+ base_mode, base_type, bands, type_str = modes[mode]
+ return ModeDescriptor(mode, bands, base_mode, base_type, type_str)
+
+ mapping_modes = {
+ # I;16 == I;16L, and I;32 == I;32L
+ "I;16": "u2",
+ "I;16BS": ">i2",
+ "I;16N": f"{endian}u2",
+ "I;16NS": f"{endian}i2",
+ "I;32": "u4",
+ "I;32L": "i4",
+ "I;32LS": "
+from __future__ import annotations
+
+import re
+
+from . import Image, _imagingmorph
+
+LUT_SIZE = 1 << 9
+
+# fmt: off
+ROTATION_MATRIX = [
+ 6, 3, 0,
+ 7, 4, 1,
+ 8, 5, 2,
+]
+MIRROR_MATRIX = [
+ 2, 1, 0,
+ 5, 4, 3,
+ 8, 7, 6,
+]
+# fmt: on
+
+
+class LutBuilder:
+ """A class for building a MorphLut from a descriptive language
+
+ The input patterns is a list of a strings sequences like these::
+
+ 4:(...
+ .1.
+ 111)->1
+
+ (whitespaces including linebreaks are ignored). The option 4
+ describes a series of symmetry operations (in this case a
+ 4-rotation), the pattern is described by:
+
+ - . or X - Ignore
+ - 1 - Pixel is on
+ - 0 - Pixel is off
+
+ The result of the operation is described after "->" string.
+
+ The default is to return the current pixel value, which is
+ returned if no other match is found.
+
+ Operations:
+
+ - 4 - 4 way rotation
+ - N - Negate
+ - 1 - Dummy op for no other operation (an op must always be given)
+ - M - Mirroring
+
+ Example::
+
+ lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
+ lut = lb.build_lut()
+
+ """
+
+ def __init__(
+ self, patterns: list[str] | None = None, op_name: str | None = None
+ ) -> None:
+ """
+ :param patterns: A list of input patterns, or None.
+ :param op_name: The name of a known pattern. One of "corner", "dilation4",
+ "dilation8", "erosion4", "erosion8" or "edge".
+ :exception Exception: If the op_name is not recognized.
+ """
+ self.lut: bytearray | None = None
+ if op_name is not None:
+ known_patterns = {
+ "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
+ "dilation4": ["4:(... .0. .1.)->1"],
+ "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
+ "erosion4": ["4:(... .1. .0.)->0"],
+ "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
+ "edge": [
+ "1:(... ... ...)->0",
+ "4:(.0. .1. ...)->1",
+ "4:(01. .1. ...)->1",
+ ],
+ }
+ if op_name not in known_patterns:
+ msg = f"Unknown pattern {op_name}!"
+ raise Exception(msg)
+
+ self.patterns = known_patterns[op_name]
+ elif patterns is not None:
+ self.patterns = patterns
+ else:
+ self.patterns = []
+
+ def add_patterns(self, patterns: list[str]) -> None:
+ """
+ Append to list of patterns.
+
+ :param patterns: Additional patterns.
+ """
+ self.patterns += patterns
+
+ def build_default_lut(self) -> bytearray:
+ """
+ Set the current LUT, and return it.
+
+ This is the default LUT that patterns will be applied against when building.
+ """
+ symbols = [0, 1]
+ m = 1 << 4 # pos of current pixel
+ self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
+ return self.lut
+
+ def get_lut(self) -> bytearray | None:
+ """
+ Returns the current LUT
+ """
+ return self.lut
+
+ def _string_permute(self, pattern: str, permutation: list[int]) -> str:
+ """Takes a pattern and a permutation and returns the
+ string permuted according to the permutation list.
+ """
+ assert len(permutation) == 9
+ return "".join(pattern[p] for p in permutation)
+
+ def _pattern_permute(
+ self, basic_pattern: str, options: str, basic_result: int
+ ) -> list[tuple[str, int]]:
+ """Takes a basic pattern and its result and clones
+ the pattern according to the modifications described in the $options
+ parameter. It returns a list of all cloned patterns."""
+ patterns = [(basic_pattern, basic_result)]
+
+ # rotations
+ if "4" in options:
+ res = patterns[-1][1]
+ for i in range(4):
+ patterns.append(
+ (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
+ )
+ # mirror
+ if "M" in options:
+ n = len(patterns)
+ for pattern, res in patterns[:n]:
+ patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
+
+ # negate
+ if "N" in options:
+ n = len(patterns)
+ for pattern, res in patterns[:n]:
+ # Swap 0 and 1
+ pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
+ res = 1 - int(res)
+ patterns.append((pattern, res))
+
+ return patterns
+
+ def build_lut(self) -> bytearray:
+ """Compile all patterns into a morphology LUT, and return it.
+
+ This is the data to be passed into MorphOp."""
+ self.build_default_lut()
+ assert self.lut is not None
+ patterns = []
+
+ # Parse and create symmetries of the patterns strings
+ for p in self.patterns:
+ m = re.search(r"(\w):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
+ if not m:
+ msg = 'Syntax error in pattern "' + p + '"'
+ raise Exception(msg)
+ options = m.group(1)
+ pattern = m.group(2)
+ result = int(m.group(3))
+
+ # Get rid of spaces
+ pattern = pattern.replace(" ", "").replace("\n", "")
+
+ patterns += self._pattern_permute(pattern, options, result)
+
+ # Compile the patterns into regular expressions for speed
+ compiled_patterns = []
+ for pattern in patterns:
+ p = pattern[0].replace(".", "X").replace("X", "[01]")
+ compiled_patterns.append((re.compile(p), pattern[1]))
+
+ # Step through table and find patterns that match.
+ # Note that all the patterns are searched. The last one found takes priority
+ for i in range(LUT_SIZE):
+ # Build the bit pattern
+ bitpattern = bin(i)[2:]
+ bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
+
+ for pattern, r in compiled_patterns:
+ if pattern.match(bitpattern):
+ self.lut[i] = [0, 1][r]
+
+ return self.lut
+
+
+class MorphOp:
+ """A class for binary morphological operators"""
+
+ def __init__(
+ self,
+ lut: bytearray | None = None,
+ op_name: str | None = None,
+ patterns: list[str] | None = None,
+ ) -> None:
+ """Create a binary morphological operator.
+
+ If the LUT is not provided, then it is built using LutBuilder from the op_name
+ or the patterns.
+
+ :param lut: The LUT data.
+ :param patterns: A list of input patterns, or None.
+ :param op_name: The name of a known pattern. One of "corner", "dilation4",
+ "dilation8", "erosion4", "erosion8", "edge".
+ :exception Exception: If the op_name is not recognized.
+ """
+ if patterns is None and op_name is None:
+ self.lut = lut
+ else:
+ self.lut = LutBuilder(patterns, op_name).build_lut()
+
+ def apply(self, image: Image.Image) -> tuple[int, Image.Image]:
+ """Run a single morphological operation on an image.
+
+ Returns a tuple of the number of changed pixels and the
+ morphed image.
+
+ :param image: A 1-mode or L-mode image.
+ :exception Exception: If the current operator is None.
+ :exception ValueError: If the image is not 1 or L mode."""
+ if self.lut is None:
+ msg = "No operator loaded"
+ raise Exception(msg)
+
+ if image.mode not in ("1", "L"):
+ msg = "Image mode must be 1 or L"
+ raise ValueError(msg)
+ outimage = Image.new(image.mode, image.size)
+ count = _imagingmorph.apply(bytes(self.lut), image.getim(), outimage.getim())
+ return count, outimage
+
+ def match(self, image: Image.Image) -> list[tuple[int, int]]:
+ """Get a list of coordinates matching the morphological operation on
+ an image.
+
+ Returns a list of tuples of (x,y) coordinates of all matching pixels. See
+ :ref:`coordinate-system`.
+
+ :param image: A 1-mode or L-mode image.
+ :exception Exception: If the current operator is None.
+ :exception ValueError: If the image is not 1 or L mode."""
+ if self.lut is None:
+ msg = "No operator loaded"
+ raise Exception(msg)
+
+ if image.mode not in ("1", "L"):
+ msg = "Image mode must be 1 or L"
+ raise ValueError(msg)
+ return _imagingmorph.match(bytes(self.lut), image.getim())
+
+ def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]:
+ """Get a list of all turned on pixels in a 1 or L mode image.
+
+ Returns a list of tuples of (x,y) coordinates of all non-empty pixels. See
+ :ref:`coordinate-system`.
+
+ :param image: A 1-mode or L-mode image.
+ :exception ValueError: If the image is not 1 or L mode."""
+
+ if image.mode not in ("1", "L"):
+ msg = "Image mode must be 1 or L"
+ raise ValueError(msg)
+ return _imagingmorph.get_on_pixels(image.getim())
+
+ def load_lut(self, filename: str) -> None:
+ """
+ Load an operator from an mrl file
+
+ :param filename: The file to read from.
+ :exception Exception: If the length of the file data is not 512.
+ """
+ with open(filename, "rb") as f:
+ self.lut = bytearray(f.read())
+
+ if len(self.lut) != LUT_SIZE:
+ self.lut = None
+ msg = "Wrong size operator file!"
+ raise Exception(msg)
+
+ def save_lut(self, filename: str) -> None:
+ """
+ Save an operator to an mrl file.
+
+ :param filename: The destination file.
+ :exception Exception: If the current operator is None.
+ """
+ if self.lut is None:
+ msg = "No operator loaded"
+ raise Exception(msg)
+ with open(filename, "wb") as f:
+ f.write(self.lut)
+
+ def set_lut(self, lut: bytearray | None) -> None:
+ """
+ Set the LUT from an external source
+
+ :param lut: A new LUT.
+ """
+ self.lut = lut
diff --git a/venv/Lib/site-packages/PIL/ImageOps.py b/venv/Lib/site-packages/PIL/ImageOps.py
new file mode 100644
index 0000000..42b10bd
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageOps.py
@@ -0,0 +1,746 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# standard image operations
+#
+# History:
+# 2001-10-20 fl Created
+# 2001-10-23 fl Added autocontrast operator
+# 2001-12-18 fl Added Kevin's fit operator
+# 2004-03-14 fl Fixed potential division by zero in equalize
+# 2005-05-05 fl Fixed equalize for low number of values
+#
+# Copyright (c) 2001-2004 by Secret Labs AB
+# Copyright (c) 2001-2004 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import functools
+import operator
+import re
+from collections.abc import Sequence
+from typing import Literal, Protocol, cast, overload
+
+from . import ExifTags, Image, ImagePalette
+
+#
+# helpers
+
+
+def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:
+ if isinstance(border, tuple):
+ if len(border) == 2:
+ left, top = right, bottom = border
+ elif len(border) == 4:
+ left, top, right, bottom = border
+ else:
+ left = top = right = bottom = border
+ return left, top, right, bottom
+
+
+def _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]:
+ if isinstance(color, str):
+ from . import ImageColor
+
+ color = ImageColor.getcolor(color, mode)
+ return color
+
+
+def _lut(image: Image.Image, lut: list[int]) -> Image.Image:
+ if image.mode == "P":
+ # FIXME: apply to lookup table, not image data
+ msg = "mode P support coming soon"
+ raise NotImplementedError(msg)
+ elif image.mode in ("L", "RGB"):
+ if image.mode == "RGB" and len(lut) == 256:
+ lut = lut + lut + lut
+ return image.point(lut)
+ else:
+ msg = f"not supported for mode {image.mode}"
+ raise OSError(msg)
+
+
+#
+# actions
+
+
+def autocontrast(
+ image: Image.Image,
+ cutoff: float | tuple[float, float] = 0,
+ ignore: int | Sequence[int] | None = None,
+ mask: Image.Image | None = None,
+ preserve_tone: bool = False,
+) -> Image.Image:
+ """
+ Maximize (normalize) image contrast. This function calculates a
+ histogram of the input image (or mask region), removes ``cutoff`` percent of the
+ lightest and darkest pixels from the histogram, and remaps the image
+ so that the darkest pixel becomes black (0), and the lightest
+ becomes white (255).
+
+ :param image: The image to process.
+ :param cutoff: The percent to cut off from the histogram on the low and
+ high ends. Either a tuple of (low, high), or a single
+ number for both.
+ :param ignore: The background pixel value (use None for no background).
+ :param mask: Histogram used in contrast operation is computed using pixels
+ within the mask. If no mask is given the entire image is used
+ for histogram computation.
+ :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.
+
+ .. versionadded:: 8.2.0
+
+ :return: An image.
+ """
+ if preserve_tone:
+ histogram = image.convert("L").histogram(mask)
+ else:
+ histogram = image.histogram(mask)
+
+ lut = []
+ for layer in range(0, len(histogram), 256):
+ h = histogram[layer : layer + 256]
+ if ignore is not None:
+ # get rid of outliers
+ if isinstance(ignore, int):
+ h[ignore] = 0
+ else:
+ for ix in ignore:
+ h[ix] = 0
+ if cutoff:
+ # cut off pixels from both ends of the histogram
+ if not isinstance(cutoff, tuple):
+ cutoff = (cutoff, cutoff)
+ # get number of pixels
+ n = 0
+ for ix in range(256):
+ n = n + h[ix]
+ # remove cutoff% pixels from the low end
+ cut = int(n * cutoff[0] // 100)
+ for lo in range(256):
+ if cut > h[lo]:
+ cut = cut - h[lo]
+ h[lo] = 0
+ else:
+ h[lo] -= cut
+ cut = 0
+ if cut <= 0:
+ break
+ # remove cutoff% samples from the high end
+ cut = int(n * cutoff[1] // 100)
+ for hi in range(255, -1, -1):
+ if cut > h[hi]:
+ cut = cut - h[hi]
+ h[hi] = 0
+ else:
+ h[hi] -= cut
+ cut = 0
+ if cut <= 0:
+ break
+ # find lowest/highest samples after preprocessing
+ for lo in range(256):
+ if h[lo]:
+ break
+ for hi in range(255, -1, -1):
+ if h[hi]:
+ break
+ if hi <= lo:
+ # don't bother
+ lut.extend(list(range(256)))
+ else:
+ scale = 255.0 / (hi - lo)
+ offset = -lo * scale
+ for ix in range(256):
+ ix = int(ix * scale + offset)
+ if ix < 0:
+ ix = 0
+ elif ix > 255:
+ ix = 255
+ lut.append(ix)
+ return _lut(image, lut)
+
+
+def colorize(
+ image: Image.Image,
+ black: str | tuple[int, ...],
+ white: str | tuple[int, ...],
+ mid: str | int | tuple[int, ...] | None = None,
+ blackpoint: int = 0,
+ whitepoint: int = 255,
+ midpoint: int = 127,
+) -> Image.Image:
+ """
+ Colorize grayscale image.
+ This function calculates a color wedge which maps all black pixels in
+ the source image to the first color and all white pixels to the
+ second color. If ``mid`` is specified, it uses three-color mapping.
+ The ``black`` and ``white`` arguments should be RGB tuples or color names;
+ optionally you can use three-color mapping by also specifying ``mid``.
+ Mapping positions for any of the colors can be specified
+ (e.g. ``blackpoint``), where these parameters are the integer
+ value corresponding to where the corresponding color should be mapped.
+ These parameters must have logical order, such that
+ ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).
+
+ :param image: The image to colorize.
+ :param black: The color to use for black input pixels.
+ :param white: The color to use for white input pixels.
+ :param mid: The color to use for midtone input pixels.
+ :param blackpoint: an int value [0, 255] for the black mapping.
+ :param whitepoint: an int value [0, 255] for the white mapping.
+ :param midpoint: an int value [0, 255] for the midtone mapping.
+ :return: An image.
+ """
+
+ # Initial asserts
+ assert image.mode == "L"
+ if mid is None:
+ assert 0 <= blackpoint <= whitepoint <= 255
+ else:
+ assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
+
+ # Define colors from arguments
+ rgb_black = cast(Sequence[int], _color(black, "RGB"))
+ rgb_white = cast(Sequence[int], _color(white, "RGB"))
+ rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None
+
+ # Empty lists for the mapping
+ red = []
+ green = []
+ blue = []
+
+ # Create the low-end values
+ for i in range(blackpoint):
+ red.append(rgb_black[0])
+ green.append(rgb_black[1])
+ blue.append(rgb_black[2])
+
+ # Create the mapping (2-color)
+ if rgb_mid is None:
+ range_map = range(whitepoint - blackpoint)
+
+ for i in range_map:
+ red.append(
+ rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map)
+ )
+ green.append(
+ rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map)
+ )
+ blue.append(
+ rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map)
+ )
+
+ # Create the mapping (3-color)
+ else:
+ range_map1 = range(midpoint - blackpoint)
+ range_map2 = range(whitepoint - midpoint)
+
+ for i in range_map1:
+ red.append(
+ rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1)
+ )
+ green.append(
+ rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1)
+ )
+ blue.append(
+ rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1)
+ )
+ for i in range_map2:
+ red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2))
+ green.append(
+ rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2)
+ )
+ blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2))
+
+ # Create the high-end values
+ for i in range(256 - whitepoint):
+ red.append(rgb_white[0])
+ green.append(rgb_white[1])
+ blue.append(rgb_white[2])
+
+ # Return converted image
+ image = image.convert("RGB")
+ return _lut(image, red + green + blue)
+
+
+def contain(
+ image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
+) -> Image.Image:
+ """
+ Returns a resized version of the image, set to the maximum width and height
+ within the requested size, while maintaining the original aspect ratio.
+
+ :param image: The image to resize.
+ :param size: The requested output size in pixels, given as a
+ (width, height) tuple.
+ :param method: Resampling method to use. Default is
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+ See :ref:`concept-filters`.
+ :return: An image.
+ """
+
+ im_ratio = image.width / image.height
+ dest_ratio = size[0] / size[1]
+
+ if im_ratio != dest_ratio:
+ if im_ratio > dest_ratio:
+ new_height = round(image.height / image.width * size[0])
+ if new_height != size[1]:
+ size = (size[0], new_height)
+ else:
+ new_width = round(image.width / image.height * size[1])
+ if new_width != size[0]:
+ size = (new_width, size[1])
+ return image.resize(size, resample=method)
+
+
+def cover(
+ image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
+) -> Image.Image:
+ """
+ Returns a resized version of the image, so that the requested size is
+ covered, while maintaining the original aspect ratio.
+
+ :param image: The image to resize.
+ :param size: The requested output size in pixels, given as a
+ (width, height) tuple.
+ :param method: Resampling method to use. Default is
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+ See :ref:`concept-filters`.
+ :return: An image.
+ """
+
+ im_ratio = image.width / image.height
+ dest_ratio = size[0] / size[1]
+
+ if im_ratio != dest_ratio:
+ if im_ratio < dest_ratio:
+ new_height = round(image.height / image.width * size[0])
+ if new_height != size[1]:
+ size = (size[0], new_height)
+ else:
+ new_width = round(image.width / image.height * size[1])
+ if new_width != size[0]:
+ size = (new_width, size[1])
+ return image.resize(size, resample=method)
+
+
+def pad(
+ image: Image.Image,
+ size: tuple[int, int],
+ method: int = Image.Resampling.BICUBIC,
+ color: str | int | tuple[int, ...] | None = None,
+ centering: tuple[float, float] = (0.5, 0.5),
+) -> Image.Image:
+ """
+ Returns a resized and padded version of the image, expanded to fill the
+ requested aspect ratio and size.
+
+ :param image: The image to resize and crop.
+ :param size: The requested output size in pixels, given as a
+ (width, height) tuple.
+ :param method: Resampling method to use. Default is
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+ See :ref:`concept-filters`.
+ :param color: The background color of the padded image.
+ :param centering: Control the position of the original image within the
+ padded version.
+
+ (0.5, 0.5) will keep the image centered
+ (0, 0) will keep the image aligned to the top left
+ (1, 1) will keep the image aligned to the bottom
+ right
+ :return: An image.
+ """
+
+ resized = contain(image, size, method)
+ if resized.size == size:
+ out = resized
+ else:
+ out = Image.new(image.mode, size, color)
+ if resized.palette:
+ palette = resized.getpalette()
+ if palette is not None:
+ out.putpalette(palette)
+ if resized.width != size[0]:
+ x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
+ out.paste(resized, (x, 0))
+ else:
+ y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
+ out.paste(resized, (0, y))
+ return out
+
+
+def crop(image: Image.Image, border: int = 0) -> Image.Image:
+ """
+ Remove border from image. The same amount of pixels are removed
+ from all four sides. This function works on all image modes.
+
+ .. seealso:: :py:meth:`~PIL.Image.Image.crop`
+
+ :param image: The image to crop.
+ :param border: The number of pixels to remove.
+ :return: An image.
+ """
+ left, top, right, bottom = _border(border)
+ return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
+
+
+def scale(
+ image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC
+) -> Image.Image:
+ """
+ Returns a rescaled image by a specific factor given in parameter.
+ A factor greater than 1 expands the image, between 0 and 1 contracts the
+ image.
+
+ :param image: The image to rescale.
+ :param factor: The expansion factor, as a float.
+ :param resample: Resampling method to use. Default is
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+ See :ref:`concept-filters`.
+ :returns: An :py:class:`~PIL.Image.Image` object.
+ """
+ if factor == 1:
+ return image.copy()
+ elif factor <= 0:
+ msg = "the factor must be greater than 0"
+ raise ValueError(msg)
+ else:
+ size = (round(factor * image.width), round(factor * image.height))
+ return image.resize(size, resample)
+
+
+class SupportsGetMesh(Protocol):
+ """
+ An object that supports the ``getmesh`` method, taking an image as an
+ argument, and returning a list of tuples. Each tuple contains two tuples,
+ the source box as a tuple of 4 integers, and a tuple of 8 integers for the
+ final quadrilateral, in order of top left, bottom left, bottom right, top
+ right.
+ """
+
+ def getmesh(
+ self, image: Image.Image
+ ) -> list[
+ tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]
+ ]: ...
+
+
+def deform(
+ image: Image.Image,
+ deformer: SupportsGetMesh,
+ resample: int = Image.Resampling.BILINEAR,
+) -> Image.Image:
+ """
+ Deform the image.
+
+ :param image: The image to deform.
+ :param deformer: A deformer object. Any object that implements a
+ ``getmesh`` method can be used.
+ :param resample: An optional resampling filter. Same values possible as
+ in the PIL.Image.transform function.
+ :return: An image.
+ """
+ return image.transform(
+ image.size, Image.Transform.MESH, deformer.getmesh(image), resample
+ )
+
+
+def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image:
+ """
+ Equalize the image histogram. This function applies a non-linear
+ mapping to the input image, in order to create a uniform
+ distribution of grayscale values in the output image.
+
+ :param image: The image to equalize.
+ :param mask: An optional mask. If given, only the pixels selected by
+ the mask are included in the analysis.
+ :return: An image.
+ """
+ if image.mode == "P":
+ image = image.convert("RGB")
+ h = image.histogram(mask)
+ lut = []
+ for b in range(0, len(h), 256):
+ histo = [_f for _f in h[b : b + 256] if _f]
+ if len(histo) <= 1:
+ lut.extend(list(range(256)))
+ else:
+ step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
+ if not step:
+ lut.extend(list(range(256)))
+ else:
+ n = step // 2
+ for i in range(256):
+ lut.append(n // step)
+ n = n + h[i + b]
+ return _lut(image, lut)
+
+
+def expand(
+ image: Image.Image,
+ border: int | tuple[int, ...] = 0,
+ fill: str | int | tuple[int, ...] = 0,
+) -> Image.Image:
+ """
+ Add border to the image
+
+ :param image: The image to expand.
+ :param border: Border width, in pixels.
+ :param fill: Pixel fill value (a color value). Default is 0 (black).
+ :return: An image.
+ """
+ left, top, right, bottom = _border(border)
+ width = left + image.size[0] + right
+ height = top + image.size[1] + bottom
+ color = _color(fill, image.mode)
+ if image.palette:
+ mode = image.palette.mode
+ palette = ImagePalette.ImagePalette(mode, image.getpalette(mode))
+ if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4):
+ color = palette.getcolor(color)
+ else:
+ palette = None
+ out = Image.new(image.mode, (width, height), color)
+ if palette:
+ out.putpalette(palette.palette, mode)
+ out.paste(image, (left, top))
+ return out
+
+
+def fit(
+ image: Image.Image,
+ size: tuple[int, int],
+ method: int = Image.Resampling.BICUBIC,
+ bleed: float = 0.0,
+ centering: tuple[float, float] = (0.5, 0.5),
+) -> Image.Image:
+ """
+ Returns a resized and cropped version of the image, cropped to the
+ requested aspect ratio and size.
+
+ This function was contributed by Kevin Cazabon.
+
+ :param image: The image to resize and crop.
+ :param size: The requested output size in pixels, given as a
+ (width, height) tuple.
+ :param method: Resampling method to use. Default is
+ :py:attr:`~PIL.Image.Resampling.BICUBIC`.
+ See :ref:`concept-filters`.
+ :param bleed: Remove a border around the outside of the image from all
+ four edges. The value is a decimal percentage (use 0.01 for
+ one percent). The default value is 0 (no border).
+ Cannot be greater than or equal to 0.5.
+ :param centering: Control the cropping position. Use (0.5, 0.5) for
+ center cropping (e.g. if cropping the width, take 50% off
+ of the left side, and therefore 50% off the right side).
+ (0.0, 0.0) will crop from the top left corner (i.e. if
+ cropping the width, take all of the crop off of the right
+ side, and if cropping the height, take all of it off the
+ bottom). (1.0, 0.0) will crop from the bottom left
+ corner, etc. (i.e. if cropping the width, take all of the
+ crop off the left side, and if cropping the height take
+ none from the top, and therefore all off the bottom).
+ :return: An image.
+ """
+
+ # by Kevin Cazabon, Feb 17/2000
+ # kevin@cazabon.com
+ # https://www.cazabon.com
+
+ centering_x, centering_y = centering
+
+ if not 0.0 <= centering_x <= 1.0:
+ centering_x = 0.5
+ if not 0.0 <= centering_y <= 1.0:
+ centering_y = 0.5
+
+ if not 0.0 <= bleed < 0.5:
+ bleed = 0.0
+
+ # calculate the area to use for resizing and cropping, subtracting
+ # the 'bleed' around the edges
+
+ # number of pixels to trim off on Top and Bottom, Left and Right
+ bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
+
+ live_size = (
+ image.size[0] - bleed_pixels[0] * 2,
+ image.size[1] - bleed_pixels[1] * 2,
+ )
+
+ # calculate the aspect ratio of the live_size
+ live_size_ratio = live_size[0] / live_size[1]
+
+ # calculate the aspect ratio of the output image
+ output_ratio = size[0] / size[1]
+
+ # figure out if the sides or top/bottom will be cropped off
+ if live_size_ratio == output_ratio:
+ # live_size is already the needed ratio
+ crop_width = live_size[0]
+ crop_height = live_size[1]
+ elif live_size_ratio >= output_ratio:
+ # live_size is wider than what's needed, crop the sides
+ crop_width = output_ratio * live_size[1]
+ crop_height = live_size[1]
+ else:
+ # live_size is taller than what's needed, crop the top and bottom
+ crop_width = live_size[0]
+ crop_height = live_size[0] / output_ratio
+
+ # make the crop
+ crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x
+ crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y
+
+ crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
+
+ # resize the image and return it
+ return image.resize(size, method, box=crop)
+
+
+def flip(image: Image.Image) -> Image.Image:
+ """
+ Flip the image vertically (top to bottom).
+
+ :param image: The image to flip.
+ :return: An image.
+ """
+ return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
+
+
+def grayscale(image: Image.Image) -> Image.Image:
+ """
+ Convert the image to grayscale.
+
+ :param image: The image to convert.
+ :return: An image.
+ """
+ return image.convert("L")
+
+
+def invert(image: Image.Image) -> Image.Image:
+ """
+ Invert (negate) the image.
+
+ :param image: The image to invert.
+ :return: An image.
+ """
+ lut = list(range(255, -1, -1))
+ return image.point(lut) if image.mode == "1" else _lut(image, lut)
+
+
+def mirror(image: Image.Image) -> Image.Image:
+ """
+ Flip image horizontally (left to right).
+
+ :param image: The image to mirror.
+ :return: An image.
+ """
+ return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
+
+
+def posterize(image: Image.Image, bits: int) -> Image.Image:
+ """
+ Reduce the number of bits for each color channel.
+
+ :param image: The image to posterize.
+ :param bits: The number of bits to keep for each channel (1-8).
+ :return: An image.
+ """
+ mask = ~(2 ** (8 - bits) - 1)
+ lut = [i & mask for i in range(256)]
+ return _lut(image, lut)
+
+
+def solarize(image: Image.Image, threshold: int = 128) -> Image.Image:
+ """
+ Invert all pixel values above a threshold.
+
+ :param image: The image to solarize.
+ :param threshold: All pixels above this grayscale level are inverted.
+ :return: An image.
+ """
+ lut = []
+ for i in range(256):
+ if i < threshold:
+ lut.append(i)
+ else:
+ lut.append(255 - i)
+ return _lut(image, lut)
+
+
+@overload
+def exif_transpose(image: Image.Image, *, in_place: Literal[True]) -> None: ...
+
+
+@overload
+def exif_transpose(
+ image: Image.Image, *, in_place: Literal[False] = False
+) -> Image.Image: ...
+
+
+def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:
+ """
+ If an image has an EXIF Orientation tag, other than 1, transpose the image
+ accordingly, and remove the orientation data.
+
+ :param image: The image to transpose.
+ :param in_place: Boolean. Keyword-only argument.
+ If ``True``, the original image is modified in-place, and ``None`` is returned.
+ If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
+ with the transposition applied. If there is no transposition, a copy of the
+ image will be returned.
+ """
+ image.load()
+ image_exif = image.getexif()
+ orientation = image_exif.get(ExifTags.Base.Orientation, 1)
+ method = {
+ 2: Image.Transpose.FLIP_LEFT_RIGHT,
+ 3: Image.Transpose.ROTATE_180,
+ 4: Image.Transpose.FLIP_TOP_BOTTOM,
+ 5: Image.Transpose.TRANSPOSE,
+ 6: Image.Transpose.ROTATE_270,
+ 7: Image.Transpose.TRANSVERSE,
+ 8: Image.Transpose.ROTATE_90,
+ }.get(orientation)
+ if method is not None:
+ if in_place:
+ image.im = image.im.transpose(method)
+ image._size = image.im.size
+ else:
+ transposed_image = image.transpose(method)
+ exif_image = image if in_place else transposed_image
+
+ exif = exif_image.getexif()
+ if ExifTags.Base.Orientation in exif:
+ del exif[ExifTags.Base.Orientation]
+ if "exif" in exif_image.info:
+ exif_image.info["exif"] = exif.tobytes()
+ elif "Raw profile type exif" in exif_image.info:
+ exif_image.info["Raw profile type exif"] = exif.tobytes().hex()
+ for key in ("XML:com.adobe.xmp", "xmp"):
+ if key in exif_image.info:
+ for pattern in (
+ r'tiff:Orientation="([0-9])"',
+ r"([0-9])",
+ ):
+ value = exif_image.info[key]
+ if isinstance(value, str):
+ value = re.sub(pattern, "", value)
+ elif isinstance(value, tuple):
+ value = tuple(
+ re.sub(pattern.encode(), b"", v) for v in value
+ )
+ else:
+ value = re.sub(pattern.encode(), b"", value)
+ exif_image.info[key] = value
+ if not in_place:
+ return transposed_image
+ elif not in_place:
+ return image.copy()
+ return None
diff --git a/venv/Lib/site-packages/PIL/ImagePalette.py b/venv/Lib/site-packages/PIL/ImagePalette.py
new file mode 100644
index 0000000..eae7aea
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImagePalette.py
@@ -0,0 +1,287 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# image palette object
+#
+# History:
+# 1996-03-11 fl Rewritten.
+# 1997-01-03 fl Up and running.
+# 1997-08-23 fl Added load hack
+# 2001-04-16 fl Fixed randint shadow bug in random()
+#
+# Copyright (c) 1997-2001 by Secret Labs AB
+# Copyright (c) 1996-1997 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import array
+from collections.abc import Sequence
+from typing import IO
+
+from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from . import Image
+
+
+class ImagePalette:
+ """
+ Color palette for palette mapped images
+
+ :param mode: The mode to use for the palette. See:
+ :ref:`concept-modes`. Defaults to "RGB"
+ :param palette: An optional palette. If given, it must be a bytearray,
+ an array or a list of ints between 0-255. The list must consist of
+ all channels for one color followed by the next color (e.g. RGBRGBRGB).
+ Defaults to an empty palette.
+ """
+
+ def __init__(
+ self,
+ mode: str = "RGB",
+ palette: Sequence[int] | bytes | bytearray | None = None,
+ ) -> None:
+ self.mode = mode
+ self.rawmode: str | None = None # if set, palette contains raw data
+ self.palette = palette or bytearray()
+ self.dirty: int | None = None
+
+ @property
+ def palette(self) -> Sequence[int] | bytes | bytearray:
+ return self._palette
+
+ @palette.setter
+ def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:
+ self._colors: dict[tuple[int, ...], int] | None = None
+ self._palette = palette
+
+ @property
+ def colors(self) -> dict[tuple[int, ...], int]:
+ if self._colors is None:
+ mode_len = len(self.mode)
+ self._colors = {}
+ for i in range(0, len(self.palette), mode_len):
+ color = tuple(self.palette[i : i + mode_len])
+ if color in self._colors:
+ continue
+ self._colors[color] = i // mode_len
+ return self._colors
+
+ @colors.setter
+ def colors(self, colors: dict[tuple[int, ...], int]) -> None:
+ self._colors = colors
+
+ def copy(self) -> ImagePalette:
+ new = ImagePalette()
+
+ new.mode = self.mode
+ new.rawmode = self.rawmode
+ if self.palette is not None:
+ new.palette = self.palette[:]
+ new.dirty = self.dirty
+
+ return new
+
+ def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]:
+ """
+ Get palette contents in format suitable for the low-level
+ ``im.putpalette`` primitive.
+
+ .. warning:: This method is experimental.
+ """
+ if self.rawmode:
+ return self.rawmode, self.palette
+ return self.mode, self.tobytes()
+
+ def tobytes(self) -> bytes:
+ """Convert palette to bytes.
+
+ .. warning:: This method is experimental.
+ """
+ if self.rawmode:
+ msg = "palette contains raw palette data"
+ raise ValueError(msg)
+ if isinstance(self.palette, bytes):
+ return self.palette
+ arr = array.array("B", self.palette)
+ return arr.tobytes()
+
+ # Declare tostring as an alias for tobytes
+ tostring = tobytes
+
+ def _new_color_index(
+ self, image: Image.Image | None = None, e: Exception | None = None
+ ) -> int:
+ if not isinstance(self.palette, bytearray):
+ self._palette = bytearray(self.palette)
+ index = len(self.palette) // len(self.mode)
+ special_colors: tuple[int | tuple[int, ...] | None, ...] = ()
+ if image:
+ special_colors = (
+ image.info.get("background"),
+ image.info.get("transparency"),
+ )
+ while index in special_colors:
+ index += 1
+ if index >= 256:
+ if image:
+ # Search for an unused index
+ for i, count in reversed(list(enumerate(image.histogram()))):
+ if count == 0 and i not in special_colors:
+ index = i
+ break
+ if index >= 256:
+ msg = "cannot allocate more than 256 colors"
+ raise ValueError(msg) from e
+ return index
+
+ def getcolor(
+ self,
+ color: tuple[int, ...],
+ image: Image.Image | None = None,
+ ) -> int:
+ """Given an rgb tuple, allocate palette entry.
+
+ .. warning:: This method is experimental.
+ """
+ if self.rawmode:
+ msg = "palette contains raw palette data"
+ raise ValueError(msg)
+ if isinstance(color, tuple):
+ if self.mode == "RGB":
+ if len(color) == 4:
+ if color[3] != 255:
+ msg = "cannot add non-opaque RGBA color to RGB palette"
+ raise ValueError(msg)
+ color = color[:3]
+ elif self.mode == "RGBA":
+ if len(color) == 3:
+ color += (255,)
+ try:
+ return self.colors[color]
+ except KeyError as e:
+ # allocate new color slot
+ index = self._new_color_index(image, e)
+ assert isinstance(self._palette, bytearray)
+ self.colors[color] = index
+ mode_len = len(self.mode)
+ if index * mode_len < len(self.palette):
+ self._palette = (
+ self._palette[: index * mode_len]
+ + bytes(color)
+ + self._palette[index * mode_len + mode_len :]
+ )
+ else:
+ self._palette += bytes(color)
+ self.dirty = 1
+ return index
+ else:
+ msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable]
+ raise ValueError(msg)
+
+ def save(self, fp: str | IO[str]) -> None:
+ """Save palette to text file.
+
+ .. warning:: This method is experimental.
+ """
+ if self.rawmode:
+ msg = "palette contains raw palette data"
+ raise ValueError(msg)
+ if isinstance(fp, str):
+ fp = open(fp, "w")
+ fp.write("# Palette\n")
+ fp.write(f"# Mode: {self.mode}\n")
+ for i in range(256):
+ fp.write(f"{i}")
+ for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
+ try:
+ fp.write(f" {self.palette[j]}")
+ except IndexError:
+ fp.write(" 0")
+ fp.write("\n")
+ fp.close()
+
+
+# --------------------------------------------------------------------
+# Internal
+
+
+def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
+ palette = ImagePalette()
+ palette.rawmode = rawmode
+ palette.palette = data
+ palette.dirty = 1
+ return palette
+
+
+# --------------------------------------------------------------------
+# Factories
+
+
+def make_linear_lut(black: int, white: float) -> list[int]:
+ if black == 0:
+ return [int(white * i // 255) for i in range(256)]
+
+ msg = "unavailable when black is non-zero"
+ raise NotImplementedError(msg) # FIXME
+
+
+def make_gamma_lut(exp: float) -> list[int]:
+ return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
+
+
+def negative(mode: str = "RGB") -> ImagePalette:
+ palette = list(range(256 * len(mode)))
+ palette.reverse()
+ return ImagePalette(mode, [i // len(mode) for i in palette])
+
+
+def random(mode: str = "RGB") -> ImagePalette:
+ from random import randint
+
+ palette = [randint(0, 255) for _ in range(256 * len(mode))]
+ return ImagePalette(mode, palette)
+
+
+def sepia(white: str = "#fff0c0") -> ImagePalette:
+ bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
+ return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])
+
+
+def wedge(mode: str = "RGB") -> ImagePalette:
+ palette = list(range(256 * len(mode)))
+ return ImagePalette(mode, [i // len(mode) for i in palette])
+
+
+def load(filename: str) -> tuple[bytes, str]:
+ # FIXME: supports GIMP gradients only
+
+ with open(filename, "rb") as fp:
+ paletteHandlers: list[
+ type[
+ GimpPaletteFile.GimpPaletteFile
+ | GimpGradientFile.GimpGradientFile
+ | PaletteFile.PaletteFile
+ ]
+ ] = [
+ GimpPaletteFile.GimpPaletteFile,
+ GimpGradientFile.GimpGradientFile,
+ PaletteFile.PaletteFile,
+ ]
+ for paletteHandler in paletteHandlers:
+ try:
+ fp.seek(0)
+ lut = paletteHandler(fp).getpalette()
+ if lut:
+ break
+ except (SyntaxError, ValueError):
+ pass
+ else:
+ msg = "cannot load palette"
+ raise OSError(msg)
+
+ return lut # data, rawmode
diff --git a/venv/Lib/site-packages/PIL/ImagePath.py b/venv/Lib/site-packages/PIL/ImagePath.py
new file mode 100644
index 0000000..77e8a60
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImagePath.py
@@ -0,0 +1,20 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# path interface
+#
+# History:
+# 1996-11-04 fl Created
+# 2002-04-14 fl Added documentation stub class
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1996.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from . import Image
+
+Path = Image.core.path
diff --git a/venv/Lib/site-packages/PIL/ImageQt.py b/venv/Lib/site-packages/PIL/ImageQt.py
new file mode 100644
index 0000000..af4d074
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageQt.py
@@ -0,0 +1,219 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# a simple Qt image interface.
+#
+# history:
+# 2006-06-03 fl: created
+# 2006-06-04 fl: inherit from QImage instead of wrapping it
+# 2006-06-05 fl: removed toimage helper; move string support to ImageQt
+# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)
+#
+# Copyright (c) 2006 by Secret Labs AB
+# Copyright (c) 2006 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import sys
+from io import BytesIO
+
+from . import Image
+from ._util import is_path
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from typing import Any
+
+ from . import ImageFile
+
+ QBuffer: type
+
+qt_version: str | None
+qt_versions = [
+ ["6", "PyQt6"],
+ ["side6", "PySide6"],
+]
+
+# If a version has already been imported, attempt it first
+qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True)
+for version, qt_module in qt_versions:
+ try:
+ qRgba: Callable[[int, int, int, int], int]
+ if qt_module == "PyQt6":
+ from PyQt6.QtCore import QBuffer, QByteArray, QIODevice
+ from PyQt6.QtGui import QImage, QPixmap, qRgba
+ elif qt_module == "PySide6":
+ from PySide6.QtCore import ( # type: ignore[assignment]
+ QBuffer,
+ QByteArray,
+ QIODevice,
+ )
+ from PySide6.QtGui import QImage, QPixmap, qRgba # type: ignore[assignment]
+ except (ImportError, RuntimeError):
+ continue
+ qt_is_installed = True
+ qt_version = version
+ break
+else:
+ qt_is_installed = False
+ qt_version = None
+
+
+def rgb(r: int, g: int, b: int, a: int = 255) -> int:
+ """(Internal) Turns an RGB color into a Qt compatible color integer."""
+ # use qRgb to pack the colors, and then turn the resulting long
+ # into a negative integer with the same bitpattern.
+ return qRgba(r, g, b, a) & 0xFFFFFFFF
+
+
+def fromqimage(im: QImage | QPixmap) -> ImageFile.ImageFile:
+ """
+ :param im: QImage or PIL ImageQt object
+ """
+ buffer = QBuffer()
+ qt_openmode: object
+ if qt_version == "6":
+ try:
+ qt_openmode = getattr(QIODevice, "OpenModeFlag")
+ except AttributeError:
+ qt_openmode = getattr(QIODevice, "OpenMode")
+ else:
+ qt_openmode = QIODevice
+ buffer.open(getattr(qt_openmode, "ReadWrite"))
+ # preserve alpha channel with png
+ # otherwise ppm is more friendly with Image.open
+ if im.hasAlphaChannel():
+ im.save(buffer, "png")
+ else:
+ im.save(buffer, "ppm")
+
+ b = BytesIO()
+ b.write(buffer.data())
+ buffer.close()
+ b.seek(0)
+
+ return Image.open(b)
+
+
+def fromqpixmap(im: QPixmap) -> ImageFile.ImageFile:
+ return fromqimage(im)
+
+
+def align8to32(bytes: bytes, width: int, mode: str) -> bytes:
+ """
+ converts each scanline of data from 8 bit to 32 bit aligned
+ """
+
+ bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode]
+
+ # calculate bytes per line and the extra padding if needed
+ bits_per_line = bits_per_pixel * width
+ full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
+ bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
+
+ extra_padding = -bytes_per_line % 4
+
+ # already 32 bit aligned by luck
+ if not extra_padding:
+ return bytes
+
+ new_data = [
+ bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding
+ for i in range(len(bytes) // bytes_per_line)
+ ]
+
+ return b"".join(new_data)
+
+
+def _toqclass_helper(im: Image.Image | str | QByteArray) -> dict[str, Any]:
+ data = None
+ colortable = None
+ exclusive_fp = False
+
+ # handle filename, if given instead of image name
+ if hasattr(im, "toUtf8"):
+ # FIXME - is this really the best way to do this?
+ im = str(im.toUtf8(), "utf-8")
+ if is_path(im):
+ im = Image.open(im)
+ exclusive_fp = True
+ assert isinstance(im, Image.Image)
+
+ qt_format = getattr(QImage, "Format") if qt_version == "6" else QImage
+ if im.mode == "1":
+ format = getattr(qt_format, "Format_Mono")
+ elif im.mode == "L":
+ format = getattr(qt_format, "Format_Indexed8")
+ colortable = [rgb(i, i, i) for i in range(256)]
+ elif im.mode == "P":
+ format = getattr(qt_format, "Format_Indexed8")
+ palette = im.getpalette()
+ assert palette is not None
+ colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
+ elif im.mode == "RGB":
+ # Populate the 4th channel with 255
+ im = im.convert("RGBA")
+
+ data = im.tobytes("raw", "BGRA")
+ format = getattr(qt_format, "Format_RGB32")
+ elif im.mode == "RGBA":
+ data = im.tobytes("raw", "BGRA")
+ format = getattr(qt_format, "Format_ARGB32")
+ elif im.mode == "I;16":
+ im = im.point(lambda i: i * 256)
+
+ format = getattr(qt_format, "Format_Grayscale16")
+ else:
+ if exclusive_fp:
+ im.close()
+ msg = f"unsupported image mode {repr(im.mode)}"
+ raise ValueError(msg)
+
+ size = im.size
+ __data = data or align8to32(im.tobytes(), size[0], im.mode)
+ if exclusive_fp:
+ im.close()
+ return {"data": __data, "size": size, "format": format, "colortable": colortable}
+
+
+if qt_is_installed:
+
+ class ImageQt(QImage):
+ def __init__(self, im: Image.Image | str | QByteArray) -> None:
+ """
+ An PIL image wrapper for Qt. This is a subclass of PyQt's QImage
+ class.
+
+ :param im: A PIL Image object, or a file name (given either as
+ Python string or a PyQt string object).
+ """
+ im_data = _toqclass_helper(im)
+ # must keep a reference, or Qt will crash!
+ # All QImage constructors that take data operate on an existing
+ # buffer, so this buffer has to hang on for the life of the image.
+ # Fixes https://github.com/python-pillow/Pillow/issues/1370
+ self.__data = im_data["data"]
+ super().__init__(
+ self.__data,
+ im_data["size"][0],
+ im_data["size"][1],
+ im_data["format"],
+ )
+ if im_data["colortable"]:
+ self.setColorTable(im_data["colortable"])
+
+
+def toqimage(im: Image.Image | str | QByteArray) -> ImageQt:
+ return ImageQt(im)
+
+
+def toqpixmap(im: Image.Image | str | QByteArray) -> QPixmap:
+ qimage = toqimage(im)
+ pixmap = getattr(QPixmap, "fromImage")(qimage)
+ if qt_version == "6":
+ pixmap.detach()
+ return pixmap
diff --git a/venv/Lib/site-packages/PIL/ImageSequence.py b/venv/Lib/site-packages/PIL/ImageSequence.py
new file mode 100644
index 0000000..361be48
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageSequence.py
@@ -0,0 +1,88 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# sequence support classes
+#
+# history:
+# 1997-02-20 fl Created
+#
+# Copyright (c) 1997 by Secret Labs AB.
+# Copyright (c) 1997 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+
+##
+from __future__ import annotations
+
+from . import Image
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+
+class Iterator:
+ """
+ This class implements an iterator object that can be used to loop
+ over an image sequence.
+
+ You can use the ``[]`` operator to access elements by index. This operator
+ will raise an :py:exc:`IndexError` if you try to access a nonexistent
+ frame.
+
+ :param im: An image object.
+ """
+
+ def __init__(self, im: Image.Image) -> None:
+ if not hasattr(im, "seek"):
+ msg = "im must have seek method"
+ raise AttributeError(msg)
+ self.im = im
+ self.position = getattr(self.im, "_min_frame", 0)
+
+ def __getitem__(self, ix: int) -> Image.Image:
+ try:
+ self.im.seek(ix)
+ return self.im
+ except EOFError as e:
+ msg = "end of sequence"
+ raise IndexError(msg) from e
+
+ def __iter__(self) -> Iterator:
+ return self
+
+ def __next__(self) -> Image.Image:
+ try:
+ self.im.seek(self.position)
+ self.position += 1
+ return self.im
+ except EOFError as e:
+ msg = "end of sequence"
+ raise StopIteration(msg) from e
+
+
+def all_frames(
+ im: Image.Image | list[Image.Image],
+ func: Callable[[Image.Image], Image.Image] | None = None,
+) -> list[Image.Image]:
+ """
+ Applies a given function to all frames in an image or a list of images.
+ The frames are returned as a list of separate images.
+
+ :param im: An image, or a list of images.
+ :param func: The function to apply to all of the image frames.
+ :returns: A list of images.
+ """
+ if not isinstance(im, list):
+ im = [im]
+
+ ims = []
+ for imSequence in im:
+ current = imSequence.tell()
+
+ ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
+
+ imSequence.seek(current)
+ return [func(im) for im in ims] if func else ims
diff --git a/venv/Lib/site-packages/PIL/ImageShow.py b/venv/Lib/site-packages/PIL/ImageShow.py
new file mode 100644
index 0000000..7705608
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageShow.py
@@ -0,0 +1,362 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# im.show() drivers
+#
+# History:
+# 2008-04-06 fl Created
+#
+# Copyright (c) Secret Labs AB 2008.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import abc
+import os
+import shutil
+import subprocess
+import sys
+from shlex import quote
+from typing import Any
+
+from . import Image
+
+_viewers = []
+
+
+def register(viewer: type[Viewer] | Viewer, order: int = 1) -> None:
+ """
+ The :py:func:`register` function is used to register additional viewers::
+
+ from PIL import ImageShow
+ ImageShow.register(MyViewer()) # MyViewer will be used as a last resort
+ ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised
+ ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised
+
+ :param viewer: The viewer to be registered.
+ :param order:
+ Zero or a negative integer to prepend this viewer to the list,
+ a positive integer to append it.
+ """
+ if isinstance(viewer, type) and issubclass(viewer, Viewer):
+ viewer = viewer()
+ if order > 0:
+ _viewers.append(viewer)
+ else:
+ _viewers.insert(0, viewer)
+
+
+def show(image: Image.Image, title: str | None = None, **options: Any) -> bool:
+ r"""
+ Display a given image.
+
+ :param image: An image object.
+ :param title: Optional title. Not all viewers can display the title.
+ :param \**options: Additional viewer options.
+ :returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
+ """
+ for viewer in _viewers:
+ if viewer.show(image, title=title, **options):
+ return True
+ return False
+
+
+class Viewer:
+ """Base class for viewers."""
+
+ # main api
+
+ def show(self, image: Image.Image, **options: Any) -> int:
+ """
+ The main function for displaying an image.
+ Converts the given image to the target format and displays it.
+ """
+
+ if not (
+ image.mode in ("1", "RGBA")
+ or (self.format == "PNG" and image.mode in ("I;16", "LA"))
+ ):
+ base = Image.getmodebase(image.mode)
+ if image.mode != base:
+ image = image.convert(base)
+
+ return self.show_image(image, **options)
+
+ # hook methods
+
+ format: str | None = None
+ """The format to convert the image into."""
+ options: dict[str, Any] = {}
+ """Additional options used to convert the image."""
+
+ def get_format(self, image: Image.Image) -> str | None:
+ """Return format name, or ``None`` to save as PGM/PPM."""
+ return self.format
+
+ def get_command(self, file: str, **options: Any) -> str:
+ """
+ Returns the command used to display the file.
+ Not implemented in the base class.
+ """
+ msg = "unavailable in base viewer"
+ raise NotImplementedError(msg)
+
+ def save_image(self, image: Image.Image) -> str:
+ """Save to temporary file and return filename."""
+ return image._dump(format=self.get_format(image), **self.options)
+
+ def show_image(self, image: Image.Image, **options: Any) -> int:
+ """Display the given image."""
+ return self.show_file(self.save_image(image), **options)
+
+ def show_file(self, path: str, **options: Any) -> int:
+ """
+ Display given file.
+ """
+ if not os.path.exists(path):
+ raise FileNotFoundError
+ os.system(self.get_command(path, **options)) # nosec
+ return 1
+
+
+# --------------------------------------------------------------------
+
+
+class WindowsViewer(Viewer):
+ """The default viewer on Windows is the default system application for PNG files."""
+
+ format = "PNG"
+ options = {"compress_level": 1, "save_all": True}
+
+ def get_command(self, file: str, **options: Any) -> str:
+ return (
+ f'start "Pillow" /WAIT "{file}" '
+ "&& ping -n 4 127.0.0.1 >NUL "
+ f'&& del /f "{file}"'
+ )
+
+ def show_file(self, path: str, **options: Any) -> int:
+ """
+ Display given file.
+ """
+ if not os.path.exists(path):
+ raise FileNotFoundError
+ subprocess.Popen(
+ self.get_command(path, **options),
+ shell=True,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW"),
+ ) # nosec
+ return 1
+
+
+if sys.platform == "win32":
+ register(WindowsViewer)
+
+
+class MacViewer(Viewer):
+ """The default viewer on macOS using ``Preview.app``."""
+
+ format = "PNG"
+ options = {"compress_level": 1, "save_all": True}
+
+ def get_command(self, file: str, **options: Any) -> str:
+ # on darwin open returns immediately resulting in the temp
+ # file removal while app is opening
+ command = "open -a Preview.app"
+ command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
+ return command
+
+ def show_file(self, path: str, **options: Any) -> int:
+ """
+ Display given file.
+ """
+ if not os.path.exists(path):
+ raise FileNotFoundError
+ subprocess.call(["open", "-a", "Preview.app", path])
+
+ pyinstaller = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")
+ executable = (not pyinstaller and sys.executable) or shutil.which("python3")
+ if executable:
+ subprocess.Popen(
+ [
+ executable,
+ "-c",
+ "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",
+ path,
+ ]
+ )
+ return 1
+
+
+if sys.platform == "darwin":
+ register(MacViewer)
+
+
+class UnixViewer(abc.ABC, Viewer):
+ format = "PNG"
+ options = {"compress_level": 1, "save_all": True}
+
+ @abc.abstractmethod
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
+ pass
+
+ def get_command(self, file: str, **options: Any) -> str:
+ command = self.get_command_ex(file, **options)[0]
+ return f"{command} {quote(file)}"
+
+
+class XDGViewer(UnixViewer):
+ """
+ The freedesktop.org ``xdg-open`` command.
+ """
+
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
+ command = executable = "xdg-open"
+ return command, executable
+
+ def show_file(self, path: str, **options: Any) -> int:
+ """
+ Display given file.
+ """
+ if not os.path.exists(path):
+ raise FileNotFoundError
+ subprocess.Popen(["xdg-open", path])
+ return 1
+
+
+class DisplayViewer(UnixViewer):
+ """
+ The ImageMagick ``display`` command.
+ This viewer supports the ``title`` parameter.
+ """
+
+ def get_command_ex(
+ self, file: str, title: str | None = None, **options: Any
+ ) -> tuple[str, str]:
+ command = executable = "display"
+ if title:
+ command += f" -title {quote(title)}"
+ return command, executable
+
+ def show_file(self, path: str, **options: Any) -> int:
+ """
+ Display given file.
+ """
+ if not os.path.exists(path):
+ raise FileNotFoundError
+ args = ["display"]
+ title = options.get("title")
+ if title:
+ args += ["-title", title]
+ args.append(path)
+
+ subprocess.Popen(args)
+ return 1
+
+
+class GmDisplayViewer(UnixViewer):
+ """The GraphicsMagick ``gm display`` command."""
+
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
+ executable = "gm"
+ command = "gm display"
+ return command, executable
+
+ def show_file(self, path: str, **options: Any) -> int:
+ """
+ Display given file.
+ """
+ if not os.path.exists(path):
+ raise FileNotFoundError
+ subprocess.Popen(["gm", "display", path])
+ return 1
+
+
+class EogViewer(UnixViewer):
+ """The GNOME Image Viewer ``eog`` command."""
+
+ def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
+ executable = "eog"
+ command = "eog -n"
+ return command, executable
+
+ def show_file(self, path: str, **options: Any) -> int:
+ """
+ Display given file.
+ """
+ if not os.path.exists(path):
+ raise FileNotFoundError
+ subprocess.Popen(["eog", "-n", path])
+ return 1
+
+
+class XVViewer(UnixViewer):
+ """
+ The X Viewer ``xv`` command.
+ This viewer supports the ``title`` parameter.
+ """
+
+ def get_command_ex(
+ self, file: str, title: str | None = None, **options: Any
+ ) -> tuple[str, str]:
+ # note: xv is pretty outdated. most modern systems have
+ # imagemagick's display command instead.
+ command = executable = "xv"
+ if title:
+ command += f" -name {quote(title)}"
+ return command, executable
+
+ def show_file(self, path: str, **options: Any) -> int:
+ """
+ Display given file.
+ """
+ if not os.path.exists(path):
+ raise FileNotFoundError
+ args = ["xv"]
+ title = options.get("title")
+ if title:
+ args += ["-name", title]
+ args.append(path)
+
+ subprocess.Popen(args)
+ return 1
+
+
+if sys.platform not in ("win32", "darwin"): # unixoids
+ if shutil.which("xdg-open"):
+ register(XDGViewer)
+ if shutil.which("display"):
+ register(DisplayViewer)
+ if shutil.which("gm"):
+ register(GmDisplayViewer)
+ if shutil.which("eog"):
+ register(EogViewer)
+ if shutil.which("xv"):
+ register(XVViewer)
+
+
+class IPythonViewer(Viewer):
+ """The viewer for IPython frontends."""
+
+ def show_image(self, image: Image.Image, **options: Any) -> int:
+ ipython_display(image)
+ return 1
+
+
+try:
+ from IPython.display import display as ipython_display
+except ImportError:
+ pass
+else:
+ register(IPythonViewer)
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ print("Syntax: python3 ImageShow.py imagefile [title]")
+ sys.exit()
+
+ with Image.open(sys.argv[1]) as im:
+ print(show(im, *sys.argv[2:]))
diff --git a/venv/Lib/site-packages/PIL/ImageStat.py b/venv/Lib/site-packages/PIL/ImageStat.py
new file mode 100644
index 0000000..3a1044b
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageStat.py
@@ -0,0 +1,167 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# global image statistics
+#
+# History:
+# 1996-04-05 fl Created
+# 1997-05-21 fl Added mask; added rms, var, stddev attributes
+# 1997-08-05 fl Added median
+# 1998-07-05 hk Fixed integer overflow error
+#
+# Notes:
+# This class shows how to implement delayed evaluation of attributes.
+# To get a certain value, simply access the corresponding attribute.
+# The __getattr__ dispatcher takes care of the rest.
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1996-97.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import math
+from functools import cached_property
+
+from . import Image
+
+
+class Stat:
+ def __init__(
+ self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None
+ ) -> None:
+ """
+ Calculate statistics for the given image. If a mask is included,
+ only the regions covered by that mask are included in the
+ statistics. You can also pass in a previously calculated histogram.
+
+ :param image: A PIL image, or a precalculated histogram.
+
+ .. note::
+
+ For a PIL image, calculations rely on the
+ :py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are
+ grouped into 256 bins, even if the image has more than 8 bits per
+ channel. So ``I`` and ``F`` mode images have a maximum ``mean``,
+ ``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum
+ of more than 255.
+
+ :param mask: An optional mask.
+ """
+ if isinstance(image_or_list, Image.Image):
+ self.h = image_or_list.histogram(mask)
+ elif isinstance(image_or_list, list):
+ self.h = image_or_list
+ else:
+ msg = "first argument must be image or list" # type: ignore[unreachable]
+ raise TypeError(msg)
+ self.bands = list(range(len(self.h) // 256))
+
+ @cached_property
+ def extrema(self) -> list[tuple[int, int]]:
+ """
+ Min/max values for each band in the image.
+
+ .. note::
+ This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and
+ simply returns the low and high bins used. This is correct for
+ images with 8 bits per channel, but fails for other modes such as
+ ``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to
+ return per-band extrema for the image. This is more correct and
+ efficient because, for non-8-bit modes, the histogram method uses
+ :py:meth:`~PIL.Image.Image.getextrema` to determine the bins used.
+ """
+
+ def minmax(histogram: list[int]) -> tuple[int, int]:
+ res_min, res_max = 255, 0
+ for i in range(256):
+ if histogram[i]:
+ res_min = i
+ break
+ for i in range(255, -1, -1):
+ if histogram[i]:
+ res_max = i
+ break
+ return res_min, res_max
+
+ return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)]
+
+ @cached_property
+ def count(self) -> list[int]:
+ """Total number of pixels for each band in the image."""
+ return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)]
+
+ @cached_property
+ def sum(self) -> list[float]:
+ """Sum of all pixels for each band in the image."""
+
+ v = []
+ for i in range(0, len(self.h), 256):
+ layer_sum = 0.0
+ for j in range(256):
+ layer_sum += j * self.h[i + j]
+ v.append(layer_sum)
+ return v
+
+ @cached_property
+ def sum2(self) -> list[float]:
+ """Squared sum of all pixels for each band in the image."""
+
+ v = []
+ for i in range(0, len(self.h), 256):
+ sum2 = 0.0
+ for j in range(256):
+ sum2 += (j**2) * float(self.h[i + j])
+ v.append(sum2)
+ return v
+
+ @cached_property
+ def mean(self) -> list[float]:
+ """Average (arithmetic mean) pixel level for each band in the image."""
+ return [self.sum[i] / self.count[i] if self.count[i] else 0 for i in self.bands]
+
+ @cached_property
+ def median(self) -> list[int]:
+ """Median pixel level for each band in the image."""
+
+ v = []
+ for i in self.bands:
+ s = 0
+ half = self.count[i] // 2
+ b = i * 256
+ for j in range(256):
+ s = s + self.h[b + j]
+ if s > half:
+ break
+ v.append(j)
+ return v
+
+ @cached_property
+ def rms(self) -> list[float]:
+ """RMS (root-mean-square) for each band in the image."""
+ return [
+ math.sqrt(self.sum2[i] / self.count[i]) if self.count[i] else 0
+ for i in self.bands
+ ]
+
+ @cached_property
+ def var(self) -> list[float]:
+ """Variance for each band in the image."""
+ return [
+ (
+ (self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]
+ if self.count[i]
+ else 0
+ )
+ for i in self.bands
+ ]
+
+ @cached_property
+ def stddev(self) -> list[float]:
+ """Standard deviation for each band in the image."""
+ return [math.sqrt(self.var[i]) for i in self.bands]
+
+
+Global = Stat # compatibility
diff --git a/venv/Lib/site-packages/PIL/ImageText.py b/venv/Lib/site-packages/PIL/ImageText.py
new file mode 100644
index 0000000..e6ccd82
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageText.py
@@ -0,0 +1,320 @@
+from __future__ import annotations
+
+from . import ImageFont
+from ._typing import _Ink
+
+
+class Text:
+ def __init__(
+ self,
+ text: str | bytes,
+ font: (
+ ImageFont.ImageFont
+ | ImageFont.FreeTypeFont
+ | ImageFont.TransposedFont
+ | None
+ ) = None,
+ mode: str = "RGB",
+ spacing: float = 4,
+ direction: str | None = None,
+ features: list[str] | None = None,
+ language: str | None = None,
+ ) -> None:
+ """
+ :param text: String to be drawn.
+ :param font: Either an :py:class:`~PIL.ImageFont.ImageFont` instance,
+ :py:class:`~PIL.ImageFont.FreeTypeFont` instance,
+ :py:class:`~PIL.ImageFont.TransposedFont` instance or ``None``. If
+ ``None``, the default font from :py:meth:`.ImageFont.load_default`
+ will be used.
+ :param mode: The image mode this will be used with.
+ :param spacing: The number of pixels between lines.
+ :param direction: Direction of the text. It can be ``"rtl"`` (right to left),
+ ``"ltr"`` (left to right) or ``"ttb"`` (top to bottom).
+ Requires libraqm.
+ :param features: A list of OpenType font features to be used during text
+ layout. This is usually used to turn on optional font features
+ that are not enabled by default, for example ``"dlig"`` or
+ ``"ss01"``, but can be also used to turn off default font
+ features, for example ``"-liga"`` to disable ligatures or
+ ``"-kern"`` to disable kerning. To get all supported
+ features, see `OpenType docs`_.
+ Requires libraqm.
+ :param language: Language of the text. Different languages may use
+ different glyph shapes or ligatures. This parameter tells
+ the font which language the text is in, and to apply the
+ correct substitutions as appropriate, if available.
+ It should be a `BCP 47 language code`_.
+ Requires libraqm.
+ """
+ self.text = text
+ self.font = font or ImageFont.load_default()
+
+ self.mode = mode
+ self.spacing = spacing
+ self.direction = direction
+ self.features = features
+ self.language = language
+
+ self.embedded_color = False
+
+ self.stroke_width: float = 0
+ self.stroke_fill: _Ink | None = None
+
+ def embed_color(self) -> None:
+ """
+ Use embedded color glyphs (COLR, CBDT, SBIX).
+ """
+ if self.mode not in ("RGB", "RGBA"):
+ msg = "Embedded color supported only in RGB and RGBA modes"
+ raise ValueError(msg)
+ self.embedded_color = True
+
+ def stroke(self, width: float = 0, fill: _Ink | None = None) -> None:
+ """
+ :param width: The width of the text stroke.
+ :param fill: Color to use for the text stroke when drawing. If not given, will
+ default to the ``fill`` parameter from
+ :py:meth:`.ImageDraw.ImageDraw.text`.
+ """
+ self.stroke_width = width
+ self.stroke_fill = fill
+
+ def _get_fontmode(self) -> str:
+ if self.mode in ("1", "P", "I", "F"):
+ return "1"
+ elif self.embedded_color:
+ return "RGBA"
+ else:
+ return "L"
+
+ def get_length(self) -> float:
+ """
+ Returns length (in pixels with 1/64 precision) of text.
+
+ This is the amount by which following text should be offset.
+ Text bounding box may extend past the length in some fonts,
+ e.g. when using italics or accents.
+
+ The result is returned as a float; it is a whole number if using basic layout.
+
+ Note that the sum of two lengths may not equal the length of a concatenated
+ string due to kerning. If you need to adjust for kerning, include the following
+ character and subtract its length.
+
+ For example, instead of::
+
+ hello = ImageText.Text("Hello", font).get_length()
+ world = ImageText.Text("World", font).get_length()
+ helloworld = ImageText.Text("HelloWorld", font).get_length()
+ assert hello + world == helloworld
+
+ use::
+
+ hello = (
+ ImageText.Text("HelloW", font).get_length() -
+ ImageText.Text("W", font).get_length()
+ ) # adjusted for kerning
+ world = ImageText.Text("World", font).get_length()
+ helloworld = ImageText.Text("HelloWorld", font).get_length()
+ assert hello + world == helloworld
+
+ or disable kerning with (requires libraqm)::
+
+ hello = ImageText.Text("Hello", font, features=["-kern"]).get_length()
+ world = ImageText.Text("World", font, features=["-kern"]).get_length()
+ helloworld = ImageText.Text(
+ "HelloWorld", font, features=["-kern"]
+ ).get_length()
+ assert hello + world == helloworld
+
+ :return: Either width for horizontal text, or height for vertical text.
+ """
+ if isinstance(self.text, str):
+ multiline = "\n" in self.text
+ else:
+ multiline = b"\n" in self.text
+ if multiline:
+ msg = "can't measure length of multiline text"
+ raise ValueError(msg)
+ return self.font.getlength(
+ self.text,
+ self._get_fontmode(),
+ self.direction,
+ self.features,
+ self.language,
+ )
+
+ def _split(
+ self, xy: tuple[float, float], anchor: str | None, align: str
+ ) -> list[tuple[tuple[float, float], str, str | bytes]]:
+ if anchor is None:
+ anchor = "lt" if self.direction == "ttb" else "la"
+ elif len(anchor) != 2:
+ msg = "anchor must be a 2 character string"
+ raise ValueError(msg)
+
+ lines = (
+ self.text.split("\n")
+ if isinstance(self.text, str)
+ else self.text.split(b"\n")
+ )
+ if len(lines) == 1:
+ return [(xy, anchor, self.text)]
+
+ if anchor[1] in "tb" and self.direction != "ttb":
+ msg = "anchor not supported for multiline text"
+ raise ValueError(msg)
+
+ fontmode = self._get_fontmode()
+ line_spacing = (
+ self.font.getbbox(
+ "A",
+ fontmode,
+ None,
+ self.features,
+ self.language,
+ self.stroke_width,
+ )[3]
+ + self.stroke_width
+ + self.spacing
+ )
+
+ top = xy[1]
+ parts = []
+ if self.direction == "ttb":
+ left = xy[0]
+ for line in lines:
+ parts.append(((left, top), anchor, line))
+ left += line_spacing
+ else:
+ widths = []
+ max_width: float = 0
+ for line in lines:
+ line_width = self.font.getlength(
+ line, fontmode, self.direction, self.features, self.language
+ )
+ widths.append(line_width)
+ max_width = max(max_width, line_width)
+
+ if anchor[1] == "m":
+ top -= (len(lines) - 1) * line_spacing / 2.0
+ elif anchor[1] == "d":
+ top -= (len(lines) - 1) * line_spacing
+
+ idx = -1
+ for line in lines:
+ left = xy[0]
+ idx += 1
+ width_difference = max_width - widths[idx]
+
+ # align by align parameter
+ if align in ("left", "justify"):
+ pass
+ elif align == "center":
+ left += width_difference / 2.0
+ elif align == "right":
+ left += width_difference
+ else:
+ msg = 'align must be "left", "center", "right" or "justify"'
+ raise ValueError(msg)
+
+ if (
+ align == "justify"
+ and width_difference != 0
+ and idx != len(lines) - 1
+ ):
+ words = (
+ line.split(" ") if isinstance(line, str) else line.split(b" ")
+ )
+ if len(words) > 1:
+ # align left by anchor
+ if anchor[0] == "m":
+ left -= max_width / 2.0
+ elif anchor[0] == "r":
+ left -= max_width
+
+ word_widths = [
+ self.font.getlength(
+ word,
+ fontmode,
+ self.direction,
+ self.features,
+ self.language,
+ )
+ for word in words
+ ]
+ word_anchor = "l" + anchor[1]
+ width_difference = max_width - sum(word_widths)
+ i = 0
+ for word in words:
+ parts.append(((left, top), word_anchor, word))
+ left += word_widths[i] + width_difference / (len(words) - 1)
+ i += 1
+ top += line_spacing
+ continue
+
+ # align left by anchor
+ if anchor[0] == "m":
+ left -= width_difference / 2.0
+ elif anchor[0] == "r":
+ left -= width_difference
+ parts.append(((left, top), anchor, line))
+ top += line_spacing
+
+ return parts
+
+ def get_bbox(
+ self,
+ xy: tuple[float, float] = (0, 0),
+ anchor: str | None = None,
+ align: str = "left",
+ ) -> tuple[float, float, float, float]:
+ """
+ Returns bounding box (in pixels) of text.
+
+ Use :py:meth:`get_length` to get the offset of following text with 1/64 pixel
+ precision. The bounding box includes extra margins for some fonts, e.g. italics
+ or accents.
+
+ :param xy: The anchor coordinates of the text.
+ :param anchor: The text anchor alignment. Determines the relative location of
+ the anchor to the text. The default alignment is top left,
+ specifically ``la`` for horizontal text and ``lt`` for
+ vertical text. See :ref:`text-anchors` for details.
+ :param align: For multiline text, ``"left"``, ``"center"``, ``"right"`` or
+ ``"justify"`` determines the relative alignment of lines. Use the
+ ``anchor`` parameter to specify the alignment to ``xy``.
+
+ :return: ``(left, top, right, bottom)`` bounding box
+ """
+ bbox: tuple[float, float, float, float] | None = None
+ fontmode = self._get_fontmode()
+ for xy, anchor, line in self._split(xy, anchor, align):
+ bbox_line = self.font.getbbox(
+ line,
+ fontmode,
+ self.direction,
+ self.features,
+ self.language,
+ self.stroke_width,
+ anchor,
+ )
+ bbox_line = (
+ bbox_line[0] + xy[0],
+ bbox_line[1] + xy[1],
+ bbox_line[2] + xy[0],
+ bbox_line[3] + xy[1],
+ )
+ if bbox is None:
+ bbox = bbox_line
+ else:
+ bbox = (
+ min(bbox[0], bbox_line[0]),
+ min(bbox[1], bbox_line[1]),
+ max(bbox[2], bbox_line[2]),
+ max(bbox[3], bbox_line[3]),
+ )
+
+ assert bbox is not None
+ return bbox
diff --git a/venv/Lib/site-packages/PIL/ImageTk.py b/venv/Lib/site-packages/PIL/ImageTk.py
new file mode 100644
index 0000000..3a4cb81
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageTk.py
@@ -0,0 +1,266 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# a Tk display interface
+#
+# History:
+# 96-04-08 fl Created
+# 96-09-06 fl Added getimage method
+# 96-11-01 fl Rewritten, removed image attribute and crop method
+# 97-05-09 fl Use PyImagingPaste method instead of image type
+# 97-05-12 fl Minor tweaks to match the IFUNC95 interface
+# 97-05-17 fl Support the "pilbitmap" booster patch
+# 97-06-05 fl Added file= and data= argument to image constructors
+# 98-03-09 fl Added width and height methods to Image classes
+# 98-07-02 fl Use default mode for "P" images without palette attribute
+# 98-07-02 fl Explicitly destroy Tkinter image objects
+# 99-07-24 fl Support multiple Tk interpreters (from Greg Couch)
+# 99-07-26 fl Automatically hook into Tkinter (if possible)
+# 99-08-15 fl Hook uses _imagingtk instead of _imaging
+#
+# Copyright (c) 1997-1999 by Secret Labs AB
+# Copyright (c) 1996-1997 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import tkinter
+from io import BytesIO
+from typing import Any
+
+from . import Image, ImageFile
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from ._typing import CapsuleType
+
+# --------------------------------------------------------------------
+# Check for Tkinter interface hooks
+
+
+def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None:
+ source = None
+ if "file" in kw:
+ source = kw.pop("file")
+ elif "data" in kw:
+ source = BytesIO(kw.pop("data"))
+ if not source:
+ return None
+ return Image.open(source)
+
+
+def _pyimagingtkcall(
+ command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: CapsuleType
+) -> None:
+ tk = photo.tk
+ try:
+ tk.call(command, photo, repr(ptr))
+ except tkinter.TclError:
+ # activate Tkinter hook
+ # may raise an error if it cannot attach to Tkinter
+ from . import _imagingtk
+
+ _imagingtk.tkinit(tk.interpaddr())
+ tk.call(command, photo, repr(ptr))
+
+
+# --------------------------------------------------------------------
+# PhotoImage
+
+
+class PhotoImage:
+ """
+ A Tkinter-compatible photo image. This can be used
+ everywhere Tkinter expects an image object. If the image is an RGBA
+ image, pixels having alpha 0 are treated as transparent.
+
+ The constructor takes either a PIL image, or a mode and a size.
+ Alternatively, you can use the ``file`` or ``data`` options to initialize
+ the photo image object.
+
+ :param image: Either a PIL image, or a mode string. If a mode string is
+ used, a size must also be given.
+ :param size: If the first argument is a mode string, this defines the size
+ of the image.
+ :keyword file: A filename to load the image from (using
+ ``Image.open(file)``).
+ :keyword data: An 8-bit string containing image data (as loaded from an
+ image file).
+ """
+
+ def __init__(
+ self,
+ image: Image.Image | str | None = None,
+ size: tuple[int, int] | None = None,
+ **kw: Any,
+ ) -> None:
+ # Tk compatibility: file or data
+ if image is None:
+ image = _get_image_from_kw(kw)
+
+ if image is None:
+ msg = "Image is required"
+ raise ValueError(msg)
+ elif isinstance(image, str):
+ mode = image
+ image = None
+
+ if size is None:
+ msg = "If first argument is mode, size is required"
+ raise ValueError(msg)
+ else:
+ # got an image instead of a mode
+ mode = image.mode
+ if mode == "P":
+ # palette mapped data
+ image.apply_transparency()
+ image.load()
+ mode = image.palette.mode if image.palette else "RGB"
+ size = image.size
+ kw["width"], kw["height"] = size
+
+ if mode not in ["1", "L", "RGB", "RGBA"]:
+ mode = Image.getmodebase(mode)
+
+ self.__mode = mode
+ self.__size = size
+ self.__photo = tkinter.PhotoImage(**kw)
+ self.tk = self.__photo.tk
+ if image:
+ self.paste(image)
+
+ def __del__(self) -> None:
+ try:
+ name = self.__photo.name
+ except AttributeError:
+ return
+ self.__photo.name = None
+ try:
+ self.__photo.tk.call("image", "delete", name)
+ except Exception:
+ pass # ignore internal errors
+
+ def __str__(self) -> str:
+ """
+ Get the Tkinter photo image identifier. This method is automatically
+ called by Tkinter whenever a PhotoImage object is passed to a Tkinter
+ method.
+
+ :return: A Tkinter photo image identifier (a string).
+ """
+ return str(self.__photo)
+
+ def width(self) -> int:
+ """
+ Get the width of the image.
+
+ :return: The width, in pixels.
+ """
+ return self.__size[0]
+
+ def height(self) -> int:
+ """
+ Get the height of the image.
+
+ :return: The height, in pixels.
+ """
+ return self.__size[1]
+
+ def paste(self, im: Image.Image) -> None:
+ """
+ Paste a PIL image into the photo image. Note that this can
+ be very slow if the photo image is displayed.
+
+ :param im: A PIL image. The size must match the target region. If the
+ mode does not match, the image is converted to the mode of
+ the bitmap image.
+ """
+ # convert to blittable
+ ptr = im.getim()
+ image = im.im
+ if not image.isblock() or im.mode != self.__mode:
+ block = Image.core.new_block(self.__mode, im.size)
+ image.convert2(block, image) # convert directly between buffers
+ ptr = block.ptr
+
+ _pyimagingtkcall("PyImagingPhoto", self.__photo, ptr)
+
+
+# --------------------------------------------------------------------
+# BitmapImage
+
+
+class BitmapImage:
+ """
+ A Tkinter-compatible bitmap image. This can be used everywhere Tkinter
+ expects an image object.
+
+ The given image must have mode "1". Pixels having value 0 are treated as
+ transparent. Options, if any, are passed on to Tkinter. The most commonly
+ used option is ``foreground``, which is used to specify the color for the
+ non-transparent parts. See the Tkinter documentation for information on
+ how to specify colours.
+
+ :param image: A PIL image.
+ """
+
+ def __init__(self, image: Image.Image | None = None, **kw: Any) -> None:
+ # Tk compatibility: file or data
+ if image is None:
+ image = _get_image_from_kw(kw)
+
+ if image is None:
+ msg = "Image is required"
+ raise ValueError(msg)
+ self.__mode = image.mode
+ self.__size = image.size
+
+ self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw)
+
+ def __del__(self) -> None:
+ try:
+ name = self.__photo.name
+ except AttributeError:
+ return
+ self.__photo.name = None
+ try:
+ self.__photo.tk.call("image", "delete", name)
+ except Exception:
+ pass # ignore internal errors
+
+ def width(self) -> int:
+ """
+ Get the width of the image.
+
+ :return: The width, in pixels.
+ """
+ return self.__size[0]
+
+ def height(self) -> int:
+ """
+ Get the height of the image.
+
+ :return: The height, in pixels.
+ """
+ return self.__size[1]
+
+ def __str__(self) -> str:
+ """
+ Get the Tkinter bitmap image identifier. This method is automatically
+ called by Tkinter whenever a BitmapImage object is passed to a Tkinter
+ method.
+
+ :return: A Tkinter bitmap image identifier (a string).
+ """
+ return str(self.__photo)
+
+
+def getimage(photo: PhotoImage) -> Image.Image:
+ """Copies the contents of a PhotoImage to a PIL image memory."""
+ im = Image.new("RGBA", (photo.width(), photo.height()))
+
+ _pyimagingtkcall("PyImagingPhotoGet", photo, im.getim())
+
+ return im
diff --git a/venv/Lib/site-packages/PIL/ImageTransform.py b/venv/Lib/site-packages/PIL/ImageTransform.py
new file mode 100644
index 0000000..fb144ff
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageTransform.py
@@ -0,0 +1,136 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# transform wrappers
+#
+# History:
+# 2002-04-08 fl Created
+#
+# Copyright (c) 2002 by Secret Labs AB
+# Copyright (c) 2002 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any
+
+from . import Image
+
+
+class Transform(Image.ImageTransformHandler):
+ """Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`."""
+
+ method: Image.Transform
+
+ def __init__(self, data: Sequence[Any]) -> None:
+ self.data = data
+
+ def getdata(self) -> tuple[Image.Transform, Sequence[int]]:
+ return self.method, self.data
+
+ def transform(
+ self,
+ size: tuple[int, int],
+ image: Image.Image,
+ **options: Any,
+ ) -> Image.Image:
+ """Perform the transform. Called from :py:meth:`.Image.transform`."""
+ # can be overridden
+ method, data = self.getdata()
+ return image.transform(size, method, data, **options)
+
+
+class AffineTransform(Transform):
+ """
+ Define an affine image transform.
+
+ This function takes a 6-tuple (a, b, c, d, e, f) which contain the first
+ two rows from the inverse of an affine transform matrix. For each pixel
+ (x, y) in the output image, the new value is taken from a position (a x +
+ b y + c, d x + e y + f) in the input image, rounded to nearest pixel.
+
+ This function can be used to scale, translate, rotate, and shear the
+ original image.
+
+ See :py:meth:`.Image.transform`
+
+ :param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows
+ from the inverse of an affine transform matrix.
+ """
+
+ method = Image.Transform.AFFINE
+
+
+class PerspectiveTransform(Transform):
+ """
+ Define a perspective image transform.
+
+ This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel
+ (x, y) in the output image, the new value is taken from a position
+ ((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in
+ the input image, rounded to nearest pixel.
+
+ This function can be used to scale, translate, rotate, and shear the
+ original image.
+
+ See :py:meth:`.Image.transform`
+
+ :param matrix: An 8-tuple (a, b, c, d, e, f, g, h).
+ """
+
+ method = Image.Transform.PERSPECTIVE
+
+
+class ExtentTransform(Transform):
+ """
+ Define a transform to extract a subregion from an image.
+
+ Maps a rectangle (defined by two corners) from the image to a rectangle of
+ the given size. The resulting image will contain data sampled from between
+ the corners, such that (x0, y0) in the input image will end up at (0,0) in
+ the output image, and (x1, y1) at size.
+
+ This method can be used to crop, stretch, shrink, or mirror an arbitrary
+ rectangle in the current image. It is slightly slower than crop, but about
+ as fast as a corresponding resize operation.
+
+ See :py:meth:`.Image.transform`
+
+ :param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the
+ input image's coordinate system. See :ref:`coordinate-system`.
+ """
+
+ method = Image.Transform.EXTENT
+
+
+class QuadTransform(Transform):
+ """
+ Define a quad image transform.
+
+ Maps a quadrilateral (a region defined by four corners) from the image to a
+ rectangle of the given size.
+
+ See :py:meth:`.Image.transform`
+
+ :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the
+ upper left, lower left, lower right, and upper right corner of the
+ source quadrilateral.
+ """
+
+ method = Image.Transform.QUAD
+
+
+class MeshTransform(Transform):
+ """
+ Define a mesh image transform. A mesh transform consists of one or more
+ individual quad transforms.
+
+ See :py:meth:`.Image.transform`
+
+ :param data: A list of (bbox, quad) tuples.
+ """
+
+ method = Image.Transform.MESH
diff --git a/venv/Lib/site-packages/PIL/ImageWin.py b/venv/Lib/site-packages/PIL/ImageWin.py
new file mode 100644
index 0000000..98c28f2
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImageWin.py
@@ -0,0 +1,247 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# a Windows DIB display interface
+#
+# History:
+# 1996-05-20 fl Created
+# 1996-09-20 fl Fixed subregion exposure
+# 1997-09-21 fl Added draw primitive (for tzPrint)
+# 2003-05-21 fl Added experimental Window/ImageWindow classes
+# 2003-09-05 fl Added fromstring/tostring methods
+#
+# Copyright (c) Secret Labs AB 1997-2003.
+# Copyright (c) Fredrik Lundh 1996-2003.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from . import Image
+
+
+class HDC:
+ """
+ Wraps an HDC integer. The resulting object can be passed to the
+ :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
+ methods.
+ """
+
+ def __init__(self, dc: int) -> None:
+ self.dc = dc
+
+ def __int__(self) -> int:
+ return self.dc
+
+
+class HWND:
+ """
+ Wraps an HWND integer. The resulting object can be passed to the
+ :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
+ methods, instead of a DC.
+ """
+
+ def __init__(self, wnd: int) -> None:
+ self.wnd = wnd
+
+ def __int__(self) -> int:
+ return self.wnd
+
+
+class Dib:
+ """
+ A Windows bitmap with the given mode and size. The mode can be one of "1",
+ "L", "P", or "RGB".
+
+ If the display requires a palette, this constructor creates a suitable
+ palette and associates it with the image. For an "L" image, 128 graylevels
+ are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together
+ with 20 graylevels.
+
+ To make sure that palettes work properly under Windows, you must call the
+ ``palette`` method upon certain events from Windows.
+
+ :param image: Either a PIL image, or a mode string. If a mode string is
+ used, a size must also be given. The mode can be one of "1",
+ "L", "P", or "RGB".
+ :param size: If the first argument is a mode string, this
+ defines the size of the image.
+ """
+
+ def __init__(
+ self, image: Image.Image | str, size: tuple[int, int] | None = None
+ ) -> None:
+ if isinstance(image, str):
+ mode = image
+ image = ""
+ if size is None:
+ msg = "If first argument is mode, size is required"
+ raise ValueError(msg)
+ else:
+ mode = image.mode
+ size = image.size
+ if mode not in ["1", "L", "P", "RGB"]:
+ mode = Image.getmodebase(mode)
+ self.image = Image.core.display(mode, size)
+ self.mode = mode
+ self.size = size
+ if image:
+ assert not isinstance(image, str)
+ self.paste(image)
+
+ def expose(self, handle: int | HDC | HWND) -> None:
+ """
+ Copy the bitmap contents to a device context.
+
+ :param handle: Device context (HDC), cast to a Python integer, or an
+ HDC or HWND instance. In PythonWin, you can use
+ ``CDC.GetHandleAttrib()`` to get a suitable handle.
+ """
+ handle_int = int(handle)
+ if isinstance(handle, HWND):
+ dc = self.image.getdc(handle_int)
+ try:
+ self.image.expose(dc)
+ finally:
+ self.image.releasedc(handle_int, dc)
+ else:
+ self.image.expose(handle_int)
+
+ def draw(
+ self,
+ handle: int | HDC | HWND,
+ dst: tuple[int, int, int, int],
+ src: tuple[int, int, int, int] | None = None,
+ ) -> None:
+ """
+ Same as expose, but allows you to specify where to draw the image, and
+ what part of it to draw.
+
+ The destination and source areas are given as 4-tuple rectangles. If
+ the source is omitted, the entire image is copied. If the source and
+ the destination have different sizes, the image is resized as
+ necessary.
+ """
+ if src is None:
+ src = (0, 0) + self.size
+ handle_int = int(handle)
+ if isinstance(handle, HWND):
+ dc = self.image.getdc(handle_int)
+ try:
+ self.image.draw(dc, dst, src)
+ finally:
+ self.image.releasedc(handle_int, dc)
+ else:
+ self.image.draw(handle_int, dst, src)
+
+ def query_palette(self, handle: int | HDC | HWND) -> int:
+ """
+ Installs the palette associated with the image in the given device
+ context.
+
+ This method should be called upon **QUERYNEWPALETTE** and
+ **PALETTECHANGED** events from Windows. If this method returns a
+ non-zero value, one or more display palette entries were changed, and
+ the image should be redrawn.
+
+ :param handle: Device context (HDC), cast to a Python integer, or an
+ HDC or HWND instance.
+ :return: The number of entries that were changed (if one or more entries,
+ this indicates that the image should be redrawn).
+ """
+ handle_int = int(handle)
+ if isinstance(handle, HWND):
+ handle = self.image.getdc(handle_int)
+ try:
+ result = self.image.query_palette(handle)
+ finally:
+ self.image.releasedc(handle, handle)
+ else:
+ result = self.image.query_palette(handle_int)
+ return result
+
+ def paste(
+ self, im: Image.Image, box: tuple[int, int, int, int] | None = None
+ ) -> None:
+ """
+ Paste a PIL image into the bitmap image.
+
+ :param im: A PIL image. The size must match the target region.
+ If the mode does not match, the image is converted to the
+ mode of the bitmap image.
+ :param box: A 4-tuple defining the left, upper, right, and
+ lower pixel coordinate. See :ref:`coordinate-system`. If
+ None is given instead of a tuple, all of the image is
+ assumed.
+ """
+ im.load()
+ if self.mode != im.mode:
+ im = im.convert(self.mode)
+ if box:
+ self.image.paste(im.im, box)
+ else:
+ self.image.paste(im.im)
+
+ def frombytes(self, buffer: bytes) -> None:
+ """
+ Load display memory contents from byte data.
+
+ :param buffer: A buffer containing display data (usually
+ data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)
+ """
+ self.image.frombytes(buffer)
+
+ def tobytes(self) -> bytes:
+ """
+ Copy display memory contents to bytes object.
+
+ :return: A bytes object containing display data.
+ """
+ return self.image.tobytes()
+
+
+class Window:
+ """Create a Window with the given title size."""
+
+ def __init__(
+ self, title: str = "PIL", width: int | None = None, height: int | None = None
+ ) -> None:
+ self.hwnd = Image.core.createwindow(
+ title, self.__dispatcher, width or 0, height or 0
+ )
+
+ def __dispatcher(self, action: str, *args: int) -> None:
+ getattr(self, f"ui_handle_{action}")(*args)
+
+ def ui_handle_clear(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
+ pass
+
+ def ui_handle_damage(self, x0: int, y0: int, x1: int, y1: int) -> None:
+ pass
+
+ def ui_handle_destroy(self) -> None:
+ pass
+
+ def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
+ pass
+
+ def ui_handle_resize(self, width: int, height: int) -> None:
+ pass
+
+ def mainloop(self) -> None:
+ Image.core.eventloop()
+
+
+class ImageWindow(Window):
+ """Create an image window which displays the given image."""
+
+ def __init__(self, image: Image.Image | Dib, title: str = "PIL") -> None:
+ if not isinstance(image, Dib):
+ image = Dib(image)
+ self.image = image
+ width, height = image.size
+ super().__init__(title, width=width, height=height)
+
+ def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:
+ self.image.draw(dc, (x0, y0, x1, y1))
diff --git a/venv/Lib/site-packages/PIL/ImtImagePlugin.py b/venv/Lib/site-packages/PIL/ImtImagePlugin.py
new file mode 100644
index 0000000..c4eccee
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/ImtImagePlugin.py
@@ -0,0 +1,103 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# IM Tools support for PIL
+#
+# history:
+# 1996-05-27 fl Created (read 8-bit images only)
+# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)
+#
+# Copyright (c) Secret Labs AB 1997-2001.
+# Copyright (c) Fredrik Lundh 1996-2001.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import re
+
+from . import Image, ImageFile
+
+#
+# --------------------------------------------------------------------
+
+field = re.compile(rb"([a-z]*) ([^ \r\n]*)")
+
+
+##
+# Image plugin for IM Tools images.
+
+
+class ImtImageFile(ImageFile.ImageFile):
+ format = "IMT"
+ format_description = "IM Tools"
+
+ def _open(self) -> None:
+ # Quick rejection: if there's not a LF among the first
+ # 100 bytes, this is (probably) not a text header.
+
+ assert self.fp is not None
+
+ buffer = self.fp.read(100)
+ if b"\n" not in buffer:
+ msg = "not an IM file"
+ raise SyntaxError(msg)
+
+ xsize = ysize = 0
+
+ while True:
+ if buffer:
+ s = buffer[:1]
+ buffer = buffer[1:]
+ else:
+ s = self.fp.read(1)
+ if not s:
+ break
+
+ if s == b"\x0c":
+ # image data begins
+ self.tile = [
+ ImageFile._Tile(
+ "raw",
+ (0, 0) + self.size,
+ self.fp.tell() - len(buffer),
+ self.mode,
+ )
+ ]
+
+ break
+
+ else:
+ # read key/value pair
+ if b"\n" not in buffer:
+ buffer += self.fp.read(100)
+ lines = buffer.split(b"\n")
+ s += lines.pop(0)
+ buffer = b"\n".join(lines)
+ if len(s) == 1 or len(s) > 100:
+ break
+ if s[0] == ord(b"*"):
+ continue # comment
+
+ m = field.match(s)
+ if not m:
+ break
+ k, v = m.group(1, 2)
+ if k == b"width":
+ xsize = int(v)
+ self._size = xsize, ysize
+ elif k == b"height":
+ ysize = int(v)
+ self._size = xsize, ysize
+ elif k == b"pixel" and v == b"n8":
+ self._mode = "L"
+
+
+#
+# --------------------------------------------------------------------
+
+Image.register_open(ImtImageFile.format, ImtImageFile)
+
+#
+# no extension registered (".im" is simply too common)
diff --git a/venv/Lib/site-packages/PIL/IptcImagePlugin.py b/venv/Lib/site-packages/PIL/IptcImagePlugin.py
new file mode 100644
index 0000000..6fc824e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/IptcImagePlugin.py
@@ -0,0 +1,233 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# IPTC/NAA file handling
+#
+# history:
+# 1995-10-01 fl Created
+# 1998-03-09 fl Cleaned up and added to PIL
+# 2002-06-18 fl Added getiptcinfo helper
+#
+# Copyright (c) Secret Labs AB 1997-2002.
+# Copyright (c) Fredrik Lundh 1995.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from io import BytesIO
+from typing import cast
+
+from . import Image, ImageFile
+from ._binary import i16be as i16
+from ._binary import i32be as i32
+
+COMPRESSION = {1: "raw", 5: "jpeg"}
+
+
+#
+# Helpers
+
+
+def _i(c: bytes) -> int:
+ return i32((b"\0\0\0\0" + c)[-4:])
+
+
+##
+# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields
+# from TIFF and JPEG files, use the getiptcinfo function.
+
+
+class IptcImageFile(ImageFile.ImageFile):
+ format = "IPTC"
+ format_description = "IPTC/NAA"
+
+ def getint(self, key: tuple[int, int]) -> int:
+ return _i(self.info[key])
+
+ def field(self) -> tuple[tuple[int, int] | None, int]:
+ #
+ # get a IPTC field header
+ assert self.fp is not None
+ s = self.fp.read(5)
+ if not s.strip(b"\x00"):
+ return None, 0
+
+ tag = s[1], s[2]
+
+ # syntax
+ if s[0] != 0x1C or tag[0] not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 240]:
+ msg = "invalid IPTC/NAA file"
+ raise SyntaxError(msg)
+
+ # field size
+ size = s[3]
+ if size > 132:
+ msg = "illegal field length in IPTC/NAA file"
+ raise OSError(msg)
+ elif size == 128:
+ size = 0
+ elif size > 128:
+ size = _i(self.fp.read(size - 128))
+ else:
+ size = i16(s, 3)
+
+ return tag, size
+
+ def _open(self) -> None:
+ # load descriptive fields
+ assert self.fp is not None
+ while True:
+ offset = self.fp.tell()
+ tag, size = self.field()
+ if not tag or tag == (8, 10):
+ break
+ if size:
+ tagdata = self.fp.read(size)
+ else:
+ tagdata = None
+ if tag in self.info:
+ if isinstance(self.info[tag], list):
+ self.info[tag].append(tagdata)
+ else:
+ self.info[tag] = [self.info[tag], tagdata]
+ else:
+ self.info[tag] = tagdata
+
+ # mode
+ layers = self.info[(3, 60)][0]
+ component = self.info[(3, 60)][1]
+ if layers == 1 and not component:
+ self._mode = "L"
+ band = None
+ else:
+ if layers == 3 and component:
+ self._mode = "RGB"
+ elif layers == 4 and component:
+ self._mode = "CMYK"
+ if (3, 65) in self.info:
+ band = self.info[(3, 65)][0] - 1
+ else:
+ band = 0
+
+ # size
+ self._size = self.getint((3, 20)), self.getint((3, 30))
+
+ # compression
+ try:
+ compression = COMPRESSION[self.getint((3, 120))]
+ except KeyError as e:
+ msg = "Unknown IPTC image compression"
+ raise OSError(msg) from e
+
+ # tile
+ if tag == (8, 10):
+ self.tile = [
+ ImageFile._Tile("iptc", (0, 0) + self.size, offset, (compression, band))
+ ]
+
+ def load(self) -> Image.core.PixelAccess | None:
+ if self.tile:
+ args = self.tile[0].args
+ assert isinstance(args, tuple)
+ compression, band = args
+
+ assert self.fp is not None
+ self.fp.seek(self.tile[0].offset)
+
+ # Copy image data to temporary file
+ o = BytesIO()
+ if compression == "raw":
+ # To simplify access to the extracted file,
+ # prepend a PPM header
+ o.write(b"P5\n%d %d\n255\n" % self.size)
+ while True:
+ type, size = self.field()
+ if type != (8, 10):
+ break
+ while size > 0:
+ s = self.fp.read(min(size, 8192))
+ if not s:
+ break
+ o.write(s)
+ size -= len(s)
+
+ with Image.open(o) as _im:
+ if band is not None:
+ bands = [Image.new("L", _im.size)] * Image.getmodebands(self.mode)
+ bands[band] = _im
+ im = Image.merge(self.mode, bands)
+ else:
+ im = _im
+ im.load()
+ self.im = im.im
+ self.tile = []
+ return ImageFile.ImageFile.load(self)
+
+
+Image.register_open(IptcImageFile.format, IptcImageFile)
+
+Image.register_extension(IptcImageFile.format, ".iim")
+
+
+def getiptcinfo(
+ im: ImageFile.ImageFile,
+) -> dict[tuple[int, int], bytes | list[bytes]] | None:
+ """
+ Get IPTC information from TIFF, JPEG, or IPTC file.
+
+ :param im: An image containing IPTC data.
+ :returns: A dictionary containing IPTC information, or None if
+ no IPTC information block was found.
+ """
+ from . import JpegImagePlugin, TiffImagePlugin
+
+ data = None
+
+ info: dict[tuple[int, int], bytes | list[bytes]] = {}
+ if isinstance(im, IptcImageFile):
+ # return info dictionary right away
+ for k, v in im.info.items():
+ if isinstance(k, tuple):
+ info[k] = v
+ return info
+
+ elif isinstance(im, JpegImagePlugin.JpegImageFile):
+ # extract the IPTC/NAA resource
+ photoshop = im.info.get("photoshop")
+ if photoshop:
+ data = photoshop.get(0x0404)
+
+ elif isinstance(im, TiffImagePlugin.TiffImageFile):
+ # get raw data from the IPTC/NAA tag (PhotoShop tags the data
+ # as 4-byte integers, so we cannot use the get method...)
+ try:
+ data = im.tag_v2._tagdata[TiffImagePlugin.IPTC_NAA_CHUNK]
+ except KeyError:
+ pass
+
+ if data is None:
+ return None # no properties
+
+ # create an IptcImagePlugin object without initializing it
+ class FakeImage:
+ pass
+
+ fake_im = FakeImage()
+ fake_im.__class__ = IptcImageFile # type: ignore[assignment]
+ iptc_im = cast(IptcImageFile, fake_im)
+
+ # parse the IPTC information chunk
+ iptc_im.info = {}
+ iptc_im.fp = BytesIO(data)
+
+ try:
+ iptc_im._open()
+ except (IndexError, KeyError):
+ pass # expected failure
+
+ for k, v in iptc_im.info.items():
+ if isinstance(k, tuple):
+ info[k] = v
+ return info
diff --git a/venv/Lib/site-packages/PIL/Jpeg2KImagePlugin.py b/venv/Lib/site-packages/PIL/Jpeg2KImagePlugin.py
new file mode 100644
index 0000000..d6ec38d
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/Jpeg2KImagePlugin.py
@@ -0,0 +1,448 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# JPEG2000 file handling
+#
+# History:
+# 2014-03-12 ajh Created
+# 2021-06-30 rogermb Extract dpi information from the 'resc' header box
+#
+# Copyright (c) 2014 Coriolis Systems Limited
+# Copyright (c) 2014 Alastair Houghton
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import io
+import os
+import struct
+from typing import cast
+
+from . import Image, ImageFile, ImagePalette, _binary
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from typing import IO
+
+
+class BoxReader:
+ """
+ A small helper class to read fields stored in JPEG2000 header boxes
+ and to easily step into and read sub-boxes.
+ """
+
+ def __init__(self, fp: IO[bytes], length: int = -1) -> None:
+ self.fp = fp
+ self.has_length = length >= 0
+ self.length = length
+ self.remaining_in_box = -1
+
+ def _can_read(self, num_bytes: int) -> bool:
+ if self.has_length and self.fp.tell() + num_bytes > self.length:
+ # Outside box: ensure we don't read past the known file length
+ return False
+ if self.remaining_in_box >= 0:
+ # Inside box contents: ensure read does not go past box boundaries
+ return num_bytes <= self.remaining_in_box
+ else:
+ return True # No length known, just read
+
+ def _read_bytes(self, num_bytes: int) -> bytes:
+ if not self._can_read(num_bytes):
+ msg = "Not enough data in header"
+ raise SyntaxError(msg)
+
+ data = self.fp.read(num_bytes)
+ if len(data) < num_bytes:
+ msg = f"Expected to read {num_bytes} bytes but only got {len(data)}."
+ raise OSError(msg)
+
+ if self.remaining_in_box > 0:
+ self.remaining_in_box -= num_bytes
+ return data
+
+ def read_fields(self, field_format: str) -> tuple[int | bytes, ...]:
+ size = struct.calcsize(field_format)
+ data = self._read_bytes(size)
+ return struct.unpack(field_format, data)
+
+ def read_boxes(self) -> BoxReader:
+ size = self.remaining_in_box
+ data = self._read_bytes(size)
+ return BoxReader(io.BytesIO(data), size)
+
+ def has_next_box(self) -> bool:
+ if self.has_length:
+ return self.fp.tell() + self.remaining_in_box < self.length
+ else:
+ return True
+
+ def next_box_type(self) -> bytes:
+ # Skip the rest of the box if it has not been read
+ if self.remaining_in_box > 0:
+ self.fp.seek(self.remaining_in_box, os.SEEK_CUR)
+ self.remaining_in_box = -1
+
+ # Read the length and type of the next box
+ lbox, tbox = cast(tuple[int, bytes], self.read_fields(">I4s"))
+ if lbox == 1:
+ lbox = cast(int, self.read_fields(">Q")[0])
+ hlen = 16
+ else:
+ hlen = 8
+
+ if lbox < hlen or not self._can_read(lbox - hlen):
+ msg = "Invalid header length"
+ raise SyntaxError(msg)
+
+ self.remaining_in_box = lbox - hlen
+ return tbox
+
+
+def _parse_codestream(fp: IO[bytes]) -> tuple[tuple[int, int], str]:
+ """Parse the JPEG 2000 codestream to extract the size and component
+ count from the SIZ marker segment, returning a PIL (size, mode) tuple."""
+
+ hdr = fp.read(2)
+ lsiz = _binary.i16be(hdr)
+ siz = hdr + fp.read(lsiz - 2)
+ lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from(
+ ">HHIIIIIIIIH", siz
+ )
+
+ size = (xsiz - xosiz, ysiz - yosiz)
+ if csiz == 1:
+ ssiz = struct.unpack_from(">B", siz, 38)
+ if (ssiz[0] & 0x7F) + 1 > 8:
+ mode = "I;16"
+ else:
+ mode = "L"
+ elif csiz == 2:
+ mode = "LA"
+ elif csiz == 3:
+ mode = "RGB"
+ elif csiz == 4:
+ mode = "RGBA"
+ else:
+ msg = "unable to determine J2K image mode"
+ raise SyntaxError(msg)
+
+ return size, mode
+
+
+def _res_to_dpi(num: int, denom: int, exp: int) -> float | None:
+ """Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution,
+ calculated as (num / denom) * 10^exp and stored in dots per meter,
+ to floating-point dots per inch."""
+ if denom == 0:
+ return None
+ return (254 * num * (10**exp)) / (10000 * denom)
+
+
+def _parse_jp2_header(
+ fp: IO[bytes],
+) -> tuple[
+ tuple[int, int],
+ str,
+ str | None,
+ tuple[float, float] | None,
+ ImagePalette.ImagePalette | None,
+]:
+ """Parse the JP2 header box to extract size, component count,
+ color space information, and optionally DPI information,
+ returning a (size, mode, mimetype, dpi) tuple."""
+
+ # Find the JP2 header box
+ reader = BoxReader(fp)
+ header = None
+ mimetype = None
+ while reader.has_next_box():
+ tbox = reader.next_box_type()
+
+ if tbox == b"jp2h":
+ header = reader.read_boxes()
+ break
+ elif tbox == b"ftyp":
+ if reader.read_fields(">4s")[0] == b"jpx ":
+ mimetype = "image/jpx"
+ assert header is not None
+
+ size = None
+ mode = None
+ bpc = None
+ nc = None
+ dpi = None # 2-tuple of DPI info, or None
+ palette = None
+
+ while header.has_next_box():
+ tbox = header.next_box_type()
+
+ if tbox == b"ihdr":
+ height, width, nc, bpc = header.read_fields(">IIHB")
+ assert isinstance(height, int)
+ assert isinstance(width, int)
+ assert isinstance(bpc, int)
+ size = (width, height)
+ if nc == 1 and (bpc & 0x7F) > 8:
+ mode = "I;16"
+ elif nc == 1:
+ mode = "L"
+ elif nc == 2:
+ mode = "LA"
+ elif nc == 3:
+ mode = "RGB"
+ elif nc == 4:
+ mode = "RGBA"
+ elif tbox == b"colr" and nc == 4:
+ meth, _, _, enumcs = header.read_fields(">BBBI")
+ if meth == 1 and enumcs == 12:
+ mode = "CMYK"
+ elif tbox == b"pclr" and mode in ("L", "LA"):
+ ne, npc = header.read_fields(">HB")
+ assert isinstance(ne, int)
+ assert isinstance(npc, int)
+ max_bitdepth = 0
+ for bitdepth in header.read_fields(">" + ("B" * npc)):
+ assert isinstance(bitdepth, int)
+ if bitdepth > max_bitdepth:
+ max_bitdepth = bitdepth
+ if max_bitdepth <= 8:
+ palette = ImagePalette.ImagePalette("RGBA" if npc == 4 else "RGB")
+ for i in range(ne):
+ color: list[int] = []
+ for value in header.read_fields(">" + ("B" * npc)):
+ assert isinstance(value, int)
+ color.append(value)
+ palette.getcolor(tuple(color))
+ mode = "P" if mode == "L" else "PA"
+ elif tbox == b"res ":
+ res = header.read_boxes()
+ while res.has_next_box():
+ tres = res.next_box_type()
+ if tres == b"resc":
+ vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB")
+ assert isinstance(vrcn, int)
+ assert isinstance(vrcd, int)
+ assert isinstance(hrcn, int)
+ assert isinstance(hrcd, int)
+ assert isinstance(vrce, int)
+ assert isinstance(hrce, int)
+ hres = _res_to_dpi(hrcn, hrcd, hrce)
+ vres = _res_to_dpi(vrcn, vrcd, vrce)
+ if hres is not None and vres is not None:
+ dpi = (hres, vres)
+ break
+
+ if size is None or mode is None:
+ msg = "Malformed JP2 header"
+ raise SyntaxError(msg)
+
+ return size, mode, mimetype, dpi, palette
+
+
+##
+# Image plugin for JPEG2000 images.
+
+
+class Jpeg2KImageFile(ImageFile.ImageFile):
+ format = "JPEG2000"
+ format_description = "JPEG 2000 (ISO 15444)"
+
+ def _open(self) -> None:
+ assert self.fp is not None
+ sig = self.fp.read(4)
+ if sig == b"\xff\x4f\xff\x51":
+ self.codec = "j2k"
+ self._size, self._mode = _parse_codestream(self.fp)
+ self._parse_comment()
+ else:
+ sig = sig + self.fp.read(8)
+
+ if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a":
+ self.codec = "jp2"
+ header = _parse_jp2_header(self.fp)
+ self._size, self._mode, self.custom_mimetype, dpi, self.palette = header
+ if dpi is not None:
+ self.info["dpi"] = dpi
+ if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"):
+ hdr = self.fp.read(2)
+ length = _binary.i16be(hdr)
+ self.fp.seek(length - 2, os.SEEK_CUR)
+ self._parse_comment()
+ else:
+ msg = "not a JPEG 2000 file"
+ raise SyntaxError(msg)
+
+ self._reduce = 0
+ self.layers = 0
+
+ fd = -1
+ length = -1
+
+ try:
+ fd = self.fp.fileno()
+ length = os.fstat(fd).st_size
+ except Exception:
+ fd = -1
+ try:
+ pos = self.fp.tell()
+ self.fp.seek(0, io.SEEK_END)
+ length = self.fp.tell()
+ self.fp.seek(pos)
+ except Exception:
+ length = -1
+
+ self.tile = [
+ ImageFile._Tile(
+ "jpeg2k",
+ (0, 0) + self.size,
+ 0,
+ (self.codec, self._reduce, self.layers, fd, length),
+ )
+ ]
+
+ def _parse_comment(self) -> None:
+ assert self.fp is not None
+ while True:
+ marker = self.fp.read(2)
+ if not marker:
+ break
+ typ = marker[1]
+ if typ in (0x90, 0xD9):
+ # Start of tile or end of codestream
+ break
+ hdr = self.fp.read(2)
+ length = _binary.i16be(hdr)
+ if typ == 0x64:
+ # Comment
+ self.info["comment"] = self.fp.read(length - 2)[2:]
+ break
+ else:
+ self.fp.seek(length - 2, os.SEEK_CUR)
+
+ @property # type: ignore[override]
+ def reduce(
+ self,
+ ) -> (
+ Callable[[int | tuple[int, int], tuple[int, int, int, int] | None], Image.Image]
+ | int
+ ):
+ # https://github.com/python-pillow/Pillow/issues/4343 found that the
+ # new Image 'reduce' method was shadowed by this plugin's 'reduce'
+ # property. This attempts to allow for both scenarios
+ return self._reduce or super().reduce
+
+ @reduce.setter
+ def reduce(self, value: int) -> None:
+ self._reduce = value
+
+ def load(self) -> Image.core.PixelAccess | None:
+ if self.tile and self._reduce:
+ power = 1 << self._reduce
+ adjust = power >> 1
+ self._size = (
+ int((self.size[0] + adjust) / power),
+ int((self.size[1] + adjust) / power),
+ )
+
+ # Update the reduce and layers settings
+ t = self.tile[0]
+ assert isinstance(t[3], tuple)
+ t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4])
+ self.tile = [ImageFile._Tile(t[0], (0, 0) + self.size, t[2], t3)]
+
+ return ImageFile.ImageFile.load(self)
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(
+ (b"\xff\x4f\xff\x51", b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a")
+ )
+
+
+# ------------------------------------------------------------
+# Save support
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ # Get the keyword arguments
+ info = im.encoderinfo
+
+ if isinstance(filename, str):
+ filename = filename.encode()
+ if filename.endswith(b".j2k") or info.get("no_jp2", False):
+ kind = "j2k"
+ else:
+ kind = "jp2"
+
+ offset = info.get("offset", None)
+ tile_offset = info.get("tile_offset", None)
+ tile_size = info.get("tile_size", None)
+ quality_mode = info.get("quality_mode", "rates")
+ quality_layers = info.get("quality_layers", None)
+ if quality_layers is not None and not (
+ isinstance(quality_layers, (list, tuple))
+ and all(
+ isinstance(quality_layer, (int, float)) for quality_layer in quality_layers
+ )
+ ):
+ msg = "quality_layers must be a sequence of numbers"
+ raise ValueError(msg)
+
+ num_resolutions = info.get("num_resolutions", 0)
+ cblk_size = info.get("codeblock_size", None)
+ precinct_size = info.get("precinct_size", None)
+ irreversible = info.get("irreversible", False)
+ progression = info.get("progression", "LRCP")
+ cinema_mode = info.get("cinema_mode", "no")
+ mct = info.get("mct", 0)
+ signed = info.get("signed", False)
+ comment = info.get("comment")
+ if isinstance(comment, str):
+ comment = comment.encode()
+ plt = info.get("plt", False)
+
+ fd = -1
+ if hasattr(fp, "fileno"):
+ try:
+ fd = fp.fileno()
+ except Exception:
+ fd = -1
+
+ im.encoderconfig = (
+ offset,
+ tile_offset,
+ tile_size,
+ quality_mode,
+ quality_layers,
+ num_resolutions,
+ cblk_size,
+ precinct_size,
+ irreversible,
+ progression,
+ cinema_mode,
+ mct,
+ signed,
+ fd,
+ comment,
+ plt,
+ )
+
+ ImageFile._save(im, fp, [ImageFile._Tile("jpeg2k", (0, 0) + im.size, 0, kind)])
+
+
+# ------------------------------------------------------------
+# Registry stuff
+
+
+Image.register_open(Jpeg2KImageFile.format, Jpeg2KImageFile, _accept)
+Image.register_save(Jpeg2KImageFile.format, _save)
+
+Image.register_extensions(
+ Jpeg2KImageFile.format, [".jp2", ".j2k", ".jpc", ".jpf", ".jpx", ".j2c"]
+)
+
+Image.register_mime(Jpeg2KImageFile.format, "image/jp2")
diff --git a/venv/Lib/site-packages/PIL/JpegImagePlugin.py b/venv/Lib/site-packages/PIL/JpegImagePlugin.py
new file mode 100644
index 0000000..894c154
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/JpegImagePlugin.py
@@ -0,0 +1,895 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# JPEG (JFIF) file handling
+#
+# See "Digital Compression and Coding of Continuous-Tone Still Images,
+# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1)
+#
+# History:
+# 1995-09-09 fl Created
+# 1995-09-13 fl Added full parser
+# 1996-03-25 fl Added hack to use the IJG command line utilities
+# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug
+# 1996-05-28 fl Added draft support, JFIF version (0.1)
+# 1996-12-30 fl Added encoder options, added progression property (0.2)
+# 1997-08-27 fl Save mode 1 images as BW (0.3)
+# 1998-07-12 fl Added YCbCr to draft and save methods (0.4)
+# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1)
+# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2)
+# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3)
+# 2003-04-25 fl Added experimental EXIF decoder (0.5)
+# 2003-06-06 fl Added experimental EXIF GPSinfo decoder
+# 2003-09-13 fl Extract COM markers
+# 2009-09-06 fl Added icc_profile support (from Florian Hoech)
+# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6)
+# 2009-03-08 fl Added subsampling support (from Justin Huff).
+#
+# Copyright (c) 1997-2003 by Secret Labs AB.
+# Copyright (c) 1995-1996 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import array
+import io
+import math
+import os
+import struct
+import subprocess
+import sys
+import tempfile
+import warnings
+
+from . import Image, ImageFile
+from ._binary import i16be as i16
+from ._binary import i32be as i32
+from ._binary import o8
+from ._binary import o16be as o16
+from .JpegPresets import presets
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from typing import IO, Any
+
+ from .MpoImagePlugin import MpoImageFile
+
+#
+# Parser
+
+
+def Skip(self: JpegImageFile, marker: int) -> None:
+ assert self.fp is not None
+ n = i16(self.fp.read(2)) - 2
+ ImageFile._safe_read(self.fp, n)
+
+
+def APP(self: JpegImageFile, marker: int) -> None:
+ #
+ # Application marker. Store these in the APP dictionary.
+ # Also look for well-known application markers.
+
+ assert self.fp is not None
+ n = i16(self.fp.read(2)) - 2
+ s = ImageFile._safe_read(self.fp, n)
+
+ app = f"APP{marker & 15}"
+
+ self.app[app] = s # compatibility
+ self.applist.append((app, s))
+
+ if marker == 0xFFE0 and s.startswith(b"JFIF"):
+ # extract JFIF information
+ self.info["jfif"] = version = i16(s, 5) # version
+ self.info["jfif_version"] = divmod(version, 256)
+ # extract JFIF properties
+ try:
+ jfif_unit = s[7]
+ jfif_density = i16(s, 8), i16(s, 10)
+ except Exception:
+ pass
+ else:
+ if jfif_unit == 1:
+ self.info["dpi"] = jfif_density
+ elif jfif_unit == 2: # cm
+ # 1 dpcm = 2.54 dpi
+ self.info["dpi"] = tuple(d * 2.54 for d in jfif_density)
+ self.info["jfif_unit"] = jfif_unit
+ self.info["jfif_density"] = jfif_density
+ elif marker == 0xFFE1 and s.startswith(b"Exif\0\0"):
+ # extract EXIF information
+ if "exif" in self.info:
+ self.info["exif"] += s[6:]
+ else:
+ self.info["exif"] = s
+ self._exif_offset = self.fp.tell() - n + 6
+ elif marker == 0xFFE1 and s.startswith(b"http://ns.adobe.com/xap/1.0/\x00"):
+ self.info["xmp"] = s.split(b"\x00", 1)[1]
+ elif marker == 0xFFE2 and s.startswith(b"FPXR\0"):
+ # extract FlashPix information (incomplete)
+ self.info["flashpix"] = s # FIXME: value will change
+ elif marker == 0xFFE2 and s.startswith(b"ICC_PROFILE\0"):
+ # Since an ICC profile can be larger than the maximum size of
+ # a JPEG marker (64K), we need provisions to split it into
+ # multiple markers. The format defined by the ICC specifies
+ # one or more APP2 markers containing the following data:
+ # Identifying string ASCII "ICC_PROFILE\0" (12 bytes)
+ # Marker sequence number 1, 2, etc (1 byte)
+ # Number of markers Total of APP2's used (1 byte)
+ # Profile data (remainder of APP2 data)
+ # Decoders should use the marker sequence numbers to
+ # reassemble the profile, rather than assuming that the APP2
+ # markers appear in the correct sequence.
+ self.icclist.append(s)
+ elif marker == 0xFFED and s.startswith(b"Photoshop 3.0\x00"):
+ # parse the image resource block
+ offset = 14
+ photoshop = self.info.setdefault("photoshop", {})
+ while s[offset : offset + 4] == b"8BIM":
+ try:
+ offset += 4
+ # resource code
+ code = i16(s, offset)
+ offset += 2
+ # resource name (usually empty)
+ name_len = s[offset]
+ # name = s[offset+1:offset+1+name_len]
+ offset += 1 + name_len
+ offset += offset & 1 # align
+ # resource data block
+ size = i32(s, offset)
+ offset += 4
+ data = s[offset : offset + size]
+ if code == 0x03ED: # ResolutionInfo
+ photoshop[code] = {
+ "XResolution": i32(data, 0) / 65536,
+ "DisplayedUnitsX": i16(data, 4),
+ "YResolution": i32(data, 8) / 65536,
+ "DisplayedUnitsY": i16(data, 12),
+ }
+ else:
+ photoshop[code] = data
+ offset += size
+ offset += offset & 1 # align
+ except struct.error:
+ break # insufficient data
+
+ elif marker == 0xFFEE and s.startswith(b"Adobe"):
+ self.info["adobe"] = i16(s, 5)
+ # extract Adobe custom properties
+ try:
+ adobe_transform = s[11]
+ except IndexError:
+ pass
+ else:
+ self.info["adobe_transform"] = adobe_transform
+ elif marker == 0xFFE2 and s.startswith(b"MPF\0"):
+ # extract MPO information
+ self.info["mp"] = s[4:]
+ # offset is current location minus buffer size
+ # plus constant header size
+ self.info["mpoffset"] = self.fp.tell() - n + 4
+
+
+def COM(self: JpegImageFile, marker: int) -> None:
+ #
+ # Comment marker. Store these in the APP dictionary.
+ assert self.fp is not None
+ n = i16(self.fp.read(2)) - 2
+ s = ImageFile._safe_read(self.fp, n)
+
+ self.info["comment"] = s
+ self.app["COM"] = s # compatibility
+ self.applist.append(("COM", s))
+
+
+def SOF(self: JpegImageFile, marker: int) -> None:
+ #
+ # Start of frame marker. Defines the size and mode of the
+ # image. JPEG is colour blind, so we use some simple
+ # heuristics to map the number of layers to an appropriate
+ # mode. Note that this could be made a bit brighter, by
+ # looking for JFIF and Adobe APP markers.
+
+ assert self.fp is not None
+ n = i16(self.fp.read(2)) - 2
+ s = ImageFile._safe_read(self.fp, n)
+ self._size = i16(s, 3), i16(s, 1)
+ if self._im is not None and self.size != self.im.size:
+ self._im = None
+
+ self.bits = s[0]
+ if self.bits != 8:
+ msg = f"cannot handle {self.bits}-bit layers"
+ raise SyntaxError(msg)
+
+ self.layers = s[5]
+ if self.layers == 1:
+ self._mode = "L"
+ elif self.layers == 3:
+ self._mode = "RGB"
+ elif self.layers == 4:
+ self._mode = "CMYK"
+ else:
+ msg = f"cannot handle {self.layers}-layer images"
+ raise SyntaxError(msg)
+
+ if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
+ self.info["progressive"] = self.info["progression"] = 1
+
+ if self.icclist:
+ # fixup icc profile
+ self.icclist.sort() # sort by sequence number
+ if self.icclist[0][13] == len(self.icclist):
+ profile = [p[14:] for p in self.icclist]
+ icc_profile = b"".join(profile)
+ else:
+ icc_profile = None # wrong number of fragments
+ self.info["icc_profile"] = icc_profile
+ self.icclist = []
+
+ for i in range(6, len(s), 3):
+ t = s[i : i + 3]
+ # 4-tuples: id, vsamp, hsamp, qtable
+ self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))
+
+
+def DQT(self: JpegImageFile, marker: int) -> None:
+ #
+ # Define quantization table. Note that there might be more
+ # than one table in each marker.
+
+ # FIXME: The quantization tables can be used to estimate the
+ # compression quality.
+
+ assert self.fp is not None
+ n = i16(self.fp.read(2)) - 2
+ s = ImageFile._safe_read(self.fp, n)
+ while len(s):
+ v = s[0]
+ precision = 1 if (v // 16 == 0) else 2 # in bytes
+ qt_length = 1 + precision * 64
+ if len(s) < qt_length:
+ msg = "bad quantization table marker"
+ raise SyntaxError(msg)
+ data = array.array("B" if precision == 1 else "H", s[1:qt_length])
+ if sys.byteorder == "little" and precision > 1:
+ data.byteswap() # the values are always big-endian
+ self.quantization[v & 15] = [data[i] for i in zigzag_index]
+ s = s[qt_length:]
+
+
+#
+# JPEG marker table
+
+MARKER = {
+ 0xFFC0: ("SOF0", "Baseline DCT", SOF),
+ 0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
+ 0xFFC2: ("SOF2", "Progressive DCT", SOF),
+ 0xFFC3: ("SOF3", "Spatial lossless", SOF),
+ 0xFFC4: ("DHT", "Define Huffman table", Skip),
+ 0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
+ 0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
+ 0xFFC7: ("SOF7", "Differential spatial", SOF),
+ 0xFFC8: ("JPG", "Extension", None),
+ 0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
+ 0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
+ 0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
+ 0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
+ 0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
+ 0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
+ 0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
+ 0xFFD0: ("RST0", "Restart 0", None),
+ 0xFFD1: ("RST1", "Restart 1", None),
+ 0xFFD2: ("RST2", "Restart 2", None),
+ 0xFFD3: ("RST3", "Restart 3", None),
+ 0xFFD4: ("RST4", "Restart 4", None),
+ 0xFFD5: ("RST5", "Restart 5", None),
+ 0xFFD6: ("RST6", "Restart 6", None),
+ 0xFFD7: ("RST7", "Restart 7", None),
+ 0xFFD8: ("SOI", "Start of image", None),
+ 0xFFD9: ("EOI", "End of image", None),
+ 0xFFDA: ("SOS", "Start of scan", Skip),
+ 0xFFDB: ("DQT", "Define quantization table", DQT),
+ 0xFFDC: ("DNL", "Define number of lines", Skip),
+ 0xFFDD: ("DRI", "Define restart interval", Skip),
+ 0xFFDE: ("DHP", "Define hierarchical progression", SOF),
+ 0xFFDF: ("EXP", "Expand reference component", Skip),
+ 0xFFE0: ("APP0", "Application segment 0", APP),
+ 0xFFE1: ("APP1", "Application segment 1", APP),
+ 0xFFE2: ("APP2", "Application segment 2", APP),
+ 0xFFE3: ("APP3", "Application segment 3", APP),
+ 0xFFE4: ("APP4", "Application segment 4", APP),
+ 0xFFE5: ("APP5", "Application segment 5", APP),
+ 0xFFE6: ("APP6", "Application segment 6", APP),
+ 0xFFE7: ("APP7", "Application segment 7", APP),
+ 0xFFE8: ("APP8", "Application segment 8", APP),
+ 0xFFE9: ("APP9", "Application segment 9", APP),
+ 0xFFEA: ("APP10", "Application segment 10", APP),
+ 0xFFEB: ("APP11", "Application segment 11", APP),
+ 0xFFEC: ("APP12", "Application segment 12", APP),
+ 0xFFED: ("APP13", "Application segment 13", APP),
+ 0xFFEE: ("APP14", "Application segment 14", APP),
+ 0xFFEF: ("APP15", "Application segment 15", APP),
+ 0xFFF0: ("JPG0", "Extension 0", None),
+ 0xFFF1: ("JPG1", "Extension 1", None),
+ 0xFFF2: ("JPG2", "Extension 2", None),
+ 0xFFF3: ("JPG3", "Extension 3", None),
+ 0xFFF4: ("JPG4", "Extension 4", None),
+ 0xFFF5: ("JPG5", "Extension 5", None),
+ 0xFFF6: ("JPG6", "Extension 6", None),
+ 0xFFF7: ("JPG7", "Extension 7", None),
+ 0xFFF8: ("JPG8", "Extension 8", None),
+ 0xFFF9: ("JPG9", "Extension 9", None),
+ 0xFFFA: ("JPG10", "Extension 10", None),
+ 0xFFFB: ("JPG11", "Extension 11", None),
+ 0xFFFC: ("JPG12", "Extension 12", None),
+ 0xFFFD: ("JPG13", "Extension 13", None),
+ 0xFFFE: ("COM", "Comment", COM),
+}
+
+
+def _accept(prefix: bytes) -> bool:
+ # Magic number was taken from https://en.wikipedia.org/wiki/JPEG
+ return prefix.startswith(b"\xff\xd8\xff")
+
+
+##
+# Image plugin for JPEG and JFIF images.
+
+
+class JpegImageFile(ImageFile.ImageFile):
+ format = "JPEG"
+ format_description = "JPEG (ISO 10918)"
+
+ def _open(self) -> None:
+ assert self.fp is not None
+ s = self.fp.read(3)
+
+ if not _accept(s):
+ msg = "not a JPEG file"
+ raise SyntaxError(msg)
+ s = b"\xff"
+
+ # Create attributes
+ self.bits = self.layers = 0
+ self._exif_offset = 0
+
+ # JPEG specifics (internal)
+ self.layer: list[tuple[int, int, int, int]] = []
+ self._huffman_dc: dict[Any, Any] = {}
+ self._huffman_ac: dict[Any, Any] = {}
+ self.quantization: dict[int, list[int]] = {}
+ self.app: dict[str, bytes] = {} # compatibility
+ self.applist: list[tuple[str, bytes]] = []
+ self.icclist: list[bytes] = []
+
+ while True:
+ i = s[0]
+ if i == 0xFF:
+ s = s + self.fp.read(1)
+ i = i16(s)
+ else:
+ # Skip non-0xFF junk
+ s = self.fp.read(1)
+ continue
+
+ if i in MARKER:
+ name, description, handler = MARKER[i]
+ if handler is not None:
+ handler(self, i)
+ if i == 0xFFDA: # start of scan
+ rawmode = self.mode
+ if self.mode == "CMYK":
+ rawmode = "CMYK;I" # assume adobe conventions
+ self.tile = [
+ ImageFile._Tile("jpeg", (0, 0) + self.size, 0, (rawmode, ""))
+ ]
+ # self.__offset = self.fp.tell()
+ break
+ s = self.fp.read(1)
+ elif i in {0, 0xFFFF}:
+ # padded marker or junk; move on
+ s = b"\xff"
+ elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)
+ s = self.fp.read(1)
+ else:
+ msg = "no marker found"
+ raise SyntaxError(msg)
+
+ self._read_dpi_from_exif()
+
+ def __getstate__(self) -> list[Any]:
+ return super().__getstate__() + [self.layers, self.layer]
+
+ def __setstate__(self, state: list[Any]) -> None:
+ self.layers, self.layer = state[6:]
+ super().__setstate__(state)
+
+ def load_read(self, read_bytes: int) -> bytes:
+ """
+ internal: read more image data
+ For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker
+ so libjpeg can finish decoding
+ """
+ assert self.fp is not None
+ s = self.fp.read(read_bytes)
+
+ if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"):
+ # Premature EOF.
+ # Pretend file is finished adding EOI marker
+ self._ended = True
+ return b"\xff\xd9"
+
+ return s
+
+ def draft(
+ self, mode: str | None, size: tuple[int, int] | None
+ ) -> tuple[str, tuple[int, int, float, float]] | None:
+ if len(self.tile) != 1:
+ return None
+
+ # Protect from second call
+ if self.decoderconfig:
+ return None
+
+ d, e, o, a = self.tile[0]
+ scale = 1
+ original_size = self.size
+
+ assert isinstance(a, tuple)
+ if a[0] == "RGB" and mode in ["L", "YCbCr"]:
+ self._mode = mode
+ a = mode, ""
+
+ if size:
+ scale = min(self.size[0] // size[0], self.size[1] // size[1])
+ for s in [8, 4, 2, 1]:
+ if scale >= s:
+ break
+ assert e is not None
+ e = (
+ e[0],
+ e[1],
+ (e[2] - e[0] + s - 1) // s + e[0],
+ (e[3] - e[1] + s - 1) // s + e[1],
+ )
+ self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)
+ scale = s
+
+ self.tile = [ImageFile._Tile(d, e, o, a)]
+ self.decoderconfig = (scale, 0)
+
+ box = (0, 0, original_size[0] / scale, original_size[1] / scale)
+ return self.mode, box
+
+ def load_djpeg(self) -> None:
+ # ALTERNATIVE: handle JPEGs via the IJG command line utilities
+
+ f, path = tempfile.mkstemp()
+ os.close(f)
+ if os.path.exists(self.filename):
+ subprocess.check_call(["djpeg", "-outfile", path, self.filename])
+ else:
+ try:
+ os.unlink(path)
+ except OSError:
+ pass
+
+ msg = "Invalid Filename"
+ raise ValueError(msg)
+
+ try:
+ with Image.open(path) as _im:
+ _im.load()
+ self.im = _im.im
+ finally:
+ try:
+ os.unlink(path)
+ except OSError:
+ pass
+
+ self._mode = self.im.mode
+ self._size = self.im.size
+
+ self.tile = []
+
+ def _getexif(self) -> dict[int, Any] | None:
+ return _getexif(self)
+
+ def _read_dpi_from_exif(self) -> None:
+ # If DPI isn't in JPEG header, fetch from EXIF
+ if "dpi" in self.info or "exif" not in self.info:
+ return
+ try:
+ exif = self.getexif()
+ resolution_unit = exif[0x0128]
+ x_resolution = exif[0x011A]
+ try:
+ dpi = float(x_resolution[0]) / x_resolution[1]
+ except TypeError:
+ dpi = x_resolution
+ if math.isnan(dpi):
+ msg = "DPI is not a number"
+ raise ValueError(msg)
+ if resolution_unit == 3: # cm
+ # 1 dpcm = 2.54 dpi
+ dpi *= 2.54
+ self.info["dpi"] = dpi, dpi
+ except (
+ struct.error, # truncated EXIF
+ KeyError, # dpi not included
+ SyntaxError, # invalid/unreadable EXIF
+ TypeError, # dpi is an invalid float
+ ValueError, # dpi is an invalid float
+ ZeroDivisionError, # invalid dpi rational value
+ ):
+ self.info["dpi"] = 72, 72
+
+ def _getmp(self) -> dict[int, Any] | None:
+ return _getmp(self)
+
+
+def _getexif(self: JpegImageFile) -> dict[int, Any] | None:
+ if "exif" not in self.info:
+ return None
+ return self.getexif()._get_merged_dict()
+
+
+def _getmp(self: JpegImageFile) -> dict[int, Any] | None:
+ # Extract MP information. This method was inspired by the "highly
+ # experimental" _getexif version that's been in use for years now,
+ # itself based on the ImageFileDirectory class in the TIFF plugin.
+
+ # The MP record essentially consists of a TIFF file embedded in a JPEG
+ # application marker.
+ try:
+ data = self.info["mp"]
+ except KeyError:
+ return None
+ file_contents = io.BytesIO(data)
+ head = file_contents.read(8)
+ endianness = ">" if head.startswith(b"\x4d\x4d\x00\x2a") else "<"
+ # process dictionary
+ from . import TiffImagePlugin
+
+ try:
+ info = TiffImagePlugin.ImageFileDirectory_v2(head)
+ file_contents.seek(info.next)
+ info.load(file_contents)
+ mp = dict(info)
+ except Exception as e:
+ msg = "malformed MP Index (unreadable directory)"
+ raise SyntaxError(msg) from e
+ # it's an error not to have a number of images
+ try:
+ quant = mp[0xB001]
+ except KeyError as e:
+ msg = "malformed MP Index (no number of images)"
+ raise SyntaxError(msg) from e
+ # get MP entries
+ mpentries = []
+ try:
+ rawmpentries = mp[0xB002]
+ for entrynum in range(quant):
+ unpackedentry = struct.unpack_from(
+ f"{endianness}LLLHH", rawmpentries, entrynum * 16
+ )
+ labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2")
+ mpentry = dict(zip(labels, unpackedentry))
+ mpentryattr = {
+ "DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)),
+ "DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)),
+ "RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)),
+ "Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27,
+ "ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24,
+ "MPType": mpentry["Attribute"] & 0x00FFFFFF,
+ }
+ if mpentryattr["ImageDataFormat"] == 0:
+ mpentryattr["ImageDataFormat"] = "JPEG"
+ else:
+ msg = "unsupported picture format in MPO"
+ raise SyntaxError(msg)
+ mptypemap = {
+ 0x000000: "Undefined",
+ 0x010001: "Large Thumbnail (VGA Equivalent)",
+ 0x010002: "Large Thumbnail (Full HD Equivalent)",
+ 0x020001: "Multi-Frame Image (Panorama)",
+ 0x020002: "Multi-Frame Image: (Disparity)",
+ 0x020003: "Multi-Frame Image: (Multi-Angle)",
+ 0x030000: "Baseline MP Primary Image",
+ }
+ mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown")
+ mpentry["Attribute"] = mpentryattr
+ mpentries.append(mpentry)
+ mp[0xB002] = mpentries
+ except KeyError as e:
+ msg = "malformed MP Index (bad MP Entry)"
+ raise SyntaxError(msg) from e
+ # Next we should try and parse the individual image unique ID list;
+ # we don't because I've never seen this actually used in a real MPO
+ # file and so can't test it.
+ return mp
+
+
+# --------------------------------------------------------------------
+# stuff to save JPEG files
+
+RAWMODE = {
+ "1": "L",
+ "L": "L",
+ "RGB": "RGB",
+ "RGBX": "RGB",
+ "CMYK": "CMYK;I", # assume adobe conventions
+ "YCbCr": "YCbCr",
+}
+
+# fmt: off
+zigzag_index = (
+ 0, 1, 5, 6, 14, 15, 27, 28,
+ 2, 4, 7, 13, 16, 26, 29, 42,
+ 3, 8, 12, 17, 25, 30, 41, 43,
+ 9, 11, 18, 24, 31, 40, 44, 53,
+ 10, 19, 23, 32, 39, 45, 52, 54,
+ 20, 22, 33, 38, 46, 51, 55, 60,
+ 21, 34, 37, 47, 50, 56, 59, 61,
+ 35, 36, 48, 49, 57, 58, 62, 63,
+)
+
+samplings = {
+ (1, 1, 1, 1, 1, 1): 0,
+ (2, 1, 1, 1, 1, 1): 1,
+ (2, 2, 1, 1, 1, 1): 2,
+}
+# fmt: on
+
+
+def get_sampling(im: Image.Image) -> int:
+ # There's no subsampling when images have only 1 layer
+ # (grayscale images) or when they are CMYK (4 layers),
+ # so set subsampling to the default value.
+ #
+ # NOTE: currently Pillow can't encode JPEG to YCCK format.
+ # If YCCK support is added in the future, subsampling code will have
+ # to be updated (here and in JpegEncode.c) to deal with 4 layers.
+ if not isinstance(im, JpegImageFile) or im.layers in (1, 4):
+ return -1
+ sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]
+ return samplings.get(sampling, -1)
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if im.width == 0 or im.height == 0:
+ msg = "cannot write empty image as JPEG"
+ raise ValueError(msg)
+
+ try:
+ rawmode = RAWMODE[im.mode]
+ except KeyError as e:
+ msg = f"cannot write mode {im.mode} as JPEG"
+ raise OSError(msg) from e
+
+ info = im.encoderinfo
+
+ dpi = [round(x) for x in info.get("dpi", (0, 0))]
+
+ quality = info.get("quality", -1)
+ subsampling = info.get("subsampling", -1)
+ qtables = info.get("qtables")
+
+ if quality == "keep":
+ quality = -1
+ subsampling = "keep"
+ qtables = "keep"
+ elif quality in presets:
+ preset = presets[quality]
+ quality = -1
+ subsampling = preset.get("subsampling", -1)
+ qtables = preset.get("quantization")
+ elif not isinstance(quality, int):
+ msg = "Invalid quality setting"
+ raise ValueError(msg)
+ else:
+ if subsampling in presets:
+ subsampling = presets[subsampling].get("subsampling", -1)
+ if isinstance(qtables, str) and qtables in presets:
+ qtables = presets[qtables].get("quantization")
+
+ if subsampling == "4:4:4":
+ subsampling = 0
+ elif subsampling == "4:2:2":
+ subsampling = 1
+ elif subsampling == "4:2:0":
+ subsampling = 2
+ elif subsampling == "4:1:1":
+ # For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0.
+ # Set 4:2:0 if someone is still using that value.
+ subsampling = 2
+ elif subsampling == "keep":
+ if im.format != "JPEG":
+ msg = "Cannot use 'keep' when original image is not a JPEG"
+ raise ValueError(msg)
+ subsampling = get_sampling(im)
+
+ def validate_qtables(
+ qtables: (
+ str | tuple[list[int], ...] | list[list[int]] | dict[int, list[int]] | None
+ ),
+ ) -> list[list[int]] | None:
+ if qtables is None:
+ return qtables
+ if isinstance(qtables, str):
+ try:
+ lines = [
+ int(num)
+ for line in qtables.splitlines()
+ for num in line.split("#", 1)[0].split()
+ ]
+ except ValueError as e:
+ msg = "Invalid quantization table"
+ raise ValueError(msg) from e
+ else:
+ qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)]
+ if isinstance(qtables, (tuple, list, dict)):
+ if isinstance(qtables, dict):
+ qtables = [
+ qtables[key] for key in range(len(qtables)) if key in qtables
+ ]
+ elif isinstance(qtables, tuple):
+ qtables = list(qtables)
+ if not (0 < len(qtables) < 5):
+ msg = "None or too many quantization tables"
+ raise ValueError(msg)
+ for idx, table in enumerate(qtables):
+ try:
+ if len(table) != 64:
+ msg = "Invalid quantization table"
+ raise TypeError(msg)
+ table_array = array.array("H", table)
+ except TypeError as e:
+ msg = "Invalid quantization table"
+ raise ValueError(msg) from e
+ else:
+ qtables[idx] = list(table_array)
+ return qtables
+
+ if qtables == "keep":
+ if im.format != "JPEG":
+ msg = "Cannot use 'keep' when original image is not a JPEG"
+ raise ValueError(msg)
+ qtables = getattr(im, "quantization", None)
+ qtables = validate_qtables(qtables)
+
+ extra = info.get("extra", b"")
+
+ MAX_BYTES_IN_MARKER = 65533
+ if xmp := info.get("xmp"):
+ overhead_len = 29 # b"http://ns.adobe.com/xap/1.0/\x00"
+ max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len
+ if len(xmp) > max_data_bytes_in_marker:
+ msg = "XMP data is too long"
+ raise ValueError(msg)
+ size = o16(2 + overhead_len + len(xmp))
+ extra += b"\xff\xe1" + size + b"http://ns.adobe.com/xap/1.0/\x00" + xmp
+
+ if icc_profile := info.get("icc_profile"):
+ overhead_len = 14 # b"ICC_PROFILE\0" + o8(i) + o8(len(markers))
+ max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len
+ markers = []
+ while icc_profile:
+ markers.append(icc_profile[:max_data_bytes_in_marker])
+ icc_profile = icc_profile[max_data_bytes_in_marker:]
+ i = 1
+ for marker in markers:
+ size = o16(2 + overhead_len + len(marker))
+ extra += (
+ b"\xff\xe2"
+ + size
+ + b"ICC_PROFILE\0"
+ + o8(i)
+ + o8(len(markers))
+ + marker
+ )
+ i += 1
+
+ comment = info.get("comment", im.info.get("comment"))
+
+ # "progressive" is the official name, but older documentation
+ # says "progression"
+ # FIXME: issue a warning if the wrong form is used (post-1.1.7)
+ progressive = info.get("progressive", False) or info.get("progression", False)
+
+ optimize = info.get("optimize", False)
+
+ exif = info.get("exif", b"")
+ if isinstance(exif, Image.Exif):
+ exif = exif.tobytes()
+ if len(exif) > MAX_BYTES_IN_MARKER:
+ msg = "EXIF data is too long"
+ raise ValueError(msg)
+
+ # get keyword arguments
+ im.encoderconfig = (
+ quality,
+ progressive,
+ info.get("smooth", 0),
+ optimize,
+ info.get("keep_rgb", False),
+ info.get("streamtype", 0),
+ dpi,
+ subsampling,
+ info.get("restart_marker_blocks", 0),
+ info.get("restart_marker_rows", 0),
+ qtables,
+ comment,
+ extra,
+ exif,
+ )
+
+ # if we optimize, libjpeg needs a buffer big enough to hold the whole image
+ # in a shot. Guessing on the size, at im.size bytes. (raw pixel size is
+ # channels*size, this is a value that's been used in a django patch.
+ # https://github.com/matthewwithanm/django-imagekit/issues/50
+ if optimize or progressive:
+ # CMYK can be bigger
+ if im.mode == "CMYK":
+ bufsize = 4 * im.size[0] * im.size[1]
+ # keep sets quality to -1, but the actual value may be high.
+ elif quality >= 95 or quality == -1:
+ bufsize = 2 * im.size[0] * im.size[1]
+ else:
+ bufsize = im.size[0] * im.size[1]
+ if exif:
+ bufsize += len(exif) + 5
+ if extra:
+ bufsize += len(extra) + 1
+ else:
+ # The EXIF info needs to be written as one block, + APP1, + one spare byte.
+ # Ensure that our buffer is big enough. Same with the icc_profile block.
+ bufsize = max(len(exif) + 5, len(extra) + 1)
+
+ ImageFile._save(
+ im, fp, [ImageFile._Tile("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize
+ )
+
+
+##
+# Factory for making JPEG and MPO instances
+def jpeg_factory(
+ fp: IO[bytes], filename: str | bytes | None = None
+) -> JpegImageFile | MpoImageFile:
+ im = JpegImageFile(fp, filename)
+ try:
+ mpheader = im._getmp()
+ if mpheader is not None and mpheader[45057] > 1:
+ for segment, content in im.applist:
+ if segment == "APP1" and b' hdrgm:Version="' in content:
+ # Ultra HDR images are not yet supported
+ return im
+ # It's actually an MPO
+ from .MpoImagePlugin import MpoImageFile
+
+ # Don't reload everything, just convert it.
+ im = MpoImageFile.adopt(im, mpheader)
+ except (TypeError, IndexError):
+ # It is really a JPEG
+ pass
+ except SyntaxError:
+ warnings.warn(
+ "Image appears to be a malformed MPO file, it will be "
+ "interpreted as a base JPEG file"
+ )
+ return im
+
+
+# ---------------------------------------------------------------------
+# Registry stuff
+
+Image.register_open(JpegImageFile.format, jpeg_factory, _accept)
+Image.register_save(JpegImageFile.format, _save)
+
+Image.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"])
+
+Image.register_mime(JpegImageFile.format, "image/jpeg")
diff --git a/venv/Lib/site-packages/PIL/JpegPresets.py b/venv/Lib/site-packages/PIL/JpegPresets.py
new file mode 100644
index 0000000..d0e64a3
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/JpegPresets.py
@@ -0,0 +1,242 @@
+"""
+JPEG quality settings equivalent to the Photoshop settings.
+Can be used when saving JPEG files.
+
+The following presets are available by default:
+``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``,
+``low``, ``medium``, ``high``, ``maximum``.
+More presets can be added to the :py:data:`presets` dict if needed.
+
+To apply the preset, specify::
+
+ quality="preset_name"
+
+To apply only the quantization table::
+
+ qtables="preset_name"
+
+To apply only the subsampling setting::
+
+ subsampling="preset_name"
+
+Example::
+
+ im.save("image_name.jpg", quality="web_high")
+
+Subsampling
+-----------
+
+Subsampling is the practice of encoding images by implementing less resolution
+for chroma information than for luma information.
+(ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)
+
+Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and
+4:2:0.
+
+You can get the subsampling of a JPEG with the
+:func:`.JpegImagePlugin.get_sampling` function.
+
+In JPEG compressed data a JPEG marker is used instead of an EXIF tag.
+(ref.: https://exiv2.org/tags.html)
+
+
+Quantization tables
+-------------------
+
+They are values use by the DCT (Discrete cosine transform) to remove
+*unnecessary* information from the image (the lossy part of the compression).
+(ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices,
+https://en.wikipedia.org/wiki/JPEG#Quantization)
+
+You can get the quantization tables of a JPEG with::
+
+ im.quantization
+
+This will return a dict with a number of lists. You can pass this dict
+directly as the qtables argument when saving a JPEG.
+
+The quantization table format in presets is a list with sublists. These formats
+are interchangeable.
+
+Libjpeg ref.:
+https://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html
+
+"""
+
+from __future__ import annotations
+
+# fmt: off
+presets = {
+ 'web_low': {'subsampling': 2, # "4:2:0"
+ 'quantization': [
+ [20, 16, 25, 39, 50, 46, 62, 68,
+ 16, 18, 23, 38, 38, 53, 65, 68,
+ 25, 23, 31, 38, 53, 65, 68, 68,
+ 39, 38, 38, 53, 65, 68, 68, 68,
+ 50, 38, 53, 65, 68, 68, 68, 68,
+ 46, 53, 65, 68, 68, 68, 68, 68,
+ 62, 65, 68, 68, 68, 68, 68, 68,
+ 68, 68, 68, 68, 68, 68, 68, 68],
+ [21, 25, 32, 38, 54, 68, 68, 68,
+ 25, 28, 24, 38, 54, 68, 68, 68,
+ 32, 24, 32, 43, 66, 68, 68, 68,
+ 38, 38, 43, 53, 68, 68, 68, 68,
+ 54, 54, 66, 68, 68, 68, 68, 68,
+ 68, 68, 68, 68, 68, 68, 68, 68,
+ 68, 68, 68, 68, 68, 68, 68, 68,
+ 68, 68, 68, 68, 68, 68, 68, 68]
+ ]},
+ 'web_medium': {'subsampling': 2, # "4:2:0"
+ 'quantization': [
+ [16, 11, 11, 16, 23, 27, 31, 30,
+ 11, 12, 12, 15, 20, 23, 23, 30,
+ 11, 12, 13, 16, 23, 26, 35, 47,
+ 16, 15, 16, 23, 26, 37, 47, 64,
+ 23, 20, 23, 26, 39, 51, 64, 64,
+ 27, 23, 26, 37, 51, 64, 64, 64,
+ 31, 23, 35, 47, 64, 64, 64, 64,
+ 30, 30, 47, 64, 64, 64, 64, 64],
+ [17, 15, 17, 21, 20, 26, 38, 48,
+ 15, 19, 18, 17, 20, 26, 35, 43,
+ 17, 18, 20, 22, 26, 30, 46, 53,
+ 21, 17, 22, 28, 30, 39, 53, 64,
+ 20, 20, 26, 30, 39, 48, 64, 64,
+ 26, 26, 30, 39, 48, 63, 64, 64,
+ 38, 35, 46, 53, 64, 64, 64, 64,
+ 48, 43, 53, 64, 64, 64, 64, 64]
+ ]},
+ 'web_high': {'subsampling': 0, # "4:4:4"
+ 'quantization': [
+ [6, 4, 4, 6, 9, 11, 12, 16,
+ 4, 5, 5, 6, 8, 10, 12, 12,
+ 4, 5, 5, 6, 10, 12, 14, 19,
+ 6, 6, 6, 11, 12, 15, 19, 28,
+ 9, 8, 10, 12, 16, 20, 27, 31,
+ 11, 10, 12, 15, 20, 27, 31, 31,
+ 12, 12, 14, 19, 27, 31, 31, 31,
+ 16, 12, 19, 28, 31, 31, 31, 31],
+ [7, 7, 13, 24, 26, 31, 31, 31,
+ 7, 12, 16, 21, 31, 31, 31, 31,
+ 13, 16, 17, 31, 31, 31, 31, 31,
+ 24, 21, 31, 31, 31, 31, 31, 31,
+ 26, 31, 31, 31, 31, 31, 31, 31,
+ 31, 31, 31, 31, 31, 31, 31, 31,
+ 31, 31, 31, 31, 31, 31, 31, 31,
+ 31, 31, 31, 31, 31, 31, 31, 31]
+ ]},
+ 'web_very_high': {'subsampling': 0, # "4:4:4"
+ 'quantization': [
+ [2, 2, 2, 2, 3, 4, 5, 6,
+ 2, 2, 2, 2, 3, 4, 5, 6,
+ 2, 2, 2, 2, 4, 5, 7, 9,
+ 2, 2, 2, 4, 5, 7, 9, 12,
+ 3, 3, 4, 5, 8, 10, 12, 12,
+ 4, 4, 5, 7, 10, 12, 12, 12,
+ 5, 5, 7, 9, 12, 12, 12, 12,
+ 6, 6, 9, 12, 12, 12, 12, 12],
+ [3, 3, 5, 9, 13, 15, 15, 15,
+ 3, 4, 6, 11, 14, 12, 12, 12,
+ 5, 6, 9, 14, 12, 12, 12, 12,
+ 9, 11, 14, 12, 12, 12, 12, 12,
+ 13, 14, 12, 12, 12, 12, 12, 12,
+ 15, 12, 12, 12, 12, 12, 12, 12,
+ 15, 12, 12, 12, 12, 12, 12, 12,
+ 15, 12, 12, 12, 12, 12, 12, 12]
+ ]},
+ 'web_maximum': {'subsampling': 0, # "4:4:4"
+ 'quantization': [
+ [1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 2,
+ 1, 1, 1, 1, 1, 1, 2, 2,
+ 1, 1, 1, 1, 1, 2, 2, 3,
+ 1, 1, 1, 1, 2, 2, 3, 3,
+ 1, 1, 1, 2, 2, 3, 3, 3,
+ 1, 1, 2, 2, 3, 3, 3, 3],
+ [1, 1, 1, 2, 2, 3, 3, 3,
+ 1, 1, 1, 2, 3, 3, 3, 3,
+ 1, 1, 1, 3, 3, 3, 3, 3,
+ 2, 2, 3, 3, 3, 3, 3, 3,
+ 2, 3, 3, 3, 3, 3, 3, 3,
+ 3, 3, 3, 3, 3, 3, 3, 3,
+ 3, 3, 3, 3, 3, 3, 3, 3,
+ 3, 3, 3, 3, 3, 3, 3, 3]
+ ]},
+ 'low': {'subsampling': 2, # "4:2:0"
+ 'quantization': [
+ [18, 14, 14, 21, 30, 35, 34, 17,
+ 14, 16, 16, 19, 26, 23, 12, 12,
+ 14, 16, 17, 21, 23, 12, 12, 12,
+ 21, 19, 21, 23, 12, 12, 12, 12,
+ 30, 26, 23, 12, 12, 12, 12, 12,
+ 35, 23, 12, 12, 12, 12, 12, 12,
+ 34, 12, 12, 12, 12, 12, 12, 12,
+ 17, 12, 12, 12, 12, 12, 12, 12],
+ [20, 19, 22, 27, 20, 20, 17, 17,
+ 19, 25, 23, 14, 14, 12, 12, 12,
+ 22, 23, 14, 14, 12, 12, 12, 12,
+ 27, 14, 14, 12, 12, 12, 12, 12,
+ 20, 14, 12, 12, 12, 12, 12, 12,
+ 20, 12, 12, 12, 12, 12, 12, 12,
+ 17, 12, 12, 12, 12, 12, 12, 12,
+ 17, 12, 12, 12, 12, 12, 12, 12]
+ ]},
+ 'medium': {'subsampling': 2, # "4:2:0"
+ 'quantization': [
+ [12, 8, 8, 12, 17, 21, 24, 17,
+ 8, 9, 9, 11, 15, 19, 12, 12,
+ 8, 9, 10, 12, 19, 12, 12, 12,
+ 12, 11, 12, 21, 12, 12, 12, 12,
+ 17, 15, 19, 12, 12, 12, 12, 12,
+ 21, 19, 12, 12, 12, 12, 12, 12,
+ 24, 12, 12, 12, 12, 12, 12, 12,
+ 17, 12, 12, 12, 12, 12, 12, 12],
+ [13, 11, 13, 16, 20, 20, 17, 17,
+ 11, 14, 14, 14, 14, 12, 12, 12,
+ 13, 14, 14, 14, 12, 12, 12, 12,
+ 16, 14, 14, 12, 12, 12, 12, 12,
+ 20, 14, 12, 12, 12, 12, 12, 12,
+ 20, 12, 12, 12, 12, 12, 12, 12,
+ 17, 12, 12, 12, 12, 12, 12, 12,
+ 17, 12, 12, 12, 12, 12, 12, 12]
+ ]},
+ 'high': {'subsampling': 0, # "4:4:4"
+ 'quantization': [
+ [6, 4, 4, 6, 9, 11, 12, 16,
+ 4, 5, 5, 6, 8, 10, 12, 12,
+ 4, 5, 5, 6, 10, 12, 12, 12,
+ 6, 6, 6, 11, 12, 12, 12, 12,
+ 9, 8, 10, 12, 12, 12, 12, 12,
+ 11, 10, 12, 12, 12, 12, 12, 12,
+ 12, 12, 12, 12, 12, 12, 12, 12,
+ 16, 12, 12, 12, 12, 12, 12, 12],
+ [7, 7, 13, 24, 20, 20, 17, 17,
+ 7, 12, 16, 14, 14, 12, 12, 12,
+ 13, 16, 14, 14, 12, 12, 12, 12,
+ 24, 14, 14, 12, 12, 12, 12, 12,
+ 20, 14, 12, 12, 12, 12, 12, 12,
+ 20, 12, 12, 12, 12, 12, 12, 12,
+ 17, 12, 12, 12, 12, 12, 12, 12,
+ 17, 12, 12, 12, 12, 12, 12, 12]
+ ]},
+ 'maximum': {'subsampling': 0, # "4:4:4"
+ 'quantization': [
+ [2, 2, 2, 2, 3, 4, 5, 6,
+ 2, 2, 2, 2, 3, 4, 5, 6,
+ 2, 2, 2, 2, 4, 5, 7, 9,
+ 2, 2, 2, 4, 5, 7, 9, 12,
+ 3, 3, 4, 5, 8, 10, 12, 12,
+ 4, 4, 5, 7, 10, 12, 12, 12,
+ 5, 5, 7, 9, 12, 12, 12, 12,
+ 6, 6, 9, 12, 12, 12, 12, 12],
+ [3, 3, 5, 9, 13, 15, 15, 15,
+ 3, 4, 6, 10, 14, 12, 12, 12,
+ 5, 6, 9, 14, 12, 12, 12, 12,
+ 9, 10, 14, 12, 12, 12, 12, 12,
+ 13, 14, 12, 12, 12, 12, 12, 12,
+ 15, 12, 12, 12, 12, 12, 12, 12,
+ 15, 12, 12, 12, 12, 12, 12, 12,
+ 15, 12, 12, 12, 12, 12, 12, 12]
+ ]},
+}
+# fmt: on
diff --git a/venv/Lib/site-packages/PIL/McIdasImagePlugin.py b/venv/Lib/site-packages/PIL/McIdasImagePlugin.py
new file mode 100644
index 0000000..9a47933
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/McIdasImagePlugin.py
@@ -0,0 +1,78 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# Basic McIdas support for PIL
+#
+# History:
+# 1997-05-05 fl Created (8-bit images only)
+# 2009-03-08 fl Added 16/32-bit support.
+#
+# Thanks to Richard Jones and Craig Swank for specs and samples.
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1997.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import struct
+
+from . import Image, ImageFile
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(b"\x00\x00\x00\x00\x00\x00\x00\x04")
+
+
+##
+# Image plugin for McIdas area images.
+
+
+class McIdasImageFile(ImageFile.ImageFile):
+ format = "MCIDAS"
+ format_description = "McIdas area file"
+
+ def _open(self) -> None:
+ # parse area file directory
+ assert self.fp is not None
+
+ s = self.fp.read(256)
+ if not _accept(s) or len(s) != 256:
+ msg = "not an McIdas area file"
+ raise SyntaxError(msg)
+
+ self.area_descriptor_raw = s
+ self.area_descriptor = w = [0, *struct.unpack("!64i", s)]
+
+ # get mode
+ if w[11] == 1:
+ mode = rawmode = "L"
+ elif w[11] == 2:
+ mode = rawmode = "I;16B"
+ elif w[11] == 4:
+ # FIXME: add memory map support
+ mode = "I"
+ rawmode = "I;32B"
+ else:
+ msg = "unsupported McIdas format"
+ raise SyntaxError(msg)
+
+ self._mode = mode
+ self._size = w[10], w[9]
+
+ offset = w[34] + w[15]
+ stride = w[15] + w[10] * w[11] * w[14]
+
+ self.tile = [
+ ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))
+ ]
+
+
+# --------------------------------------------------------------------
+# registry
+
+Image.register_open(McIdasImageFile.format, McIdasImageFile, _accept)
+
+# no default extension
diff --git a/venv/Lib/site-packages/PIL/MicImagePlugin.py b/venv/Lib/site-packages/PIL/MicImagePlugin.py
new file mode 100644
index 0000000..99a07ba
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/MicImagePlugin.py
@@ -0,0 +1,103 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# Microsoft Image Composer support for PIL
+#
+# Notes:
+# uses TiffImagePlugin.py to read the actual image streams
+#
+# History:
+# 97-01-20 fl Created
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1997.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import olefile
+
+from . import Image, TiffImagePlugin
+
+#
+# --------------------------------------------------------------------
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(olefile.MAGIC)
+
+
+##
+# Image plugin for Microsoft's Image Composer file format.
+
+
+class MicImageFile(TiffImagePlugin.TiffImageFile):
+ format = "MIC"
+ format_description = "Microsoft Image Composer"
+ _close_exclusive_fp_after_loading = False
+
+ def _open(self) -> None:
+ # read the OLE directory and see if this is a likely
+ # to be a Microsoft Image Composer file
+
+ try:
+ self.ole = olefile.OleFileIO(self.fp)
+ except OSError as e:
+ msg = "not an MIC file; invalid OLE file"
+ raise SyntaxError(msg) from e
+
+ # find ACI subfiles with Image members (maybe not the
+ # best way to identify MIC files, but what the... ;-)
+
+ self.images = [
+ path
+ for path in self.ole.listdir()
+ if path[1:] and path[0].endswith(".ACI") and path[1] == "Image"
+ ]
+
+ # if we didn't find any images, this is probably not
+ # an MIC file.
+ if not self.images:
+ msg = "not an MIC file; no image entries"
+ raise SyntaxError(msg)
+
+ self.frame = -1
+ self._n_frames = len(self.images)
+ self.is_animated = self._n_frames > 1
+
+ assert self.fp is not None
+ self.__fp = self.fp
+ self.seek(0)
+
+ def seek(self, frame: int) -> None:
+ if not self._seek_check(frame):
+ return
+ filename = self.images[frame]
+ self.fp = self.ole.openstream(filename)
+
+ TiffImagePlugin.TiffImageFile._open(self)
+
+ self.frame = frame
+
+ def tell(self) -> int:
+ return self.frame
+
+ def close(self) -> None:
+ self.__fp.close()
+ self.ole.close()
+ super().close()
+
+ def __exit__(self, *args: object) -> None:
+ self.__fp.close()
+ self.ole.close()
+ super().__exit__()
+
+
+#
+# --------------------------------------------------------------------
+
+Image.register_open(MicImageFile.format, MicImageFile, _accept)
+
+Image.register_extension(MicImageFile.format, ".mic")
diff --git a/venv/Lib/site-packages/PIL/MpegImagePlugin.py b/venv/Lib/site-packages/PIL/MpegImagePlugin.py
new file mode 100644
index 0000000..47ebe9d
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/MpegImagePlugin.py
@@ -0,0 +1,84 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# MPEG file handling
+#
+# History:
+# 95-09-09 fl Created
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1995.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from . import Image, ImageFile
+from ._binary import i8
+from ._typing import SupportsRead
+
+#
+# Bitstream parser
+
+
+class BitStream:
+ def __init__(self, fp: SupportsRead[bytes]) -> None:
+ self.fp = fp
+ self.bits = 0
+ self.bitbuffer = 0
+
+ def next(self) -> int:
+ return i8(self.fp.read(1))
+
+ def peek(self, bits: int) -> int:
+ while self.bits < bits:
+ self.bitbuffer = (self.bitbuffer << 8) + self.next()
+ self.bits += 8
+ return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1
+
+ def skip(self, bits: int) -> None:
+ while self.bits < bits:
+ self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1))
+ self.bits += 8
+ self.bits = self.bits - bits
+
+ def read(self, bits: int) -> int:
+ v = self.peek(bits)
+ self.bits = self.bits - bits
+ return v
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(b"\x00\x00\x01\xb3")
+
+
+##
+# Image plugin for MPEG streams. This plugin can identify a stream,
+# but it cannot read it.
+
+
+class MpegImageFile(ImageFile.ImageFile):
+ format = "MPEG"
+ format_description = "MPEG"
+
+ def _open(self) -> None:
+ assert self.fp is not None
+
+ s = BitStream(self.fp)
+ if s.read(32) != 0x1B3:
+ msg = "not an MPEG file"
+ raise SyntaxError(msg)
+
+ self._mode = "RGB"
+ self._size = s.read(12), s.read(12)
+
+
+# --------------------------------------------------------------------
+# Registry stuff
+
+Image.register_open(MpegImageFile.format, MpegImageFile, _accept)
+
+Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"])
+
+Image.register_mime(MpegImageFile.format, "video/mpeg")
diff --git a/venv/Lib/site-packages/PIL/MpoImagePlugin.py b/venv/Lib/site-packages/PIL/MpoImagePlugin.py
new file mode 100644
index 0000000..9360061
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/MpoImagePlugin.py
@@ -0,0 +1,204 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# MPO file handling
+#
+# See "Multi-Picture Format" (CIPA DC-007-Translation 2009, Standard of the
+# Camera & Imaging Products Association)
+#
+# The multi-picture object combines multiple JPEG images (with a modified EXIF
+# data format) into a single file. While it can theoretically be used much like
+# a GIF animation, it is commonly used to represent 3D photographs and is (as
+# of this writing) the most commonly used format by 3D cameras.
+#
+# History:
+# 2014-03-13 Feneric Created
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import os
+import struct
+from typing import IO, Any, cast
+
+from . import (
+ Image,
+ ImageFile,
+ ImageSequence,
+ JpegImagePlugin,
+ TiffImagePlugin,
+)
+from ._binary import o32le
+from ._util import DeferredError
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ JpegImagePlugin._save(im, fp, filename)
+
+
+def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ append_images = im.encoderinfo.get("append_images", [])
+ if not append_images and not getattr(im, "is_animated", False):
+ _save(im, fp, filename)
+ return
+
+ mpf_offset = 28
+ offsets: list[int] = []
+ im_sequences = [im, *append_images]
+ total = sum(getattr(seq, "n_frames", 1) for seq in im_sequences)
+ for im_sequence in im_sequences:
+ for im_frame in ImageSequence.Iterator(im_sequence):
+ if not offsets:
+ # APP2 marker
+ ifd_length = 66 + 16 * total
+ im_frame.encoderinfo["extra"] = (
+ b"\xff\xe2"
+ + struct.pack(">H", 6 + ifd_length)
+ + b"MPF\0"
+ + b" " * ifd_length
+ )
+ exif = im_frame.encoderinfo.get("exif")
+ if isinstance(exif, Image.Exif):
+ exif = exif.tobytes()
+ im_frame.encoderinfo["exif"] = exif
+ if exif:
+ mpf_offset += 4 + len(exif)
+
+ JpegImagePlugin._save(im_frame, fp, filename)
+ offsets.append(fp.tell())
+ else:
+ encoderinfo = im_frame._attach_default_encoderinfo(im)
+ im_frame.save(fp, "JPEG")
+ im_frame.encoderinfo = encoderinfo
+ offsets.append(fp.tell() - offsets[-1])
+
+ ifd = TiffImagePlugin.ImageFileDirectory_v2()
+ ifd[0xB000] = b"0100"
+ ifd[0xB001] = len(offsets)
+
+ mpentries = b""
+ data_offset = 0
+ for i, size in enumerate(offsets):
+ if i == 0:
+ mptype = 0x030000 # Baseline MP Primary Image
+ else:
+ mptype = 0x000000 # Undefined
+ mpentries += struct.pack(" None:
+ assert self.fp is not None
+ self.fp.seek(0) # prep the fp in order to pass the JPEG test
+ JpegImagePlugin.JpegImageFile._open(self)
+ self._after_jpeg_open()
+
+ def _after_jpeg_open(self, mpheader: dict[int, Any] | None = None) -> None:
+ self.mpinfo = mpheader if mpheader is not None else self._getmp()
+ if self.mpinfo is None:
+ msg = "Image appears to be a malformed MPO file"
+ raise ValueError(msg)
+ self.n_frames = self.mpinfo[0xB001]
+ self.__mpoffsets = [
+ mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]
+ ]
+ self.__mpoffsets[0] = 0
+ # Note that the following assertion will only be invalid if something
+ # gets broken within JpegImagePlugin.
+ assert self.n_frames == len(self.__mpoffsets)
+ del self.info["mpoffset"] # no longer needed
+ self.is_animated = self.n_frames > 1
+ assert self.fp is not None
+ self._fp = self.fp # FIXME: hack
+ self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame
+ self.__frame = 0
+ self.offset = 0
+ # for now we can only handle reading and individual frame extraction
+ self.readonly = 1
+
+ def load_seek(self, pos: int) -> None:
+ if isinstance(self._fp, DeferredError):
+ raise self._fp.ex
+ self._fp.seek(pos)
+
+ def seek(self, frame: int) -> None:
+ if not self._seek_check(frame):
+ return
+ if isinstance(self._fp, DeferredError):
+ raise self._fp.ex
+ self.fp = self._fp
+ self.offset = self.__mpoffsets[frame]
+
+ original_exif = self.info.get("exif")
+ if "exif" in self.info:
+ del self.info["exif"]
+
+ self.fp.seek(self.offset + 2) # skip SOI marker
+ if not self.fp.read(2):
+ msg = "No data found for frame"
+ raise ValueError(msg)
+ self.fp.seek(self.offset)
+ JpegImagePlugin.JpegImageFile._open(self)
+ if self.info.get("exif") != original_exif:
+ self._reload_exif()
+
+ self.tile = [
+ ImageFile._Tile("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])
+ ]
+ self.__frame = frame
+
+ def tell(self) -> int:
+ return self.__frame
+
+ @staticmethod
+ def adopt(
+ jpeg_instance: JpegImagePlugin.JpegImageFile,
+ mpheader: dict[int, Any] | None = None,
+ ) -> MpoImageFile:
+ """
+ Transform the instance of JpegImageFile into
+ an instance of MpoImageFile.
+ After the call, the JpegImageFile is extended
+ to be an MpoImageFile.
+
+ This is essentially useful when opening a JPEG
+ file that reveals itself as an MPO, to avoid
+ double call to _open.
+ """
+ jpeg_instance.__class__ = MpoImageFile
+ mpo_instance = cast(MpoImageFile, jpeg_instance)
+ mpo_instance._after_jpeg_open(mpheader)
+ return mpo_instance
+
+
+# ---------------------------------------------------------------------
+# Registry stuff
+
+# Note that since MPO shares a factory with JPEG, we do not need to do a
+# separate registration for it here.
+# Image.register_open(MpoImageFile.format,
+# JpegImagePlugin.jpeg_factory, _accept)
+Image.register_save(MpoImageFile.format, _save)
+Image.register_save_all(MpoImageFile.format, _save_all)
+
+Image.register_extension(MpoImageFile.format, ".mpo")
+
+Image.register_mime(MpoImageFile.format, "image/mpo")
diff --git a/venv/Lib/site-packages/PIL/MspImagePlugin.py b/venv/Lib/site-packages/PIL/MspImagePlugin.py
new file mode 100644
index 0000000..277087a
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/MspImagePlugin.py
@@ -0,0 +1,200 @@
+#
+# The Python Imaging Library.
+#
+# MSP file handling
+#
+# This is the format used by the Paint program in Windows 1 and 2.
+#
+# History:
+# 95-09-05 fl Created
+# 97-01-03 fl Read/write MSP images
+# 17-02-21 es Fixed RLE interpretation
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1995-97.
+# Copyright (c) Eric Soroos 2017.
+#
+# See the README file for information on usage and redistribution.
+#
+# More info on this format: https://archive.org/details/gg243631
+# Page 313:
+# Figure 205. Windows Paint Version 1: "DanM" Format
+# Figure 206. Windows Paint Version 2: "LinS" Format. Used in Windows V2.03
+#
+# See also: https://www.fileformat.info/format/mspaint/egff.htm
+from __future__ import annotations
+
+import io
+import struct
+from typing import IO
+
+from . import Image, ImageFile
+from ._binary import i16le as i16
+from ._binary import o16le as o16
+
+#
+# read MSP files
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith((b"DanM", b"LinS"))
+
+
+##
+# Image plugin for Windows MSP images. This plugin supports both
+# uncompressed (Windows 1.0).
+
+
+class MspImageFile(ImageFile.ImageFile):
+ format = "MSP"
+ format_description = "Windows Paint"
+
+ def _open(self) -> None:
+ # Header
+ assert self.fp is not None
+
+ s = self.fp.read(32)
+ if not _accept(s):
+ msg = "not an MSP file"
+ raise SyntaxError(msg)
+
+ # Header checksum
+ checksum = 0
+ for i in range(0, 32, 2):
+ checksum = checksum ^ i16(s, i)
+ if checksum != 0:
+ msg = "bad MSP checksum"
+ raise SyntaxError(msg)
+
+ self._mode = "1"
+ self._size = i16(s, 4), i16(s, 6)
+
+ if s.startswith(b"DanM"):
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 32, "1")]
+ else:
+ self.tile = [ImageFile._Tile("MSP", (0, 0) + self.size, 32)]
+
+
+class MspDecoder(ImageFile.PyDecoder):
+ # The algo for the MSP decoder is from
+ # https://www.fileformat.info/format/mspaint/egff.htm
+ # cc-by-attribution -- That page references is taken from the
+ # Encyclopedia of Graphics File Formats and is licensed by
+ # O'Reilly under the Creative Common/Attribution license
+ #
+ # For RLE encoded files, the 32byte header is followed by a scan
+ # line map, encoded as one 16bit word of encoded byte length per
+ # line.
+ #
+ # NOTE: the encoded length of the line can be 0. This was not
+ # handled in the previous version of this encoder, and there's no
+ # mention of how to handle it in the documentation. From the few
+ # examples I've seen, I've assumed that it is a fill of the
+ # background color, in this case, white.
+ #
+ #
+ # Pseudocode of the decoder:
+ # Read a BYTE value as the RunType
+ # If the RunType value is zero
+ # Read next byte as the RunCount
+ # Read the next byte as the RunValue
+ # Write the RunValue byte RunCount times
+ # If the RunType value is non-zero
+ # Use this value as the RunCount
+ # Read and write the next RunCount bytes literally
+ #
+ # e.g.:
+ # 0x00 03 ff 05 00 01 02 03 04
+ # would yield the bytes:
+ # 0xff ff ff 00 01 02 03 04
+ #
+ # which are then interpreted as a bit packed mode '1' image
+
+ _pulls_fd = True
+
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+ assert self.fd is not None
+
+ img = io.BytesIO()
+ blank_line = bytearray((0xFF,) * ((self.state.xsize + 7) // 8))
+ try:
+ self.fd.seek(32)
+ rowmap = struct.unpack_from(
+ f"<{self.state.ysize}H", self.fd.read(self.state.ysize * 2)
+ )
+ except struct.error as e:
+ msg = "Truncated MSP file in row map"
+ raise OSError(msg) from e
+
+ for x, rowlen in enumerate(rowmap):
+ try:
+ if rowlen == 0:
+ img.write(blank_line)
+ continue
+ row = self.fd.read(rowlen)
+ if len(row) != rowlen:
+ msg = f"Truncated MSP file, expected {rowlen} bytes on row {x}"
+ raise OSError(msg)
+ idx = 0
+ while idx < rowlen:
+ runtype = row[idx]
+ idx += 1
+ if runtype == 0:
+ (runcount, runval) = struct.unpack_from("Bc", row, idx)
+ img.write(runval * runcount)
+ idx += 2
+ else:
+ runcount = runtype
+ img.write(row[idx : idx + runcount])
+ idx += runcount
+
+ except struct.error as e:
+ msg = f"Corrupted MSP file in row {x}"
+ raise OSError(msg) from e
+
+ self.set_as_raw(img.getvalue(), "1")
+
+ return -1, 0
+
+
+Image.register_decoder("MSP", MspDecoder)
+
+
+#
+# write MSP files (uncompressed only)
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if im.mode != "1":
+ msg = f"cannot write mode {im.mode} as MSP"
+ raise OSError(msg)
+
+ # create MSP header
+ header = [0] * 16
+
+ header[0], header[1] = i16(b"Da"), i16(b"nM") # version 1
+ header[2], header[3] = im.size
+ header[4], header[5] = 1, 1
+ header[6], header[7] = 1, 1
+ header[8], header[9] = im.size
+
+ checksum = 0
+ for h in header:
+ checksum = checksum ^ h
+ header[12] = checksum # FIXME: is this the right field?
+
+ # header
+ for h in header:
+ fp.write(o16(h))
+
+ # image body
+ ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 32, "1")])
+
+
+#
+# registry
+
+Image.register_open(MspImageFile.format, MspImageFile, _accept)
+Image.register_save(MspImageFile.format, _save)
+
+Image.register_extension(MspImageFile.format, ".msp")
diff --git a/venv/Lib/site-packages/PIL/PSDraw.py b/venv/Lib/site-packages/PIL/PSDraw.py
new file mode 100644
index 0000000..7fd4c5c
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PSDraw.py
@@ -0,0 +1,237 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# Simple PostScript graphics interface
+#
+# History:
+# 1996-04-20 fl Created
+# 1999-01-10 fl Added gsave/grestore to image method
+# 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge)
+#
+# Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved.
+# Copyright (c) 1996 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import sys
+from typing import IO
+
+from . import EpsImagePlugin
+
+TYPE_CHECKING = False
+
+
+##
+# Simple PostScript graphics interface.
+
+
+class PSDraw:
+ """
+ Sets up printing to the given file. If ``fp`` is omitted,
+ ``sys.stdout.buffer`` is assumed.
+ """
+
+ def __init__(self, fp: IO[bytes] | None = None) -> None:
+ if not fp:
+ fp = sys.stdout.buffer
+ self.fp = fp
+
+ def begin_document(self, id: str | None = None) -> None:
+ """Set up printing of a document. (Write PostScript DSC header.)"""
+ # FIXME: incomplete
+ self.fp.write(
+ b"%!PS-Adobe-3.0\n"
+ b"save\n"
+ b"/showpage { } def\n"
+ b"%%EndComments\n"
+ b"%%BeginDocument\n"
+ )
+ # self.fp.write(ERROR_PS) # debugging!
+ self.fp.write(EDROFF_PS)
+ self.fp.write(VDI_PS)
+ self.fp.write(b"%%EndProlog\n")
+ self.isofont: dict[bytes, int] = {}
+
+ def end_document(self) -> None:
+ """Ends printing. (Write PostScript DSC footer.)"""
+ self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n")
+ if hasattr(self.fp, "flush"):
+ self.fp.flush()
+
+ def setfont(self, font: str, size: int) -> None:
+ """
+ Selects which font to use.
+
+ :param font: A PostScript font name
+ :param size: Size in points.
+ """
+ font_bytes = bytes(font, "UTF-8")
+ if font_bytes not in self.isofont:
+ # reencode font
+ self.fp.write(
+ b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font_bytes, font_bytes)
+ )
+ self.isofont[font_bytes] = 1
+ # rough
+ self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font_bytes))
+
+ def line(self, xy0: tuple[int, int], xy1: tuple[int, int]) -> None:
+ """
+ Draws a line between the two points. Coordinates are given in
+ PostScript point coordinates (72 points per inch, (0, 0) is the lower
+ left corner of the page).
+ """
+ self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1))
+
+ def rectangle(self, box: tuple[int, int, int, int]) -> None:
+ """
+ Draws a rectangle.
+
+ :param box: A tuple of four integers, specifying left, bottom, width and
+ height.
+ """
+ self.fp.write(b"%d %d M 0 %d %d Vr\n" % box)
+
+ def text(self, xy: tuple[int, int], text: str) -> None:
+ """
+ Draws text at the given position. You must use
+ :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method.
+ """
+ text_bytes = bytes(text, "UTF-8")
+ text_bytes = b"\\(".join(text_bytes.split(b"("))
+ text_bytes = b"\\)".join(text_bytes.split(b")"))
+ self.fp.write(b"%d %d M (%s) S\n" % (xy + (text_bytes,)))
+
+ if TYPE_CHECKING:
+ from . import Image
+
+ def image(
+ self, box: tuple[int, int, int, int], im: Image.Image, dpi: int | None = None
+ ) -> None:
+ """Draw a PIL image, centered in the given box."""
+ # default resolution depends on mode
+ if not dpi:
+ if im.mode == "1":
+ dpi = 200 # fax
+ else:
+ dpi = 100 # grayscale
+ # image size (on paper)
+ x = im.size[0] * 72 / dpi
+ y = im.size[1] * 72 / dpi
+ # max allowed size
+ xmax = float(box[2] - box[0])
+ ymax = float(box[3] - box[1])
+ if x > xmax:
+ y = y * xmax / x
+ x = xmax
+ if y > ymax:
+ x = x * ymax / y
+ y = ymax
+ dx = (xmax - x) / 2 + box[0]
+ dy = (ymax - y) / 2 + box[1]
+ self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy))
+ if (x, y) != im.size:
+ # EpsImagePlugin._save prints the image at (0,0,xsize,ysize)
+ sx = x / im.size[0]
+ sy = y / im.size[1]
+ self.fp.write(b"%f %f scale\n" % (sx, sy))
+ EpsImagePlugin._save(im, self.fp, "", 0)
+ self.fp.write(b"\ngrestore\n")
+
+
+# --------------------------------------------------------------------
+# PostScript driver
+
+#
+# EDROFF.PS -- PostScript driver for Edroff 2
+#
+# History:
+# 94-01-25 fl: created (edroff 2.04)
+#
+# Copyright (c) Fredrik Lundh 1994.
+#
+
+
+EDROFF_PS = b"""\
+/S { show } bind def
+/P { moveto show } bind def
+/M { moveto } bind def
+/X { 0 rmoveto } bind def
+/Y { 0 exch rmoveto } bind def
+/E { findfont
+ dup maxlength dict begin
+ {
+ 1 index /FID ne { def } { pop pop } ifelse
+ } forall
+ /Encoding exch def
+ dup /FontName exch def
+ currentdict end definefont pop
+} bind def
+/F { findfont exch scalefont dup setfont
+ [ exch /setfont cvx ] cvx bind def
+} bind def
+"""
+
+#
+# VDI.PS -- PostScript driver for VDI meta commands
+#
+# History:
+# 94-01-25 fl: created (edroff 2.04)
+#
+# Copyright (c) Fredrik Lundh 1994.
+#
+
+VDI_PS = b"""\
+/Vm { moveto } bind def
+/Va { newpath arcn stroke } bind def
+/Vl { moveto lineto stroke } bind def
+/Vc { newpath 0 360 arc closepath } bind def
+/Vr { exch dup 0 rlineto
+ exch dup 0 exch rlineto
+ exch neg 0 rlineto
+ 0 exch neg rlineto
+ setgray fill } bind def
+/Tm matrix def
+/Ve { Tm currentmatrix pop
+ translate scale newpath 0 0 .5 0 360 arc closepath
+ Tm setmatrix
+} bind def
+/Vf { currentgray exch setgray fill setgray } bind def
+"""
+
+#
+# ERROR.PS -- Error handler
+#
+# History:
+# 89-11-21 fl: created (pslist 1.10)
+#
+
+ERROR_PS = b"""\
+/landscape false def
+/errorBUF 200 string def
+/errorNL { currentpoint 10 sub exch pop 72 exch moveto } def
+errordict begin /handleerror {
+ initmatrix /Courier findfont 10 scalefont setfont
+ newpath 72 720 moveto $error begin /newerror false def
+ (PostScript Error) show errorNL errorNL
+ (Error: ) show
+ /errorname load errorBUF cvs show errorNL errorNL
+ (Command: ) show
+ /command load dup type /stringtype ne { errorBUF cvs } if show
+ errorNL errorNL
+ (VMstatus: ) show
+ vmstatus errorBUF cvs show ( bytes available, ) show
+ errorBUF cvs show ( bytes used at level ) show
+ errorBUF cvs show errorNL errorNL
+ (Operand stargck: ) show errorNL /ostargck load {
+ dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL
+ } forall errorNL
+ (Execution stargck: ) show errorNL /estargck load {
+ dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL
+ } forall
+ end showpage
+} def end
+"""
diff --git a/venv/Lib/site-packages/PIL/PaletteFile.py b/venv/Lib/site-packages/PIL/PaletteFile.py
new file mode 100644
index 0000000..2a26e5d
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PaletteFile.py
@@ -0,0 +1,54 @@
+#
+# Python Imaging Library
+# $Id$
+#
+# stuff to read simple, teragon-style palette files
+#
+# History:
+# 97-08-23 fl Created
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1997.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from typing import IO
+
+from ._binary import o8
+
+
+class PaletteFile:
+ """File handler for Teragon-style palette files."""
+
+ rawmode = "RGB"
+
+ def __init__(self, fp: IO[bytes]) -> None:
+ palette = [o8(i) * 3 for i in range(256)]
+
+ while True:
+ s = fp.readline()
+
+ if not s:
+ break
+ if s.startswith(b"#"):
+ continue
+ if len(s) > 100:
+ msg = "bad palette file"
+ raise SyntaxError(msg)
+
+ v = [int(x) for x in s.split()]
+ try:
+ [i, r, g, b] = v
+ except ValueError:
+ [i, r] = v
+ g = b = r
+
+ if 0 <= i <= 255:
+ palette[i] = o8(r) + o8(g) + o8(b)
+
+ self.palette = b"".join(palette)
+
+ def getpalette(self) -> tuple[bytes, str]:
+ return self.palette, self.rawmode
diff --git a/venv/Lib/site-packages/PIL/PalmImagePlugin.py b/venv/Lib/site-packages/PIL/PalmImagePlugin.py
new file mode 100644
index 0000000..15f7129
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PalmImagePlugin.py
@@ -0,0 +1,217 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+
+##
+# Image plugin for Palm pixmap images (output only).
+##
+from __future__ import annotations
+
+from typing import IO
+
+from . import Image, ImageFile
+from ._binary import o8
+from ._binary import o16be as o16b
+
+# fmt: off
+_Palm8BitColormapValues = (
+ (255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255),
+ (255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204),
+ (255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204),
+ (255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153),
+ (255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255),
+ (204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255),
+ (204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204),
+ (204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153),
+ (204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153),
+ (153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255),
+ (153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204),
+ (153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204),
+ (153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153),
+ (153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255),
+ (102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255),
+ (102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204),
+ (102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153),
+ (102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153),
+ (51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255),
+ (51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204),
+ (51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204),
+ (51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153),
+ (51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255),
+ (0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255),
+ (0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204),
+ (0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153),
+ (0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153),
+ (255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102),
+ (255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51),
+ (255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51),
+ (255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0),
+ (255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102),
+ (204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102),
+ (204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51),
+ (204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0),
+ (204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0),
+ (153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102),
+ (153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51),
+ (153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51),
+ (153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0),
+ (153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102),
+ (102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102),
+ (102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51),
+ (102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0),
+ (102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0),
+ (51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102),
+ (51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51),
+ (51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51),
+ (51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0),
+ (51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102),
+ (0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102),
+ (0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51),
+ (0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0),
+ (0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17),
+ (34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119),
+ (136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221),
+ (238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128),
+ (0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),
+ (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0))
+# fmt: on
+
+
+# so build a prototype image to be used for palette resampling
+def build_prototype_image() -> Image.Image:
+ image = Image.new("L", (1, len(_Palm8BitColormapValues)))
+ image.putdata(list(range(len(_Palm8BitColormapValues))))
+ palettedata: tuple[int, ...] = ()
+ for colormapValue in _Palm8BitColormapValues:
+ palettedata += colormapValue
+ palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues))
+ image.putpalette(palettedata)
+ return image
+
+
+Palm8BitColormapImage = build_prototype_image()
+
+# OK, we now have in Palm8BitColormapImage,
+# a "P"-mode image with the right palette
+#
+# --------------------------------------------------------------------
+
+_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000}
+
+_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00}
+
+
+#
+# --------------------------------------------------------------------
+
+##
+# (Internal) Image save plugin for the Palm format.
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if im.mode == "P":
+ rawmode = "P"
+ bpp = 8
+ version = 1
+
+ elif im.mode == "L":
+ if im.encoderinfo.get("bpp") in (1, 2, 4):
+ # this is 8-bit grayscale, so we shift it to get the high-order bits,
+ # and invert it because
+ # Palm does grayscale from white (0) to black (1)
+ bpp = im.encoderinfo["bpp"]
+ maxval = (1 << bpp) - 1
+ shift = 8 - bpp
+ im = im.point(lambda x: maxval - (x >> shift))
+ elif im.info.get("bpp") in (1, 2, 4):
+ # here we assume that even though the inherent mode is 8-bit grayscale,
+ # only the lower bpp bits are significant.
+ # We invert them to match the Palm.
+ bpp = im.info["bpp"]
+ maxval = (1 << bpp) - 1
+ im = im.point(lambda x: maxval - (x & maxval))
+ else:
+ msg = f"cannot write mode {im.mode} as Palm"
+ raise OSError(msg)
+
+ # we ignore the palette here
+ im._mode = "P"
+ rawmode = f"P;{bpp}"
+ version = 1
+
+ elif im.mode == "1":
+ # monochrome -- write it inverted, as is the Palm standard
+ rawmode = "1;I"
+ bpp = 1
+ version = 0
+
+ else:
+ msg = f"cannot write mode {im.mode} as Palm"
+ raise OSError(msg)
+
+ #
+ # make sure image data is available
+ im.load()
+
+ # write header
+
+ cols = im.size[0]
+ rows = im.size[1]
+
+ rowbytes = int((cols + (16 // bpp - 1)) / (16 // bpp)) * 2
+ transparent_index = 0
+ compression_type = _COMPRESSION_TYPES["none"]
+
+ flags = 0
+ if im.mode == "P":
+ flags |= _FLAGS["custom-colormap"]
+ colormap = im.im.getpalette()
+ colors = len(colormap) // 3
+ colormapsize = 4 * colors + 2
+ else:
+ colormapsize = 0
+
+ if "offset" in im.info:
+ offset = (rowbytes * rows + 16 + 3 + colormapsize) // 4
+ else:
+ offset = 0
+
+ fp.write(o16b(cols) + o16b(rows) + o16b(rowbytes) + o16b(flags))
+ fp.write(o8(bpp))
+ fp.write(o8(version))
+ fp.write(o16b(offset))
+ fp.write(o8(transparent_index))
+ fp.write(o8(compression_type))
+ fp.write(o16b(0)) # reserved by Palm
+
+ # now write colormap if necessary
+
+ if colormapsize:
+ fp.write(o16b(colors))
+ for i in range(colors):
+ fp.write(o8(i))
+ fp.write(colormap[3 * i : 3 * i + 3])
+
+ # now convert data to raw form
+ ImageFile._save(
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, rowbytes, 1))]
+ )
+
+ if hasattr(fp, "flush"):
+ fp.flush()
+
+
+#
+# --------------------------------------------------------------------
+
+Image.register_save("Palm", _save)
+
+Image.register_extension("Palm", ".palm")
+
+Image.register_mime("Palm", "image/palm")
diff --git a/venv/Lib/site-packages/PIL/PcdImagePlugin.py b/venv/Lib/site-packages/PIL/PcdImagePlugin.py
new file mode 100644
index 0000000..296f377
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PcdImagePlugin.py
@@ -0,0 +1,68 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# PCD file handling
+#
+# History:
+# 96-05-10 fl Created
+# 96-05-27 fl Added draft mode (128x192, 256x384)
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1996.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from . import Image, ImageFile
+
+##
+# Image plugin for PhotoCD images. This plugin only reads the 768x512
+# image from the file; higher resolutions are encoded in a proprietary
+# encoding.
+
+
+class PcdImageFile(ImageFile.ImageFile):
+ format = "PCD"
+ format_description = "Kodak PhotoCD"
+
+ def _open(self) -> None:
+ # rough
+ assert self.fp is not None
+
+ self.fp.seek(2048)
+ s = self.fp.read(1539)
+
+ if not s.startswith(b"PCD_"):
+ msg = "not a PCD file"
+ raise SyntaxError(msg)
+
+ orientation = s[1538] & 3
+ self.tile_post_rotate = None
+ if orientation == 1:
+ self.tile_post_rotate = 90
+ elif orientation == 3:
+ self.tile_post_rotate = 270
+
+ self._mode = "RGB"
+ self._size = (512, 768) if orientation in (1, 3) else (768, 512)
+ self.tile = [ImageFile._Tile("pcd", (0, 0, 768, 512), 96 * 2048)]
+
+ def load_prepare(self) -> None:
+ if self._im is None and self.tile_post_rotate:
+ self.im = Image.core.new(self.mode, (768, 512))
+ ImageFile.ImageFile.load_prepare(self)
+
+ def load_end(self) -> None:
+ if self.tile_post_rotate:
+ # Handle rotated PCDs
+ self.im = self.rotate(self.tile_post_rotate, expand=True).im
+
+
+#
+# registry
+
+Image.register_open(PcdImageFile.format, PcdImageFile)
+
+Image.register_extension(PcdImageFile.format, ".pcd")
diff --git a/venv/Lib/site-packages/PIL/PcfFontFile.py b/venv/Lib/site-packages/PIL/PcfFontFile.py
new file mode 100644
index 0000000..a00e9b9
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PcfFontFile.py
@@ -0,0 +1,258 @@
+#
+# THIS IS WORK IN PROGRESS
+#
+# The Python Imaging Library
+# $Id$
+#
+# portable compiled font file parser
+#
+# history:
+# 1997-08-19 fl created
+# 2003-09-13 fl fixed loading of unicode fonts
+#
+# Copyright (c) 1997-2003 by Secret Labs AB.
+# Copyright (c) 1997-2003 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import io
+
+from . import FontFile, Image
+from ._binary import i8
+from ._binary import i16be as b16
+from ._binary import i16le as l16
+from ._binary import i32be as b32
+from ._binary import i32le as l32
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from typing import BinaryIO
+
+# --------------------------------------------------------------------
+# declarations
+
+PCF_MAGIC = 0x70636601 # "\x01fcp"
+
+PCF_PROPERTIES = 1 << 0
+PCF_ACCELERATORS = 1 << 1
+PCF_METRICS = 1 << 2
+PCF_BITMAPS = 1 << 3
+PCF_INK_METRICS = 1 << 4
+PCF_BDF_ENCODINGS = 1 << 5
+PCF_SWIDTHS = 1 << 6
+PCF_GLYPH_NAMES = 1 << 7
+PCF_BDF_ACCELERATORS = 1 << 8
+
+BYTES_PER_ROW: list[Callable[[int], int]] = [
+ lambda bits: ((bits + 7) >> 3),
+ lambda bits: ((bits + 15) >> 3) & ~1,
+ lambda bits: ((bits + 31) >> 3) & ~3,
+ lambda bits: ((bits + 63) >> 3) & ~7,
+]
+
+
+def sz(s: bytes, o: int) -> bytes:
+ return s[o : s.index(b"\0", o)]
+
+
+class PcfFontFile(FontFile.FontFile):
+ """Font file plugin for the X11 PCF format."""
+
+ name = "name"
+
+ def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"):
+ self.charset_encoding = charset_encoding
+
+ magic = l32(fp.read(4))
+ if magic != PCF_MAGIC:
+ msg = "not a PCF file"
+ raise SyntaxError(msg)
+
+ super().__init__()
+
+ count = l32(fp.read(4))
+ self.toc = {}
+ for i in range(count):
+ type = l32(fp.read(4))
+ self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4))
+
+ self.fp = fp
+
+ self.info = self._load_properties()
+
+ metrics = self._load_metrics()
+ bitmaps = self._load_bitmaps(metrics)
+ encoding = self._load_encoding()
+
+ #
+ # create glyph structure
+
+ for ch, ix in enumerate(encoding):
+ if ix is not None:
+ (
+ xsize,
+ ysize,
+ left,
+ right,
+ width,
+ ascent,
+ descent,
+ attributes,
+ ) = metrics[ix]
+ self.glyph[ch] = (
+ (width, 0),
+ (left, descent - ysize, xsize + left, descent),
+ (0, 0, xsize, ysize),
+ bitmaps[ix],
+ )
+
+ def _getformat(
+ self, tag: int
+ ) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]:
+ format, size, offset = self.toc[tag]
+
+ fp = self.fp
+ fp.seek(offset)
+
+ format = l32(fp.read(4))
+
+ if format & 4:
+ i16, i32 = b16, b32
+ else:
+ i16, i32 = l16, l32
+
+ return fp, format, i16, i32
+
+ def _load_properties(self) -> dict[bytes, bytes | int]:
+ #
+ # font properties
+
+ properties = {}
+
+ fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)
+
+ nprops = i32(fp.read(4))
+
+ # read property description
+ p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)]
+
+ if nprops & 3:
+ fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad
+
+ data = fp.read(i32(fp.read(4)))
+
+ for k, s, v in p:
+ property_value: bytes | int = sz(data, v) if s else v
+ properties[sz(data, k)] = property_value
+
+ return properties
+
+ def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]:
+ #
+ # font metrics
+
+ metrics: list[tuple[int, int, int, int, int, int, int, int]] = []
+
+ fp, format, i16, i32 = self._getformat(PCF_METRICS)
+
+ append = metrics.append
+
+ if (format & 0xFF00) == 0x100:
+ # "compressed" metrics
+ for i in range(i16(fp.read(2))):
+ left = i8(fp.read(1)) - 128
+ right = i8(fp.read(1)) - 128
+ width = i8(fp.read(1)) - 128
+ ascent = i8(fp.read(1)) - 128
+ descent = i8(fp.read(1)) - 128
+ xsize = right - left
+ ysize = ascent + descent
+ append((xsize, ysize, left, right, width, ascent, descent, 0))
+
+ else:
+ # "jumbo" metrics
+ for i in range(i32(fp.read(4))):
+ left = i16(fp.read(2))
+ right = i16(fp.read(2))
+ width = i16(fp.read(2))
+ ascent = i16(fp.read(2))
+ descent = i16(fp.read(2))
+ attributes = i16(fp.read(2))
+ xsize = right - left
+ ysize = ascent + descent
+ append((xsize, ysize, left, right, width, ascent, descent, attributes))
+
+ return metrics
+
+ def _load_bitmaps(
+ self, metrics: list[tuple[int, int, int, int, int, int, int, int]]
+ ) -> list[Image.Image]:
+ #
+ # bitmap data
+
+ fp, format, i16, i32 = self._getformat(PCF_BITMAPS)
+
+ nbitmaps = i32(fp.read(4))
+
+ if nbitmaps != len(metrics):
+ msg = "Wrong number of bitmaps"
+ raise OSError(msg)
+
+ offsets = [i32(fp.read(4)) for _ in range(nbitmaps)]
+
+ bitmap_sizes = [i32(fp.read(4)) for _ in range(4)]
+
+ # byteorder = format & 4 # non-zero => MSB
+ bitorder = format & 8 # non-zero => MSB
+ padindex = format & 3
+
+ bitmapsize = bitmap_sizes[padindex]
+ offsets.append(bitmapsize)
+
+ data = fp.read(bitmapsize)
+
+ pad = BYTES_PER_ROW[padindex]
+ mode = "1;R"
+ if bitorder:
+ mode = "1"
+
+ bitmaps = []
+ for i in range(nbitmaps):
+ xsize, ysize = metrics[i][:2]
+ b, e = offsets[i : i + 2]
+ bitmaps.append(
+ Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize))
+ )
+
+ return bitmaps
+
+ def _load_encoding(self) -> list[int | None]:
+ fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)
+
+ first_col, last_col = i16(fp.read(2)), i16(fp.read(2))
+ first_row, last_row = i16(fp.read(2)), i16(fp.read(2))
+
+ i16(fp.read(2)) # default
+
+ nencoding = (last_col - first_col + 1) * (last_row - first_row + 1)
+
+ # map character code to bitmap index
+ encoding: list[int | None] = [None] * min(256, nencoding)
+
+ encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)]
+
+ for i in range(first_col, len(encoding)):
+ try:
+ encoding_offset = encoding_offsets[
+ ord(bytearray([i]).decode(self.charset_encoding))
+ ]
+ if encoding_offset != 0xFFFF:
+ encoding[i] = encoding_offset
+ except UnicodeDecodeError:
+ # character is not supported in selected encoding
+ pass
+
+ return encoding
diff --git a/venv/Lib/site-packages/PIL/PcxImagePlugin.py b/venv/Lib/site-packages/PIL/PcxImagePlugin.py
new file mode 100644
index 0000000..6b16d53
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PcxImagePlugin.py
@@ -0,0 +1,228 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# PCX file handling
+#
+# This format was originally used by ZSoft's popular PaintBrush
+# program for the IBM PC. It is also supported by many MS-DOS and
+# Windows applications, including the Windows PaintBrush program in
+# Windows 3.
+#
+# history:
+# 1995-09-01 fl Created
+# 1996-05-20 fl Fixed RGB support
+# 1997-01-03 fl Fixed 2-bit and 4-bit support
+# 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1)
+# 1999-02-07 fl Added write support
+# 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust
+# 2002-07-30 fl Seek from to current position, not beginning of file
+# 2003-06-03 fl Extract DPI settings (info["dpi"])
+#
+# Copyright (c) 1997-2003 by Secret Labs AB.
+# Copyright (c) 1995-2003 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import io
+import logging
+from typing import IO
+
+from . import Image, ImageFile, ImagePalette
+from ._binary import i16le as i16
+from ._binary import o8
+from ._binary import o16le as o16
+
+logger = logging.getLogger(__name__)
+
+
+def _accept(prefix: bytes) -> bool:
+ return len(prefix) >= 2 and prefix[0] == 10 and prefix[1] in [0, 2, 3, 5]
+
+
+##
+# Image plugin for Paintbrush images.
+
+
+class PcxImageFile(ImageFile.ImageFile):
+ format = "PCX"
+ format_description = "Paintbrush"
+
+ def _open(self) -> None:
+ # header
+ assert self.fp is not None
+
+ s = self.fp.read(68)
+ if not _accept(s):
+ msg = "not a PCX file"
+ raise SyntaxError(msg)
+
+ # image
+ bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1
+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
+ msg = "bad PCX image size"
+ raise SyntaxError(msg)
+ logger.debug("BBox: %s %s %s %s", *bbox)
+
+ offset = self.fp.tell() + 60
+
+ # format
+ version = s[1]
+ bits = s[3]
+ planes = s[65]
+ provided_stride = i16(s, 66)
+ logger.debug(
+ "PCX version %s, bits %s, planes %s, stride %s",
+ version,
+ bits,
+ planes,
+ provided_stride,
+ )
+
+ self.info["dpi"] = i16(s, 12), i16(s, 14)
+
+ if bits == 1 and planes == 1:
+ mode = rawmode = "1"
+
+ elif bits == 1 and planes in (2, 4):
+ mode = "P"
+ rawmode = f"P;{planes}L"
+ self.palette = ImagePalette.raw("RGB", s[16:64])
+
+ elif version == 5 and bits == 8 and planes == 1:
+ mode = rawmode = "L"
+ # FIXME: hey, this doesn't work with the incremental loader !!!
+ self.fp.seek(-769, io.SEEK_END)
+ s = self.fp.read(769)
+ if len(s) == 769 and s[0] == 12:
+ # check if the palette is linear grayscale
+ for i in range(256):
+ if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3:
+ mode = rawmode = "P"
+ break
+ if mode == "P":
+ self.palette = ImagePalette.raw("RGB", s[1:])
+
+ elif version == 5 and bits == 8 and planes == 3:
+ mode = "RGB"
+ rawmode = "RGB;L"
+
+ else:
+ msg = "unknown PCX mode"
+ raise OSError(msg)
+
+ self._mode = mode
+ self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]
+
+ # Don't trust the passed in stride.
+ # Calculate the approximate position for ourselves.
+ # CVE-2020-35653
+ stride = (self._size[0] * bits + 7) // 8
+
+ # While the specification states that this must be even,
+ # not all images follow this
+ if provided_stride != stride:
+ stride += stride % 2
+
+ bbox = (0, 0) + self.size
+ logger.debug("size: %sx%s", *self.size)
+
+ self.tile = [ImageFile._Tile("pcx", bbox, offset, (rawmode, planes * stride))]
+
+
+# --------------------------------------------------------------------
+# save PCX files
+
+
+SAVE = {
+ # mode: (version, bits, planes, raw mode)
+ "1": (2, 1, 1, "1"),
+ "L": (5, 8, 1, "L"),
+ "P": (5, 8, 1, "P"),
+ "RGB": (5, 8, 3, "RGB;L"),
+}
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ try:
+ version, bits, planes, rawmode = SAVE[im.mode]
+ except KeyError as e:
+ msg = f"Cannot save {im.mode} images as PCX"
+ raise ValueError(msg) from e
+
+ # bytes per plane
+ stride = (im.size[0] * bits + 7) // 8
+ # stride should be even
+ stride += stride % 2
+ # Stride needs to be kept in sync with the PcxEncode.c version.
+ # Ideally it should be passed in in the state, but the bytes value
+ # gets overwritten.
+
+ logger.debug(
+ "PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d",
+ im.size[0],
+ bits,
+ stride,
+ )
+
+ # under windows, we could determine the current screen size with
+ # "Image.core.display_mode()[1]", but I think that's overkill...
+
+ screen = im.size
+
+ dpi = 100, 100
+
+ # PCX header
+ fp.write(
+ o8(10)
+ + o8(version)
+ + o8(1)
+ + o8(bits)
+ + o16(0)
+ + o16(0)
+ + o16(im.size[0] - 1)
+ + o16(im.size[1] - 1)
+ + o16(dpi[0])
+ + o16(dpi[1])
+ + b"\0" * 24
+ + b"\xff" * 24
+ + b"\0"
+ + o8(planes)
+ + o16(stride)
+ + o16(1)
+ + o16(screen[0])
+ + o16(screen[1])
+ + b"\0" * 54
+ )
+
+ assert fp.tell() == 128
+
+ ImageFile._save(
+ im, fp, [ImageFile._Tile("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))]
+ )
+
+ if im.mode == "P":
+ # colour palette
+ fp.write(o8(12))
+ palette = im.im.getpalette("RGB", "RGB")
+ palette += b"\x00" * (768 - len(palette))
+ fp.write(palette) # 768 bytes
+ elif im.mode == "L":
+ # grayscale palette
+ fp.write(o8(12))
+ for i in range(256):
+ fp.write(o8(i) * 3)
+
+
+# --------------------------------------------------------------------
+# registry
+
+
+Image.register_open(PcxImageFile.format, PcxImageFile, _accept)
+Image.register_save(PcxImageFile.format, _save)
+
+Image.register_extension(PcxImageFile.format, ".pcx")
+
+Image.register_mime(PcxImageFile.format, "image/x-pcx")
diff --git a/venv/Lib/site-packages/PIL/PdfImagePlugin.py b/venv/Lib/site-packages/PIL/PdfImagePlugin.py
new file mode 100644
index 0000000..5594c7e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PdfImagePlugin.py
@@ -0,0 +1,311 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# PDF (Acrobat) file handling
+#
+# History:
+# 1996-07-16 fl Created
+# 1997-01-18 fl Fixed header
+# 2004-02-21 fl Fixes for 1/L/CMYK images, etc.
+# 2004-02-24 fl Fixes for 1 and P images.
+#
+# Copyright (c) 1997-2004 by Secret Labs AB. All rights reserved.
+# Copyright (c) 1996-1997 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+
+##
+# Image plugin for PDF images (output only).
+##
+from __future__ import annotations
+
+import io
+import math
+import os
+import time
+from typing import IO, Any
+
+from . import Image, ImageFile, ImageSequence, PdfParser, features
+
+#
+# --------------------------------------------------------------------
+
+# object ids:
+# 1. catalogue
+# 2. pages
+# 3. image
+# 4. page
+# 5. page contents
+
+
+def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ _save(im, fp, filename, save_all=True)
+
+
+##
+# (Internal) Image save plugin for the PDF format.
+
+
+def _write_image(
+ im: Image.Image,
+ filename: str | bytes,
+ existing_pdf: PdfParser.PdfParser,
+ image_refs: list[PdfParser.IndirectReference],
+) -> tuple[PdfParser.IndirectReference, str]:
+ # FIXME: Should replace ASCIIHexDecode with RunLengthDecode
+ # (packbits) or LZWDecode (tiff/lzw compression). Note that
+ # PDF 1.2 also supports Flatedecode (zip compression).
+
+ params = None
+ decode = None
+
+ #
+ # Get image characteristics
+
+ width, height = im.size
+
+ dict_obj: dict[str, Any] = {"BitsPerComponent": 8}
+ if im.mode == "1":
+ if features.check("libtiff"):
+ decode_filter = "CCITTFaxDecode"
+ dict_obj["BitsPerComponent"] = 1
+ params = PdfParser.PdfArray(
+ [
+ PdfParser.PdfDict(
+ {
+ "K": -1,
+ "BlackIs1": True,
+ "Columns": width,
+ "Rows": height,
+ }
+ )
+ ]
+ )
+ else:
+ decode_filter = "DCTDecode"
+ dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
+ procset = "ImageB" # grayscale
+ elif im.mode == "L":
+ decode_filter = "DCTDecode"
+ # params = f"<< /Predictor 15 /Columns {width-2} >>"
+ dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
+ procset = "ImageB" # grayscale
+ elif im.mode == "LA":
+ decode_filter = "JPXDecode"
+ # params = f"<< /Predictor 15 /Columns {width-2} >>"
+ procset = "ImageB" # grayscale
+ dict_obj["SMaskInData"] = 1
+ elif im.mode == "P":
+ decode_filter = "ASCIIHexDecode"
+ palette = im.getpalette()
+ assert palette is not None
+ dict_obj["ColorSpace"] = [
+ PdfParser.PdfName("Indexed"),
+ PdfParser.PdfName("DeviceRGB"),
+ len(palette) // 3 - 1,
+ PdfParser.PdfBinary(palette),
+ ]
+ procset = "ImageI" # indexed color
+
+ if "transparency" in im.info:
+ smask = im.convert("LA").getchannel("A")
+ smask.encoderinfo = {}
+
+ image_ref = _write_image(smask, filename, existing_pdf, image_refs)[0]
+ dict_obj["SMask"] = image_ref
+ elif im.mode == "RGB":
+ decode_filter = "DCTDecode"
+ dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceRGB")
+ procset = "ImageC" # color images
+ elif im.mode == "RGBA":
+ decode_filter = "JPXDecode"
+ procset = "ImageC" # color images
+ dict_obj["SMaskInData"] = 1
+ elif im.mode == "CMYK":
+ decode_filter = "DCTDecode"
+ dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceCMYK")
+ procset = "ImageC" # color images
+ decode = [1, 0, 1, 0, 1, 0, 1, 0]
+ else:
+ msg = f"cannot save mode {im.mode}"
+ raise ValueError(msg)
+
+ #
+ # image
+
+ op = io.BytesIO()
+
+ if decode_filter == "ASCIIHexDecode":
+ ImageFile._save(im, op, [ImageFile._Tile("hex", (0, 0) + im.size, 0, im.mode)])
+ elif decode_filter == "CCITTFaxDecode":
+ im.save(
+ op,
+ "TIFF",
+ compression="group4",
+ # use a single strip
+ strip_size=math.ceil(width / 8) * height,
+ )
+ elif decode_filter == "DCTDecode":
+ Image.SAVE["JPEG"](im, op, filename)
+ elif decode_filter == "JPXDecode":
+ del dict_obj["BitsPerComponent"]
+ Image.SAVE["JPEG2000"](im, op, filename)
+ else:
+ msg = f"unsupported PDF filter ({decode_filter})"
+ raise ValueError(msg)
+
+ stream = op.getvalue()
+ filter: PdfParser.PdfArray | PdfParser.PdfName
+ if decode_filter == "CCITTFaxDecode":
+ stream = stream[8:]
+ filter = PdfParser.PdfArray([PdfParser.PdfName(decode_filter)])
+ else:
+ filter = PdfParser.PdfName(decode_filter)
+
+ image_ref = image_refs.pop(0)
+ existing_pdf.write_obj(
+ image_ref,
+ stream=stream,
+ Type=PdfParser.PdfName("XObject"),
+ Subtype=PdfParser.PdfName("Image"),
+ Width=width, # * 72.0 / x_resolution,
+ Height=height, # * 72.0 / y_resolution,
+ Filter=filter,
+ Decode=decode,
+ DecodeParms=params,
+ **dict_obj,
+ )
+
+ return image_ref, procset
+
+
+def _save(
+ im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False
+) -> None:
+ is_appending = im.encoderinfo.get("append", False)
+ filename_str = filename.decode() if isinstance(filename, bytes) else filename
+ if is_appending:
+ existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="r+b")
+ else:
+ existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="w+b")
+
+ dpi = im.encoderinfo.get("dpi")
+ if dpi:
+ x_resolution = dpi[0]
+ y_resolution = dpi[1]
+ else:
+ x_resolution = y_resolution = im.encoderinfo.get("resolution", 72.0)
+
+ info = {
+ "title": (
+ None if is_appending else os.path.splitext(os.path.basename(filename))[0]
+ ),
+ "author": None,
+ "subject": None,
+ "keywords": None,
+ "creator": None,
+ "producer": None,
+ "creationDate": None if is_appending else time.gmtime(),
+ "modDate": None if is_appending else time.gmtime(),
+ }
+ for k, default in info.items():
+ v = im.encoderinfo.get(k) if k in im.encoderinfo else default
+ if v:
+ existing_pdf.info[k[0].upper() + k[1:]] = v
+
+ #
+ # make sure image data is available
+ im.load()
+
+ existing_pdf.start_writing()
+ existing_pdf.write_header()
+ existing_pdf.write_comment("created by Pillow PDF driver")
+
+ #
+ # pages
+ ims = [im]
+ if save_all:
+ append_images = im.encoderinfo.get("append_images", [])
+ for append_im in append_images:
+ append_im.encoderinfo = im.encoderinfo.copy()
+ ims.append(append_im)
+ number_of_pages = 0
+ image_refs = []
+ page_refs = []
+ contents_refs = []
+ for im in ims:
+ im_number_of_pages = 1
+ if save_all:
+ im_number_of_pages = getattr(im, "n_frames", 1)
+ number_of_pages += im_number_of_pages
+ for i in range(im_number_of_pages):
+ image_refs.append(existing_pdf.next_object_id(0))
+ if im.mode == "P" and "transparency" in im.info:
+ image_refs.append(existing_pdf.next_object_id(0))
+
+ page_refs.append(existing_pdf.next_object_id(0))
+ contents_refs.append(existing_pdf.next_object_id(0))
+ existing_pdf.pages.append(page_refs[-1])
+
+ #
+ # catalog and list of pages
+ existing_pdf.write_catalog()
+
+ page_number = 0
+ for im_sequence in ims:
+ im_pages: ImageSequence.Iterator | list[Image.Image] = (
+ ImageSequence.Iterator(im_sequence) if save_all else [im_sequence]
+ )
+ for im in im_pages:
+ image_ref, procset = _write_image(im, filename, existing_pdf, image_refs)
+
+ #
+ # page
+
+ existing_pdf.write_page(
+ page_refs[page_number],
+ Resources=PdfParser.PdfDict(
+ ProcSet=[PdfParser.PdfName("PDF"), PdfParser.PdfName(procset)],
+ XObject=PdfParser.PdfDict(image=image_ref),
+ ),
+ MediaBox=[
+ 0,
+ 0,
+ im.width * 72.0 / x_resolution,
+ im.height * 72.0 / y_resolution,
+ ],
+ Contents=contents_refs[page_number],
+ )
+
+ #
+ # page contents
+
+ page_contents = b"q %f 0 0 %f 0 0 cm /image Do Q\n" % (
+ im.width * 72.0 / x_resolution,
+ im.height * 72.0 / y_resolution,
+ )
+
+ existing_pdf.write_obj(contents_refs[page_number], stream=page_contents)
+
+ page_number += 1
+
+ #
+ # trailer
+ existing_pdf.write_xref_and_trailer()
+ if hasattr(fp, "flush"):
+ fp.flush()
+ existing_pdf.close()
+
+
+#
+# --------------------------------------------------------------------
+
+
+Image.register_save("PDF", _save)
+Image.register_save_all("PDF", _save_all)
+
+Image.register_extension("PDF", ".pdf")
+
+Image.register_mime("PDF", "application/pdf")
diff --git a/venv/Lib/site-packages/PIL/PdfParser.py b/venv/Lib/site-packages/PIL/PdfParser.py
new file mode 100644
index 0000000..2c90314
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PdfParser.py
@@ -0,0 +1,1075 @@
+from __future__ import annotations
+
+import calendar
+import codecs
+import collections
+import mmap
+import os
+import re
+import time
+import zlib
+from typing import Any, NamedTuple
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from typing import IO
+
+ _DictBase = collections.UserDict[str | bytes, Any]
+else:
+ _DictBase = collections.UserDict
+
+
+# see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set
+# on page 656
+def encode_text(s: str) -> bytes:
+ return codecs.BOM_UTF16_BE + s.encode("utf_16_be")
+
+
+PDFDocEncoding = {
+ 0x16: "\u0017",
+ 0x18: "\u02d8",
+ 0x19: "\u02c7",
+ 0x1A: "\u02c6",
+ 0x1B: "\u02d9",
+ 0x1C: "\u02dd",
+ 0x1D: "\u02db",
+ 0x1E: "\u02da",
+ 0x1F: "\u02dc",
+ 0x80: "\u2022",
+ 0x81: "\u2020",
+ 0x82: "\u2021",
+ 0x83: "\u2026",
+ 0x84: "\u2014",
+ 0x85: "\u2013",
+ 0x86: "\u0192",
+ 0x87: "\u2044",
+ 0x88: "\u2039",
+ 0x89: "\u203a",
+ 0x8A: "\u2212",
+ 0x8B: "\u2030",
+ 0x8C: "\u201e",
+ 0x8D: "\u201c",
+ 0x8E: "\u201d",
+ 0x8F: "\u2018",
+ 0x90: "\u2019",
+ 0x91: "\u201a",
+ 0x92: "\u2122",
+ 0x93: "\ufb01",
+ 0x94: "\ufb02",
+ 0x95: "\u0141",
+ 0x96: "\u0152",
+ 0x97: "\u0160",
+ 0x98: "\u0178",
+ 0x99: "\u017d",
+ 0x9A: "\u0131",
+ 0x9B: "\u0142",
+ 0x9C: "\u0153",
+ 0x9D: "\u0161",
+ 0x9E: "\u017e",
+ 0xA0: "\u20ac",
+}
+
+
+def decode_text(b: bytes) -> str:
+ if b[: len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE:
+ return b[len(codecs.BOM_UTF16_BE) :].decode("utf_16_be")
+ else:
+ return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b)
+
+
+class PdfFormatError(RuntimeError):
+ """An error that probably indicates a syntactic or semantic error in the
+ PDF file structure"""
+
+ pass
+
+
+def check_format_condition(condition: bool, error_message: str) -> None:
+ if not condition:
+ raise PdfFormatError(error_message)
+
+
+class IndirectReferenceTuple(NamedTuple):
+ object_id: int
+ generation: int
+
+
+class IndirectReference(IndirectReferenceTuple):
+ def __str__(self) -> str:
+ return f"{self.object_id} {self.generation} R"
+
+ def __bytes__(self) -> bytes:
+ return self.__str__().encode("us-ascii")
+
+ def __eq__(self, other: object) -> bool:
+ if self.__class__ is not other.__class__:
+ return False
+ assert isinstance(other, IndirectReference)
+ return other.object_id == self.object_id and other.generation == self.generation
+
+ def __ne__(self, other: object) -> bool:
+ return not (self == other)
+
+ def __hash__(self) -> int:
+ return hash((self.object_id, self.generation))
+
+
+class IndirectObjectDef(IndirectReference):
+ def __str__(self) -> str:
+ return f"{self.object_id} {self.generation} obj"
+
+
+class XrefTable:
+ def __init__(self) -> None:
+ self.existing_entries: dict[int, tuple[int, int]] = (
+ {}
+ ) # object ID => (offset, generation)
+ self.new_entries: dict[int, tuple[int, int]] = (
+ {}
+ ) # object ID => (offset, generation)
+ self.deleted_entries = {0: 65536} # object ID => generation
+ self.reading_finished = False
+
+ def __setitem__(self, key: int, value: tuple[int, int]) -> None:
+ if self.reading_finished:
+ self.new_entries[key] = value
+ else:
+ self.existing_entries[key] = value
+ if key in self.deleted_entries:
+ del self.deleted_entries[key]
+
+ def __getitem__(self, key: int) -> tuple[int, int]:
+ try:
+ return self.new_entries[key]
+ except KeyError:
+ return self.existing_entries[key]
+
+ def __delitem__(self, key: int) -> None:
+ if key in self.new_entries:
+ generation = self.new_entries[key][1] + 1
+ del self.new_entries[key]
+ self.deleted_entries[key] = generation
+ elif key in self.existing_entries:
+ generation = self.existing_entries[key][1] + 1
+ self.deleted_entries[key] = generation
+ elif key in self.deleted_entries:
+ generation = self.deleted_entries[key]
+ else:
+ msg = f"object ID {key} cannot be deleted because it doesn't exist"
+ raise IndexError(msg)
+
+ def __contains__(self, key: int) -> bool:
+ return key in self.existing_entries or key in self.new_entries
+
+ def __len__(self) -> int:
+ return len(
+ set(self.existing_entries.keys())
+ | set(self.new_entries.keys())
+ | set(self.deleted_entries.keys())
+ )
+
+ def keys(self) -> set[int]:
+ return (
+ set(self.existing_entries.keys()) - set(self.deleted_entries.keys())
+ ) | set(self.new_entries.keys())
+
+ def write(self, f: IO[bytes]) -> int:
+ keys = sorted(set(self.new_entries.keys()) | set(self.deleted_entries.keys()))
+ deleted_keys = sorted(set(self.deleted_entries.keys()))
+ startxref = f.tell()
+ f.write(b"xref\n")
+ while keys:
+ # find a contiguous sequence of object IDs
+ prev: int | None = None
+ for index, key in enumerate(keys):
+ if prev is None or prev + 1 == key:
+ prev = key
+ else:
+ contiguous_keys = keys[:index]
+ keys = keys[index:]
+ break
+ else:
+ contiguous_keys = keys
+ keys = []
+ f.write(b"%d %d\n" % (contiguous_keys[0], len(contiguous_keys)))
+ for object_id in contiguous_keys:
+ if object_id in self.new_entries:
+ f.write(b"%010d %05d n \n" % self.new_entries[object_id])
+ else:
+ this_deleted_object_id = deleted_keys.pop(0)
+ check_format_condition(
+ object_id == this_deleted_object_id,
+ f"expected the next deleted object ID to be {object_id}, "
+ f"instead found {this_deleted_object_id}",
+ )
+ try:
+ next_in_linked_list = deleted_keys[0]
+ except IndexError:
+ next_in_linked_list = 0
+ f.write(
+ b"%010d %05d f \n"
+ % (next_in_linked_list, self.deleted_entries[object_id])
+ )
+ return startxref
+
+
+class PdfName:
+ name: bytes
+
+ def __init__(self, name: PdfName | bytes | str) -> None:
+ if isinstance(name, PdfName):
+ self.name = name.name
+ elif isinstance(name, bytes):
+ self.name = name
+ else:
+ self.name = name.encode("us-ascii")
+
+ def name_as_str(self) -> str:
+ return self.name.decode("us-ascii")
+
+ def __eq__(self, other: object) -> bool:
+ return (
+ isinstance(other, PdfName) and other.name == self.name
+ ) or other == self.name
+
+ def __hash__(self) -> int:
+ return hash(self.name)
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}({repr(self.name)})"
+
+ @classmethod
+ def from_pdf_stream(cls, data: bytes) -> PdfName:
+ return cls(PdfParser.interpret_name(data))
+
+ allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"}
+
+ def __bytes__(self) -> bytes:
+ result = bytearray(b"/")
+ for b in self.name:
+ if b in self.allowed_chars:
+ result.append(b)
+ else:
+ result.extend(b"#%02X" % b)
+ return bytes(result)
+
+
+class PdfArray(list[Any]):
+ def __bytes__(self) -> bytes:
+ return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]"
+
+
+class PdfDict(_DictBase):
+ def __setattr__(self, key: str, value: Any) -> None:
+ if key == "data":
+ collections.UserDict.__setattr__(self, key, value)
+ else:
+ self[key.encode("us-ascii")] = value
+
+ def __getattr__(self, key: str) -> str | time.struct_time:
+ try:
+ value = self[key.encode("us-ascii")]
+ except KeyError as e:
+ raise AttributeError(key) from e
+ if isinstance(value, bytes):
+ value = decode_text(value)
+ if key.endswith("Date"):
+ if value.startswith("D:"):
+ value = value[2:]
+
+ relationship = "Z"
+ if len(value) > 17:
+ relationship = value[14]
+ offset = int(value[15:17]) * 60
+ if len(value) > 20:
+ offset += int(value[18:20])
+
+ format = "%Y%m%d%H%M%S"[: len(value) - 2]
+ value = time.strptime(value[: len(format) + 2], format)
+ if relationship in ["+", "-"]:
+ offset *= 60
+ if relationship == "+":
+ offset *= -1
+ value = time.gmtime(calendar.timegm(value) + offset)
+ return value
+
+ def __bytes__(self) -> bytes:
+ out = bytearray(b"<<")
+ for key, value in self.items():
+ if value is None:
+ continue
+ value = pdf_repr(value)
+ out.extend(b"\n")
+ out.extend(bytes(PdfName(key)))
+ out.extend(b" ")
+ out.extend(value)
+ out.extend(b"\n>>")
+ return bytes(out)
+
+
+class PdfBinary:
+ def __init__(self, data: list[int] | bytes) -> None:
+ self.data = data
+
+ def __bytes__(self) -> bytes:
+ return b"<%s>" % b"".join(b"%02X" % b for b in self.data)
+
+
+class PdfStream:
+ def __init__(self, dictionary: PdfDict, buf: bytes) -> None:
+ self.dictionary = dictionary
+ self.buf = buf
+
+ def decode(self) -> bytes:
+ try:
+ filter = self.dictionary[b"Filter"]
+ except KeyError:
+ return self.buf
+ if filter == b"FlateDecode":
+ try:
+ expected_length = self.dictionary[b"DL"]
+ except KeyError:
+ expected_length = self.dictionary[b"Length"]
+ return zlib.decompress(self.buf, bufsize=int(expected_length))
+ else:
+ msg = f"stream filter {repr(filter)} unknown/unsupported"
+ raise NotImplementedError(msg)
+
+
+def pdf_repr(x: Any) -> bytes:
+ if x is True:
+ return b"true"
+ elif x is False:
+ return b"false"
+ elif x is None:
+ return b"null"
+ elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)):
+ return bytes(x)
+ elif isinstance(x, (int, float)):
+ return str(x).encode("us-ascii")
+ elif isinstance(x, time.struct_time):
+ return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")"
+ elif isinstance(x, dict):
+ return bytes(PdfDict(x))
+ elif isinstance(x, list):
+ return bytes(PdfArray(x))
+ elif isinstance(x, str):
+ return pdf_repr(encode_text(x))
+ elif isinstance(x, bytes):
+ # XXX escape more chars? handle binary garbage
+ x = x.replace(b"\\", b"\\\\")
+ x = x.replace(b"(", b"\\(")
+ x = x.replace(b")", b"\\)")
+ return b"(" + x + b")"
+ else:
+ return bytes(x)
+
+
+class PdfParser:
+ """Based on
+ https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
+ Supports PDF up to 1.4
+ """
+
+ def __init__(
+ self,
+ filename: str | None = None,
+ f: IO[bytes] | None = None,
+ buf: bytes | bytearray | None = None,
+ start_offset: int = 0,
+ mode: str = "rb",
+ ) -> None:
+ if buf and f:
+ msg = "specify buf or f or filename, but not both buf and f"
+ raise RuntimeError(msg)
+ self.filename = filename
+ self.buf: bytes | bytearray | mmap.mmap | None = buf
+ self.f = f
+ self.start_offset = start_offset
+ self.should_close_buf = False
+ self.should_close_file = False
+ if filename is not None and f is None:
+ self.f = f = open(filename, mode)
+ self.should_close_file = True
+ if f is not None:
+ self.buf = self.get_buf_from_file(f)
+ self.should_close_buf = True
+ if not filename and hasattr(f, "name"):
+ self.filename = f.name
+ self.cached_objects: dict[IndirectReference, Any] = {}
+ self.root_ref: IndirectReference | None
+ self.info_ref: IndirectReference | None
+ self.pages_ref: IndirectReference | None
+ self.last_xref_section_offset: int | None
+ if self.buf:
+ self.read_pdf_info()
+ else:
+ self.file_size_total = self.file_size_this = 0
+ self.root = PdfDict()
+ self.root_ref = None
+ self.info = PdfDict()
+ self.info_ref = None
+ self.page_tree_root = PdfDict()
+ self.pages: list[IndirectReference] = []
+ self.orig_pages: list[IndirectReference] = []
+ self.pages_ref = None
+ self.last_xref_section_offset = None
+ self.trailer_dict: dict[bytes, Any] = {}
+ self.xref_table = XrefTable()
+ self.xref_table.reading_finished = True
+ if f:
+ self.seek_end()
+
+ def __enter__(self) -> PdfParser:
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ self.close()
+
+ def start_writing(self) -> None:
+ self.close_buf()
+ self.seek_end()
+
+ def close_buf(self) -> None:
+ if isinstance(self.buf, mmap.mmap):
+ self.buf.close()
+ self.buf = None
+
+ def close(self) -> None:
+ if self.should_close_buf:
+ self.close_buf()
+ if self.f is not None and self.should_close_file:
+ self.f.close()
+ self.f = None
+
+ def seek_end(self) -> None:
+ assert self.f is not None
+ self.f.seek(0, os.SEEK_END)
+
+ def write_header(self) -> None:
+ assert self.f is not None
+ self.f.write(b"%PDF-1.4\n")
+
+ def write_comment(self, s: str) -> None:
+ assert self.f is not None
+ self.f.write(f"% {s}\n".encode())
+
+ def write_catalog(self) -> IndirectReference:
+ assert self.f is not None
+ self.del_root()
+ self.root_ref = self.next_object_id(self.f.tell())
+ self.pages_ref = self.next_object_id(0)
+ self.rewrite_pages()
+ self.write_obj(self.root_ref, Type=PdfName(b"Catalog"), Pages=self.pages_ref)
+ self.write_obj(
+ self.pages_ref,
+ Type=PdfName(b"Pages"),
+ Count=len(self.pages),
+ Kids=self.pages,
+ )
+ return self.root_ref
+
+ def rewrite_pages(self) -> None:
+ pages_tree_nodes_to_delete = []
+ for i, page_ref in enumerate(self.orig_pages):
+ page_info = self.cached_objects[page_ref]
+ del self.xref_table[page_ref.object_id]
+ pages_tree_nodes_to_delete.append(page_info[PdfName(b"Parent")])
+ if page_ref not in self.pages:
+ # the page has been deleted
+ continue
+ # make dict keys into strings for passing to write_page
+ stringified_page_info = {}
+ for key, value in page_info.items():
+ # key should be a PdfName
+ stringified_page_info[key.name_as_str()] = value
+ stringified_page_info["Parent"] = self.pages_ref
+ new_page_ref = self.write_page(None, **stringified_page_info)
+ for j, cur_page_ref in enumerate(self.pages):
+ if cur_page_ref == page_ref:
+ # replace the page reference with the new one
+ self.pages[j] = new_page_ref
+ # delete redundant Pages tree nodes from xref table
+ for pages_tree_node_ref in pages_tree_nodes_to_delete:
+ while pages_tree_node_ref:
+ pages_tree_node = self.cached_objects[pages_tree_node_ref]
+ if pages_tree_node_ref.object_id in self.xref_table:
+ del self.xref_table[pages_tree_node_ref.object_id]
+ pages_tree_node_ref = pages_tree_node.get(b"Parent", None)
+ self.orig_pages = []
+
+ def write_xref_and_trailer(
+ self, new_root_ref: IndirectReference | None = None
+ ) -> None:
+ assert self.f is not None
+ if new_root_ref:
+ self.del_root()
+ self.root_ref = new_root_ref
+ if self.info:
+ self.info_ref = self.write_obj(None, self.info)
+ start_xref = self.xref_table.write(self.f)
+ num_entries = len(self.xref_table)
+ trailer_dict: dict[str | bytes, Any] = {
+ b"Root": self.root_ref,
+ b"Size": num_entries,
+ }
+ if self.last_xref_section_offset is not None:
+ trailer_dict[b"Prev"] = self.last_xref_section_offset
+ if self.info:
+ trailer_dict[b"Info"] = self.info_ref
+ self.last_xref_section_offset = start_xref
+ self.f.write(
+ b"trailer\n"
+ + bytes(PdfDict(trailer_dict))
+ + b"\nstartxref\n%d\n%%%%EOF" % start_xref
+ )
+
+ def write_page(
+ self, ref: int | IndirectReference | None, *objs: Any, **dict_obj: Any
+ ) -> IndirectReference:
+ obj_ref = self.pages[ref] if isinstance(ref, int) else ref
+ if "Type" not in dict_obj:
+ dict_obj["Type"] = PdfName(b"Page")
+ if "Parent" not in dict_obj:
+ dict_obj["Parent"] = self.pages_ref
+ return self.write_obj(obj_ref, *objs, **dict_obj)
+
+ def write_obj(
+ self, ref: IndirectReference | None, *objs: Any, **dict_obj: Any
+ ) -> IndirectReference:
+ assert self.f is not None
+ f = self.f
+ if ref is None:
+ ref = self.next_object_id(f.tell())
+ else:
+ self.xref_table[ref.object_id] = (f.tell(), ref.generation)
+ f.write(bytes(IndirectObjectDef(*ref)))
+ stream = dict_obj.pop("stream", None)
+ if stream is not None:
+ dict_obj["Length"] = len(stream)
+ if dict_obj:
+ f.write(pdf_repr(dict_obj))
+ for obj in objs:
+ f.write(pdf_repr(obj))
+ if stream is not None:
+ f.write(b"stream\n")
+ f.write(stream)
+ f.write(b"\nendstream\n")
+ f.write(b"endobj\n")
+ return ref
+
+ def del_root(self) -> None:
+ if self.root_ref is None:
+ return
+ del self.xref_table[self.root_ref.object_id]
+ del self.xref_table[self.root[b"Pages"].object_id]
+
+ @staticmethod
+ def get_buf_from_file(f: IO[bytes]) -> bytes | mmap.mmap:
+ if hasattr(f, "getbuffer"):
+ return f.getbuffer()
+ elif hasattr(f, "getvalue"):
+ return f.getvalue()
+ else:
+ try:
+ return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
+ except ValueError: # cannot mmap an empty file
+ return b""
+
+ def read_pdf_info(self) -> None:
+ assert self.buf is not None
+ self.file_size_total = len(self.buf)
+ self.file_size_this = self.file_size_total - self.start_offset
+ self.read_trailer()
+ check_format_condition(
+ self.trailer_dict.get(b"Root") is not None, "Root is missing"
+ )
+ self.root_ref = self.trailer_dict[b"Root"]
+ assert self.root_ref is not None
+ self.info_ref = self.trailer_dict.get(b"Info", None)
+ self.root = PdfDict(self.read_indirect(self.root_ref))
+ if self.info_ref is None:
+ self.info = PdfDict()
+ else:
+ self.info = PdfDict(self.read_indirect(self.info_ref))
+ check_format_condition(b"Type" in self.root, "/Type missing in Root")
+ check_format_condition(
+ self.root[b"Type"] == b"Catalog", "/Type in Root is not /Catalog"
+ )
+ check_format_condition(
+ self.root.get(b"Pages") is not None, "/Pages missing in Root"
+ )
+ check_format_condition(
+ isinstance(self.root[b"Pages"], IndirectReference),
+ "/Pages in Root is not an indirect reference",
+ )
+ self.pages_ref = self.root[b"Pages"]
+ assert self.pages_ref is not None
+ self.page_tree_root = self.read_indirect(self.pages_ref)
+ self.pages = self.linearize_page_tree(self.page_tree_root)
+ # save the original list of page references
+ # in case the user modifies, adds or deletes some pages
+ # and we need to rewrite the pages and their list
+ self.orig_pages = self.pages[:]
+
+ def next_object_id(self, offset: int | None = None) -> IndirectReference:
+ try:
+ # TODO: support reuse of deleted objects
+ reference = IndirectReference(max(self.xref_table.keys()) + 1, 0)
+ except ValueError:
+ reference = IndirectReference(1, 0)
+ if offset is not None:
+ self.xref_table[reference.object_id] = (offset, 0)
+ return reference
+
+ delimiter = rb"[][()<>{}/%]"
+ delimiter_or_ws = rb"[][()<>{}/%\000\011\012\014\015\040]"
+ whitespace = rb"[\000\011\012\014\015\040]"
+ whitespace_or_hex = rb"[\000\011\012\014\015\0400-9a-fA-F]"
+ whitespace_optional = whitespace + b"*"
+ whitespace_mandatory = whitespace + b"+"
+ # No "\012" aka "\n" or "\015" aka "\r":
+ whitespace_optional_no_nl = rb"[\000\011\014\040]*"
+ newline_only = rb"[\r\n]+"
+ newline = whitespace_optional_no_nl + newline_only + whitespace_optional_no_nl
+ re_trailer_end = re.compile(
+ whitespace_mandatory
+ + rb"trailer"
+ + whitespace_optional
+ + rb"<<(.*>>)"
+ + newline
+ + rb"startxref"
+ + newline
+ + rb"([0-9]+)"
+ + newline
+ + rb"%%EOF"
+ + whitespace_optional
+ + rb"$",
+ re.DOTALL,
+ )
+ re_trailer_prev = re.compile(
+ whitespace_optional
+ + rb"trailer"
+ + whitespace_optional
+ + rb"<<(.*?>>)"
+ + newline
+ + rb"startxref"
+ + newline
+ + rb"([0-9]+)"
+ + newline
+ + rb"%%EOF"
+ + whitespace_optional,
+ re.DOTALL,
+ )
+
+ def read_trailer(self) -> None:
+ assert self.buf is not None
+ search_start_offset = len(self.buf) - 16384
+ if search_start_offset < self.start_offset:
+ search_start_offset = self.start_offset
+ m = self.re_trailer_end.search(self.buf, search_start_offset)
+ check_format_condition(m is not None, "trailer end not found")
+ # make sure we found the LAST trailer
+ last_match = m
+ while m:
+ last_match = m
+ m = self.re_trailer_end.search(self.buf, m.start() + 16)
+ if not m:
+ m = last_match
+ assert m is not None
+ trailer_data = m.group(1)
+ self.last_xref_section_offset = int(m.group(2))
+ self.trailer_dict = self.interpret_trailer(trailer_data)
+ self.xref_table = XrefTable()
+ self.read_xref_table(xref_section_offset=self.last_xref_section_offset)
+ if b"Prev" in self.trailer_dict:
+ self.read_prev_trailer(self.trailer_dict[b"Prev"])
+
+ def read_prev_trailer(self, xref_section_offset: int) -> None:
+ assert self.buf is not None
+ trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset)
+ m = self.re_trailer_prev.search(
+ self.buf[trailer_offset : trailer_offset + 16384]
+ )
+ check_format_condition(m is not None, "previous trailer not found")
+ assert m is not None
+ trailer_data = m.group(1)
+ check_format_condition(
+ int(m.group(2)) == xref_section_offset,
+ "xref section offset in previous trailer doesn't match what was expected",
+ )
+ trailer_dict = self.interpret_trailer(trailer_data)
+ if b"Prev" in trailer_dict:
+ self.read_prev_trailer(trailer_dict[b"Prev"])
+
+ re_whitespace_optional = re.compile(whitespace_optional)
+ re_name = re.compile(
+ whitespace_optional
+ + rb"/([!-$&'*-.0-;=?-Z\\^-z|~]+)(?="
+ + delimiter_or_ws
+ + rb")"
+ )
+ re_dict_start = re.compile(whitespace_optional + rb"<<")
+ re_dict_end = re.compile(whitespace_optional + rb">>" + whitespace_optional)
+
+ @classmethod
+ def interpret_trailer(cls, trailer_data: bytes) -> dict[bytes, Any]:
+ trailer = {}
+ offset = 0
+ while True:
+ m = cls.re_name.match(trailer_data, offset)
+ if not m:
+ m = cls.re_dict_end.match(trailer_data, offset)
+ check_format_condition(
+ m is not None and m.end() == len(trailer_data),
+ "name not found in trailer, remaining data: "
+ + repr(trailer_data[offset:]),
+ )
+ break
+ key = cls.interpret_name(m.group(1))
+ assert isinstance(key, bytes)
+ value, value_offset = cls.get_value(trailer_data, m.end())
+ trailer[key] = value
+ if value_offset is None:
+ break
+ offset = value_offset
+ check_format_condition(
+ b"Size" in trailer and isinstance(trailer[b"Size"], int),
+ "/Size not in trailer or not an integer",
+ )
+ check_format_condition(
+ b"Root" in trailer and isinstance(trailer[b"Root"], IndirectReference),
+ "/Root not in trailer or not an indirect reference",
+ )
+ return trailer
+
+ re_hashes_in_name = re.compile(rb"([^#]*)(#([0-9a-fA-F]{2}))?")
+
+ @classmethod
+ def interpret_name(cls, raw: bytes, as_text: bool = False) -> str | bytes:
+ name = b""
+ for m in cls.re_hashes_in_name.finditer(raw):
+ if m.group(3):
+ name += m.group(1) + bytearray.fromhex(m.group(3).decode("us-ascii"))
+ else:
+ name += m.group(1)
+ if as_text:
+ return name.decode("utf-8")
+ else:
+ return bytes(name)
+
+ re_null = re.compile(whitespace_optional + rb"null(?=" + delimiter_or_ws + rb")")
+ re_true = re.compile(whitespace_optional + rb"true(?=" + delimiter_or_ws + rb")")
+ re_false = re.compile(whitespace_optional + rb"false(?=" + delimiter_or_ws + rb")")
+ re_int = re.compile(
+ whitespace_optional + rb"([-+]?[0-9]+)(?=" + delimiter_or_ws + rb")"
+ )
+ re_real = re.compile(
+ whitespace_optional
+ + rb"([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+))(?="
+ + delimiter_or_ws
+ + rb")"
+ )
+ re_array_start = re.compile(whitespace_optional + rb"\[")
+ re_array_end = re.compile(whitespace_optional + rb"]")
+ re_string_hex = re.compile(
+ whitespace_optional + rb"<(" + whitespace_or_hex + rb"*)>"
+ )
+ re_string_lit = re.compile(whitespace_optional + rb"\(")
+ re_indirect_reference = re.compile(
+ whitespace_optional
+ + rb"([-+]?[0-9]+)"
+ + whitespace_mandatory
+ + rb"([-+]?[0-9]+)"
+ + whitespace_mandatory
+ + rb"R(?="
+ + delimiter_or_ws
+ + rb")"
+ )
+ re_indirect_def_start = re.compile(
+ whitespace_optional
+ + rb"([-+]?[0-9]+)"
+ + whitespace_mandatory
+ + rb"([-+]?[0-9]+)"
+ + whitespace_mandatory
+ + rb"obj(?="
+ + delimiter_or_ws
+ + rb")"
+ )
+ re_indirect_def_end = re.compile(
+ whitespace_optional + rb"endobj(?=" + delimiter_or_ws + rb")"
+ )
+ re_comment = re.compile(
+ rb"(" + whitespace_optional + rb"%[^\r\n]*" + newline + rb")*"
+ )
+ re_stream_start = re.compile(whitespace_optional + rb"stream\r?\n")
+ re_stream_end = re.compile(
+ whitespace_optional + rb"endstream(?=" + delimiter_or_ws + rb")"
+ )
+
+ @classmethod
+ def get_value(
+ cls,
+ data: bytes | bytearray | mmap.mmap,
+ offset: int,
+ expect_indirect: IndirectReference | None = None,
+ max_nesting: int = -1,
+ ) -> tuple[Any, int | None]:
+ if max_nesting == 0:
+ return None, None
+ m = cls.re_comment.match(data, offset)
+ if m:
+ offset = m.end()
+ m = cls.re_indirect_def_start.match(data, offset)
+ if m:
+ check_format_condition(
+ int(m.group(1)) > 0,
+ "indirect object definition: object ID must be greater than 0",
+ )
+ check_format_condition(
+ int(m.group(2)) >= 0,
+ "indirect object definition: generation must be non-negative",
+ )
+ check_format_condition(
+ expect_indirect is None
+ or expect_indirect
+ == IndirectReference(int(m.group(1)), int(m.group(2))),
+ "indirect object definition different than expected",
+ )
+ object, object_offset = cls.get_value(
+ data, m.end(), max_nesting=max_nesting - 1
+ )
+ if object_offset is None:
+ return object, None
+ m = cls.re_indirect_def_end.match(data, object_offset)
+ check_format_condition(
+ m is not None, "indirect object definition end not found"
+ )
+ assert m is not None
+ return object, m.end()
+ check_format_condition(
+ not expect_indirect, "indirect object definition not found"
+ )
+ m = cls.re_indirect_reference.match(data, offset)
+ if m:
+ check_format_condition(
+ int(m.group(1)) > 0,
+ "indirect object reference: object ID must be greater than 0",
+ )
+ check_format_condition(
+ int(m.group(2)) >= 0,
+ "indirect object reference: generation must be non-negative",
+ )
+ return IndirectReference(int(m.group(1)), int(m.group(2))), m.end()
+ m = cls.re_dict_start.match(data, offset)
+ if m:
+ offset = m.end()
+ result: dict[Any, Any] = {}
+ m = cls.re_dict_end.match(data, offset)
+ current_offset: int | None = offset
+ while not m:
+ assert current_offset is not None
+ key, current_offset = cls.get_value(
+ data, current_offset, max_nesting=max_nesting - 1
+ )
+ if current_offset is None:
+ return result, None
+ value, current_offset = cls.get_value(
+ data, current_offset, max_nesting=max_nesting - 1
+ )
+ result[key] = value
+ if current_offset is None:
+ return result, None
+ m = cls.re_dict_end.match(data, current_offset)
+ current_offset = m.end()
+ m = cls.re_stream_start.match(data, current_offset)
+ if m:
+ stream_len = result.get(b"Length")
+ if stream_len is None or not isinstance(stream_len, int):
+ msg = f"bad or missing Length in stream dict ({stream_len})"
+ raise PdfFormatError(msg)
+ stream_data = data[m.end() : m.end() + stream_len]
+ m = cls.re_stream_end.match(data, m.end() + stream_len)
+ check_format_condition(m is not None, "stream end not found")
+ assert m is not None
+ current_offset = m.end()
+ return PdfStream(PdfDict(result), stream_data), current_offset
+ return PdfDict(result), current_offset
+ m = cls.re_array_start.match(data, offset)
+ if m:
+ offset = m.end()
+ results = []
+ m = cls.re_array_end.match(data, offset)
+ current_offset = offset
+ while not m:
+ assert current_offset is not None
+ value, current_offset = cls.get_value(
+ data, current_offset, max_nesting=max_nesting - 1
+ )
+ results.append(value)
+ if current_offset is None:
+ return results, None
+ m = cls.re_array_end.match(data, current_offset)
+ return results, m.end()
+ m = cls.re_null.match(data, offset)
+ if m:
+ return None, m.end()
+ m = cls.re_true.match(data, offset)
+ if m:
+ return True, m.end()
+ m = cls.re_false.match(data, offset)
+ if m:
+ return False, m.end()
+ m = cls.re_name.match(data, offset)
+ if m:
+ return PdfName(cls.interpret_name(m.group(1))), m.end()
+ m = cls.re_int.match(data, offset)
+ if m:
+ return int(m.group(1)), m.end()
+ m = cls.re_real.match(data, offset)
+ if m:
+ # XXX Decimal instead of float???
+ return float(m.group(1)), m.end()
+ m = cls.re_string_hex.match(data, offset)
+ if m:
+ # filter out whitespace
+ hex_string = bytearray(
+ b for b in m.group(1) if b in b"0123456789abcdefABCDEF"
+ )
+ if len(hex_string) % 2 == 1:
+ # append a 0 if the length is not even - yes, at the end
+ hex_string.append(ord(b"0"))
+ return bytearray.fromhex(hex_string.decode("us-ascii")), m.end()
+ m = cls.re_string_lit.match(data, offset)
+ if m:
+ return cls.get_literal_string(data, m.end())
+ # return None, offset # fallback (only for debugging)
+ msg = f"unrecognized object: {repr(data[offset : offset + 32])}"
+ raise PdfFormatError(msg)
+
+ re_lit_str_token = re.compile(
+ rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))"
+ )
+ escaped_chars = {
+ b"n": b"\n",
+ b"r": b"\r",
+ b"t": b"\t",
+ b"b": b"\b",
+ b"f": b"\f",
+ b"(": b"(",
+ b")": b")",
+ b"\\": b"\\",
+ ord(b"n"): b"\n",
+ ord(b"r"): b"\r",
+ ord(b"t"): b"\t",
+ ord(b"b"): b"\b",
+ ord(b"f"): b"\f",
+ ord(b"("): b"(",
+ ord(b")"): b")",
+ ord(b"\\"): b"\\",
+ }
+
+ @classmethod
+ def get_literal_string(
+ cls, data: bytes | bytearray | mmap.mmap, offset: int
+ ) -> tuple[bytes, int]:
+ nesting_depth = 0
+ result = bytearray()
+ for m in cls.re_lit_str_token.finditer(data, offset):
+ result.extend(data[offset : m.start()])
+ if m.group(1):
+ result.extend(cls.escaped_chars[m.group(1)[1]])
+ elif m.group(2):
+ result.append(int(m.group(2)[1:], 8))
+ elif m.group(3):
+ pass
+ elif m.group(5):
+ result.extend(b"\n")
+ elif m.group(6):
+ result.extend(b"(")
+ nesting_depth += 1
+ elif m.group(7):
+ if nesting_depth == 0:
+ return bytes(result), m.end()
+ result.extend(b")")
+ nesting_depth -= 1
+ offset = m.end()
+ msg = "unfinished literal string"
+ raise PdfFormatError(msg)
+
+ re_xref_section_start = re.compile(whitespace_optional + rb"xref" + newline)
+ re_xref_subsection_start = re.compile(
+ whitespace_optional
+ + rb"([0-9]+)"
+ + whitespace_mandatory
+ + rb"([0-9]+)"
+ + whitespace_optional
+ + newline_only
+ )
+ re_xref_entry = re.compile(rb"([0-9]{10}) ([0-9]{5}) ([fn])( \r| \n|\r\n)")
+
+ def read_xref_table(self, xref_section_offset: int) -> int:
+ assert self.buf is not None
+ subsection_found = False
+ m = self.re_xref_section_start.match(
+ self.buf, xref_section_offset + self.start_offset
+ )
+ check_format_condition(m is not None, "xref section start not found")
+ assert m is not None
+ offset = m.end()
+ while True:
+ m = self.re_xref_subsection_start.match(self.buf, offset)
+ if not m:
+ check_format_condition(
+ subsection_found, "xref subsection start not found"
+ )
+ break
+ subsection_found = True
+ offset = m.end()
+ first_object = int(m.group(1))
+ num_objects = int(m.group(2))
+ for i in range(first_object, first_object + num_objects):
+ m = self.re_xref_entry.match(self.buf, offset)
+ check_format_condition(m is not None, "xref entry not found")
+ assert m is not None
+ offset = m.end()
+ is_free = m.group(3) == b"f"
+ if not is_free:
+ generation = int(m.group(2))
+ new_entry = (int(m.group(1)), generation)
+ if i not in self.xref_table:
+ self.xref_table[i] = new_entry
+ return offset
+
+ def read_indirect(self, ref: IndirectReference, max_nesting: int = -1) -> Any:
+ offset, generation = self.xref_table[ref[0]]
+ check_format_condition(
+ generation == ref[1],
+ f"expected to find generation {ref[1]} for object ID {ref[0]} in xref "
+ f"table, instead found generation {generation} at offset {offset}",
+ )
+ assert self.buf is not None
+ value = self.get_value(
+ self.buf,
+ offset + self.start_offset,
+ expect_indirect=IndirectReference(*ref),
+ max_nesting=max_nesting,
+ )[0]
+ self.cached_objects[ref] = value
+ return value
+
+ def linearize_page_tree(
+ self, node: PdfDict | None = None
+ ) -> list[IndirectReference]:
+ page_node = node if node is not None else self.page_tree_root
+ check_format_condition(
+ page_node[b"Type"] == b"Pages", "/Type of page tree node is not /Pages"
+ )
+ pages = []
+ for kid in page_node[b"Kids"]:
+ kid_object = self.read_indirect(kid)
+ if kid_object[b"Type"] == b"Page":
+ pages.append(kid)
+ else:
+ pages.extend(self.linearize_page_tree(node=kid_object))
+ return pages
diff --git a/venv/Lib/site-packages/PIL/PixarImagePlugin.py b/venv/Lib/site-packages/PIL/PixarImagePlugin.py
new file mode 100644
index 0000000..d2b6d0a
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PixarImagePlugin.py
@@ -0,0 +1,72 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# PIXAR raster support for PIL
+#
+# history:
+# 97-01-29 fl Created
+#
+# notes:
+# This is incomplete; it is based on a few samples created with
+# Photoshop 2.5 and 3.0, and a summary description provided by
+# Greg Coats . Hopefully, "L" and
+# "RGBA" support will be added in future versions.
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1997.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from . import Image, ImageFile
+from ._binary import i16le as i16
+
+#
+# helpers
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(b"\200\350\000\000")
+
+
+##
+# Image plugin for PIXAR raster images.
+
+
+class PixarImageFile(ImageFile.ImageFile):
+ format = "PIXAR"
+ format_description = "PIXAR raster image"
+
+ def _open(self) -> None:
+ # assuming a 4-byte magic label
+ assert self.fp is not None
+
+ s = self.fp.read(4)
+ if not _accept(s):
+ msg = "not a PIXAR file"
+ raise SyntaxError(msg)
+
+ # read rest of header
+ s = s + self.fp.read(508)
+
+ self._size = i16(s, 418), i16(s, 416)
+
+ # get channel/depth descriptions
+ mode = i16(s, 424), i16(s, 426)
+
+ if mode == (14, 2):
+ self._mode = "RGB"
+ # FIXME: to be continued...
+
+ # create tile descriptor (assuming "dumped")
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 1024, self.mode)]
+
+
+#
+# --------------------------------------------------------------------
+
+Image.register_open(PixarImageFile.format, PixarImageFile, _accept)
+
+Image.register_extension(PixarImageFile.format, ".pxr")
diff --git a/venv/Lib/site-packages/PIL/PngImagePlugin.py b/venv/Lib/site-packages/PIL/PngImagePlugin.py
new file mode 100644
index 0000000..9826a4c
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PngImagePlugin.py
@@ -0,0 +1,1564 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# PNG support code
+#
+# See "PNG (Portable Network Graphics) Specification, version 1.0;
+# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
+#
+# history:
+# 1996-05-06 fl Created (couldn't resist it)
+# 1996-12-14 fl Upgraded, added read and verify support (0.2)
+# 1996-12-15 fl Separate PNG stream parser
+# 1996-12-29 fl Added write support, added getchunks
+# 1996-12-30 fl Eliminated circular references in decoder (0.3)
+# 1998-07-12 fl Read/write 16-bit images as mode I (0.4)
+# 2001-02-08 fl Added transparency support (from Zircon) (0.5)
+# 2001-04-16 fl Don't close data source in "open" method (0.6)
+# 2004-02-24 fl Don't even pretend to support interlaced files (0.7)
+# 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8)
+# 2004-09-20 fl Added PngInfo chunk container
+# 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev)
+# 2008-08-13 fl Added tRNS support for RGB images
+# 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech)
+# 2009-03-08 fl Added zTXT support (from Lowell Alleman)
+# 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
+#
+# Copyright (c) 1997-2009 by Secret Labs AB
+# Copyright (c) 1996 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import itertools
+import logging
+import re
+import struct
+import warnings
+import zlib
+from enum import IntEnum
+from fractions import Fraction
+from typing import IO, NamedTuple, cast
+
+from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
+from ._binary import i16be as i16
+from ._binary import i32be as i32
+from ._binary import o8
+from ._binary import o16be as o16
+from ._binary import o32be as o32
+from ._deprecate import deprecate
+from ._util import DeferredError
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Callable
+ from typing import Any, NoReturn
+
+ from . import _imaging
+
+logger = logging.getLogger(__name__)
+
+is_cid = re.compile(rb"\w\w\w\w").match
+
+
+_MAGIC = b"\211PNG\r\n\032\n"
+
+
+_MODES = {
+ # supported bits/color combinations, and corresponding modes/rawmodes
+ # Grayscale
+ (1, 0): ("1", "1"),
+ (2, 0): ("L", "L;2"),
+ (4, 0): ("L", "L;4"),
+ (8, 0): ("L", "L"),
+ (16, 0): ("I;16", "I;16B"),
+ # Truecolour
+ (8, 2): ("RGB", "RGB"),
+ (16, 2): ("RGB", "RGB;16B"),
+ # Indexed-colour
+ (1, 3): ("P", "P;1"),
+ (2, 3): ("P", "P;2"),
+ (4, 3): ("P", "P;4"),
+ (8, 3): ("P", "P"),
+ # Grayscale with alpha
+ (8, 4): ("LA", "LA"),
+ (16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available
+ # Truecolour with alpha
+ (8, 6): ("RGBA", "RGBA"),
+ (16, 6): ("RGBA", "RGBA;16B"),
+}
+
+
+_simple_palette = re.compile(b"^\xff*\x00\xff*$")
+
+MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
+"""
+Maximum decompressed size for a iTXt or zTXt chunk.
+Eliminates decompression bombs where compressed chunks can expand 1000x.
+See :ref:`Text in PNG File Format`.
+"""
+MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK
+"""
+Set the maximum total text chunk size.
+See :ref:`Text in PNG File Format`.
+"""
+
+
+# APNG frame disposal modes
+class Disposal(IntEnum):
+ OP_NONE = 0
+ """
+ No disposal is done on this frame before rendering the next frame.
+ See :ref:`Saving APNG sequences`.
+ """
+ OP_BACKGROUND = 1
+ """
+ This frame’s modified region is cleared to fully transparent black before rendering
+ the next frame.
+ See :ref:`Saving APNG sequences`.
+ """
+ OP_PREVIOUS = 2
+ """
+ This frame’s modified region is reverted to the previous frame’s contents before
+ rendering the next frame.
+ See :ref:`Saving APNG sequences`.
+ """
+
+
+# APNG frame blend modes
+class Blend(IntEnum):
+ OP_SOURCE = 0
+ """
+ All color components of this frame, including alpha, overwrite the previous output
+ image contents.
+ See :ref:`Saving APNG sequences`.
+ """
+ OP_OVER = 1
+ """
+ This frame should be alpha composited with the previous output image contents.
+ See :ref:`Saving APNG sequences`.
+ """
+
+
+def _safe_zlib_decompress(s: bytes) -> bytes:
+ dobj = zlib.decompressobj()
+ plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
+ if dobj.unconsumed_tail:
+ msg = "Decompressed data too large for PngImagePlugin.MAX_TEXT_CHUNK"
+ raise ValueError(msg)
+ return plaintext
+
+
+def _crc32(data: bytes, seed: int = 0) -> int:
+ return zlib.crc32(data, seed) & 0xFFFFFFFF
+
+
+# --------------------------------------------------------------------
+# Support classes. Suitable for PNG and related formats like MNG etc.
+
+
+class ChunkStream:
+ def __init__(self, fp: IO[bytes]) -> None:
+ self.fp: IO[bytes] | None = fp
+ self.queue: list[tuple[bytes, int, int]] | None = []
+
+ def read(self) -> tuple[bytes, int, int]:
+ """Fetch a new chunk. Returns header information."""
+ cid = None
+
+ assert self.fp is not None
+ if self.queue:
+ cid, pos, length = self.queue.pop()
+ self.fp.seek(pos)
+ else:
+ s = self.fp.read(8)
+ cid = s[4:]
+ pos = self.fp.tell()
+ length = i32(s)
+
+ if not is_cid(cid):
+ if not ImageFile.LOAD_TRUNCATED_IMAGES:
+ msg = f"broken PNG file (chunk {repr(cid)})"
+ raise SyntaxError(msg)
+
+ return cid, pos, length
+
+ def __enter__(self) -> ChunkStream:
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ self.close()
+
+ def close(self) -> None:
+ self.queue = self.fp = None
+
+ def push(self, cid: bytes, pos: int, length: int) -> None:
+ assert self.queue is not None
+ self.queue.append((cid, pos, length))
+
+ def call(self, cid: bytes, pos: int, length: int) -> bytes:
+ """Call the appropriate chunk handler"""
+
+ logger.debug("STREAM %r %s %s", cid, pos, length)
+ return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)
+
+ def crc(self, cid: bytes, data: bytes) -> None:
+ """Read and verify checksum"""
+
+ # Skip CRC checks for ancillary chunks if allowed to load truncated
+ # images
+ # 5th byte of first char is 1 [specs, section 5.4]
+ if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1):
+ self.crc_skip(cid, data)
+ return
+
+ assert self.fp is not None
+ try:
+ crc1 = _crc32(data, _crc32(cid))
+ crc2 = i32(self.fp.read(4))
+ if crc1 != crc2:
+ msg = f"broken PNG file (bad header checksum in {repr(cid)})"
+ raise SyntaxError(msg)
+ except struct.error as e:
+ msg = f"broken PNG file (incomplete checksum in {repr(cid)})"
+ raise SyntaxError(msg) from e
+
+ def crc_skip(self, cid: bytes, data: bytes) -> None:
+ """Read checksum"""
+
+ assert self.fp is not None
+ self.fp.read(4)
+
+ def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:
+ # Simple approach; just calculate checksum for all remaining
+ # blocks. Must be called directly after open.
+
+ cids = []
+
+ assert self.fp is not None
+ while True:
+ try:
+ cid, pos, length = self.read()
+ except struct.error as e:
+ msg = "truncated PNG file"
+ raise OSError(msg) from e
+
+ if cid == endchunk:
+ break
+ self.crc(cid, ImageFile._safe_read(self.fp, length))
+ cids.append(cid)
+
+ return cids
+
+
+class iTXt(str):
+ """
+ Subclass of string to allow iTXt chunks to look like strings while
+ keeping their extra information
+
+ """
+
+ lang: str | bytes | None
+ tkey: str | bytes | None
+
+ @staticmethod
+ def __new__(
+ cls, text: str, lang: str | None = None, tkey: str | None = None
+ ) -> iTXt:
+ """
+ :param cls: the class to use when creating the instance
+ :param text: value for this key
+ :param lang: language code
+ :param tkey: UTF-8 version of the key name
+ """
+
+ self = str.__new__(cls, text)
+ self.lang = lang
+ self.tkey = tkey
+ return self
+
+
+class PngInfo:
+ """
+ PNG chunk container (for use with save(pnginfo=))
+
+ """
+
+ def __init__(self) -> None:
+ self.chunks: list[tuple[bytes, bytes, bool]] = []
+
+ def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None:
+ """Appends an arbitrary chunk. Use with caution.
+
+ :param cid: a byte string, 4 bytes long.
+ :param data: a byte string of the encoded data
+ :param after_idat: for use with private chunks. Whether the chunk
+ should be written after IDAT
+
+ """
+
+ self.chunks.append((cid, data, after_idat))
+
+ def add_itxt(
+ self,
+ key: str | bytes,
+ value: str | bytes,
+ lang: str | bytes = "",
+ tkey: str | bytes = "",
+ zip: bool = False,
+ ) -> None:
+ """Appends an iTXt chunk.
+
+ :param key: latin-1 encodable text key name
+ :param value: value for this key
+ :param lang: language code
+ :param tkey: UTF-8 version of the key name
+ :param zip: compression flag
+
+ """
+
+ if not isinstance(key, bytes):
+ key = key.encode("latin-1", "strict")
+ if not isinstance(value, bytes):
+ value = value.encode("utf-8", "strict")
+ if not isinstance(lang, bytes):
+ lang = lang.encode("utf-8", "strict")
+ if not isinstance(tkey, bytes):
+ tkey = tkey.encode("utf-8", "strict")
+
+ if zip:
+ self.add(
+ b"iTXt",
+ key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
+ )
+ else:
+ self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)
+
+ def add_text(
+ self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False
+ ) -> None:
+ """Appends a text chunk.
+
+ :param key: latin-1 encodable text key name
+ :param value: value for this key, text or an
+ :py:class:`PIL.PngImagePlugin.iTXt` instance
+ :param zip: compression flag
+
+ """
+ if isinstance(value, iTXt):
+ return self.add_itxt(
+ key,
+ value,
+ value.lang if value.lang is not None else b"",
+ value.tkey if value.tkey is not None else b"",
+ zip=zip,
+ )
+
+ # The tEXt chunk stores latin-1 text
+ if not isinstance(value, bytes):
+ try:
+ value = value.encode("latin-1", "strict")
+ except UnicodeError:
+ return self.add_itxt(key, value, zip=zip)
+
+ if not isinstance(key, bytes):
+ key = key.encode("latin-1", "strict")
+
+ if zip:
+ self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
+ else:
+ self.add(b"tEXt", key + b"\0" + value)
+
+
+# --------------------------------------------------------------------
+# PNG image stream (IHDR/IEND)
+
+
+class _RewindState(NamedTuple):
+ info: dict[str | tuple[int, int], Any]
+ tile: list[ImageFile._Tile]
+ seq_num: int | None
+
+
+class PngStream(ChunkStream):
+ def __init__(self, fp: IO[bytes]) -> None:
+ super().__init__(fp)
+
+ # local copies of Image attributes
+ self.im_info: dict[str | tuple[int, int], Any] = {}
+ self.im_text: dict[str, str | iTXt] = {}
+ self.im_size = (0, 0)
+ self.im_mode = ""
+ self.im_tile: list[ImageFile._Tile] = []
+ self.im_palette: tuple[str, bytes] | None = None
+ self.im_custom_mimetype: str | None = None
+ self.im_n_frames: int | None = None
+ self._seq_num: int | None = None
+ self.rewind_state = _RewindState({}, [], None)
+
+ self.text_memory = 0
+
+ def check_text_memory(self, chunklen: int) -> None:
+ self.text_memory += chunklen
+ if self.text_memory > MAX_TEXT_MEMORY:
+ msg = (
+ "Too much memory used in text chunks: "
+ f"{self.text_memory}>MAX_TEXT_MEMORY"
+ )
+ raise ValueError(msg)
+
+ def save_rewind(self) -> None:
+ self.rewind_state = _RewindState(
+ self.im_info.copy(),
+ self.im_tile,
+ self._seq_num,
+ )
+
+ def rewind(self) -> None:
+ self.im_info = self.rewind_state.info.copy()
+ self.im_tile = self.rewind_state.tile
+ self._seq_num = self.rewind_state.seq_num
+
+ def chunk_iCCP(self, pos: int, length: int) -> bytes:
+ # ICC profile
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ # according to PNG spec, the iCCP chunk contains:
+ # Profile name 1-79 bytes (character string)
+ # Null separator 1 byte (null character)
+ # Compression method 1 byte (0)
+ # Compressed profile n bytes (zlib with deflate compression)
+ i = s.find(b"\0")
+ logger.debug("iCCP profile name %r", s[:i])
+ comp_method = s[i + 1]
+ logger.debug("Compression method %s", comp_method)
+ if comp_method != 0:
+ msg = f"Unknown compression method {comp_method} in iCCP chunk"
+ raise SyntaxError(msg)
+ try:
+ icc_profile = _safe_zlib_decompress(s[i + 2 :])
+ except ValueError:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ icc_profile = None
+ else:
+ raise
+ except zlib.error:
+ icc_profile = None # FIXME
+ self.im_info["icc_profile"] = icc_profile
+ return s
+
+ def chunk_IHDR(self, pos: int, length: int) -> bytes:
+ # image header
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ if length < 13:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ return s
+ msg = "Truncated IHDR chunk"
+ raise ValueError(msg)
+ self.im_size = i32(s, 0), i32(s, 4)
+ try:
+ self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
+ except Exception:
+ pass
+ if s[12]:
+ self.im_info["interlace"] = 1
+ if s[11]:
+ msg = "unknown filter category"
+ raise SyntaxError(msg)
+ return s
+
+ def chunk_IDAT(self, pos: int, length: int) -> NoReturn:
+ # image data
+ if "bbox" in self.im_info:
+ tile = [ImageFile._Tile("zip", self.im_info["bbox"], pos, self.im_rawmode)]
+ else:
+ if self.im_n_frames is not None:
+ self.im_info["default_image"] = True
+ tile = [ImageFile._Tile("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
+ self.im_tile = tile
+ self.im_idat = length
+ msg = "image data found"
+ raise EOFError(msg)
+
+ def chunk_IEND(self, pos: int, length: int) -> NoReturn:
+ msg = "end of PNG image"
+ raise EOFError(msg)
+
+ def chunk_PLTE(self, pos: int, length: int) -> bytes:
+ # palette
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ if self.im_mode == "P":
+ self.im_palette = "RGB", s
+ return s
+
+ def chunk_tRNS(self, pos: int, length: int) -> bytes:
+ # transparency
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ if self.im_mode == "P":
+ if _simple_palette.match(s):
+ # tRNS contains only one full-transparent entry,
+ # other entries are full opaque
+ i = s.find(b"\0")
+ if i >= 0:
+ self.im_info["transparency"] = i
+ else:
+ # otherwise, we have a byte string with one alpha value
+ # for each palette entry
+ self.im_info["transparency"] = s
+ elif self.im_mode == "1":
+ self.im_info["transparency"] = 255 if i16(s) else 0
+ elif self.im_mode in ("L", "I;16"):
+ self.im_info["transparency"] = i16(s)
+ elif self.im_mode == "RGB":
+ self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)
+ return s
+
+ def chunk_gAMA(self, pos: int, length: int) -> bytes:
+ # gamma setting
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ self.im_info["gamma"] = i32(s) / 100000.0
+ return s
+
+ def chunk_cHRM(self, pos: int, length: int) -> bytes:
+ # chromaticity, 8 unsigned ints, actual value is scaled by 100,000
+ # WP x,y, Red x,y, Green x,y Blue x,y
+
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ raw_vals = struct.unpack(f">{len(s) // 4}I", s)
+ self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
+ return s
+
+ def chunk_sRGB(self, pos: int, length: int) -> bytes:
+ # srgb rendering intent, 1 byte
+ # 0 perceptual
+ # 1 relative colorimetric
+ # 2 saturation
+ # 3 absolute colorimetric
+
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ if length < 1:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ return s
+ msg = "Truncated sRGB chunk"
+ raise ValueError(msg)
+ self.im_info["srgb"] = s[0]
+ return s
+
+ def chunk_pHYs(self, pos: int, length: int) -> bytes:
+ # pixels per unit
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ if length < 9:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ return s
+ msg = "Truncated pHYs chunk"
+ raise ValueError(msg)
+ px, py = i32(s, 0), i32(s, 4)
+ unit = s[8]
+ if unit == 1: # meter
+ dpi = px * 0.0254, py * 0.0254
+ self.im_info["dpi"] = dpi
+ elif unit == 0:
+ self.im_info["aspect"] = px, py
+ return s
+
+ def chunk_tEXt(self, pos: int, length: int) -> bytes:
+ # text
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ try:
+ k, v = s.split(b"\0", 1)
+ except ValueError:
+ # fallback for broken tEXt tags
+ k = s
+ v = b""
+ if k:
+ k_str = k.decode("latin-1", "strict")
+ v_str = v.decode("latin-1", "replace")
+
+ self.im_info[k_str] = v if k == b"exif" else v_str
+ self.im_text[k_str] = v_str
+ self.check_text_memory(len(v_str))
+
+ return s
+
+ def chunk_zTXt(self, pos: int, length: int) -> bytes:
+ # compressed text
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ try:
+ k, v = s.split(b"\0", 1)
+ except ValueError:
+ k = s
+ v = b""
+ if v:
+ comp_method = v[0]
+ else:
+ comp_method = 0
+ if comp_method != 0:
+ msg = f"Unknown compression method {comp_method} in zTXt chunk"
+ raise SyntaxError(msg)
+ try:
+ v = _safe_zlib_decompress(v[1:])
+ except ValueError:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ v = b""
+ else:
+ raise
+ except zlib.error:
+ v = b""
+
+ if k:
+ k_str = k.decode("latin-1", "strict")
+ v_str = v.decode("latin-1", "replace")
+
+ self.im_info[k_str] = self.im_text[k_str] = v_str
+ self.check_text_memory(len(v_str))
+
+ return s
+
+ def chunk_iTXt(self, pos: int, length: int) -> bytes:
+ # international text
+ assert self.fp is not None
+ r = s = ImageFile._safe_read(self.fp, length)
+ try:
+ k, r = r.split(b"\0", 1)
+ except ValueError:
+ return s
+ if len(r) < 2:
+ return s
+ cf, cm, r = r[0], r[1], r[2:]
+ try:
+ lang, tk, v = r.split(b"\0", 2)
+ except ValueError:
+ return s
+ if cf != 0:
+ if cm == 0:
+ try:
+ v = _safe_zlib_decompress(v)
+ except ValueError:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ return s
+ else:
+ raise
+ except zlib.error:
+ return s
+ else:
+ return s
+ if k == b"XML:com.adobe.xmp":
+ self.im_info["xmp"] = v
+ try:
+ k_str = k.decode("latin-1", "strict")
+ lang_str = lang.decode("utf-8", "strict")
+ tk_str = tk.decode("utf-8", "strict")
+ v_str = v.decode("utf-8", "strict")
+ except UnicodeError:
+ return s
+
+ self.im_info[k_str] = self.im_text[k_str] = iTXt(v_str, lang_str, tk_str)
+ self.check_text_memory(len(v_str))
+
+ return s
+
+ def chunk_eXIf(self, pos: int, length: int) -> bytes:
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ self.im_info["exif"] = b"Exif\x00\x00" + s
+ return s
+
+ # APNG chunks
+ def chunk_acTL(self, pos: int, length: int) -> bytes:
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ if length < 8:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ return s
+ msg = "APNG contains truncated acTL chunk"
+ raise ValueError(msg)
+ if self.im_n_frames is not None:
+ self.im_n_frames = None
+ warnings.warn("Invalid APNG, will use default PNG image if possible")
+ return s
+ n_frames = i32(s)
+ if n_frames == 0 or n_frames > 0x80000000:
+ warnings.warn("Invalid APNG, will use default PNG image if possible")
+ return s
+ self.im_n_frames = n_frames
+ self.im_info["loop"] = i32(s, 4)
+ self.im_custom_mimetype = "image/apng"
+ return s
+
+ def chunk_fcTL(self, pos: int, length: int) -> bytes:
+ assert self.fp is not None
+ s = ImageFile._safe_read(self.fp, length)
+ if length < 26:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ return s
+ msg = "APNG contains truncated fcTL chunk"
+ raise ValueError(msg)
+ seq = i32(s)
+ if (self._seq_num is None and seq != 0) or (
+ self._seq_num is not None and self._seq_num != seq - 1
+ ):
+ msg = "APNG contains frame sequence errors"
+ raise SyntaxError(msg)
+ self._seq_num = seq
+ width, height = i32(s, 4), i32(s, 8)
+ px, py = i32(s, 12), i32(s, 16)
+ im_w, im_h = self.im_size
+ if px + width > im_w or py + height > im_h:
+ msg = "APNG contains invalid frames"
+ raise SyntaxError(msg)
+ self.im_info["bbox"] = (px, py, px + width, py + height)
+ delay_num, delay_den = i16(s, 20), i16(s, 22)
+ if delay_den == 0:
+ delay_den = 100
+ self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
+ self.im_info["disposal"] = s[24]
+ self.im_info["blend"] = s[25]
+ return s
+
+ def chunk_fdAT(self, pos: int, length: int) -> bytes:
+ assert self.fp is not None
+ if length < 4:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ s = ImageFile._safe_read(self.fp, length)
+ return s
+ msg = "APNG contains truncated fDAT chunk"
+ raise ValueError(msg)
+ s = ImageFile._safe_read(self.fp, 4)
+ seq = i32(s)
+ if self._seq_num != seq - 1:
+ msg = "APNG contains frame sequence errors"
+ raise SyntaxError(msg)
+ self._seq_num = seq
+ return self.chunk_IDAT(pos + 4, length - 4)
+
+
+# --------------------------------------------------------------------
+# PNG reader
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(_MAGIC)
+
+
+##
+# Image plugin for PNG images.
+
+
+class PngImageFile(ImageFile.ImageFile):
+ format = "PNG"
+ format_description = "Portable network graphics"
+
+ def _open(self) -> None:
+ assert self.fp is not None
+ if not _accept(self.fp.read(8)):
+ msg = "not a PNG file"
+ raise SyntaxError(msg)
+ self._fp = self.fp
+ self.__frame = 0
+
+ #
+ # Parse headers up to the first IDAT or fDAT chunk
+
+ self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
+ self.png: PngStream | None = PngStream(self.fp)
+
+ while True:
+ #
+ # get next chunk
+
+ cid, pos, length = self.png.read()
+
+ try:
+ s = self.png.call(cid, pos, length)
+ except EOFError:
+ break
+ except AttributeError:
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
+ s = ImageFile._safe_read(self.fp, length)
+ if cid[1:2].islower():
+ self.private_chunks.append((cid, s))
+
+ self.png.crc(cid, s)
+
+ #
+ # Copy relevant attributes from the PngStream. An alternative
+ # would be to let the PngStream class modify these attributes
+ # directly, but that introduces circular references which are
+ # difficult to break if things go wrong in the decoder...
+ # (believe me, I've tried ;-)
+
+ self._mode = self.png.im_mode
+ self._size = self.png.im_size
+ self.info = self.png.im_info
+ self._text: dict[str, str | iTXt] | None = None
+ self.tile = self.png.im_tile
+ self.custom_mimetype = self.png.im_custom_mimetype
+ self.n_frames = self.png.im_n_frames or 1
+ self.default_image = self.info.get("default_image", False)
+
+ if self.png.im_palette:
+ rawmode, data = self.png.im_palette
+ self.palette = ImagePalette.raw(rawmode, data)
+
+ if cid == b"fdAT":
+ self.__prepare_idat = length - 4
+ else:
+ self.__prepare_idat = length # used by load_prepare()
+
+ if self.png.im_n_frames is not None:
+ self._close_exclusive_fp_after_loading = False
+ self.png.save_rewind()
+ self.__rewind_idat = self.__prepare_idat
+ self.__rewind = self._fp.tell()
+ if self.default_image:
+ # IDAT chunk contains default image and not first animation frame
+ self.n_frames += 1
+ self._seek(0)
+ self.is_animated = self.n_frames > 1
+
+ @property
+ def text(self) -> dict[str, str | iTXt]:
+ # experimental
+ if self._text is None:
+ # iTxt, tEXt and zTXt chunks may appear at the end of the file
+ # So load the file to ensure that they are read
+ if self.is_animated:
+ frame = self.__frame
+ # for APNG, seek to the final frame before loading
+ self.seek(self.n_frames - 1)
+ self.load()
+ if self.is_animated:
+ self.seek(frame)
+ assert self._text is not None
+ return self._text
+
+ def verify(self) -> None:
+ """Verify PNG file"""
+
+ if self.fp is None:
+ msg = "verify must be called directly after open"
+ raise RuntimeError(msg)
+
+ # back up to beginning of IDAT block
+ self.fp.seek(self.tile[0][2] - 8)
+
+ assert self.png is not None
+ self.png.verify()
+ self.png.close()
+
+ super().verify()
+
+ def seek(self, frame: int) -> None:
+ if not self._seek_check(frame):
+ return
+ if frame < self.__frame:
+ self._seek(0, True)
+
+ last_frame = self.__frame
+ for f in range(self.__frame + 1, frame + 1):
+ try:
+ self._seek(f)
+ except EOFError as e:
+ self.seek(last_frame)
+ msg = "no more images in APNG file"
+ raise EOFError(msg) from e
+
+ def _seek(self, frame: int, rewind: bool = False) -> None:
+ assert self.png is not None
+ if isinstance(self._fp, DeferredError):
+ raise self._fp.ex
+
+ self.dispose: _imaging.ImagingCore | None
+ dispose_extent = None
+ if frame == 0:
+ if rewind:
+ self._fp.seek(self.__rewind)
+ self.png.rewind()
+ self.__prepare_idat = self.__rewind_idat
+ self._im = None
+ self.info = self.png.im_info
+ self.tile = self.png.im_tile
+ self.fp = self._fp
+ self._prev_im = None
+ self.dispose = None
+ self.default_image = self.info.get("default_image", False)
+ self.dispose_op = self.info.get("disposal")
+ self.blend_op = self.info.get("blend")
+ dispose_extent = self.info.get("bbox")
+ self.__frame = 0
+ else:
+ if frame != self.__frame + 1:
+ msg = f"cannot seek to frame {frame}"
+ raise ValueError(msg)
+
+ # ensure previous frame was loaded
+ self.load()
+
+ if self.dispose:
+ self.im.paste(self.dispose, self.dispose_extent)
+ self._prev_im = self.im.copy()
+
+ self.fp = self._fp
+
+ # advance to the next frame
+ if self.__prepare_idat:
+ ImageFile._safe_read(self.fp, self.__prepare_idat)
+ self.__prepare_idat = 0
+ frame_start = False
+ while True:
+ self.fp.read(4) # CRC
+
+ try:
+ cid, pos, length = self.png.read()
+ except (struct.error, SyntaxError):
+ break
+
+ if cid == b"IEND":
+ msg = "No more images in APNG file"
+ raise EOFError(msg)
+ if cid == b"fcTL":
+ if frame_start:
+ # there must be at least one fdAT chunk between fcTL chunks
+ msg = "APNG missing frame data"
+ raise SyntaxError(msg)
+ frame_start = True
+
+ try:
+ self.png.call(cid, pos, length)
+ except UnicodeDecodeError:
+ break
+ except EOFError:
+ if cid == b"fdAT":
+ length -= 4
+ if frame_start:
+ self.__prepare_idat = length
+ break
+ ImageFile._safe_read(self.fp, length)
+ except AttributeError:
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
+ ImageFile._safe_read(self.fp, length)
+
+ self.__frame = frame
+ self.tile = self.png.im_tile
+ self.dispose_op = self.info.get("disposal")
+ self.blend_op = self.info.get("blend")
+ dispose_extent = self.info.get("bbox")
+
+ if not self.tile:
+ msg = "image not found in APNG frame"
+ raise EOFError(msg)
+ if dispose_extent:
+ self.dispose_extent: tuple[float, float, float, float] = dispose_extent
+
+ # setup frame disposal (actual disposal done when needed in the next _seek())
+ if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:
+ self.dispose_op = Disposal.OP_BACKGROUND
+
+ self.dispose = None
+ if self.dispose_op == Disposal.OP_PREVIOUS:
+ if self._prev_im:
+ self.dispose = self._prev_im.copy()
+ self.dispose = self._crop(self.dispose, self.dispose_extent)
+ elif self.dispose_op == Disposal.OP_BACKGROUND:
+ self.dispose = Image.core.fill(self.mode, self.size)
+ self.dispose = self._crop(self.dispose, self.dispose_extent)
+
+ def tell(self) -> int:
+ return self.__frame
+
+ def load_prepare(self) -> None:
+ """internal: prepare to read PNG file"""
+
+ if self.info.get("interlace"):
+ self.decoderconfig = self.decoderconfig + (1,)
+
+ self.__idat = self.__prepare_idat # used by load_read()
+ ImageFile.ImageFile.load_prepare(self)
+
+ def load_read(self, read_bytes: int) -> bytes:
+ """internal: read more image data"""
+
+ assert self.png is not None
+ assert self.fp is not None
+ while self.__idat == 0:
+ # end of chunk, skip forward to next one
+
+ self.fp.read(4) # CRC
+
+ cid, pos, length = self.png.read()
+
+ if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
+ self.png.push(cid, pos, length)
+ return b""
+
+ if cid == b"fdAT":
+ try:
+ self.png.call(cid, pos, length)
+ except EOFError:
+ pass
+ self.__idat = length - 4 # sequence_num has already been read
+ else:
+ self.__idat = length # empty chunks are allowed
+
+ # read more data from this chunk
+ if read_bytes <= 0:
+ read_bytes = self.__idat
+ else:
+ read_bytes = min(read_bytes, self.__idat)
+
+ self.__idat = self.__idat - read_bytes
+
+ return self.fp.read(read_bytes)
+
+ def load_end(self) -> None:
+ """internal: finished reading image data"""
+ assert self.png is not None
+ assert self.fp is not None
+ if self.__idat != 0:
+ self.fp.read(self.__idat)
+ while True:
+ self.fp.read(4) # CRC
+
+ try:
+ cid, pos, length = self.png.read()
+ except (struct.error, SyntaxError):
+ break
+
+ if cid == b"IEND":
+ break
+ elif cid == b"fcTL" and self.is_animated:
+ # start of the next frame, stop reading
+ self.__prepare_idat = 0
+ self.png.push(cid, pos, length)
+ break
+
+ try:
+ self.png.call(cid, pos, length)
+ except UnicodeDecodeError:
+ break
+ except EOFError:
+ if cid == b"fdAT":
+ length -= 4
+ try:
+ ImageFile._safe_read(self.fp, length)
+ except OSError as e:
+ if ImageFile.LOAD_TRUNCATED_IMAGES:
+ break
+ else:
+ raise e
+ except AttributeError:
+ logger.debug("%r %s %s (unknown)", cid, pos, length)
+ s = ImageFile._safe_read(self.fp, length)
+ if cid[1:2].islower():
+ self.private_chunks.append((cid, s, True))
+ self._text = self.png.im_text
+ if not self.is_animated:
+ self.png.close()
+ self.png = None
+ else:
+ if self._prev_im and self.blend_op == Blend.OP_OVER:
+ updated = self._crop(self.im, self.dispose_extent)
+ if self.im.mode == "RGB" and "transparency" in self.info:
+ mask = updated.convert_transparent(
+ "RGBA", self.info["transparency"]
+ )
+ else:
+ if self.im.mode == "P" and "transparency" in self.info:
+ t = self.info["transparency"]
+ if isinstance(t, bytes):
+ updated.putpalettealphas(t)
+ elif isinstance(t, int):
+ updated.putpalettealpha(t)
+ mask = updated.convert("RGBA")
+ self._prev_im.paste(updated, self.dispose_extent, mask)
+ self.im = self._prev_im
+
+ def _getexif(self) -> dict[int, Any] | None:
+ if "exif" not in self.info:
+ self.load()
+ if "exif" not in self.info and "Raw profile type exif" not in self.info:
+ return None
+ return self.getexif()._get_merged_dict()
+
+ def getexif(self) -> Image.Exif:
+ if "exif" not in self.info:
+ self.load()
+
+ return super().getexif()
+
+
+# --------------------------------------------------------------------
+# PNG writer
+
+_OUTMODES = {
+ # supported PIL modes, and corresponding rawmode, bit depth and color type
+ "1": ("1", b"\x01", b"\x00"),
+ "L;1": ("L;1", b"\x01", b"\x00"),
+ "L;2": ("L;2", b"\x02", b"\x00"),
+ "L;4": ("L;4", b"\x04", b"\x00"),
+ "L": ("L", b"\x08", b"\x00"),
+ "LA": ("LA", b"\x08", b"\x04"),
+ "I": ("I;16B", b"\x10", b"\x00"),
+ "I;16": ("I;16B", b"\x10", b"\x00"),
+ "I;16B": ("I;16B", b"\x10", b"\x00"),
+ "P;1": ("P;1", b"\x01", b"\x03"),
+ "P;2": ("P;2", b"\x02", b"\x03"),
+ "P;4": ("P;4", b"\x04", b"\x03"),
+ "P": ("P", b"\x08", b"\x03"),
+ "RGB": ("RGB", b"\x08", b"\x02"),
+ "RGBA": ("RGBA", b"\x08", b"\x06"),
+}
+
+
+def putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
+ """Write a PNG chunk (including CRC field)"""
+
+ byte_data = b"".join(data)
+
+ fp.write(o32(len(byte_data)) + cid)
+ fp.write(byte_data)
+ crc = _crc32(byte_data, _crc32(cid))
+ fp.write(o32(crc))
+
+
+class _idat:
+ # wrap output from the encoder in IDAT chunks
+
+ def __init__(self, fp: IO[bytes], chunk: Callable[..., None]) -> None:
+ self.fp = fp
+ self.chunk = chunk
+
+ def write(self, data: bytes) -> None:
+ self.chunk(self.fp, b"IDAT", data)
+
+
+class _fdat:
+ # wrap encoder output in fdAT chunks
+
+ def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None:
+ self.fp = fp
+ self.chunk = chunk
+ self.seq_num = seq_num
+
+ def write(self, data: bytes) -> None:
+ self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
+ self.seq_num += 1
+
+
+def _apply_encoderinfo(im: Image.Image, encoderinfo: dict[str, Any]) -> None:
+ im.encoderconfig = (
+ encoderinfo.get("optimize", False),
+ encoderinfo.get("compress_level", -1),
+ encoderinfo.get("compress_type", -1),
+ encoderinfo.get("dictionary", b""),
+ )
+
+
+class _Frame(NamedTuple):
+ im: Image.Image
+ bbox: tuple[int, int, int, int] | None
+ encoderinfo: dict[str, Any]
+
+
+def _write_multiple_frames(
+ im: Image.Image,
+ fp: IO[bytes],
+ chunk: Callable[..., None],
+ mode: str,
+ rawmode: str,
+ default_image: Image.Image | None,
+ append_images: list[Image.Image],
+) -> Image.Image | None:
+ duration = im.encoderinfo.get("duration")
+ loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
+ disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE))
+ blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE))
+
+ if default_image:
+ chain = itertools.chain(append_images)
+ else:
+ chain = itertools.chain([im], append_images)
+
+ im_frames: list[_Frame] = []
+ frame_count = 0
+ for im_seq in chain:
+ for im_frame in ImageSequence.Iterator(im_seq):
+ if im_frame.mode == mode:
+ im_frame = im_frame.copy()
+ else:
+ im_frame = im_frame.convert(mode)
+ encoderinfo = im.encoderinfo.copy()
+ if isinstance(duration, (list, tuple)):
+ encoderinfo["duration"] = duration[frame_count]
+ elif duration is None and "duration" in im_frame.info:
+ encoderinfo["duration"] = im_frame.info["duration"]
+ if isinstance(disposal, (list, tuple)):
+ encoderinfo["disposal"] = disposal[frame_count]
+ if isinstance(blend, (list, tuple)):
+ encoderinfo["blend"] = blend[frame_count]
+ frame_count += 1
+
+ if im_frames:
+ previous = im_frames[-1]
+ prev_disposal = previous.encoderinfo.get("disposal")
+ prev_blend = previous.encoderinfo.get("blend")
+ if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2:
+ prev_disposal = Disposal.OP_BACKGROUND
+
+ if prev_disposal == Disposal.OP_BACKGROUND:
+ base_im = previous.im.copy()
+ dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
+ bbox = previous.bbox
+ if bbox:
+ dispose = dispose.crop(bbox)
+ else:
+ bbox = (0, 0) + im.size
+ base_im.paste(dispose, bbox)
+ elif prev_disposal == Disposal.OP_PREVIOUS:
+ base_im = im_frames[-2].im
+ else:
+ base_im = previous.im
+ delta = ImageChops.subtract_modulo(
+ im_frame.convert("RGBA"), base_im.convert("RGBA")
+ )
+ bbox = delta.getbbox(alpha_only=False)
+ if (
+ not bbox
+ and prev_disposal == encoderinfo.get("disposal")
+ and prev_blend == encoderinfo.get("blend")
+ and "duration" in encoderinfo
+ ):
+ previous.encoderinfo["duration"] += encoderinfo["duration"]
+ continue
+ else:
+ bbox = None
+ im_frames.append(_Frame(im_frame, bbox, encoderinfo))
+
+ if len(im_frames) == 1 and not default_image:
+ return im_frames[0].im
+
+ # animation control
+ chunk(
+ fp,
+ b"acTL",
+ o32(len(im_frames)), # 0: num_frames
+ o32(loop), # 4: num_plays
+ )
+
+ # default image IDAT (if it exists)
+ if default_image:
+ default_im = im if im.mode == mode else im.convert(mode)
+ _apply_encoderinfo(default_im, im.encoderinfo)
+ ImageFile._save(
+ default_im,
+ cast(IO[bytes], _idat(fp, chunk)),
+ [ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)],
+ )
+
+ seq_num = 0
+ for frame, frame_data in enumerate(im_frames):
+ im_frame = frame_data.im
+ if not frame_data.bbox:
+ bbox = (0, 0) + im_frame.size
+ else:
+ bbox = frame_data.bbox
+ im_frame = im_frame.crop(bbox)
+ size = im_frame.size
+ encoderinfo = frame_data.encoderinfo
+ frame_duration = encoderinfo.get("duration", 0)
+ delay = Fraction(frame_duration / 1000).limit_denominator(65535)
+ if delay.numerator > 65535:
+ msg = "cannot write duration"
+ raise ValueError(msg)
+ frame_disposal = encoderinfo.get("disposal", disposal)
+ frame_blend = encoderinfo.get("blend", blend)
+ # frame control
+ chunk(
+ fp,
+ b"fcTL",
+ o32(seq_num), # sequence_number
+ o32(size[0]), # width
+ o32(size[1]), # height
+ o32(bbox[0]), # x_offset
+ o32(bbox[1]), # y_offset
+ o16(delay.numerator), # delay_numerator
+ o16(delay.denominator), # delay_denominator
+ o8(frame_disposal), # dispose_op
+ o8(frame_blend), # blend_op
+ )
+ seq_num += 1
+ # frame data
+ _apply_encoderinfo(im_frame, im.encoderinfo)
+ if frame == 0 and not default_image:
+ # first frame must be in IDAT chunks for backwards compatibility
+ ImageFile._save(
+ im_frame,
+ cast(IO[bytes], _idat(fp, chunk)),
+ [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
+ )
+ else:
+ fdat_chunks = _fdat(fp, chunk, seq_num)
+ ImageFile._save(
+ im_frame,
+ cast(IO[bytes], fdat_chunks),
+ [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],
+ )
+ seq_num = fdat_chunks.seq_num
+ return None
+
+
+def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ _save(im, fp, filename, save_all=True)
+
+
+def _save(
+ im: Image.Image,
+ fp: IO[bytes],
+ filename: str | bytes,
+ chunk: Callable[..., None] = putchunk,
+ save_all: bool = False,
+) -> None:
+ # save an image to disk (called by the save method)
+
+ if save_all:
+ default_image = im.encoderinfo.get(
+ "default_image", im.info.get("default_image")
+ )
+ modes = set()
+ sizes = set()
+ append_images = im.encoderinfo.get("append_images", [])
+ for im_seq in itertools.chain([im], append_images):
+ for im_frame in ImageSequence.Iterator(im_seq):
+ modes.add(im_frame.mode)
+ sizes.add(im_frame.size)
+ for mode in ("RGBA", "RGB", "P"):
+ if mode in modes:
+ break
+ else:
+ mode = modes.pop()
+ size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2))
+ else:
+ size = im.size
+ mode = im.mode
+
+ outmode = mode
+ if mode == "P":
+ #
+ # attempt to minimize storage requirements for palette images
+ if "bits" in im.encoderinfo:
+ # number of bits specified by user
+ colors = min(1 << im.encoderinfo["bits"], 256)
+ else:
+ # check palette contents
+ if im.palette:
+ colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1)
+ else:
+ colors = 256
+
+ if colors <= 16:
+ if colors <= 2:
+ bits = 1
+ elif colors <= 4:
+ bits = 2
+ else:
+ bits = 4
+ outmode += f";{bits}"
+
+ # get the corresponding PNG mode
+ try:
+ rawmode, bit_depth, color_type = _OUTMODES[outmode]
+ except KeyError as e:
+ msg = f"cannot write mode {mode} as PNG"
+ raise OSError(msg) from e
+ if outmode == "I":
+ deprecate("Saving I mode images as PNG", 13, stacklevel=4)
+
+ #
+ # write minimal PNG file
+
+ fp.write(_MAGIC)
+
+ chunk(
+ fp,
+ b"IHDR",
+ o32(size[0]), # 0: size
+ o32(size[1]),
+ bit_depth,
+ color_type,
+ b"\0", # 10: compression
+ b"\0", # 11: filter category
+ b"\0", # 12: interlace flag
+ )
+
+ chunks = [b"cHRM", b"cICP", b"gAMA", b"sBIT", b"sRGB", b"tIME"]
+
+ icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
+ if icc:
+ # ICC profile
+ # according to PNG spec, the iCCP chunk contains:
+ # Profile name 1-79 bytes (character string)
+ # Null separator 1 byte (null character)
+ # Compression method 1 byte (0)
+ # Compressed profile n bytes (zlib with deflate compression)
+ name = b"ICC Profile"
+ data = name + b"\0\0" + zlib.compress(icc)
+ chunk(fp, b"iCCP", data)
+
+ # You must either have sRGB or iCCP.
+ # Disallow sRGB chunks when an iCCP-chunk has been emitted.
+ chunks.remove(b"sRGB")
+
+ info = im.encoderinfo.get("pnginfo")
+ if info:
+ chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
+ for info_chunk in info.chunks:
+ cid, data = info_chunk[:2]
+ if cid in chunks:
+ chunks.remove(cid)
+ chunk(fp, cid, data)
+ elif cid in chunks_multiple_allowed:
+ chunk(fp, cid, data)
+ elif cid[1:2].islower():
+ # Private chunk
+ after_idat = len(info_chunk) == 3 and info_chunk[2]
+ if not after_idat:
+ chunk(fp, cid, data)
+
+ if im.mode == "P":
+ palette_byte_number = colors * 3
+ palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
+ while len(palette_bytes) < palette_byte_number:
+ palette_bytes += b"\0"
+ chunk(fp, b"PLTE", palette_bytes)
+
+ transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))
+
+ if transparency or transparency == 0:
+ if im.mode == "P":
+ # limit to actual palette size
+ alpha_bytes = colors
+ if isinstance(transparency, bytes):
+ chunk(fp, b"tRNS", transparency[:alpha_bytes])
+ else:
+ transparency = max(0, min(255, transparency))
+ alpha = b"\xff" * transparency + b"\0"
+ chunk(fp, b"tRNS", alpha[:alpha_bytes])
+ elif im.mode in ("1", "L", "I", "I;16"):
+ transparency = max(0, min(65535, transparency))
+ chunk(fp, b"tRNS", o16(transparency))
+ elif im.mode == "RGB":
+ red, green, blue = transparency
+ chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
+ else:
+ if "transparency" in im.encoderinfo:
+ # don't bother with transparency if it's an RGBA
+ # and it's in the info dict. It's probably just stale.
+ msg = "cannot use transparency for this mode"
+ raise OSError(msg)
+ else:
+ if im.mode == "P" and im.im.getpalettemode() == "RGBA":
+ alpha = im.im.getpalette("RGBA", "A")
+ alpha_bytes = colors
+ chunk(fp, b"tRNS", alpha[:alpha_bytes])
+
+ dpi = im.encoderinfo.get("dpi")
+ if dpi:
+ chunk(
+ fp,
+ b"pHYs",
+ o32(int(dpi[0] / 0.0254 + 0.5)),
+ o32(int(dpi[1] / 0.0254 + 0.5)),
+ b"\x01",
+ )
+
+ if info:
+ chunks = [b"bKGD", b"hIST"]
+ for info_chunk in info.chunks:
+ cid, data = info_chunk[:2]
+ if cid in chunks:
+ chunks.remove(cid)
+ chunk(fp, cid, data)
+
+ exif = im.encoderinfo.get("exif")
+ if exif:
+ if isinstance(exif, Image.Exif):
+ exif = exif.tobytes(8)
+ if exif.startswith(b"Exif\x00\x00"):
+ exif = exif[6:]
+ chunk(fp, b"eXIf", exif)
+
+ single_im: Image.Image | None = im
+ if save_all:
+ single_im = _write_multiple_frames(
+ im, fp, chunk, mode, rawmode, default_image, append_images
+ )
+ if single_im:
+ _apply_encoderinfo(single_im, im.encoderinfo)
+ ImageFile._save(
+ single_im,
+ cast(IO[bytes], _idat(fp, chunk)),
+ [ImageFile._Tile("zip", (0, 0) + single_im.size, 0, rawmode)],
+ )
+
+ if info:
+ for info_chunk in info.chunks:
+ cid, data = info_chunk[:2]
+ if cid[1:2].islower():
+ # Private chunk
+ after_idat = len(info_chunk) == 3 and info_chunk[2]
+ if after_idat:
+ chunk(fp, cid, data)
+
+ chunk(fp, b"IEND", b"")
+
+ if hasattr(fp, "flush"):
+ fp.flush()
+
+
+# --------------------------------------------------------------------
+# PNG chunk converter
+
+
+def getchunks(im: Image.Image, **params: Any) -> list[tuple[bytes, bytes, bytes]]:
+ """Return a list of PNG chunks representing this image."""
+ from io import BytesIO
+
+ chunks = []
+
+ def append(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
+ byte_data = b"".join(data)
+ crc = o32(_crc32(byte_data, _crc32(cid)))
+ chunks.append((cid, byte_data, crc))
+
+ fp = BytesIO()
+
+ try:
+ im.encoderinfo = params
+ _save(im, fp, "", append)
+ finally:
+ del im.encoderinfo
+
+ return chunks
+
+
+# --------------------------------------------------------------------
+# Registry
+
+Image.register_open(PngImageFile.format, PngImageFile, _accept)
+Image.register_save(PngImageFile.format, _save)
+Image.register_save_all(PngImageFile.format, _save_all)
+
+Image.register_extensions(PngImageFile.format, [".png", ".apng"])
+
+Image.register_mime(PngImageFile.format, "image/png")
diff --git a/venv/Lib/site-packages/PIL/PpmImagePlugin.py b/venv/Lib/site-packages/PIL/PpmImagePlugin.py
new file mode 100644
index 0000000..307bc97
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PpmImagePlugin.py
@@ -0,0 +1,375 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# PPM support for PIL
+#
+# History:
+# 96-03-24 fl Created
+# 98-03-06 fl Write RGBA images (as RGB, that is)
+#
+# Copyright (c) Secret Labs AB 1997-98.
+# Copyright (c) Fredrik Lundh 1996.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import math
+from typing import IO
+
+from . import Image, ImageFile
+from ._binary import i16be as i16
+from ._binary import o8
+from ._binary import o32le as o32
+
+#
+# --------------------------------------------------------------------
+
+b_whitespace = b"\x20\x09\x0a\x0b\x0c\x0d"
+
+MODES = {
+ # standard
+ b"P1": "1",
+ b"P2": "L",
+ b"P3": "RGB",
+ b"P4": "1",
+ b"P5": "L",
+ b"P6": "RGB",
+ # extensions
+ b"P0CMYK": "CMYK",
+ b"Pf": "F",
+ # PIL extensions (for test purposes only)
+ b"PyP": "P",
+ b"PyRGBA": "RGBA",
+ b"PyCMYK": "CMYK",
+}
+
+
+def _accept(prefix: bytes) -> bool:
+ return len(prefix) >= 2 and prefix.startswith(b"P") and prefix[1] in b"0123456fy"
+
+
+##
+# Image plugin for PBM, PGM, and PPM images.
+
+
+class PpmImageFile(ImageFile.ImageFile):
+ format = "PPM"
+ format_description = "Pbmplus image"
+
+ def _read_magic(self) -> bytes:
+ assert self.fp is not None
+
+ magic = b""
+ # read until whitespace or longest available magic number
+ for _ in range(6):
+ c = self.fp.read(1)
+ if not c or c in b_whitespace:
+ break
+ magic += c
+ return magic
+
+ def _read_token(self) -> bytes:
+ assert self.fp is not None
+
+ token = b""
+ while len(token) <= 10: # read until next whitespace or limit of 10 characters
+ c = self.fp.read(1)
+ if not c:
+ break
+ elif c in b_whitespace: # token ended
+ if not token:
+ # skip whitespace at start
+ continue
+ break
+ elif c == b"#":
+ # ignores rest of the line; stops at CR, LF or EOF
+ while self.fp.read(1) not in b"\r\n":
+ pass
+ continue
+ token += c
+ if not token:
+ # Token was not even 1 byte
+ msg = "Reached EOF while reading header"
+ raise ValueError(msg)
+ elif len(token) > 10:
+ msg_too_long = b"Token too long in file header: %s" % token
+ raise ValueError(msg_too_long)
+ return token
+
+ def _open(self) -> None:
+ assert self.fp is not None
+
+ magic_number = self._read_magic()
+ try:
+ mode = MODES[magic_number]
+ except KeyError:
+ msg = "not a PPM file"
+ raise SyntaxError(msg)
+ self._mode = mode
+
+ if magic_number in (b"P1", b"P4"):
+ self.custom_mimetype = "image/x-portable-bitmap"
+ elif magic_number in (b"P2", b"P5"):
+ self.custom_mimetype = "image/x-portable-graymap"
+ elif magic_number in (b"P3", b"P6"):
+ self.custom_mimetype = "image/x-portable-pixmap"
+
+ self._size = int(self._read_token()), int(self._read_token())
+
+ decoder_name = "raw"
+ if magic_number in (b"P1", b"P2", b"P3"):
+ decoder_name = "ppm_plain"
+
+ args: str | tuple[str | int, ...]
+ if mode == "1":
+ args = "1;I"
+ elif mode == "F":
+ scale = float(self._read_token())
+ if scale == 0.0 or not math.isfinite(scale):
+ msg = "scale must be finite and non-zero"
+ raise ValueError(msg)
+ self.info["scale"] = abs(scale)
+
+ rawmode = "F;32F" if scale < 0 else "F;32BF"
+ args = (rawmode, 0, -1)
+ else:
+ maxval = int(self._read_token())
+ if not 0 < maxval < 65536:
+ msg = "maxval must be greater than 0 and less than 65536"
+ raise ValueError(msg)
+ if maxval > 255 and mode == "L":
+ self._mode = "I"
+
+ rawmode = mode
+ if decoder_name != "ppm_plain":
+ # If maxval matches a bit depth, use the raw decoder directly
+ if maxval == 65535 and mode == "L":
+ rawmode = "I;16B"
+ elif maxval != 255:
+ decoder_name = "ppm"
+
+ args = rawmode if decoder_name == "raw" else (rawmode, maxval)
+ self.tile = [
+ ImageFile._Tile(decoder_name, (0, 0) + self.size, self.fp.tell(), args)
+ ]
+
+
+#
+# --------------------------------------------------------------------
+
+
+class PpmPlainDecoder(ImageFile.PyDecoder):
+ _pulls_fd = True
+ _comment_spans: bool
+
+ def _read_block(self) -> bytes:
+ assert self.fd is not None
+
+ return self.fd.read(ImageFile.SAFEBLOCK)
+
+ def _find_comment_end(self, block: bytes, start: int = 0) -> int:
+ a = block.find(b"\n", start)
+ b = block.find(b"\r", start)
+ return min(a, b) if a * b > 0 else max(a, b) # lowest nonnegative index (or -1)
+
+ def _ignore_comments(self, block: bytes) -> bytes:
+ if self._comment_spans:
+ # Finish current comment
+ while block:
+ comment_end = self._find_comment_end(block)
+ if comment_end != -1:
+ # Comment ends in this block
+ # Delete tail of comment
+ block = block[comment_end + 1 :]
+ break
+ else:
+ # Comment spans whole block
+ # So read the next block, looking for the end
+ block = self._read_block()
+
+ # Search for any further comments
+ self._comment_spans = False
+ while True:
+ comment_start = block.find(b"#")
+ if comment_start == -1:
+ # No comment found
+ break
+ comment_end = self._find_comment_end(block, comment_start)
+ if comment_end != -1:
+ # Comment ends in this block
+ # Delete comment
+ block = block[:comment_start] + block[comment_end + 1 :]
+ else:
+ # Comment continues to next block(s)
+ block = block[:comment_start]
+ self._comment_spans = True
+ break
+ return block
+
+ def _decode_bitonal(self) -> bytearray:
+ """
+ This is a separate method because in the plain PBM format, all data tokens are
+ exactly one byte, so the inter-token whitespace is optional.
+ """
+ data = bytearray()
+ total_bytes = self.state.xsize * self.state.ysize
+
+ while len(data) != total_bytes:
+ block = self._read_block() # read next block
+ if not block:
+ # eof
+ break
+
+ block = self._ignore_comments(block)
+
+ tokens = b"".join(block.split())
+ for token in tokens:
+ if token not in (48, 49):
+ msg = b"Invalid token for this mode: %s" % bytes([token])
+ raise ValueError(msg)
+ data = (data + tokens)[:total_bytes]
+ invert = bytes.maketrans(b"01", b"\xff\x00")
+ return data.translate(invert)
+
+ def _decode_blocks(self, maxval: int) -> bytearray:
+ data = bytearray()
+ max_len = 10
+ out_byte_count = 4 if self.mode == "I" else 1
+ out_max = 65535 if self.mode == "I" else 255
+ bands = Image.getmodebands(self.mode)
+ total_bytes = self.state.xsize * self.state.ysize * bands * out_byte_count
+
+ half_token = b""
+ while len(data) != total_bytes:
+ block = self._read_block() # read next block
+ if not block:
+ if half_token:
+ block = bytearray(b" ") # flush half_token
+ else:
+ # eof
+ break
+
+ block = self._ignore_comments(block)
+
+ if half_token:
+ block = half_token + block # stitch half_token to new block
+ half_token = b""
+
+ tokens = block.split()
+
+ if block and not block[-1:].isspace(): # block might split token
+ half_token = tokens.pop() # save half token for later
+ if len(half_token) > max_len: # prevent buildup of half_token
+ msg = (
+ b"Token too long found in data: %s" % half_token[: max_len + 1]
+ )
+ raise ValueError(msg)
+
+ for token in tokens:
+ if len(token) > max_len:
+ msg = b"Token too long found in data: %s" % token[: max_len + 1]
+ raise ValueError(msg)
+ value = int(token)
+ if value < 0:
+ msg_str = f"Channel value is negative: {value}"
+ raise ValueError(msg_str)
+ if value > maxval:
+ msg_str = f"Channel value too large for this mode: {value}"
+ raise ValueError(msg_str)
+ value = round(value / maxval * out_max)
+ data += o32(value) if self.mode == "I" else o8(value)
+ if len(data) == total_bytes: # finished!
+ break
+ return data
+
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+ self._comment_spans = False
+ if self.mode == "1":
+ data = self._decode_bitonal()
+ rawmode = "1;8"
+ else:
+ maxval = self.args[-1]
+ data = self._decode_blocks(maxval)
+ rawmode = "I;32" if self.mode == "I" else self.mode
+ self.set_as_raw(bytes(data), rawmode)
+ return -1, 0
+
+
+class PpmDecoder(ImageFile.PyDecoder):
+ _pulls_fd = True
+
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+ assert self.fd is not None
+
+ data = bytearray()
+ maxval = self.args[-1]
+ in_byte_count = 1 if maxval < 256 else 2
+ out_byte_count = 4 if self.mode == "I" else 1
+ out_max = 65535 if self.mode == "I" else 255
+ bands = Image.getmodebands(self.mode)
+ dest_length = self.state.xsize * self.state.ysize * bands * out_byte_count
+ while len(data) < dest_length:
+ pixels = self.fd.read(in_byte_count * bands)
+ if len(pixels) < in_byte_count * bands:
+ # eof
+ break
+ for b in range(bands):
+ value = (
+ pixels[b] if in_byte_count == 1 else i16(pixels, b * in_byte_count)
+ )
+ value = min(out_max, round(value / maxval * out_max))
+ data += o32(value) if self.mode == "I" else o8(value)
+ rawmode = "I;32" if self.mode == "I" else self.mode
+ self.set_as_raw(bytes(data), rawmode)
+ return -1, 0
+
+
+#
+# --------------------------------------------------------------------
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if im.mode == "1":
+ rawmode, head = "1;I", b"P4"
+ elif im.mode == "L":
+ rawmode, head = "L", b"P5"
+ elif im.mode in ("I", "I;16"):
+ rawmode, head = "I;16B", b"P5"
+ elif im.mode in ("RGB", "RGBA"):
+ rawmode, head = "RGB", b"P6"
+ elif im.mode == "F":
+ rawmode, head = "F;32F", b"Pf"
+ else:
+ msg = f"cannot write mode {im.mode} as PPM"
+ raise OSError(msg)
+ fp.write(head + b"\n%d %d\n" % im.size)
+ if head == b"P6":
+ fp.write(b"255\n")
+ elif head == b"P5":
+ if rawmode == "L":
+ fp.write(b"255\n")
+ else:
+ fp.write(b"65535\n")
+ elif head == b"Pf":
+ fp.write(b"-1.0\n")
+ row_order = -1 if im.mode == "F" else 1
+ ImageFile._save(
+ im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, row_order))]
+ )
+
+
+#
+# --------------------------------------------------------------------
+
+
+Image.register_open(PpmImageFile.format, PpmImageFile, _accept)
+Image.register_save(PpmImageFile.format, _save)
+
+Image.register_decoder("ppm", PpmDecoder)
+Image.register_decoder("ppm_plain", PpmPlainDecoder)
+
+Image.register_extensions(PpmImageFile.format, [".pbm", ".pgm", ".ppm", ".pnm", ".pfm"])
+
+Image.register_mime(PpmImageFile.format, "image/x-portable-anymap")
diff --git a/venv/Lib/site-packages/PIL/PsdImagePlugin.py b/venv/Lib/site-packages/PIL/PsdImagePlugin.py
new file mode 100644
index 0000000..69a8703
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/PsdImagePlugin.py
@@ -0,0 +1,334 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# Adobe PSD 2.5/3.0 file handling
+#
+# History:
+# 1995-09-01 fl Created
+# 1997-01-03 fl Read most PSD images
+# 1997-01-18 fl Fixed P and CMYK support
+# 2001-10-21 fl Added seek/tell support (for layers)
+#
+# Copyright (c) 1997-2001 by Secret Labs AB.
+# Copyright (c) 1995-2001 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import io
+from functools import cached_property
+from typing import IO
+
+from . import Image, ImageFile, ImagePalette
+from ._binary import i8
+from ._binary import i16be as i16
+from ._binary import i32be as i32
+from ._binary import si16be as si16
+from ._binary import si32be as si32
+from ._util import DeferredError
+
+MODES = {
+ # (photoshop mode, bits) -> (pil mode, required channels)
+ (0, 1): ("1", 1),
+ (0, 8): ("L", 1),
+ (1, 8): ("L", 1),
+ (2, 8): ("P", 1),
+ (3, 8): ("RGB", 3),
+ (4, 8): ("CMYK", 4),
+ (7, 8): ("L", 1), # FIXME: multilayer
+ (8, 8): ("L", 1), # duotone
+ (9, 8): ("LAB", 3),
+}
+
+
+# --------------------------------------------------------------------.
+# read PSD images
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(b"8BPS")
+
+
+##
+# Image plugin for Photoshop images.
+
+
+class PsdImageFile(ImageFile.ImageFile):
+ format = "PSD"
+ format_description = "Adobe Photoshop"
+ _close_exclusive_fp_after_loading = False
+
+ def _open(self) -> None:
+ assert self.fp is not None
+ read = self.fp.read
+
+ #
+ # header
+
+ s = read(26)
+ if not _accept(s) or i16(s, 4) != 1:
+ msg = "not a PSD file"
+ raise SyntaxError(msg)
+
+ psd_bits = i16(s, 22)
+ psd_channels = i16(s, 12)
+ psd_mode = i16(s, 24)
+
+ mode, channels = MODES[(psd_mode, psd_bits)]
+
+ if channels > psd_channels:
+ msg = "not enough channels"
+ raise OSError(msg)
+ if mode == "RGB" and psd_channels == 4:
+ mode = "RGBA"
+ channels = 4
+
+ self._mode = mode
+ self._size = i32(s, 18), i32(s, 14)
+
+ #
+ # color mode data
+
+ size = i32(read(4))
+ if size:
+ data = read(size)
+ if mode == "P" and size == 768:
+ self.palette = ImagePalette.raw("RGB;L", data)
+
+ #
+ # image resources
+
+ self.resources = []
+
+ size = i32(read(4))
+ if size:
+ # load resources
+ end = self.fp.tell() + size
+ while self.fp.tell() < end:
+ read(4) # signature
+ id = i16(read(2))
+ name = read(i8(read(1)))
+ if not (len(name) & 1):
+ read(1) # padding
+ data = read(i32(read(4)))
+ if len(data) & 1:
+ read(1) # padding
+ self.resources.append((id, name, data))
+ if id == 1039: # ICC profile
+ self.info["icc_profile"] = data
+
+ #
+ # layer and mask information
+
+ self._layers_position = None
+
+ size = i32(read(4))
+ if size:
+ end = self.fp.tell() + size
+ size = i32(read(4))
+ if size:
+ self._layers_position = self.fp.tell()
+ self._layers_size = size
+ self.fp.seek(end)
+ self._n_frames: int | None = None
+
+ #
+ # image descriptor
+
+ self.tile = _maketile(self.fp, mode, (0, 0) + self.size, channels)
+
+ # keep the file open
+ self._fp = self.fp
+ self.frame = 1
+ self._min_frame = 1
+
+ @cached_property
+ def layers(
+ self,
+ ) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]:
+ layers = []
+ if self._layers_position is not None:
+ if isinstance(self._fp, DeferredError):
+ raise self._fp.ex
+ self._fp.seek(self._layers_position)
+ _layer_data = io.BytesIO(ImageFile._safe_read(self._fp, self._layers_size))
+ layers = _layerinfo(_layer_data, self._layers_size)
+ self._n_frames = len(layers)
+ return layers
+
+ @property
+ def n_frames(self) -> int:
+ if self._n_frames is None:
+ self._n_frames = len(self.layers)
+ return self._n_frames
+
+ @property
+ def is_animated(self) -> bool:
+ return len(self.layers) > 1
+
+ def seek(self, layer: int) -> None:
+ if not self._seek_check(layer):
+ return
+ if isinstance(self._fp, DeferredError):
+ raise self._fp.ex
+
+ # seek to given layer (1..max)
+ _, mode, _, tile = self.layers[layer - 1]
+ self._mode = mode
+ self.tile = tile
+ self.frame = layer
+ self.fp = self._fp
+
+ def tell(self) -> int:
+ # return layer number (0=image, 1..max=layers)
+ return self.frame
+
+
+def _layerinfo(
+ fp: IO[bytes], ct_bytes: int
+) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]:
+ # read layerinfo block
+ layers = []
+
+ def read(size: int) -> bytes:
+ return ImageFile._safe_read(fp, size)
+
+ ct = si16(read(2))
+
+ # sanity check
+ if ct_bytes < (abs(ct) * 20):
+ msg = "Layer block too short for number of layers requested"
+ raise SyntaxError(msg)
+
+ for _ in range(abs(ct)):
+ # bounding box
+ y0 = si32(read(4))
+ x0 = si32(read(4))
+ y1 = si32(read(4))
+ x1 = si32(read(4))
+
+ # image info
+ bands = []
+ ct_types = i16(read(2))
+ if ct_types > 4:
+ fp.seek(ct_types * 6 + 12, io.SEEK_CUR)
+ size = i32(read(4))
+ fp.seek(size, io.SEEK_CUR)
+ continue
+
+ for _ in range(ct_types):
+ type = i16(read(2))
+
+ if type == 65535:
+ b = "A"
+ else:
+ b = "RGBA"[type]
+
+ bands.append(b)
+ read(4) # size
+
+ # figure out the image mode
+ bands.sort()
+ if bands == ["R"]:
+ mode = "L"
+ elif bands == ["B", "G", "R"]:
+ mode = "RGB"
+ elif bands == ["A", "B", "G", "R"]:
+ mode = "RGBA"
+ else:
+ mode = "" # unknown
+
+ # skip over blend flags and extra information
+ read(12) # filler
+ name = ""
+ size = i32(read(4)) # length of the extra data field
+ if size:
+ data_end = fp.tell() + size
+
+ length = i32(read(4))
+ if length:
+ fp.seek(length - 16, io.SEEK_CUR)
+
+ length = i32(read(4))
+ if length:
+ fp.seek(length, io.SEEK_CUR)
+
+ length = i8(read(1))
+ if length:
+ # Don't know the proper encoding,
+ # Latin-1 should be a good guess
+ name = read(length).decode("latin-1", "replace")
+
+ fp.seek(data_end)
+ layers.append((name, mode, (x0, y0, x1, y1)))
+
+ # get tiles
+ layerinfo = []
+ for i, (name, mode, bbox) in enumerate(layers):
+ tile = []
+ for m in mode:
+ t = _maketile(fp, m, bbox, 1)
+ if t:
+ tile.extend(t)
+ layerinfo.append((name, mode, bbox, tile))
+
+ return layerinfo
+
+
+def _maketile(
+ file: IO[bytes], mode: str, bbox: tuple[int, int, int, int], channels: int
+) -> list[ImageFile._Tile]:
+ tiles = []
+ read = file.read
+
+ compression = i16(read(2))
+
+ xsize = bbox[2] - bbox[0]
+ ysize = bbox[3] - bbox[1]
+
+ offset = file.tell()
+
+ if compression == 0:
+ #
+ # raw compression
+ for channel in range(channels):
+ layer = mode[channel]
+ if mode == "CMYK":
+ layer += ";I"
+ tiles.append(ImageFile._Tile("raw", bbox, offset, layer))
+ offset = offset + xsize * ysize
+
+ elif compression == 1:
+ #
+ # packbits compression
+ i = 0
+ bytecount = read(channels * ysize * 2)
+ offset = file.tell()
+ for channel in range(channels):
+ layer = mode[channel]
+ if mode == "CMYK":
+ layer += ";I"
+ tiles.append(ImageFile._Tile("packbits", bbox, offset, layer))
+ for y in range(ysize):
+ offset = offset + i16(bytecount, i)
+ i += 2
+
+ file.seek(offset)
+
+ if offset & 1:
+ read(1) # padding
+
+ return tiles
+
+
+# --------------------------------------------------------------------
+# registry
+
+
+Image.register_open(PsdImageFile.format, PsdImageFile, _accept)
+
+Image.register_extension(PsdImageFile.format, ".psd")
+
+Image.register_mime(PsdImageFile.format, "image/vnd.adobe.photoshop")
diff --git a/venv/Lib/site-packages/PIL/QoiImagePlugin.py b/venv/Lib/site-packages/PIL/QoiImagePlugin.py
new file mode 100644
index 0000000..d0709b1
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/QoiImagePlugin.py
@@ -0,0 +1,235 @@
+#
+# The Python Imaging Library.
+#
+# QOI support for PIL
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import os
+from typing import IO
+
+from . import Image, ImageFile
+from ._binary import i32be as i32
+from ._binary import o8
+from ._binary import o32be as o32
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(b"qoif")
+
+
+class QoiImageFile(ImageFile.ImageFile):
+ format = "QOI"
+ format_description = "Quite OK Image"
+
+ def _open(self) -> None:
+ assert self.fp is not None
+ if not _accept(self.fp.read(4)):
+ msg = "not a QOI file"
+ raise SyntaxError(msg)
+
+ self._size = i32(self.fp.read(4)), i32(self.fp.read(4))
+
+ channels = self.fp.read(1)[0]
+ self._mode = "RGB" if channels == 3 else "RGBA"
+
+ self.fp.seek(1, os.SEEK_CUR) # colorspace
+ self.tile = [ImageFile._Tile("qoi", (0, 0) + self._size, self.fp.tell())]
+
+
+class QoiDecoder(ImageFile.PyDecoder):
+ _pulls_fd = True
+ _previous_pixel: bytes | bytearray | None = None
+ _previously_seen_pixels: dict[int, bytes | bytearray] = {}
+
+ def _add_to_previous_pixels(self, value: bytes | bytearray) -> None:
+ self._previous_pixel = value
+
+ r, g, b, a = value
+ hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64
+ self._previously_seen_pixels[hash_value] = value
+
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+ assert self.fd is not None
+
+ self._previously_seen_pixels = {}
+ self._previous_pixel = bytearray((0, 0, 0, 255))
+
+ data = bytearray()
+ bands = Image.getmodebands(self.mode)
+ dest_length = self.state.xsize * self.state.ysize * bands
+ while len(data) < dest_length:
+ byte = self.fd.read(1)[0]
+ value: bytes | bytearray
+ if byte == 0b11111110 and self._previous_pixel: # QOI_OP_RGB
+ value = bytearray(self.fd.read(3)) + self._previous_pixel[3:]
+ elif byte == 0b11111111: # QOI_OP_RGBA
+ value = self.fd.read(4)
+ else:
+ op = byte >> 6
+ if op == 0: # QOI_OP_INDEX
+ op_index = byte & 0b00111111
+ value = self._previously_seen_pixels.get(
+ op_index, bytearray((0, 0, 0, 0))
+ )
+ elif op == 1 and self._previous_pixel: # QOI_OP_DIFF
+ value = bytearray(
+ (
+ (self._previous_pixel[0] + ((byte & 0b00110000) >> 4) - 2)
+ % 256,
+ (self._previous_pixel[1] + ((byte & 0b00001100) >> 2) - 2)
+ % 256,
+ (self._previous_pixel[2] + (byte & 0b00000011) - 2) % 256,
+ self._previous_pixel[3],
+ )
+ )
+ elif op == 2 and self._previous_pixel: # QOI_OP_LUMA
+ second_byte = self.fd.read(1)[0]
+ diff_green = (byte & 0b00111111) - 32
+ diff_red = ((second_byte & 0b11110000) >> 4) - 8
+ diff_blue = (second_byte & 0b00001111) - 8
+
+ value = bytearray(
+ tuple(
+ (self._previous_pixel[i] + diff_green + diff) % 256
+ for i, diff in enumerate((diff_red, 0, diff_blue))
+ )
+ )
+ value += self._previous_pixel[3:]
+ elif op == 3 and self._previous_pixel: # QOI_OP_RUN
+ run_length = (byte & 0b00111111) + 1
+ value = self._previous_pixel
+ if bands == 3:
+ value = value[:3]
+ data += value * run_length
+ continue
+ self._add_to_previous_pixels(value)
+
+ if bands == 3:
+ value = value[:3]
+ data += value
+ self.set_as_raw(data)
+ return -1, 0
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if im.mode == "RGB":
+ channels = 3
+ elif im.mode == "RGBA":
+ channels = 4
+ else:
+ msg = "Unsupported QOI image mode"
+ raise ValueError(msg)
+
+ colorspace = 0 if im.encoderinfo.get("colorspace") == "sRGB" else 1
+
+ fp.write(b"qoif")
+ fp.write(o32(im.size[0]))
+ fp.write(o32(im.size[1]))
+ fp.write(o8(channels))
+ fp.write(o8(colorspace))
+
+ ImageFile._save(im, fp, [ImageFile._Tile("qoi", (0, 0) + im.size)])
+
+
+class QoiEncoder(ImageFile.PyEncoder):
+ _pushes_fd = True
+ _previous_pixel: tuple[int, int, int, int] | None = None
+ _previously_seen_pixels: dict[int, tuple[int, int, int, int]] = {}
+ _run = 0
+
+ def _write_run(self) -> bytes:
+ data = o8(0b11000000 | (self._run - 1)) # QOI_OP_RUN
+ self._run = 0
+ return data
+
+ def _delta(self, left: int, right: int) -> int:
+ result = (left - right) & 255
+ if result >= 128:
+ result -= 256
+ return result
+
+ def encode(self, bufsize: int) -> tuple[int, int, bytes]:
+ assert self.im is not None
+
+ self._previously_seen_pixels = {0: (0, 0, 0, 0)}
+ self._previous_pixel = (0, 0, 0, 255)
+
+ data = bytearray()
+ w, h = self.im.size
+ bands = Image.getmodebands(self.mode)
+
+ for y in range(h):
+ for x in range(w):
+ pixel = self.im.getpixel((x, y))
+ if bands == 3:
+ pixel = (*pixel, 255)
+
+ if pixel == self._previous_pixel:
+ self._run += 1
+ if self._run == 62:
+ data += self._write_run()
+ else:
+ if self._run:
+ data += self._write_run()
+
+ r, g, b, a = pixel
+ hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64
+ if self._previously_seen_pixels.get(hash_value) == pixel:
+ data += o8(hash_value) # QOI_OP_INDEX
+ elif self._previous_pixel:
+ self._previously_seen_pixels[hash_value] = pixel
+
+ prev_r, prev_g, prev_b, prev_a = self._previous_pixel
+ if prev_a == a:
+ delta_r = self._delta(r, prev_r)
+ delta_g = self._delta(g, prev_g)
+ delta_b = self._delta(b, prev_b)
+
+ if (
+ -2 <= delta_r < 2
+ and -2 <= delta_g < 2
+ and -2 <= delta_b < 2
+ ):
+ data += o8(
+ 0b01000000
+ | (delta_r + 2) << 4
+ | (delta_g + 2) << 2
+ | (delta_b + 2)
+ ) # QOI_OP_DIFF
+ else:
+ delta_gr = self._delta(delta_r, delta_g)
+ delta_gb = self._delta(delta_b, delta_g)
+ if (
+ -8 <= delta_gr < 8
+ and -32 <= delta_g < 32
+ and -8 <= delta_gb < 8
+ ):
+ data += o8(
+ 0b10000000 | (delta_g + 32)
+ ) # QOI_OP_LUMA
+ data += o8((delta_gr + 8) << 4 | (delta_gb + 8))
+ else:
+ data += o8(0b11111110) # QOI_OP_RGB
+ data += bytes(pixel[:3])
+ else:
+ data += o8(0b11111111) # QOI_OP_RGBA
+ data += bytes(pixel)
+
+ self._previous_pixel = pixel
+
+ if self._run:
+ data += self._write_run()
+ data += bytes((0, 0, 0, 0, 0, 0, 0, 1)) # padding
+
+ return len(data), 0, data
+
+
+Image.register_open(QoiImageFile.format, QoiImageFile, _accept)
+Image.register_decoder("qoi", QoiDecoder)
+Image.register_extension(QoiImageFile.format, ".qoi")
+
+Image.register_save(QoiImageFile.format, _save)
+Image.register_encoder("qoi", QoiEncoder)
diff --git a/venv/Lib/site-packages/PIL/SgiImagePlugin.py b/venv/Lib/site-packages/PIL/SgiImagePlugin.py
new file mode 100644
index 0000000..8530221
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/SgiImagePlugin.py
@@ -0,0 +1,231 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# SGI image file handling
+#
+# See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli.
+#
+#
+#
+# History:
+# 2017-22-07 mb Add RLE decompression
+# 2016-16-10 mb Add save method without compression
+# 1995-09-10 fl Created
+#
+# Copyright (c) 2016 by Mickael Bonfill.
+# Copyright (c) 2008 by Karsten Hiddemann.
+# Copyright (c) 1997 by Secret Labs AB.
+# Copyright (c) 1995 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import os
+import struct
+from typing import IO
+
+from . import Image, ImageFile
+from ._binary import i16be as i16
+from ._binary import o8
+
+
+def _accept(prefix: bytes) -> bool:
+ return len(prefix) >= 2 and i16(prefix) == 474
+
+
+MODES = {
+ (1, 1, 1): "L",
+ (1, 2, 1): "L",
+ (2, 1, 1): "L;16B",
+ (2, 2, 1): "L;16B",
+ (1, 3, 3): "RGB",
+ (2, 3, 3): "RGB;16B",
+ (1, 3, 4): "RGBA",
+ (2, 3, 4): "RGBA;16B",
+}
+
+
+##
+# Image plugin for SGI images.
+class SgiImageFile(ImageFile.ImageFile):
+ format = "SGI"
+ format_description = "SGI Image File Format"
+
+ def _open(self) -> None:
+ # HEAD
+ assert self.fp is not None
+
+ headlen = 512
+ s = self.fp.read(headlen)
+
+ if not _accept(s):
+ msg = "Not an SGI image file"
+ raise ValueError(msg)
+
+ # compression : verbatim or RLE
+ compression = s[2]
+
+ # bpc : 1 or 2 bytes (8bits or 16bits)
+ bpc = s[3]
+
+ # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize)
+ dimension = i16(s, 4)
+
+ # xsize : width
+ xsize = i16(s, 6)
+
+ # ysize : height
+ ysize = i16(s, 8)
+
+ # zsize : channels count
+ zsize = i16(s, 10)
+
+ # determine mode from bits/zsize
+ try:
+ rawmode = MODES[(bpc, dimension, zsize)]
+ except KeyError:
+ msg = "Unsupported SGI image mode"
+ raise ValueError(msg)
+
+ self._size = xsize, ysize
+ self._mode = rawmode.split(";")[0]
+ if self.mode == "RGB":
+ self.custom_mimetype = "image/rgb"
+
+ # orientation -1 : scanlines begins at the bottom-left corner
+ orientation = -1
+
+ # decoder info
+ if compression == 0:
+ pagesize = xsize * ysize * bpc
+ if bpc == 2:
+ self.tile = [
+ ImageFile._Tile(
+ "SGI16",
+ (0, 0) + self.size,
+ headlen,
+ (self.mode, 0, orientation),
+ )
+ ]
+ else:
+ self.tile = []
+ offset = headlen
+ for layer in self.mode:
+ self.tile.append(
+ ImageFile._Tile(
+ "raw", (0, 0) + self.size, offset, (layer, 0, orientation)
+ )
+ )
+ offset += pagesize
+ elif compression == 1:
+ self.tile = [
+ ImageFile._Tile(
+ "sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc)
+ )
+ ]
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if im.mode not in {"RGB", "RGBA", "L"}:
+ msg = "Unsupported SGI image mode"
+ raise ValueError(msg)
+
+ # Get the keyword arguments
+ info = im.encoderinfo
+
+ # Byte-per-pixel precision, 1 = 8bits per pixel
+ bpc = info.get("bpc", 1)
+
+ if bpc not in (1, 2):
+ msg = "Unsupported number of bytes per pixel"
+ raise ValueError(msg)
+
+ # Flip the image, since the origin of SGI file is the bottom-left corner
+ orientation = -1
+ # Define the file as SGI File Format
+ magic_number = 474
+ # Run-Length Encoding Compression - Unsupported at this time
+ rle = 0
+
+ # X Dimension = width / Y Dimension = height
+ x, y = im.size
+ # Z Dimension: Number of channels
+ z = len(im.mode)
+ # Number of dimensions (x,y,z)
+ if im.mode == "L":
+ dimension = 1 if y == 1 else 2
+ else:
+ dimension = 3
+
+ # Minimum Byte value
+ pinmin = 0
+ # Maximum Byte value (255 = 8bits per pixel)
+ pinmax = 255
+ # Image name (79 characters max, truncated below in write)
+ img_name = os.path.splitext(os.path.basename(filename))[0]
+ if isinstance(img_name, str):
+ img_name = img_name.encode("ascii", "ignore")
+ # Standard representation of pixel in the file
+ colormap = 0
+ fp.write(struct.pack(">h", magic_number))
+ fp.write(o8(rle))
+ fp.write(o8(bpc))
+ fp.write(struct.pack(">H", dimension))
+ fp.write(struct.pack(">H", x))
+ fp.write(struct.pack(">H", y))
+ fp.write(struct.pack(">H", z))
+ fp.write(struct.pack(">l", pinmin))
+ fp.write(struct.pack(">l", pinmax))
+ fp.write(struct.pack("4s", b"")) # dummy
+ fp.write(struct.pack("79s", img_name)) # truncates to 79 chars
+ fp.write(struct.pack("s", b"")) # force null byte after img_name
+ fp.write(struct.pack(">l", colormap))
+ fp.write(struct.pack("404s", b"")) # dummy
+
+ rawmode = "L"
+ if bpc == 2:
+ rawmode = "L;16B"
+
+ for channel in im.split():
+ fp.write(channel.tobytes("raw", rawmode, 0, orientation))
+
+ if hasattr(fp, "flush"):
+ fp.flush()
+
+
+class SGI16Decoder(ImageFile.PyDecoder):
+ _pulls_fd = True
+
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+ assert self.fd is not None
+ assert self.im is not None
+
+ rawmode, stride, orientation = self.args
+ pagesize = self.state.xsize * self.state.ysize
+ zsize = len(self.mode)
+ self.fd.seek(512)
+
+ for band in range(zsize):
+ channel = Image.new("L", (self.state.xsize, self.state.ysize))
+ channel.frombytes(
+ self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation
+ )
+ self.im.putband(channel.im, band)
+
+ return -1, 0
+
+
+#
+# registry
+
+
+Image.register_decoder("SGI16", SGI16Decoder)
+Image.register_open(SgiImageFile.format, SgiImageFile, _accept)
+Image.register_save(SgiImageFile.format, _save)
+Image.register_mime(SgiImageFile.format, "image/sgi")
+
+Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"])
+
+# End of file
diff --git a/venv/Lib/site-packages/PIL/SpiderImagePlugin.py b/venv/Lib/site-packages/PIL/SpiderImagePlugin.py
new file mode 100644
index 0000000..8662922
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/SpiderImagePlugin.py
@@ -0,0 +1,332 @@
+#
+# The Python Imaging Library.
+#
+# SPIDER image file handling
+#
+# History:
+# 2004-08-02 Created BB
+# 2006-03-02 added save method
+# 2006-03-13 added support for stack images
+#
+# Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144.
+# Copyright (c) 2004 by William Baxter.
+# Copyright (c) 2004 by Secret Labs AB.
+# Copyright (c) 2004 by Fredrik Lundh.
+#
+
+##
+# Image plugin for the Spider image format. This format is used
+# by the SPIDER software, in processing image data from electron
+# microscopy and tomography.
+##
+
+#
+# SpiderImagePlugin.py
+#
+# The Spider image format is used by SPIDER software, in processing
+# image data from electron microscopy and tomography.
+#
+# Spider home page:
+# https://spider.wadsworth.org/spider_doc/spider/docs/spider.html
+#
+# Details about the Spider image format:
+# https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html
+#
+from __future__ import annotations
+
+import os
+import struct
+import sys
+from typing import IO, Any, cast
+
+from . import Image, ImageFile
+from ._util import DeferredError
+
+TYPE_CHECKING = False
+
+
+def isInt(f: Any) -> int:
+ try:
+ i = int(f)
+ if f - i == 0:
+ return 1
+ else:
+ return 0
+ except (ValueError, OverflowError):
+ return 0
+
+
+iforms = [1, 3, -11, -12, -21, -22]
+
+
+# There is no magic number to identify Spider files, so just check a
+# series of header locations to see if they have reasonable values.
+# Returns no. of bytes in the header, if it is a valid Spider header,
+# otherwise returns 0
+
+
+def isSpiderHeader(t: tuple[float, ...]) -> int:
+ h = (99,) + t # add 1 value so can use spider header index start=1
+ # header values 1,2,5,12,13,22,23 should be integers
+ for i in [1, 2, 5, 12, 13, 22, 23]:
+ if not isInt(h[i]):
+ return 0
+ # check iform
+ iform = int(h[5])
+ if iform not in iforms:
+ return 0
+ # check other header values
+ labrec = int(h[13]) # no. records in file header
+ labbyt = int(h[22]) # total no. of bytes in header
+ lenbyt = int(h[23]) # record length in bytes
+ if labbyt != (labrec * lenbyt):
+ return 0
+ # looks like a valid header
+ return labbyt
+
+
+def isSpiderImage(filename: str) -> int:
+ with open(filename, "rb") as fp:
+ f = fp.read(92) # read 23 * 4 bytes
+ t = struct.unpack(">23f", f) # try big-endian first
+ hdrlen = isSpiderHeader(t)
+ if hdrlen == 0:
+ t = struct.unpack("<23f", f) # little-endian
+ hdrlen = isSpiderHeader(t)
+ return hdrlen
+
+
+class SpiderImageFile(ImageFile.ImageFile):
+ format = "SPIDER"
+ format_description = "Spider 2D image"
+ _close_exclusive_fp_after_loading = False
+
+ def _open(self) -> None:
+ # check header
+ n = 27 * 4 # read 27 float values
+ assert self.fp is not None
+ f = self.fp.read(n)
+
+ try:
+ self.bigendian = 1
+ t = struct.unpack(">27f", f) # try big-endian first
+ hdrlen = isSpiderHeader(t)
+ if hdrlen == 0:
+ self.bigendian = 0
+ t = struct.unpack("<27f", f) # little-endian
+ hdrlen = isSpiderHeader(t)
+ if hdrlen == 0:
+ msg = "not a valid Spider file"
+ raise SyntaxError(msg)
+ except struct.error as e:
+ msg = "not a valid Spider file"
+ raise SyntaxError(msg) from e
+
+ h = (99,) + t # add 1 value : spider header index starts at 1
+ iform = int(h[5])
+ if iform != 1:
+ msg = "not a Spider 2D image"
+ raise SyntaxError(msg)
+
+ self._size = int(h[12]), int(h[2]) # size in pixels (width, height)
+ self.istack = int(h[24])
+ self.imgnumber = int(h[27])
+
+ if self.istack == 0 and self.imgnumber == 0:
+ # stk=0, img=0: a regular 2D image
+ offset = hdrlen
+ self._nimages = 1
+ elif self.istack > 0 and self.imgnumber == 0:
+ # stk>0, img=0: Opening the stack for the first time
+ self.imgbytes = int(h[12]) * int(h[2]) * 4
+ self.hdrlen = hdrlen
+ self._nimages = int(h[26])
+ # Point to the first image in the stack
+ offset = hdrlen * 2
+ self.imgnumber = 1
+ elif self.istack == 0 and self.imgnumber > 0:
+ # stk=0, img>0: an image within the stack
+ offset = hdrlen + self.stkoffset
+ self.istack = 2 # So Image knows it's still a stack
+ else:
+ msg = "inconsistent stack header values"
+ raise SyntaxError(msg)
+
+ if self.bigendian:
+ self.rawmode = "F;32BF"
+ else:
+ self.rawmode = "F;32F"
+ self._mode = "F"
+
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, offset, self.rawmode)]
+ self._fp = self.fp # FIXME: hack
+
+ @property
+ def n_frames(self) -> int:
+ return self._nimages
+
+ @property
+ def is_animated(self) -> bool:
+ return self._nimages > 1
+
+ # 1st image index is zero (although SPIDER imgnumber starts at 1)
+ def tell(self) -> int:
+ if self.imgnumber < 1:
+ return 0
+ else:
+ return self.imgnumber - 1
+
+ def seek(self, frame: int) -> None:
+ if self.istack == 0:
+ msg = "attempt to seek in a non-stack file"
+ raise EOFError(msg)
+ if not self._seek_check(frame):
+ return
+ if isinstance(self._fp, DeferredError):
+ raise self._fp.ex
+ self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes)
+ self.fp = self._fp
+ self.fp.seek(self.stkoffset)
+ self._open()
+
+ # returns a byte image after rescaling to 0..255
+ def convert2byte(self, depth: int = 255) -> Image.Image:
+ extrema = self.getextrema()
+ assert isinstance(extrema[0], float)
+ minimum, maximum = cast(tuple[float, float], extrema)
+ m: float = 1
+ if maximum != minimum:
+ m = depth / (maximum - minimum)
+ b = -m * minimum
+ return self.point(lambda i: i * m + b).convert("L")
+
+ if TYPE_CHECKING:
+ from . import ImageTk
+
+ # returns a ImageTk.PhotoImage object, after rescaling to 0..255
+ def tkPhotoImage(self) -> ImageTk.PhotoImage:
+ from . import ImageTk
+
+ return ImageTk.PhotoImage(self.convert2byte(), palette=256)
+
+
+# --------------------------------------------------------------------
+# Image series
+
+
+# given a list of filenames, return a list of images
+def loadImageSeries(filelist: list[str] | None = None) -> list[Image.Image] | None:
+ """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage"""
+ if filelist is None or len(filelist) < 1:
+ return None
+
+ byte_imgs = []
+ for img in filelist:
+ if not os.path.exists(img):
+ print(f"unable to find {img}")
+ continue
+ try:
+ with Image.open(img) as im:
+ assert isinstance(im, SpiderImageFile)
+ byte_im = im.convert2byte()
+ except Exception:
+ if not isSpiderImage(img):
+ print(f"{img} is not a Spider image file")
+ continue
+ byte_im.info["filename"] = img
+ byte_imgs.append(byte_im)
+ return byte_imgs
+
+
+# --------------------------------------------------------------------
+# For saving images in Spider format
+
+
+def makeSpiderHeader(im: Image.Image) -> list[bytes]:
+ nsam, nrow = im.size
+ lenbyt = nsam * 4 # There are labrec records in the header
+ labrec = int(1024 / lenbyt)
+ if 1024 % lenbyt != 0:
+ labrec += 1
+ labbyt = labrec * lenbyt
+ nvalues = int(labbyt / 4)
+ if nvalues < 23:
+ return []
+
+ hdr = [0.0] * nvalues
+
+ # NB these are Fortran indices
+ hdr[1] = 1.0 # nslice (=1 for an image)
+ hdr[2] = float(nrow) # number of rows per slice
+ hdr[3] = float(nrow) # number of records in the image
+ hdr[5] = 1.0 # iform for 2D image
+ hdr[12] = float(nsam) # number of pixels per line
+ hdr[13] = float(labrec) # number of records in file header
+ hdr[22] = float(labbyt) # total number of bytes in header
+ hdr[23] = float(lenbyt) # record length in bytes
+
+ # adjust for Fortran indexing
+ hdr = hdr[1:]
+ hdr.append(0.0)
+ # pack binary data into a string
+ return [struct.pack("f", v) for v in hdr]
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if im.mode != "F":
+ im = im.convert("F")
+
+ hdr = makeSpiderHeader(im)
+ if len(hdr) < 256:
+ msg = "Error creating Spider header"
+ raise OSError(msg)
+
+ # write the SPIDER header
+ fp.writelines(hdr)
+
+ rawmode = "F;32NF" # 32-bit native floating point
+ ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, rawmode)])
+
+
+def _save_spider(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ # get the filename extension and register it with Image
+ filename_ext = os.path.splitext(filename)[1]
+ ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext
+ Image.register_extension(SpiderImageFile.format, ext)
+ _save(im, fp, filename)
+
+
+# --------------------------------------------------------------------
+
+
+Image.register_open(SpiderImageFile.format, SpiderImageFile)
+Image.register_save(SpiderImageFile.format, _save_spider)
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]")
+ sys.exit()
+
+ filename = sys.argv[1]
+ if not isSpiderImage(filename):
+ print("input image must be in Spider format")
+ sys.exit()
+
+ with Image.open(filename) as im:
+ print(f"image: {im}")
+ print(f"format: {im.format}")
+ print(f"size: {im.size}")
+ print(f"mode: {im.mode}")
+ print("max, min: ", end=" ")
+ print(im.getextrema())
+
+ if len(sys.argv) > 2:
+ outfile = sys.argv[2]
+
+ # perform some image operation
+ transposed_im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
+ print(
+ f"saving a flipped version of {os.path.basename(filename)} "
+ f"as {outfile} "
+ )
+ transposed_im.save(outfile, SpiderImageFile.format)
diff --git a/venv/Lib/site-packages/PIL/SunImagePlugin.py b/venv/Lib/site-packages/PIL/SunImagePlugin.py
new file mode 100644
index 0000000..8912379
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/SunImagePlugin.py
@@ -0,0 +1,145 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# Sun image file handling
+#
+# History:
+# 1995-09-10 fl Created
+# 1996-05-28 fl Fixed 32-bit alignment
+# 1998-12-29 fl Import ImagePalette module
+# 2001-12-18 fl Fixed palette loading (from Jean-Claude Rimbault)
+#
+# Copyright (c) 1997-2001 by Secret Labs AB
+# Copyright (c) 1995-1996 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+from . import Image, ImageFile, ImagePalette
+from ._binary import i32be as i32
+
+
+def _accept(prefix: bytes) -> bool:
+ return len(prefix) >= 4 and i32(prefix) == 0x59A66A95
+
+
+##
+# Image plugin for Sun raster files.
+
+
+class SunImageFile(ImageFile.ImageFile):
+ format = "SUN"
+ format_description = "Sun Raster File"
+
+ def _open(self) -> None:
+ # The Sun Raster file header is 32 bytes in length
+ # and has the following format:
+
+ # typedef struct _SunRaster
+ # {
+ # DWORD MagicNumber; /* Magic (identification) number */
+ # DWORD Width; /* Width of image in pixels */
+ # DWORD Height; /* Height of image in pixels */
+ # DWORD Depth; /* Number of bits per pixel */
+ # DWORD Length; /* Size of image data in bytes */
+ # DWORD Type; /* Type of raster file */
+ # DWORD ColorMapType; /* Type of color map */
+ # DWORD ColorMapLength; /* Size of the color map in bytes */
+ # } SUNRASTER;
+
+ assert self.fp is not None
+
+ # HEAD
+ s = self.fp.read(32)
+ if not _accept(s):
+ msg = "not an SUN raster file"
+ raise SyntaxError(msg)
+
+ offset = 32
+
+ self._size = i32(s, 4), i32(s, 8)
+
+ depth = i32(s, 12)
+ # data_length = i32(s, 16) # unreliable, ignore.
+ file_type = i32(s, 20)
+ palette_type = i32(s, 24) # 0: None, 1: RGB, 2: Raw/arbitrary
+ palette_length = i32(s, 28)
+
+ if depth == 1:
+ self._mode, rawmode = "1", "1;I"
+ elif depth == 4:
+ self._mode, rawmode = "L", "L;4"
+ elif depth == 8:
+ self._mode = rawmode = "L"
+ elif depth == 24:
+ if file_type == 3:
+ self._mode, rawmode = "RGB", "RGB"
+ else:
+ self._mode, rawmode = "RGB", "BGR"
+ elif depth == 32:
+ if file_type == 3:
+ self._mode, rawmode = "RGB", "RGBX"
+ else:
+ self._mode, rawmode = "RGB", "BGRX"
+ else:
+ msg = "Unsupported Mode/Bit Depth"
+ raise SyntaxError(msg)
+
+ if palette_length:
+ if palette_length > 1024:
+ msg = "Unsupported Color Palette Length"
+ raise SyntaxError(msg)
+
+ if palette_type != 1:
+ msg = "Unsupported Palette Type"
+ raise SyntaxError(msg)
+
+ offset = offset + palette_length
+ self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length))
+ if self.mode == "L":
+ self._mode = "P"
+ rawmode = rawmode.replace("L", "P")
+
+ # 16 bit boundaries on stride
+ stride = ((self.size[0] * depth + 15) // 16) * 2
+
+ # file type: Type is the version (or flavor) of the bitmap
+ # file. The following values are typically found in the Type
+ # field:
+ # 0000h Old
+ # 0001h Standard
+ # 0002h Byte-encoded
+ # 0003h RGB format
+ # 0004h TIFF format
+ # 0005h IFF format
+ # FFFFh Experimental
+
+ # Old and standard are the same, except for the length tag.
+ # byte-encoded is run-length-encoded
+ # RGB looks similar to standard, but RGB byte order
+ # TIFF and IFF mean that they were converted from T/IFF
+ # Experimental means that it's something else.
+ # (https://www.fileformat.info/format/sunraster/egff.htm)
+
+ if file_type in (0, 1, 3, 4, 5):
+ self.tile = [
+ ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride))
+ ]
+ elif file_type == 2:
+ self.tile = [
+ ImageFile._Tile("sun_rle", (0, 0) + self.size, offset, rawmode)
+ ]
+ else:
+ msg = "Unsupported Sun Raster file type"
+ raise SyntaxError(msg)
+
+
+#
+# registry
+
+
+Image.register_open(SunImageFile.format, SunImageFile, _accept)
+
+Image.register_extension(SunImageFile.format, ".ras")
diff --git a/venv/Lib/site-packages/PIL/TarIO.py b/venv/Lib/site-packages/PIL/TarIO.py
new file mode 100644
index 0000000..86490a4
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/TarIO.py
@@ -0,0 +1,61 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# read files from within a tar file
+#
+# History:
+# 95-06-18 fl Created
+# 96-05-28 fl Open files in binary mode
+#
+# Copyright (c) Secret Labs AB 1997.
+# Copyright (c) Fredrik Lundh 1995-96.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import io
+
+from . import ContainerIO
+
+
+class TarIO(ContainerIO.ContainerIO[bytes]):
+ """A file object that provides read access to a given member of a TAR file."""
+
+ def __init__(self, tarfile: str, file: str) -> None:
+ """
+ Create file object.
+
+ :param tarfile: Name of TAR file.
+ :param file: Name of member file.
+ """
+ self.fh = open(tarfile, "rb")
+
+ while True:
+ s = self.fh.read(512)
+ if len(s) != 512:
+ self.fh.close()
+
+ msg = "unexpected end of tar file"
+ raise OSError(msg)
+
+ name = s[:100].decode("utf-8")
+ i = name.find("\0")
+ if i == 0:
+ self.fh.close()
+
+ msg = "cannot find subfile"
+ raise OSError(msg)
+ if i > 0:
+ name = name[:i]
+
+ size = int(s[124:135], 8)
+
+ if file == name:
+ break
+
+ self.fh.seek((size + 511) & (~511), io.SEEK_CUR)
+
+ # Open region
+ super().__init__(self.fh, self.fh.tell(), size)
diff --git a/venv/Lib/site-packages/PIL/TgaImagePlugin.py b/venv/Lib/site-packages/PIL/TgaImagePlugin.py
new file mode 100644
index 0000000..90d5b5c
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/TgaImagePlugin.py
@@ -0,0 +1,264 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# TGA file handling
+#
+# History:
+# 95-09-01 fl created (reads 24-bit files only)
+# 97-01-04 fl support more TGA versions, including compressed images
+# 98-07-04 fl fixed orientation and alpha layer bugs
+# 98-09-11 fl fixed orientation for runlength decoder
+#
+# Copyright (c) Secret Labs AB 1997-98.
+# Copyright (c) Fredrik Lundh 1995-97.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import warnings
+from typing import IO
+
+from . import Image, ImageFile, ImagePalette
+from ._binary import i16le as i16
+from ._binary import o8
+from ._binary import o16le as o16
+
+#
+# --------------------------------------------------------------------
+# Read RGA file
+
+
+MODES = {
+ # map imagetype/depth to rawmode
+ (1, 8): "P",
+ (3, 1): "1",
+ (3, 8): "L",
+ (3, 16): "LA",
+ (2, 16): "BGRA;15Z",
+ (2, 24): "BGR",
+ (2, 32): "BGRA",
+}
+
+
+##
+# Image plugin for Targa files.
+
+
+class TgaImageFile(ImageFile.ImageFile):
+ format = "TGA"
+ format_description = "Targa"
+
+ def _open(self) -> None:
+ # process header
+ assert self.fp is not None
+
+ s = self.fp.read(18)
+
+ id_len = s[0]
+
+ colormaptype = s[1]
+ imagetype = s[2]
+
+ depth = s[16]
+
+ flags = s[17]
+
+ self._size = i16(s, 12), i16(s, 14)
+
+ # validate header fields
+ if (
+ colormaptype not in (0, 1)
+ or self.size[0] <= 0
+ or self.size[1] <= 0
+ or depth not in (1, 8, 16, 24, 32)
+ ):
+ msg = "not a TGA file"
+ raise SyntaxError(msg)
+
+ # image mode
+ if imagetype in (3, 11):
+ self._mode = "L"
+ if depth == 1:
+ self._mode = "1" # ???
+ elif depth == 16:
+ self._mode = "LA"
+ elif imagetype in (1, 9):
+ self._mode = "P" if colormaptype else "L"
+ elif imagetype in (2, 10):
+ self._mode = "RGB" if depth == 24 else "RGBA"
+ else:
+ msg = "unknown TGA mode"
+ raise SyntaxError(msg)
+
+ # orientation
+ orientation = flags & 0x30
+ self._flip_horizontally = orientation in [0x10, 0x30]
+ if orientation in [0x20, 0x30]:
+ orientation = 1
+ elif orientation in [0, 0x10]:
+ orientation = -1
+ else:
+ msg = "unknown TGA orientation"
+ raise SyntaxError(msg)
+
+ self.info["orientation"] = orientation
+
+ if imagetype & 8:
+ self.info["compression"] = "tga_rle"
+
+ if id_len:
+ self.info["id_section"] = self.fp.read(id_len)
+
+ if colormaptype:
+ # read palette
+ start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]
+ if mapdepth == 16:
+ self.palette = ImagePalette.raw(
+ "BGRA;15Z", bytes(2 * start) + self.fp.read(2 * size)
+ )
+ self.palette.mode = "RGBA"
+ elif mapdepth == 24:
+ self.palette = ImagePalette.raw(
+ "BGR", bytes(3 * start) + self.fp.read(3 * size)
+ )
+ elif mapdepth == 32:
+ self.palette = ImagePalette.raw(
+ "BGRA", bytes(4 * start) + self.fp.read(4 * size)
+ )
+ else:
+ msg = "unknown TGA map depth"
+ raise SyntaxError(msg)
+
+ # setup tile descriptor
+ try:
+ rawmode = MODES[(imagetype & 7, depth)]
+ if imagetype & 8:
+ # compressed
+ self.tile = [
+ ImageFile._Tile(
+ "tga_rle",
+ (0, 0) + self.size,
+ self.fp.tell(),
+ (rawmode, orientation, depth),
+ )
+ ]
+ else:
+ self.tile = [
+ ImageFile._Tile(
+ "raw",
+ (0, 0) + self.size,
+ self.fp.tell(),
+ (rawmode, 0, orientation),
+ )
+ ]
+ except KeyError:
+ pass # cannot decode
+
+ def load_end(self) -> None:
+ if self._flip_horizontally:
+ self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
+
+
+#
+# --------------------------------------------------------------------
+# Write TGA file
+
+
+SAVE = {
+ "1": ("1", 1, 0, 3),
+ "L": ("L", 8, 0, 3),
+ "LA": ("LA", 16, 0, 3),
+ "P": ("P", 8, 1, 1),
+ "RGB": ("BGR", 24, 0, 2),
+ "RGBA": ("BGRA", 32, 0, 2),
+}
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ try:
+ rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
+ except KeyError as e:
+ msg = f"cannot write mode {im.mode} as TGA"
+ raise OSError(msg) from e
+
+ if "rle" in im.encoderinfo:
+ rle = im.encoderinfo["rle"]
+ else:
+ compression = im.encoderinfo.get("compression", im.info.get("compression"))
+ rle = compression == "tga_rle"
+ if rle:
+ imagetype += 8
+
+ id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
+ id_len = len(id_section)
+ if id_len > 255:
+ id_len = 255
+ id_section = id_section[:255]
+ warnings.warn("id_section has been trimmed to 255 characters")
+
+ if colormaptype:
+ palette = im.im.getpalette("RGB", "BGR")
+ colormaplength, colormapentry = len(palette) // 3, 24
+ else:
+ colormaplength, colormapentry = 0, 0
+
+ if im.mode in ("LA", "RGBA"):
+ flags = 8
+ else:
+ flags = 0
+
+ orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
+ if orientation > 0:
+ flags = flags | 0x20
+
+ fp.write(
+ o8(id_len)
+ + o8(colormaptype)
+ + o8(imagetype)
+ + o16(0) # colormapfirst
+ + o16(colormaplength)
+ + o8(colormapentry)
+ + o16(0)
+ + o16(0)
+ + o16(im.size[0])
+ + o16(im.size[1])
+ + o8(bits)
+ + o8(flags)
+ )
+
+ if id_section:
+ fp.write(id_section)
+
+ if colormaptype:
+ fp.write(palette)
+
+ if rle:
+ ImageFile._save(
+ im,
+ fp,
+ [ImageFile._Tile("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))],
+ )
+ else:
+ ImageFile._save(
+ im,
+ fp,
+ [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))],
+ )
+
+ # write targa version 2 footer
+ fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")
+
+
+#
+# --------------------------------------------------------------------
+# Registry
+
+
+Image.register_open(TgaImageFile.format, TgaImageFile)
+Image.register_save(TgaImageFile.format, _save)
+
+Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])
+
+Image.register_mime(TgaImageFile.format, "image/x-tga")
diff --git a/venv/Lib/site-packages/PIL/TiffImagePlugin.py b/venv/Lib/site-packages/PIL/TiffImagePlugin.py
new file mode 100644
index 0000000..de2ce06
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/TiffImagePlugin.py
@@ -0,0 +1,2338 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# TIFF file handling
+#
+# TIFF is a flexible, if somewhat aged, image file format originally
+# defined by Aldus. Although TIFF supports a wide variety of pixel
+# layouts and compression methods, the name doesn't really stand for
+# "thousands of incompatible file formats," it just feels that way.
+#
+# To read TIFF data from a stream, the stream must be seekable. For
+# progressive decoding, make sure to use TIFF files where the tag
+# directory is placed first in the file.
+#
+# History:
+# 1995-09-01 fl Created
+# 1996-05-04 fl Handle JPEGTABLES tag
+# 1996-05-18 fl Fixed COLORMAP support
+# 1997-01-05 fl Fixed PREDICTOR support
+# 1997-08-27 fl Added support for rational tags (from Perry Stoll)
+# 1998-01-10 fl Fixed seek/tell (from Jan Blom)
+# 1998-07-15 fl Use private names for internal variables
+# 1999-06-13 fl Rewritten for PIL 1.0 (1.0)
+# 2000-10-11 fl Additional fixes for Python 2.0 (1.1)
+# 2001-04-17 fl Fixed rewind support (seek to frame 0) (1.2)
+# 2001-05-12 fl Added write support for more tags (from Greg Couch) (1.3)
+# 2001-12-18 fl Added workaround for broken Matrox library
+# 2002-01-18 fl Don't mess up if photometric tag is missing (D. Alan Stewart)
+# 2003-05-19 fl Check FILLORDER tag
+# 2003-09-26 fl Added RGBa support
+# 2004-02-24 fl Added DPI support; fixed rational write support
+# 2005-02-07 fl Added workaround for broken Corel Draw 10 files
+# 2006-01-09 fl Added support for float/double tags (from Russell Nelson)
+#
+# Copyright (c) 1997-2006 by Secret Labs AB. All rights reserved.
+# Copyright (c) 1995-1997 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import io
+import itertools
+import logging
+import math
+import os
+import struct
+import warnings
+from collections.abc import Callable, MutableMapping
+from fractions import Fraction
+from numbers import Number, Rational
+from typing import IO, Any, cast
+
+from . import ExifTags, Image, ImageFile, ImageOps, ImagePalette, TiffTags
+from ._binary import i16be as i16
+from ._binary import i32be as i32
+from ._binary import o8
+from ._util import DeferredError, is_path
+from .TiffTags import TYPES
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+ from typing import NoReturn
+
+ from ._typing import Buffer, IntegralLike, StrOrBytesPath
+
+logger = logging.getLogger(__name__)
+
+# Set these to true to force use of libtiff for reading or writing.
+READ_LIBTIFF = False
+WRITE_LIBTIFF = False
+STRIP_SIZE = 65536
+
+II = b"II" # little-endian (Intel style)
+MM = b"MM" # big-endian (Motorola style)
+
+#
+# --------------------------------------------------------------------
+# Read TIFF files
+
+# a few tag names, just to make the code below a bit more readable
+OSUBFILETYPE = 255
+IMAGEWIDTH = 256
+IMAGELENGTH = 257
+BITSPERSAMPLE = 258
+COMPRESSION = 259
+PHOTOMETRIC_INTERPRETATION = 262
+FILLORDER = 266
+IMAGEDESCRIPTION = 270
+STRIPOFFSETS = 273
+SAMPLESPERPIXEL = 277
+ROWSPERSTRIP = 278
+STRIPBYTECOUNTS = 279
+X_RESOLUTION = 282
+Y_RESOLUTION = 283
+PLANAR_CONFIGURATION = 284
+RESOLUTION_UNIT = 296
+TRANSFERFUNCTION = 301
+SOFTWARE = 305
+DATE_TIME = 306
+ARTIST = 315
+PREDICTOR = 317
+COLORMAP = 320
+TILEWIDTH = 322
+TILELENGTH = 323
+TILEOFFSETS = 324
+TILEBYTECOUNTS = 325
+SUBIFD = 330
+EXTRASAMPLES = 338
+SAMPLEFORMAT = 339
+JPEGTABLES = 347
+YCBCRSUBSAMPLING = 530
+REFERENCEBLACKWHITE = 532
+COPYRIGHT = 33432
+IPTC_NAA_CHUNK = 33723 # newsphoto properties
+PHOTOSHOP_CHUNK = 34377 # photoshop properties
+ICCPROFILE = 34675
+EXIFIFD = 34665
+XMP = 700
+JPEGQUALITY = 65537 # pseudo-tag by libtiff
+
+# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java
+IMAGEJ_META_DATA_BYTE_COUNTS = 50838
+IMAGEJ_META_DATA = 50839
+
+COMPRESSION_INFO = {
+ # Compression => pil compression name
+ 1: "raw",
+ 2: "tiff_ccitt",
+ 3: "group3",
+ 4: "group4",
+ 5: "tiff_lzw",
+ 6: "tiff_jpeg", # obsolete
+ 7: "jpeg",
+ 8: "tiff_adobe_deflate",
+ 32771: "tiff_raw_16", # 16-bit padding
+ 32773: "packbits",
+ 32809: "tiff_thunderscan",
+ 32946: "tiff_deflate",
+ 34676: "tiff_sgilog",
+ 34677: "tiff_sgilog24",
+ 34925: "lzma",
+ 50000: "zstd",
+ 50001: "webp",
+}
+
+COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}
+
+OPEN_INFO = {
+ # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,
+ # ExtraSamples) => mode, rawmode
+ (II, 0, (1,), 1, (1,), ()): ("1", "1;I"),
+ (MM, 0, (1,), 1, (1,), ()): ("1", "1;I"),
+ (II, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
+ (MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
+ (II, 1, (1,), 1, (1,), ()): ("1", "1"),
+ (MM, 1, (1,), 1, (1,), ()): ("1", "1"),
+ (II, 1, (1,), 2, (1,), ()): ("1", "1;R"),
+ (MM, 1, (1,), 2, (1,), ()): ("1", "1;R"),
+ (II, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
+ (MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
+ (II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
+ (MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
+ (II, 1, (1,), 1, (2,), ()): ("L", "L;2"),
+ (MM, 1, (1,), 1, (2,), ()): ("L", "L;2"),
+ (II, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
+ (MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
+ (II, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
+ (MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
+ (II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
+ (MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
+ (II, 1, (1,), 1, (4,), ()): ("L", "L;4"),
+ (MM, 1, (1,), 1, (4,), ()): ("L", "L;4"),
+ (II, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
+ (MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
+ (II, 0, (1,), 1, (8,), ()): ("L", "L;I"),
+ (MM, 0, (1,), 1, (8,), ()): ("L", "L;I"),
+ (II, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
+ (MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
+ (II, 1, (1,), 1, (8,), ()): ("L", "L"),
+ (MM, 1, (1,), 1, (8,), ()): ("L", "L"),
+ (II, 1, (2,), 1, (8,), ()): ("L", "L"),
+ (MM, 1, (2,), 1, (8,), ()): ("L", "L"),
+ (II, 1, (1,), 2, (8,), ()): ("L", "L;R"),
+ (MM, 1, (1,), 2, (8,), ()): ("L", "L;R"),
+ (II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),
+ (II, 0, (1,), 1, (16,), ()): ("I;16", "I;16"),
+ (II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"),
+ (MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"),
+ (II, 1, (1,), 2, (16,), ()): ("I;16", "I;16R"),
+ (II, 1, (2,), 1, (16,), ()): ("I", "I;16S"),
+ (MM, 1, (2,), 1, (16,), ()): ("I", "I;16BS"),
+ (II, 0, (3,), 1, (32,), ()): ("F", "F;32F"),
+ (MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"),
+ (II, 1, (1,), 1, (32,), ()): ("I", "I;32N"),
+ (II, 1, (2,), 1, (32,), ()): ("I", "I;32S"),
+ (MM, 1, (2,), 1, (32,), ()): ("I", "I;32BS"),
+ (II, 1, (3,), 1, (32,), ()): ("F", "F;32F"),
+ (MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"),
+ (II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
+ (MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
+ (II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
+ (MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
+ (II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
+ (MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
+ (II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
+ (MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples
+ (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),
+ (II, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),
+ (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),
+ (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
+ (II, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),
+ (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),
+ (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
+ (II, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),
+ (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
+ (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),
+ (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
+ (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10
+ (II, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16L"),
+ (MM, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16B"),
+ (II, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16L"),
+ (MM, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16B"),
+ (II, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16L"),
+ (MM, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16B"),
+ (II, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16L"),
+ (MM, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16B"),
+ (II, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16L"),
+ (MM, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16B"),
+ (II, 3, (1,), 1, (1,), ()): ("P", "P;1"),
+ (MM, 3, (1,), 1, (1,), ()): ("P", "P;1"),
+ (II, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
+ (MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
+ (II, 3, (1,), 1, (2,), ()): ("P", "P;2"),
+ (MM, 3, (1,), 1, (2,), ()): ("P", "P;2"),
+ (II, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
+ (MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
+ (II, 3, (1,), 1, (4,), ()): ("P", "P;4"),
+ (MM, 3, (1,), 1, (4,), ()): ("P", "P;4"),
+ (II, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
+ (MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
+ (II, 3, (1,), 1, (8,), ()): ("P", "P"),
+ (MM, 3, (1,), 1, (8,), ()): ("P", "P"),
+ (II, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),
+ (MM, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),
+ (II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
+ (MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
+ (II, 3, (1,), 2, (8,), ()): ("P", "P;R"),
+ (MM, 3, (1,), 2, (8,), ()): ("P", "P;R"),
+ (II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
+ (MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
+ (II, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
+ (MM, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),
+ (II, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
+ (MM, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),
+ (II, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16L"),
+ (MM, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16B"),
+ (II, 6, (1,), 1, (8,), ()): ("L", "L"),
+ (MM, 6, (1,), 1, (8,), ()): ("L", "L"),
+ # JPEG compressed images handled by LibTiff and auto-converted to RGBX
+ # Minimal Baseline TIFF requires YCbCr images to have 3 SamplesPerPixel
+ (II, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),
+ (MM, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),
+ (II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
+ (MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
+}
+
+MAX_SAMPLESPERPIXEL = max(len(key_tp[4]) for key_tp in OPEN_INFO)
+
+PREFIXES = [
+ b"MM\x00\x2a", # Valid TIFF header with big-endian byte order
+ b"II\x2a\x00", # Valid TIFF header with little-endian byte order
+ b"MM\x2a\x00", # Invalid TIFF header, assume big-endian
+ b"II\x00\x2a", # Invalid TIFF header, assume little-endian
+ b"MM\x00\x2b", # BigTIFF with big-endian byte order
+ b"II\x2b\x00", # BigTIFF with little-endian byte order
+]
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(tuple(PREFIXES))
+
+
+def _limit_rational(
+ val: float | Fraction | IFDRational, max_val: int
+) -> tuple[IntegralLike, IntegralLike]:
+ inv = abs(val) > 1
+ n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)
+ return n_d[::-1] if inv else n_d
+
+
+def _limit_signed_rational(
+ val: IFDRational, max_val: int, min_val: int
+) -> tuple[IntegralLike, IntegralLike]:
+ frac = Fraction(val)
+ n_d: tuple[IntegralLike, IntegralLike] = frac.numerator, frac.denominator
+
+ if min(float(i) for i in n_d) < min_val:
+ n_d = _limit_rational(val, abs(min_val))
+
+ n_d_float = tuple(float(i) for i in n_d)
+ if max(n_d_float) > max_val:
+ n_d = _limit_rational(n_d_float[0] / n_d_float[1], max_val)
+
+ return n_d
+
+
+##
+# Wrapper for TIFF IFDs.
+
+_load_dispatch = {}
+_write_dispatch = {}
+
+
+def _delegate(op: str) -> Any:
+ def delegate(
+ self: IFDRational, *args: tuple[float, ...]
+ ) -> bool | float | Fraction:
+ return getattr(self._val, op)(*args)
+
+ return delegate
+
+
+class IFDRational(Rational):
+ """Implements a rational class where 0/0 is a legal value to match
+ the in the wild use of exif rationals.
+
+ e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used
+ """
+
+ """ If the denominator is 0, store this as a float('nan'), otherwise store
+ as a fractions.Fraction(). Delegate as appropriate
+
+ """
+
+ __slots__ = ("_numerator", "_denominator", "_val")
+
+ def __init__(
+ self, value: float | Fraction | IFDRational, denominator: int = 1
+ ) -> None:
+ """
+ :param value: either an integer numerator, a
+ float/rational/other number, or an IFDRational
+ :param denominator: Optional integer denominator
+ """
+ self._val: Fraction | float
+ if isinstance(value, IFDRational):
+ self._numerator = value.numerator
+ self._denominator = value.denominator
+ self._val = value._val
+ return
+
+ if isinstance(value, Fraction):
+ self._numerator = value.numerator
+ self._denominator = value.denominator
+ else:
+ if TYPE_CHECKING:
+ self._numerator = cast(IntegralLike, value)
+ else:
+ self._numerator = value
+ self._denominator = denominator
+
+ if denominator == 0:
+ self._val = float("nan")
+ elif denominator == 1:
+ self._val = Fraction(value)
+ elif int(value) == value:
+ self._val = Fraction(int(value), denominator)
+ else:
+ self._val = Fraction(value / denominator)
+
+ @property
+ def numerator(self) -> IntegralLike:
+ return self._numerator
+
+ @property
+ def denominator(self) -> int:
+ return self._denominator
+
+ def limit_rational(self, max_denominator: int) -> tuple[IntegralLike, int]:
+ """
+
+ :param max_denominator: Integer, the maximum denominator value
+ :returns: Tuple of (numerator, denominator)
+ """
+
+ if self.denominator == 0:
+ return self.numerator, self.denominator
+
+ assert isinstance(self._val, Fraction)
+ f = self._val.limit_denominator(max_denominator)
+ return f.numerator, f.denominator
+
+ def __repr__(self) -> str:
+ return str(float(self._val))
+
+ def __hash__(self) -> int: # type: ignore[override]
+ return self._val.__hash__()
+
+ def __eq__(self, other: object) -> bool:
+ val = self._val
+ if isinstance(other, IFDRational):
+ other = other._val
+ if isinstance(other, float):
+ val = float(val)
+ return val == other
+
+ def __getstate__(self) -> list[float | Fraction | IntegralLike]:
+ return [self._val, self._numerator, self._denominator]
+
+ def __setstate__(self, state: list[float | Fraction | IntegralLike]) -> None:
+ IFDRational.__init__(self, 0)
+ _val, _numerator, _denominator = state
+ assert isinstance(_val, (float, Fraction))
+ self._val = _val
+ if TYPE_CHECKING:
+ self._numerator = cast(IntegralLike, _numerator)
+ else:
+ self._numerator = _numerator
+ assert isinstance(_denominator, int)
+ self._denominator = _denominator
+
+ """ a = ['add','radd', 'sub', 'rsub', 'mul', 'rmul',
+ 'truediv', 'rtruediv', 'floordiv', 'rfloordiv',
+ 'mod','rmod', 'pow','rpow', 'pos', 'neg',
+ 'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'bool',
+ 'ceil', 'floor', 'round']
+ print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a))
+ """
+
+ __add__ = _delegate("__add__")
+ __radd__ = _delegate("__radd__")
+ __sub__ = _delegate("__sub__")
+ __rsub__ = _delegate("__rsub__")
+ __mul__ = _delegate("__mul__")
+ __rmul__ = _delegate("__rmul__")
+ __truediv__ = _delegate("__truediv__")
+ __rtruediv__ = _delegate("__rtruediv__")
+ __floordiv__ = _delegate("__floordiv__")
+ __rfloordiv__ = _delegate("__rfloordiv__")
+ __mod__ = _delegate("__mod__")
+ __rmod__ = _delegate("__rmod__")
+ __pow__ = _delegate("__pow__")
+ __rpow__ = _delegate("__rpow__")
+ __pos__ = _delegate("__pos__")
+ __neg__ = _delegate("__neg__")
+ __abs__ = _delegate("__abs__")
+ __trunc__ = _delegate("__trunc__")
+ __lt__ = _delegate("__lt__")
+ __gt__ = _delegate("__gt__")
+ __le__ = _delegate("__le__")
+ __ge__ = _delegate("__ge__")
+ __bool__ = _delegate("__bool__")
+ __ceil__ = _delegate("__ceil__")
+ __floor__ = _delegate("__floor__")
+ __round__ = _delegate("__round__")
+ # Python >= 3.11
+ if hasattr(Fraction, "__int__"):
+ __int__ = _delegate("__int__")
+
+
+_LoaderFunc = Callable[["ImageFileDirectory_v2", bytes, bool], Any]
+
+
+def _register_loader(idx: int, size: int) -> Callable[[_LoaderFunc], _LoaderFunc]:
+ def decorator(func: _LoaderFunc) -> _LoaderFunc:
+ from .TiffTags import TYPES
+
+ if func.__name__.startswith("load_"):
+ TYPES[idx] = func.__name__[5:].replace("_", " ")
+ _load_dispatch[idx] = size, func # noqa: F821
+ return func
+
+ return decorator
+
+
+def _register_writer(idx: int) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
+ _write_dispatch[idx] = func # noqa: F821
+ return func
+
+ return decorator
+
+
+def _register_basic(idx_fmt_name: tuple[int, str, str]) -> None:
+ from .TiffTags import TYPES
+
+ idx, fmt, name = idx_fmt_name
+ TYPES[idx] = name
+ size = struct.calcsize(f"={fmt}")
+
+ def basic_handler(
+ self: ImageFileDirectory_v2, data: bytes, legacy_api: bool = True
+ ) -> tuple[Any, ...]:
+ return self._unpack(f"{len(data) // size}{fmt}", data)
+
+ _load_dispatch[idx] = size, basic_handler # noqa: F821
+ _write_dispatch[idx] = lambda self, *values: ( # noqa: F821
+ b"".join(self._pack(fmt, value) for value in values)
+ )
+
+
+if TYPE_CHECKING:
+ _IFDv2Base = MutableMapping[int, Any]
+else:
+ _IFDv2Base = MutableMapping
+
+
+class ImageFileDirectory_v2(_IFDv2Base):
+ """This class represents a TIFF tag directory. To speed things up, we
+ don't decode tags unless they're asked for.
+
+ Exposes a dictionary interface of the tags in the directory::
+
+ ifd = ImageFileDirectory_v2()
+ ifd[key] = 'Some Data'
+ ifd.tagtype[key] = TiffTags.ASCII
+ print(ifd[key])
+ 'Some Data'
+
+ Individual values are returned as the strings or numbers, sequences are
+ returned as tuples of the values.
+
+ The tiff metadata type of each item is stored in a dictionary of
+ tag types in
+ :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types
+ are read from a tiff file, guessed from the type added, or added
+ manually.
+
+ Data Structures:
+
+ * ``self.tagtype = {}``
+
+ * Key: numerical TIFF tag number
+ * Value: integer corresponding to the data type from
+ :py:data:`.TiffTags.TYPES`
+
+ .. versionadded:: 3.0.0
+
+ 'Internal' data structures:
+
+ * ``self._tags_v2 = {}``
+
+ * Key: numerical TIFF tag number
+ * Value: decoded data, as tuple for multiple values
+
+ * ``self._tagdata = {}``
+
+ * Key: numerical TIFF tag number
+ * Value: undecoded byte string from file
+
+ * ``self._tags_v1 = {}``
+
+ * Key: numerical TIFF tag number
+ * Value: decoded data in the v1 format
+
+ Tags will be found in the private attributes ``self._tagdata``, and in
+ ``self._tags_v2`` once decoded.
+
+ ``self.legacy_api`` is a value for internal use, and shouldn't be changed
+ from outside code. In cooperation with
+ :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`, if ``legacy_api``
+ is true, then decoded tags will be populated into both ``_tags_v1`` and
+ ``_tags_v2``. ``_tags_v2`` will be used if this IFD is used in the TIFF
+ save routine. Tags should be read from ``_tags_v1`` if
+ ``legacy_api == true``.
+
+ """
+
+ _load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {}
+ _write_dispatch: dict[int, Callable[..., Any]] = {}
+
+ def __init__(
+ self,
+ ifh: bytes = b"II\x2a\x00\x00\x00\x00\x00",
+ prefix: bytes | None = None,
+ group: int | None = None,
+ ) -> None:
+ """Initialize an ImageFileDirectory.
+
+ To construct an ImageFileDirectory from a real file, pass the 8-byte
+ magic header to the constructor. To only set the endianness, pass it
+ as the 'prefix' keyword argument.
+
+ :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets
+ endianness.
+ :param prefix: Override the endianness of the file.
+ """
+ if not _accept(ifh):
+ msg = f"not a TIFF file (header {repr(ifh)} not valid)"
+ raise SyntaxError(msg)
+ self._prefix = prefix if prefix is not None else ifh[:2]
+ if self._prefix == MM:
+ self._endian = ">"
+ elif self._prefix == II:
+ self._endian = "<"
+ else:
+ msg = "not a TIFF IFD"
+ raise SyntaxError(msg)
+ self._bigtiff = ifh[2] == 43
+ self.group = group
+ self.tagtype: dict[int, int] = {}
+ """ Dictionary of tag types """
+ self.reset()
+ self.next = (
+ self._unpack("Q", ifh[8:])[0]
+ if self._bigtiff
+ else self._unpack("L", ifh[4:])[0]
+ )
+ self._legacy_api = False
+
+ prefix = property(lambda self: self._prefix)
+ offset = property(lambda self: self._offset)
+
+ @property
+ def legacy_api(self) -> bool:
+ return self._legacy_api
+
+ @legacy_api.setter
+ def legacy_api(self, value: bool) -> NoReturn:
+ msg = "Not allowing setting of legacy api"
+ raise Exception(msg)
+
+ def reset(self) -> None:
+ self._tags_v1: dict[int, Any] = {} # will remain empty if legacy_api is false
+ self._tags_v2: dict[int, Any] = {} # main tag storage
+ self._tagdata: dict[int, bytes] = {}
+ self.tagtype = {} # added 2008-06-05 by Florian Hoech
+ self._next = None
+ self._offset: int | None = None
+
+ def __str__(self) -> str:
+ return str(dict(self))
+
+ def named(self) -> dict[str, Any]:
+ """
+ :returns: dict of name|key: value
+
+ Returns the complete tag dictionary, with named tags where possible.
+ """
+ return {
+ TiffTags.lookup(code, self.group).name: value
+ for code, value in self.items()
+ }
+
+ def __len__(self) -> int:
+ return len(set(self._tagdata) | set(self._tags_v2))
+
+ def __getitem__(self, tag: int) -> Any:
+ if tag not in self._tags_v2: # unpack on the fly
+ data = self._tagdata[tag]
+ typ = self.tagtype[tag]
+ size, handler = self._load_dispatch[typ]
+ self[tag] = handler(self, data, self.legacy_api) # check type
+ val = self._tags_v2[tag]
+ if self.legacy_api and not isinstance(val, (tuple, bytes)):
+ val = (val,)
+ return val
+
+ def __contains__(self, tag: object) -> bool:
+ return tag in self._tags_v2 or tag in self._tagdata
+
+ def __setitem__(self, tag: int, value: Any) -> None:
+ self._setitem(tag, value, self.legacy_api)
+
+ def _setitem(self, tag: int, value: Any, legacy_api: bool) -> None:
+ basetypes = (Number, bytes, str)
+
+ info = TiffTags.lookup(tag, self.group)
+ values = [value] if isinstance(value, basetypes) else value
+
+ if tag not in self.tagtype:
+ if info.type:
+ self.tagtype[tag] = info.type
+ else:
+ self.tagtype[tag] = TiffTags.UNDEFINED
+ if all(isinstance(v, IFDRational) for v in values):
+ for v in values:
+ assert isinstance(v, IFDRational)
+ if v < 0:
+ self.tagtype[tag] = TiffTags.SIGNED_RATIONAL
+ break
+ else:
+ self.tagtype[tag] = TiffTags.RATIONAL
+ elif all(isinstance(v, int) for v in values):
+ short = True
+ signed_short = True
+ long = True
+ for v in values:
+ assert isinstance(v, int)
+ if short and not (0 <= v < 2**16):
+ short = False
+ if signed_short and not (-(2**15) < v < 2**15):
+ signed_short = False
+ if long and v < 0:
+ long = False
+ if short:
+ self.tagtype[tag] = TiffTags.SHORT
+ elif signed_short:
+ self.tagtype[tag] = TiffTags.SIGNED_SHORT
+ elif long:
+ self.tagtype[tag] = TiffTags.LONG
+ else:
+ self.tagtype[tag] = TiffTags.SIGNED_LONG
+ elif all(isinstance(v, float) for v in values):
+ self.tagtype[tag] = TiffTags.DOUBLE
+ elif all(isinstance(v, str) for v in values):
+ self.tagtype[tag] = TiffTags.ASCII
+ elif all(isinstance(v, bytes) for v in values):
+ self.tagtype[tag] = TiffTags.BYTE
+
+ if self.tagtype[tag] == TiffTags.UNDEFINED:
+ values = [
+ v.encode("ascii", "replace") if isinstance(v, str) else v
+ for v in values
+ ]
+ elif self.tagtype[tag] == TiffTags.RATIONAL:
+ values = [float(v) if isinstance(v, int) else v for v in values]
+
+ is_ifd = self.tagtype[tag] == TiffTags.LONG and isinstance(values, dict)
+ if not is_ifd:
+ values = tuple(
+ info.cvt_enum(value) if isinstance(value, str) else value
+ for value in values
+ )
+
+ dest = self._tags_v1 if legacy_api else self._tags_v2
+
+ # Three branches:
+ # Spec'd length == 1, Actual length 1, store as element
+ # Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed.
+ # No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple.
+ # Don't mess with the legacy api, since it's frozen.
+ if not is_ifd and (
+ (info.length == 1)
+ or self.tagtype[tag] == TiffTags.BYTE
+ or (info.length is None and len(values) == 1 and not legacy_api)
+ ):
+ # Don't mess with the legacy api, since it's frozen.
+ if legacy_api and self.tagtype[tag] in [
+ TiffTags.RATIONAL,
+ TiffTags.SIGNED_RATIONAL,
+ ]: # rationals
+ values = (values,)
+ try:
+ (dest[tag],) = values
+ except ValueError:
+ # We've got a builtin tag with 1 expected entry
+ warnings.warn(
+ f"Metadata Warning, tag {tag} had too many entries: "
+ f"{len(values)}, expected 1"
+ )
+ dest[tag] = values[0]
+
+ else:
+ # Spec'd length > 1 or undefined
+ # Unspec'd, and length > 1
+ dest[tag] = values
+
+ def __delitem__(self, tag: int) -> None:
+ self._tags_v2.pop(tag, None)
+ self._tags_v1.pop(tag, None)
+ self._tagdata.pop(tag, None)
+
+ def __iter__(self) -> Iterator[int]:
+ return iter(set(self._tagdata) | set(self._tags_v2))
+
+ def _unpack(self, fmt: str, data: bytes) -> tuple[Any, ...]:
+ return struct.unpack(self._endian + fmt, data)
+
+ def _pack(self, fmt: str, *values: Any) -> bytes:
+ return struct.pack(self._endian + fmt, *values)
+
+ list(
+ map(
+ _register_basic,
+ [
+ (TiffTags.SHORT, "H", "short"),
+ (TiffTags.LONG, "L", "long"),
+ (TiffTags.SIGNED_BYTE, "b", "signed byte"),
+ (TiffTags.SIGNED_SHORT, "h", "signed short"),
+ (TiffTags.SIGNED_LONG, "l", "signed long"),
+ (TiffTags.FLOAT, "f", "float"),
+ (TiffTags.DOUBLE, "d", "double"),
+ (TiffTags.IFD, "L", "long"),
+ (TiffTags.LONG8, "Q", "long8"),
+ ],
+ )
+ )
+
+ @_register_loader(1, 1) # Basic type, except for the legacy API.
+ def load_byte(self, data: bytes, legacy_api: bool = True) -> bytes:
+ return data
+
+ @_register_writer(1) # Basic type, except for the legacy API.
+ def write_byte(self, data: bytes | int | IFDRational) -> bytes:
+ if isinstance(data, IFDRational):
+ data = int(data)
+ if isinstance(data, int):
+ data = bytes((data,))
+ return data
+
+ @_register_loader(2, 1)
+ def load_string(self, data: bytes, legacy_api: bool = True) -> str:
+ if data.endswith(b"\0"):
+ data = data[:-1]
+ return data.decode("latin-1", "replace")
+
+ @_register_writer(2)
+ def write_string(self, value: str | bytes | int) -> bytes:
+ # remerge of https://github.com/python-pillow/Pillow/pull/1416
+ if isinstance(value, int):
+ value = str(value)
+ if not isinstance(value, bytes):
+ value = value.encode("ascii", "replace")
+ return value + b"\0"
+
+ @_register_loader(5, 8)
+ def load_rational(
+ self, data: bytes, legacy_api: bool = True
+ ) -> tuple[tuple[int, int] | IFDRational, ...]:
+ vals = self._unpack(f"{len(data) // 4}L", data)
+
+ def combine(a: int, b: int) -> tuple[int, int] | IFDRational:
+ return (a, b) if legacy_api else IFDRational(a, b)
+
+ return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))
+
+ @_register_writer(5)
+ def write_rational(self, *values: IFDRational) -> bytes:
+ return b"".join(
+ self._pack("2L", *_limit_rational(frac, 2**32 - 1)) for frac in values
+ )
+
+ @_register_loader(7, 1)
+ def load_undefined(self, data: bytes, legacy_api: bool = True) -> bytes:
+ return data
+
+ @_register_writer(7)
+ def write_undefined(self, value: bytes | int | IFDRational) -> bytes:
+ if isinstance(value, IFDRational):
+ value = int(value)
+ if isinstance(value, int):
+ value = str(value).encode("ascii", "replace")
+ return value
+
+ @_register_loader(10, 8)
+ def load_signed_rational(
+ self, data: bytes, legacy_api: bool = True
+ ) -> tuple[tuple[int, int] | IFDRational, ...]:
+ vals = self._unpack(f"{len(data) // 4}l", data)
+
+ def combine(a: int, b: int) -> tuple[int, int] | IFDRational:
+ return (a, b) if legacy_api else IFDRational(a, b)
+
+ return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))
+
+ @_register_writer(10)
+ def write_signed_rational(self, *values: IFDRational) -> bytes:
+ return b"".join(
+ self._pack("2l", *_limit_signed_rational(frac, 2**31 - 1, -(2**31)))
+ for frac in values
+ )
+
+ def _ensure_read(self, fp: IO[bytes], size: int) -> bytes:
+ ret = fp.read(size)
+ if len(ret) != size:
+ msg = (
+ "Corrupt EXIF data. "
+ f"Expecting to read {size} bytes but only got {len(ret)}. "
+ )
+ raise OSError(msg)
+ return ret
+
+ def load(self, fp: IO[bytes]) -> None:
+ self.reset()
+ self._offset = fp.tell()
+
+ try:
+ tag_count = (
+ self._unpack("Q", self._ensure_read(fp, 8))
+ if self._bigtiff
+ else self._unpack("H", self._ensure_read(fp, 2))
+ )[0]
+ for i in range(tag_count):
+ tag, typ, count, data = (
+ self._unpack("HHQ8s", self._ensure_read(fp, 20))
+ if self._bigtiff
+ else self._unpack("HHL4s", self._ensure_read(fp, 12))
+ )
+
+ tagname = TiffTags.lookup(tag, self.group).name
+ typname = TYPES.get(typ, "unknown")
+ msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})"
+
+ try:
+ unit_size, handler = self._load_dispatch[typ]
+ except KeyError:
+ logger.debug("%s - unsupported type %s", msg, typ)
+ continue # ignore unsupported type
+ size = count * unit_size
+ if size > (8 if self._bigtiff else 4):
+ here = fp.tell()
+ (offset,) = self._unpack("Q" if self._bigtiff else "L", data)
+ msg += f" Tag Location: {here} - Data Location: {offset}"
+ fp.seek(offset)
+ data = ImageFile._safe_read(fp, size)
+ fp.seek(here)
+ else:
+ data = data[:size]
+
+ if len(data) != size:
+ warnings.warn(
+ "Possibly corrupt EXIF data. "
+ f"Expecting to read {size} bytes but only got {len(data)}."
+ f" Skipping tag {tag}"
+ )
+ logger.debug(msg)
+ continue
+
+ if not data:
+ logger.debug(msg)
+ continue
+
+ self._tagdata[tag] = data
+ self.tagtype[tag] = typ
+
+ msg += " - value: "
+ msg += f"" if size > 32 else repr(data)
+
+ logger.debug(msg)
+
+ (self.next,) = (
+ self._unpack("Q", self._ensure_read(fp, 8))
+ if self._bigtiff
+ else self._unpack("L", self._ensure_read(fp, 4))
+ )
+ except OSError as msg:
+ warnings.warn(str(msg))
+ return
+
+ def _get_ifh(self) -> bytes:
+ ifh = self._prefix + self._pack("H", 43 if self._bigtiff else 42)
+ if self._bigtiff:
+ ifh += self._pack("HH", 8, 0)
+ ifh += self._pack("Q", 16) if self._bigtiff else self._pack("L", 8)
+
+ return ifh
+
+ def tobytes(self, offset: int = 0) -> bytes:
+ # FIXME What about tagdata?
+ result = self._pack("Q" if self._bigtiff else "H", len(self._tags_v2))
+
+ entries: list[tuple[int, int, int, bytes, bytes]] = []
+
+ fmt = "Q" if self._bigtiff else "L"
+ fmt_size = 8 if self._bigtiff else 4
+ offset += (
+ len(result) + len(self._tags_v2) * (20 if self._bigtiff else 12) + fmt_size
+ )
+ stripoffsets = None
+
+ # pass 1: convert tags to binary format
+ # always write tags in ascending order
+ for tag, value in sorted(self._tags_v2.items()):
+ if tag == STRIPOFFSETS:
+ stripoffsets = len(entries)
+ typ = self.tagtype[tag]
+ logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value))
+ is_ifd = typ == TiffTags.LONG and isinstance(value, dict)
+ if is_ifd:
+ ifd = ImageFileDirectory_v2(self._get_ifh(), group=tag)
+ values = self._tags_v2[tag]
+ for ifd_tag, ifd_value in values.items():
+ ifd[ifd_tag] = ifd_value
+ data = ifd.tobytes(offset)
+ else:
+ values = value if isinstance(value, tuple) else (value,)
+ data = self._write_dispatch[typ](self, *values)
+
+ tagname = TiffTags.lookup(tag, self.group).name
+ typname = "ifd" if is_ifd else TYPES.get(typ, "unknown")
+ msg = f"save: {tagname} ({tag}) - type: {typname} ({typ}) - value: "
+ msg += f"" if len(data) >= 16 else str(values)
+ logger.debug(msg)
+
+ # count is sum of lengths for string and arbitrary data
+ if is_ifd:
+ count = 1
+ elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:
+ count = len(data)
+ else:
+ count = len(values)
+ # figure out if data fits into the entry
+ if len(data) <= fmt_size:
+ entries.append((tag, typ, count, data.ljust(fmt_size, b"\0"), b""))
+ else:
+ entries.append((tag, typ, count, self._pack(fmt, offset), data))
+ offset += (len(data) + 1) // 2 * 2 # pad to word
+
+ # update strip offset data to point beyond auxiliary data
+ if stripoffsets is not None:
+ tag, typ, count, value, data = entries[stripoffsets]
+ if data:
+ size, handler = self._load_dispatch[typ]
+ values = [val + offset for val in handler(self, data, self.legacy_api)]
+ data = self._write_dispatch[typ](self, *values)
+ else:
+ value = self._pack(fmt, self._unpack(fmt, value)[0] + offset)
+ entries[stripoffsets] = tag, typ, count, value, data
+
+ # pass 2: write entries to file
+ for tag, typ, count, value, data in entries:
+ logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data))
+ result += self._pack(
+ "HHQ8s" if self._bigtiff else "HHL4s", tag, typ, count, value
+ )
+
+ # -- overwrite here for multi-page --
+ result += self._pack(fmt, 0) # end of entries
+
+ # pass 3: write auxiliary data to file
+ for tag, typ, count, value, data in entries:
+ result += data
+ if len(data) & 1:
+ result += b"\0"
+
+ return result
+
+ def save(self, fp: IO[bytes]) -> int:
+ if fp.tell() == 0: # skip TIFF header on subsequent pages
+ fp.write(self._get_ifh())
+
+ offset = fp.tell()
+ result = self.tobytes(offset)
+ fp.write(result)
+ return offset + len(result)
+
+
+ImageFileDirectory_v2._load_dispatch = _load_dispatch
+ImageFileDirectory_v2._write_dispatch = _write_dispatch
+for idx, name in TYPES.items():
+ name = name.replace(" ", "_")
+ setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1])
+ setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx])
+del _load_dispatch, _write_dispatch, idx, name
+
+
+# Legacy ImageFileDirectory support.
+class ImageFileDirectory_v1(ImageFileDirectory_v2):
+ """This class represents the **legacy** interface to a TIFF tag directory.
+
+ Exposes a dictionary interface of the tags in the directory::
+
+ ifd = ImageFileDirectory_v1()
+ ifd[key] = 'Some Data'
+ ifd.tagtype[key] = TiffTags.ASCII
+ print(ifd[key])
+ ('Some Data',)
+
+ Also contains a dictionary of tag types as read from the tiff image file,
+ :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.
+
+ Values are returned as a tuple.
+
+ .. deprecated:: 3.0.0
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self._legacy_api = True
+
+ tags = property(lambda self: self._tags_v1)
+ tagdata = property(lambda self: self._tagdata)
+
+ # defined in ImageFileDirectory_v2
+ tagtype: dict[int, int]
+ """Dictionary of tag types"""
+
+ @classmethod
+ def from_v2(cls, original: ImageFileDirectory_v2) -> ImageFileDirectory_v1:
+ """Returns an
+ :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
+ instance with the same data as is contained in the original
+ :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
+ instance.
+
+ :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
+
+ """
+
+ ifd = cls(prefix=original.prefix)
+ ifd._tagdata = original._tagdata
+ ifd.tagtype = original.tagtype
+ ifd.next = original.next # an indicator for multipage tiffs
+ return ifd
+
+ def to_v2(self) -> ImageFileDirectory_v2:
+ """Returns an
+ :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
+ instance with the same data as is contained in the original
+ :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
+ instance.
+
+ :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
+
+ """
+
+ ifd = ImageFileDirectory_v2(prefix=self.prefix)
+ ifd._tagdata = dict(self._tagdata)
+ ifd.tagtype = dict(self.tagtype)
+ ifd._tags_v2 = dict(self._tags_v2)
+ return ifd
+
+ def __contains__(self, tag: object) -> bool:
+ return tag in self._tags_v1 or tag in self._tagdata
+
+ def __len__(self) -> int:
+ return len(set(self._tagdata) | set(self._tags_v1))
+
+ def __iter__(self) -> Iterator[int]:
+ return iter(set(self._tagdata) | set(self._tags_v1))
+
+ def __setitem__(self, tag: int, value: Any) -> None:
+ for legacy_api in (False, True):
+ self._setitem(tag, value, legacy_api)
+
+ def __getitem__(self, tag: int) -> Any:
+ if tag not in self._tags_v1: # unpack on the fly
+ data = self._tagdata[tag]
+ typ = self.tagtype[tag]
+ size, handler = self._load_dispatch[typ]
+ for legacy in (False, True):
+ self._setitem(tag, handler(self, data, legacy), legacy)
+ val = self._tags_v1[tag]
+ if not isinstance(val, (tuple, bytes)):
+ val = (val,)
+ return val
+
+
+# undone -- switch this pointer
+ImageFileDirectory = ImageFileDirectory_v1
+
+
+##
+# Image plugin for TIFF files.
+
+
+class TiffImageFile(ImageFile.ImageFile):
+ format = "TIFF"
+ format_description = "Adobe TIFF"
+ _close_exclusive_fp_after_loading = False
+
+ def __init__(
+ self,
+ fp: StrOrBytesPath | IO[bytes],
+ filename: str | bytes | None = None,
+ ) -> None:
+ self.tag_v2: ImageFileDirectory_v2
+ """ Image file directory (tag dictionary) """
+
+ self.tag: ImageFileDirectory_v1
+ """ Legacy tag entries """
+
+ super().__init__(fp, filename)
+
+ def _open(self) -> None:
+ """Open the first image in a TIFF file"""
+
+ # Header
+ assert self.fp is not None
+ ifh = self.fp.read(8)
+ if ifh[2] == 43:
+ ifh += self.fp.read(8)
+
+ self.tag_v2 = ImageFileDirectory_v2(ifh)
+
+ # setup frame pointers
+ self.__first = self.__next = self.tag_v2.next
+ self.__frame = -1
+ self._fp = self.fp
+ self._frame_pos: list[int] = []
+ self._n_frames: int | None = None
+
+ logger.debug("*** TiffImageFile._open ***")
+ logger.debug("- __first: %s", self.__first)
+ logger.debug("- ifh: %s", repr(ifh)) # Use repr to avoid str(bytes)
+
+ # and load the first frame
+ self._seek(0)
+
+ @property
+ def n_frames(self) -> int:
+ current_n_frames = self._n_frames
+ if current_n_frames is None:
+ current = self.tell()
+ self._seek(len(self._frame_pos))
+ while self._n_frames is None:
+ self._seek(self.tell() + 1)
+ self.seek(current)
+ assert self._n_frames is not None
+ return self._n_frames
+
+ def seek(self, frame: int) -> None:
+ """Select a given frame as current image"""
+ if not self._seek_check(frame):
+ return
+ self._seek(frame)
+ if self._im is not None and (
+ self.im.size != self._tile_size
+ or self.im.mode != self.mode
+ or self.readonly
+ ):
+ self._im = None
+
+ def _seek(self, frame: int) -> None:
+ if isinstance(self._fp, DeferredError):
+ raise self._fp.ex
+ self.fp = self._fp
+
+ while len(self._frame_pos) <= frame:
+ if not self.__next:
+ msg = "no more images in TIFF file"
+ raise EOFError(msg)
+ logger.debug(
+ "Seeking to frame %s, on frame %s, __next %s, location: %s",
+ frame,
+ self.__frame,
+ self.__next,
+ self.fp.tell(),
+ )
+ if self.__next >= 2**63:
+ msg = "Unable to seek to frame"
+ raise ValueError(msg)
+ self.fp.seek(self.__next)
+ self._frame_pos.append(self.__next)
+ logger.debug("Loading tags, location: %s", self.fp.tell())
+ self.tag_v2.load(self.fp)
+ if self.tag_v2.next in self._frame_pos:
+ # This IFD has already been processed
+ # Declare this to be the end of the image
+ self.__next = 0
+ else:
+ self.__next = self.tag_v2.next
+ if self.__next == 0:
+ self._n_frames = frame + 1
+ if len(self._frame_pos) == 1:
+ self.is_animated = self.__next != 0
+ self.__frame += 1
+ self.fp.seek(self._frame_pos[frame])
+ self.tag_v2.load(self.fp)
+ if XMP in self.tag_v2:
+ xmp = self.tag_v2[XMP]
+ if isinstance(xmp, tuple) and len(xmp) == 1:
+ xmp = xmp[0]
+ self.info["xmp"] = xmp
+ elif "xmp" in self.info:
+ del self.info["xmp"]
+ self._reload_exif()
+ # fill the legacy tag/ifd entries
+ self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
+ self.__frame = frame
+ self._setup()
+
+ def tell(self) -> int:
+ """Return the current frame number"""
+ return self.__frame
+
+ def get_photoshop_blocks(self) -> dict[int, dict[str, bytes]]:
+ """
+ Returns a dictionary of Photoshop "Image Resource Blocks".
+ The keys are the image resource ID. For more information, see
+ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037727
+
+ :returns: Photoshop "Image Resource Blocks" in a dictionary.
+ """
+ blocks = {}
+ val = self.tag_v2.get(ExifTags.Base.ImageResources)
+ if val:
+ while val.startswith(b"8BIM"):
+ id = i16(val[4:6])
+ n = math.ceil((val[6] + 1) / 2) * 2
+ size = i32(val[6 + n : 10 + n])
+ data = val[10 + n : 10 + n + size]
+ blocks[id] = {"data": data}
+
+ val = val[math.ceil((10 + n + size) / 2) * 2 :]
+ return blocks
+
+ def load(self) -> Image.core.PixelAccess | None:
+ if self.tile and self.use_load_libtiff:
+ return self._load_libtiff()
+ return super().load()
+
+ def load_prepare(self) -> None:
+ if self._im is None:
+ Image._decompression_bomb_check(self._tile_size)
+ self.im = Image.core.new(self.mode, self._tile_size)
+ ImageFile.ImageFile.load_prepare(self)
+
+ def load_end(self) -> None:
+ # allow closing if we're on the first frame, there's no next
+ # This is the ImageFile.load path only, libtiff specific below.
+ if not self.is_animated:
+ self._close_exclusive_fp_after_loading = True
+
+ # load IFD data from fp before it is closed
+ exif = self.getexif()
+ for key in TiffTags.TAGS_V2_GROUPS:
+ if key not in exif:
+ continue
+ exif.get_ifd(key)
+
+ ImageOps.exif_transpose(self, in_place=True)
+ if ExifTags.Base.Orientation in self.tag_v2:
+ del self.tag_v2[ExifTags.Base.Orientation]
+
+ def _load_libtiff(self) -> Image.core.PixelAccess | None:
+ """Overload method triggered when we detect a compressed tiff
+ Calls out to libtiff"""
+
+ Image.Image.load(self)
+
+ self.load_prepare()
+
+ if not len(self.tile) == 1:
+ msg = "Not exactly one tile"
+ raise OSError(msg)
+
+ # (self._compression, (extents tuple),
+ # 0, (rawmode, self._compression, fp))
+ extents = self.tile[0][1]
+ args = self.tile[0][3]
+
+ # To be nice on memory footprint, if there's a
+ # file descriptor, use that instead of reading
+ # into a string in python.
+ assert self.fp is not None
+ try:
+ fp = hasattr(self.fp, "fileno") and self.fp.fileno()
+ # flush the file descriptor, prevents error on pypy 2.4+
+ # should also eliminate the need for fp.tell
+ # in _seek
+ if hasattr(self.fp, "flush"):
+ self.fp.flush()
+ except OSError:
+ # io.BytesIO have a fileno, but returns an OSError if
+ # it doesn't use a file descriptor.
+ fp = False
+
+ if fp:
+ assert isinstance(args, tuple)
+ args_list = list(args)
+ args_list[2] = fp
+ args = tuple(args_list)
+
+ decoder = Image._getdecoder(self.mode, "libtiff", args, self.decoderconfig)
+ try:
+ decoder.setimage(self.im, extents)
+ except ValueError as e:
+ msg = "Couldn't set the image"
+ raise OSError(msg) from e
+
+ close_self_fp = self._exclusive_fp and not self.is_animated
+ if hasattr(self.fp, "getvalue"):
+ # We've got a stringio like thing passed in. Yay for all in memory.
+ # The decoder needs the entire file in one shot, so there's not
+ # a lot we can do here other than give it the entire file.
+ # unless we could do something like get the address of the
+ # underlying string for stringio.
+ #
+ # Rearranging for supporting byteio items, since they have a fileno
+ # that returns an OSError if there's no underlying fp. Easier to
+ # deal with here by reordering.
+ logger.debug("have getvalue. just sending in a string from getvalue")
+ n, err = decoder.decode(self.fp.getvalue())
+ elif fp:
+ # we've got a actual file on disk, pass in the fp.
+ logger.debug("have fileno, calling fileno version of the decoder.")
+ if not close_self_fp:
+ self.fp.seek(0)
+ # Save and restore the file position, because libtiff will move it
+ # outside of the Python runtime, and that will confuse
+ # io.BufferedReader and possible others.
+ # NOTE: This must use os.lseek(), and not fp.tell()/fp.seek(),
+ # because the buffer read head already may not equal the actual
+ # file position, and fp.seek() may just adjust it's internal
+ # pointer and not actually seek the OS file handle.
+ pos = os.lseek(fp, 0, os.SEEK_CUR)
+ # 4 bytes, otherwise the trace might error out
+ n, err = decoder.decode(b"fpfp")
+ os.lseek(fp, pos, os.SEEK_SET)
+ else:
+ # we have something else.
+ logger.debug("don't have fileno or getvalue. just reading")
+ self.fp.seek(0)
+ # UNDONE -- so much for that buffer size thing.
+ n, err = decoder.decode(self.fp.read())
+
+ self.tile = []
+ self.readonly = 0
+
+ self.load_end()
+
+ if close_self_fp:
+ self.fp.close()
+ self.fp = None # might be shared
+
+ if err < 0:
+ msg = f"decoder error {err}"
+ raise OSError(msg)
+
+ return Image.Image.load(self)
+
+ def _setup(self) -> None:
+ """Setup this image object based on current tags"""
+
+ if 0xBC01 in self.tag_v2:
+ msg = "Windows Media Photo files not yet supported"
+ raise OSError(msg)
+
+ # extract relevant tags
+ self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
+ self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
+
+ # photometric is a required tag, but not everyone is reading
+ # the specification
+ photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)
+
+ # old style jpeg compression images most certainly are YCbCr
+ if self._compression == "tiff_jpeg":
+ photo = 6
+
+ fillorder = self.tag_v2.get(FILLORDER, 1)
+
+ logger.debug("*** Summary ***")
+ logger.debug("- compression: %s", self._compression)
+ logger.debug("- photometric_interpretation: %s", photo)
+ logger.debug("- planar_configuration: %s", self._planar_configuration)
+ logger.debug("- fill_order: %s", fillorder)
+ logger.debug("- YCbCr subsampling: %s", self.tag_v2.get(YCBCRSUBSAMPLING))
+
+ # size
+ try:
+ xsize = self.tag_v2[IMAGEWIDTH]
+ ysize = self.tag_v2[IMAGELENGTH]
+ except KeyError as e:
+ msg = "Missing dimensions"
+ raise TypeError(msg) from e
+ if not isinstance(xsize, int) or not isinstance(ysize, int):
+ msg = "Invalid dimensions"
+ raise ValueError(msg)
+ self._tile_size = xsize, ysize
+ orientation = self.tag_v2.get(ExifTags.Base.Orientation)
+ if orientation in (5, 6, 7, 8):
+ self._size = ysize, xsize
+ else:
+ self._size = xsize, ysize
+
+ logger.debug("- size: %s", self.size)
+
+ sample_format = self.tag_v2.get(SAMPLEFORMAT, (1,))
+ if len(sample_format) > 1 and max(sample_format) == min(sample_format) == 1:
+ # SAMPLEFORMAT is properly per band, so an RGB image will
+ # be (1,1,1). But, we don't support per band pixel types,
+ # and anything more than one band is a uint8. So, just
+ # take the first element. Revisit this if adding support
+ # for more exotic images.
+ sample_format = (1,)
+
+ bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,))
+ extra_tuple = self.tag_v2.get(EXTRASAMPLES, ())
+ if photo in (2, 6, 8): # RGB, YCbCr, LAB
+ bps_count = 3
+ elif photo == 5: # CMYK
+ bps_count = 4
+ else:
+ bps_count = 1
+ bps_count += len(extra_tuple)
+ bps_actual_count = len(bps_tuple)
+ samples_per_pixel = self.tag_v2.get(
+ SAMPLESPERPIXEL,
+ 3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1,
+ )
+
+ if samples_per_pixel > MAX_SAMPLESPERPIXEL:
+ # DOS check, samples_per_pixel can be a Long, and we extend the tuple below
+ logger.error(
+ "More samples per pixel than can be decoded: %s", samples_per_pixel
+ )
+ msg = "Invalid value for samples per pixel"
+ raise SyntaxError(msg)
+
+ if samples_per_pixel < bps_actual_count:
+ # If a file has more values in bps_tuple than expected,
+ # remove the excess.
+ bps_tuple = bps_tuple[:samples_per_pixel]
+ elif samples_per_pixel > bps_actual_count and bps_actual_count == 1:
+ # If a file has only one value in bps_tuple, when it should have more,
+ # presume it is the same number of bits for all of the samples.
+ bps_tuple = bps_tuple * samples_per_pixel
+
+ if len(bps_tuple) != samples_per_pixel:
+ msg = "unknown data organization"
+ raise SyntaxError(msg)
+
+ # mode: check photometric interpretation and bits per pixel
+ key = (
+ self.tag_v2.prefix,
+ photo,
+ sample_format,
+ fillorder,
+ bps_tuple,
+ extra_tuple,
+ )
+ logger.debug("format key: %s", key)
+ try:
+ self._mode, rawmode = OPEN_INFO[key]
+ except KeyError as e:
+ logger.debug("- unsupported format")
+ msg = "unknown pixel mode"
+ raise SyntaxError(msg) from e
+
+ logger.debug("- raw mode: %s", rawmode)
+ logger.debug("- pil mode: %s", self.mode)
+
+ self.info["compression"] = self._compression
+
+ xres = self.tag_v2.get(X_RESOLUTION, 1)
+ yres = self.tag_v2.get(Y_RESOLUTION, 1)
+
+ if xres and yres:
+ resunit = self.tag_v2.get(RESOLUTION_UNIT)
+ if resunit == 2: # dots per inch
+ self.info["dpi"] = (xres, yres)
+ elif resunit == 3: # dots per centimeter. convert to dpi
+ self.info["dpi"] = (xres * 2.54, yres * 2.54)
+ elif resunit is None: # used to default to 1, but now 2)
+ self.info["dpi"] = (xres, yres)
+ # For backward compatibility,
+ # we also preserve the old behavior
+ self.info["resolution"] = xres, yres
+ else: # No absolute unit of measurement
+ self.info["resolution"] = xres, yres
+
+ # build tile descriptors
+ x = y = layer = 0
+ self.tile = []
+ self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw"
+ if self.use_load_libtiff:
+ # Decoder expects entire file as one tile.
+ # There's a buffer size limit in load (64k)
+ # so large g4 images will fail if we use that
+ # function.
+ #
+ # Setup the one tile for the whole image, then
+ # use the _load_libtiff function.
+
+ # libtiff handles the fillmode for us, so 1;IR should
+ # actually be 1;I. Including the R double reverses the
+ # bits, so stripes of the image are reversed. See
+ # https://github.com/python-pillow/Pillow/issues/279
+ if fillorder == 2:
+ # Replace fillorder with fillorder=1
+ key = key[:3] + (1,) + key[4:]
+ logger.debug("format key: %s", key)
+ # this should always work, since all the
+ # fillorder==2 modes have a corresponding
+ # fillorder=1 mode
+ self._mode, rawmode = OPEN_INFO[key]
+ # YCbCr images with new jpeg compression with pixels in one plane
+ # unpacked straight into RGB values
+ if (
+ photo == 6
+ and self._compression == "jpeg"
+ and self._planar_configuration == 1
+ ):
+ rawmode = "RGB"
+ # libtiff always returns the bytes in native order.
+ # we're expecting image byte order. So, if the rawmode
+ # contains I;16, we need to convert from native to image
+ # byte order.
+ elif rawmode == "I;16":
+ rawmode = "I;16N"
+ elif rawmode.endswith((";16B", ";16L")):
+ rawmode = rawmode[:-1] + "N"
+
+ # Offset in the tile tuple is 0, we go from 0,0 to
+ # w,h, and we only do this once -- eds
+ a = (rawmode, self._compression, False, self.tag_v2.offset)
+ self.tile.append(ImageFile._Tile("libtiff", (0, 0, xsize, ysize), 0, a))
+
+ elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:
+ # striped image
+ if STRIPOFFSETS in self.tag_v2:
+ offsets = self.tag_v2[STRIPOFFSETS]
+ h = self.tag_v2.get(ROWSPERSTRIP, ysize)
+ w = xsize
+ else:
+ # tiled image
+ offsets = self.tag_v2[TILEOFFSETS]
+ tilewidth = self.tag_v2.get(TILEWIDTH)
+ h = self.tag_v2.get(TILELENGTH)
+ if not isinstance(tilewidth, int) or not isinstance(h, int):
+ msg = "Invalid tile dimensions"
+ raise ValueError(msg)
+ w = tilewidth
+
+ if w == xsize and h == ysize and self._planar_configuration != 2:
+ # Every tile covers the image. Only use the last offset
+ offsets = offsets[-1:]
+
+ for offset in offsets:
+ if x + w > xsize:
+ stride = w * sum(bps_tuple) / 8 # bytes per line
+ else:
+ stride = 0
+
+ tile_rawmode = rawmode
+ if self._planar_configuration == 2:
+ # each band on it's own layer
+ tile_rawmode = rawmode[layer]
+ # adjust stride width accordingly
+ stride /= bps_count
+
+ args = (tile_rawmode, int(stride), 1)
+ self.tile.append(
+ ImageFile._Tile(
+ self._compression,
+ (x, y, min(x + w, xsize), min(y + h, ysize)),
+ offset,
+ args,
+ )
+ )
+ x += w
+ if x >= xsize:
+ x, y = 0, y + h
+ if y >= ysize:
+ y = 0
+ layer += 1
+ else:
+ logger.debug("- unsupported data organization")
+ msg = "unknown data organization"
+ raise SyntaxError(msg)
+
+ # Fix up info.
+ if ICCPROFILE in self.tag_v2:
+ self.info["icc_profile"] = self.tag_v2[ICCPROFILE]
+
+ # fixup palette descriptor
+
+ if self.mode in ["P", "PA"]:
+ palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]
+ self.palette = ImagePalette.raw("RGB;L", b"".join(palette))
+
+
+#
+# --------------------------------------------------------------------
+# Write TIFF files
+
+# little endian is default except for image modes with
+# explicit big endian byte-order
+
+SAVE_INFO = {
+ # mode => rawmode, byteorder, photometrics,
+ # sampleformat, bitspersample, extra
+ "1": ("1", II, 1, 1, (1,), None),
+ "L": ("L", II, 1, 1, (8,), None),
+ "LA": ("LA", II, 1, 1, (8, 8), 2),
+ "P": ("P", II, 3, 1, (8,), None),
+ "PA": ("PA", II, 3, 1, (8, 8), 2),
+ "I": ("I;32S", II, 1, 2, (32,), None),
+ "I;16": ("I;16", II, 1, 1, (16,), None),
+ "I;16L": ("I;16L", II, 1, 1, (16,), None),
+ "F": ("F;32F", II, 1, 3, (32,), None),
+ "RGB": ("RGB", II, 2, 1, (8, 8, 8), None),
+ "RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0),
+ "RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2),
+ "CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None),
+ "YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None),
+ "LAB": ("LAB", II, 8, 1, (8, 8, 8), None),
+ "I;16B": ("I;16B", MM, 1, 1, (16,), None),
+}
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ try:
+ rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]
+ except KeyError as e:
+ msg = f"cannot write mode {im.mode} as TIFF"
+ raise OSError(msg) from e
+
+ encoderinfo = im.encoderinfo
+ encoderconfig = im.encoderconfig
+
+ ifd = ImageFileDirectory_v2(prefix=prefix)
+ if encoderinfo.get("big_tiff"):
+ ifd._bigtiff = True
+
+ try:
+ compression = encoderinfo["compression"]
+ except KeyError:
+ compression = im.info.get("compression")
+ if isinstance(compression, int):
+ # compression value may be from BMP. Ignore it
+ compression = None
+ if compression is None:
+ compression = "raw"
+ elif compression == "tiff_jpeg":
+ # OJPEG is obsolete, so use new-style JPEG compression instead
+ compression = "jpeg"
+ elif compression == "tiff_deflate":
+ compression = "tiff_adobe_deflate"
+
+ libtiff = WRITE_LIBTIFF or compression != "raw"
+
+ # required for color libtiff images
+ ifd[PLANAR_CONFIGURATION] = 1
+
+ ifd[IMAGEWIDTH] = im.size[0]
+ ifd[IMAGELENGTH] = im.size[1]
+
+ # write any arbitrary tags passed in as an ImageFileDirectory
+ if "tiffinfo" in encoderinfo:
+ info = encoderinfo["tiffinfo"]
+ elif "exif" in encoderinfo:
+ info = encoderinfo["exif"]
+ if isinstance(info, bytes):
+ exif = Image.Exif()
+ exif.load(info)
+ info = exif
+ else:
+ info = {}
+ logger.debug("Tiffinfo Keys: %s", list(info))
+ if isinstance(info, ImageFileDirectory_v1):
+ info = info.to_v2()
+ for key in info:
+ if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS:
+ ifd[key] = info.get_ifd(key)
+ else:
+ ifd[key] = info.get(key)
+ try:
+ ifd.tagtype[key] = info.tagtype[key]
+ except Exception:
+ pass # might not be an IFD. Might not have populated type
+
+ legacy_ifd = {}
+ if hasattr(im, "tag"):
+ legacy_ifd = im.tag.to_v2()
+
+ supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})}
+ for tag in (
+ # IFD offset that may not be correct in the saved image
+ EXIFIFD,
+ # Determined by the image format and should not be copied from legacy_ifd.
+ SAMPLEFORMAT,
+ ):
+ if tag in supplied_tags:
+ del supplied_tags[tag]
+
+ # additions written by Greg Couch, gregc@cgl.ucsf.edu
+ # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com
+ if hasattr(im, "tag_v2"):
+ # preserve tags from original TIFF image file
+ for key in (
+ RESOLUTION_UNIT,
+ X_RESOLUTION,
+ Y_RESOLUTION,
+ IPTC_NAA_CHUNK,
+ PHOTOSHOP_CHUNK,
+ XMP,
+ ):
+ if key in im.tag_v2:
+ if key == IPTC_NAA_CHUNK and im.tag_v2.tagtype[key] not in (
+ TiffTags.BYTE,
+ TiffTags.UNDEFINED,
+ ):
+ del supplied_tags[key]
+ else:
+ ifd[key] = im.tag_v2[key]
+ ifd.tagtype[key] = im.tag_v2.tagtype[key]
+
+ # preserve ICC profile (should also work when saving other formats
+ # which support profiles as TIFF) -- 2008-06-06 Florian Hoech
+ icc = encoderinfo.get("icc_profile", im.info.get("icc_profile"))
+ if icc:
+ ifd[ICCPROFILE] = icc
+
+ for key, name in [
+ (IMAGEDESCRIPTION, "description"),
+ (X_RESOLUTION, "resolution"),
+ (Y_RESOLUTION, "resolution"),
+ (X_RESOLUTION, "x_resolution"),
+ (Y_RESOLUTION, "y_resolution"),
+ (RESOLUTION_UNIT, "resolution_unit"),
+ (SOFTWARE, "software"),
+ (DATE_TIME, "date_time"),
+ (ARTIST, "artist"),
+ (COPYRIGHT, "copyright"),
+ ]:
+ if name in encoderinfo:
+ ifd[key] = encoderinfo[name]
+
+ dpi = encoderinfo.get("dpi")
+ if dpi:
+ ifd[RESOLUTION_UNIT] = 2
+ ifd[X_RESOLUTION] = dpi[0]
+ ifd[Y_RESOLUTION] = dpi[1]
+
+ if bits != (1,):
+ ifd[BITSPERSAMPLE] = bits
+ if len(bits) != 1:
+ ifd[SAMPLESPERPIXEL] = len(bits)
+ if extra is not None:
+ ifd[EXTRASAMPLES] = extra
+ if format != 1:
+ ifd[SAMPLEFORMAT] = format
+
+ if PHOTOMETRIC_INTERPRETATION not in ifd:
+ ifd[PHOTOMETRIC_INTERPRETATION] = photo
+ elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0:
+ if im.mode == "1":
+ inverted_im = im.copy()
+ px = inverted_im.load()
+ if px is not None:
+ for y in range(inverted_im.height):
+ for x in range(inverted_im.width):
+ px[x, y] = 0 if px[x, y] == 255 else 255
+ im = inverted_im
+ else:
+ im = ImageOps.invert(im)
+
+ if im.mode in ["P", "PA"]:
+ lut = im.im.getpalette("RGB", "RGB;L")
+ colormap = []
+ colors = len(lut) // 3
+ for i in range(3):
+ colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]]
+ colormap += [0] * (256 - colors)
+ ifd[COLORMAP] = colormap
+ # data orientation
+ w, h = ifd[IMAGEWIDTH], ifd[IMAGELENGTH]
+ stride = len(bits) * ((w * bits[0] + 7) // 8)
+ if ROWSPERSTRIP not in ifd:
+ # aim for given strip size (64 KB by default) when using libtiff writer
+ if libtiff:
+ im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE)
+ rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, h)
+ # JPEG encoder expects multiple of 8 rows
+ if compression == "jpeg":
+ rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, h)
+ else:
+ rows_per_strip = h
+ if rows_per_strip == 0:
+ rows_per_strip = 1
+ ifd[ROWSPERSTRIP] = rows_per_strip
+ strip_byte_counts = 1 if stride == 0 else stride * ifd[ROWSPERSTRIP]
+ strips_per_image = (h + ifd[ROWSPERSTRIP] - 1) // ifd[ROWSPERSTRIP]
+ if strip_byte_counts >= 2**16:
+ ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG
+ ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + (
+ stride * h - strip_byte_counts * (strips_per_image - 1),
+ )
+ ifd[STRIPOFFSETS] = tuple(
+ range(0, strip_byte_counts * strips_per_image, strip_byte_counts)
+ ) # this is adjusted by IFD writer
+ # no compression by default:
+ ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)
+
+ if im.mode == "YCbCr":
+ for tag, default_value in {
+ YCBCRSUBSAMPLING: (1, 1),
+ REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255),
+ }.items():
+ ifd.setdefault(tag, default_value)
+
+ blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS]
+ if libtiff:
+ if "quality" in encoderinfo:
+ quality = encoderinfo["quality"]
+ if not isinstance(quality, int) or quality < 0 or quality > 100:
+ msg = "Invalid quality setting"
+ raise ValueError(msg)
+ if compression != "jpeg":
+ msg = "quality setting only supported for 'jpeg' compression"
+ raise ValueError(msg)
+ ifd[JPEGQUALITY] = quality
+
+ logger.debug("Saving using libtiff encoder")
+ logger.debug("Items: %s", sorted(ifd.items()))
+ _fp = 0
+ if hasattr(fp, "fileno"):
+ try:
+ fp.seek(0)
+ _fp = fp.fileno()
+ except io.UnsupportedOperation:
+ pass
+
+ # optional types for non core tags
+ types = {}
+ # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
+ # based on the data in the strip.
+ # OSUBFILETYPE is deprecated.
+ # The other tags expect arrays with a certain length (fixed or depending on
+ # BITSPERSAMPLE, etc), passing arrays with a different length will result in
+ # segfaults. Block these tags until we add extra validation.
+ # SUBIFD may also cause a segfault.
+ blocklist += [
+ OSUBFILETYPE,
+ REFERENCEBLACKWHITE,
+ STRIPBYTECOUNTS,
+ STRIPOFFSETS,
+ TRANSFERFUNCTION,
+ SUBIFD,
+ ]
+
+ # bits per sample is a single short in the tiff directory, not a list.
+ atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}
+ # Merge the ones that we have with (optional) more bits from
+ # the original file, e.g x,y resolution so that we can
+ # save(load('')) == original file.
+ for tag, value in itertools.chain(ifd.items(), supplied_tags.items()):
+ # Libtiff can only process certain core items without adding
+ # them to the custom dictionary.
+ # Custom items are supported for int, float, unicode, string and byte
+ # values. Other types and tuples require a tagtype.
+ if tag not in TiffTags.LIBTIFF_CORE:
+ if tag in TiffTags.TAGS_V2_GROUPS:
+ types[tag] = TiffTags.LONG8
+ elif tag in ifd.tagtype:
+ types[tag] = ifd.tagtype[tag]
+ elif isinstance(value, (int, float, str, bytes)) or (
+ isinstance(value, tuple)
+ and all(isinstance(v, (int, float, IFDRational)) for v in value)
+ ):
+ type = TiffTags.lookup(tag).type
+ if type:
+ types[tag] = type
+ if tag not in atts and tag not in blocklist:
+ if isinstance(value, str):
+ atts[tag] = value.encode("ascii", "replace") + b"\0"
+ elif isinstance(value, IFDRational):
+ atts[tag] = float(value)
+ else:
+ atts[tag] = value
+
+ if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1:
+ atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0]
+
+ logger.debug("Converted items: %s", sorted(atts.items()))
+
+ # libtiff always expects the bytes in native order.
+ # we're storing image byte order. So, if the rawmode
+ # contains I;16, we need to convert from native to image
+ # byte order.
+ if im.mode in ("I;16", "I;16B", "I;16L"):
+ rawmode = "I;16N"
+
+ # Pass tags as sorted list so that the tags are set in a fixed order.
+ # This is required by libtiff for some tags. For example, the JPEGQUALITY
+ # pseudo tag requires that the COMPRESS tag was already set.
+ tags = list(atts.items())
+ tags.sort()
+ a = (rawmode, compression, _fp, filename, tags, types)
+ encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig)
+ encoder.setimage(im.im, (0, 0) + im.size)
+ while True:
+ errcode, data = encoder.encode(ImageFile.MAXBLOCK)[1:]
+ if not _fp:
+ fp.write(data)
+ if errcode:
+ break
+ if errcode < 0:
+ msg = f"encoder error {errcode} when writing image file"
+ raise OSError(msg)
+
+ else:
+ for tag in blocklist:
+ del ifd[tag]
+ offset = ifd.save(fp)
+
+ ImageFile._save(
+ im,
+ fp,
+ [ImageFile._Tile("raw", (0, 0) + im.size, offset, (rawmode, stride, 1))],
+ )
+
+ # -- helper for multi-page save --
+ if "_debug_multipage" in encoderinfo:
+ # just to access o32 and o16 (using correct byte order)
+ setattr(im, "_debug_multipage", ifd)
+
+
+class AppendingTiffWriter(io.BytesIO):
+ fieldSizes = [
+ 0, # None
+ 1, # byte
+ 1, # ascii
+ 2, # short
+ 4, # long
+ 8, # rational
+ 1, # sbyte
+ 1, # undefined
+ 2, # sshort
+ 4, # slong
+ 8, # srational
+ 4, # float
+ 8, # double
+ 4, # ifd
+ 2, # unicode
+ 4, # complex
+ 8, # long8
+ ]
+
+ Tags = {
+ 273, # StripOffsets
+ 288, # FreeOffsets
+ 324, # TileOffsets
+ 519, # JPEGQTables
+ 520, # JPEGDCTables
+ 521, # JPEGACTables
+ }
+
+ def __init__(self, fn: StrOrBytesPath | IO[bytes], new: bool = False) -> None:
+ self.f: IO[bytes]
+ if is_path(fn):
+ self.name = fn
+ self.close_fp = True
+ try:
+ self.f = open(fn, "w+b" if new else "r+b")
+ except OSError:
+ self.f = open(fn, "w+b")
+ else:
+ self.f = cast(IO[bytes], fn)
+ self.close_fp = False
+ self.beginning = self.f.tell()
+ self.setup()
+
+ def setup(self) -> None:
+ # Reset everything.
+ self.f.seek(self.beginning, os.SEEK_SET)
+
+ self.whereToWriteNewIFDOffset: int | None = None
+ self.offsetOfNewPage = 0
+
+ self.IIMM = iimm = self.f.read(4)
+ self._bigtiff = b"\x2b" in iimm
+ if not iimm:
+ # empty file - first page
+ self.isFirst = True
+ return
+
+ self.isFirst = False
+ if iimm not in PREFIXES:
+ msg = "Invalid TIFF file header"
+ raise RuntimeError(msg)
+
+ self.setEndian("<" if iimm.startswith(II) else ">")
+
+ if self._bigtiff:
+ self.f.seek(4, os.SEEK_CUR)
+ self.skipIFDs()
+ self.goToEnd()
+
+ def finalize(self) -> None:
+ if self.isFirst:
+ return
+
+ # fix offsets
+ self.f.seek(self.offsetOfNewPage)
+
+ iimm = self.f.read(4)
+ if not iimm:
+ # Make it easy to finish a frame without committing to a new one.
+ return
+
+ if iimm != self.IIMM:
+ msg = "IIMM of new page doesn't match IIMM of first page"
+ raise RuntimeError(msg)
+
+ if self._bigtiff:
+ self.f.seek(4, os.SEEK_CUR)
+ ifd_offset = self._read(8 if self._bigtiff else 4)
+ ifd_offset += self.offsetOfNewPage
+ assert self.whereToWriteNewIFDOffset is not None
+ self.f.seek(self.whereToWriteNewIFDOffset)
+ self._write(ifd_offset, 8 if self._bigtiff else 4)
+ self.f.seek(ifd_offset)
+ self.fixIFD()
+
+ def newFrame(self) -> None:
+ # Call this to finish a frame.
+ self.finalize()
+ self.setup()
+
+ def __enter__(self) -> AppendingTiffWriter:
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ if self.close_fp:
+ self.close()
+
+ def tell(self) -> int:
+ return self.f.tell() - self.offsetOfNewPage
+
+ def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
+ """
+ :param offset: Distance to seek.
+ :param whence: Whether the distance is relative to the start,
+ end or current position.
+ :returns: The resulting position, relative to the start.
+ """
+ if whence == os.SEEK_SET:
+ offset += self.offsetOfNewPage
+
+ self.f.seek(offset, whence)
+ return self.tell()
+
+ def goToEnd(self) -> None:
+ self.f.seek(0, os.SEEK_END)
+ pos = self.f.tell()
+
+ # pad to 16 byte boundary
+ pad_bytes = 16 - pos % 16
+ if 0 < pad_bytes < 16:
+ self.f.write(bytes(pad_bytes))
+ self.offsetOfNewPage = self.f.tell()
+
+ def setEndian(self, endian: str) -> None:
+ self.endian = endian
+ self.longFmt = f"{self.endian}L"
+ self.shortFmt = f"{self.endian}H"
+ self.tagFormat = f"{self.endian}HH" + ("Q" if self._bigtiff else "L")
+
+ def skipIFDs(self) -> None:
+ while True:
+ ifd_offset = self._read(8 if self._bigtiff else 4)
+ if ifd_offset == 0:
+ self.whereToWriteNewIFDOffset = self.f.tell() - (
+ 8 if self._bigtiff else 4
+ )
+ break
+
+ self.f.seek(ifd_offset)
+ num_tags = self._read(8 if self._bigtiff else 2)
+ self.f.seek(num_tags * (20 if self._bigtiff else 12), os.SEEK_CUR)
+
+ def write(self, data: Buffer, /) -> int:
+ return self.f.write(data)
+
+ def _fmt(self, field_size: int) -> str:
+ try:
+ return {2: "H", 4: "L", 8: "Q"}[field_size]
+ except KeyError:
+ msg = "offset is not supported"
+ raise RuntimeError(msg)
+
+ def _read(self, field_size: int) -> int:
+ (value,) = struct.unpack(
+ self.endian + self._fmt(field_size), self.f.read(field_size)
+ )
+ return value
+
+ def readShort(self) -> int:
+ return self._read(2)
+
+ def readLong(self) -> int:
+ return self._read(4)
+
+ @staticmethod
+ def _verify_bytes_written(bytes_written: int | None, expected: int) -> None:
+ if bytes_written is not None and bytes_written != expected:
+ msg = f"wrote only {bytes_written} bytes but wanted {expected}"
+ raise RuntimeError(msg)
+
+ def _rewriteLast(
+ self, value: int, field_size: int, new_field_size: int = 0
+ ) -> None:
+ self.f.seek(-field_size, os.SEEK_CUR)
+ if not new_field_size:
+ new_field_size = field_size
+ bytes_written = self.f.write(
+ struct.pack(self.endian + self._fmt(new_field_size), value)
+ )
+ self._verify_bytes_written(bytes_written, new_field_size)
+
+ def rewriteLastShortToLong(self, value: int) -> None:
+ self._rewriteLast(value, 2, 4)
+
+ def rewriteLastShort(self, value: int) -> None:
+ return self._rewriteLast(value, 2)
+
+ def rewriteLastLong(self, value: int) -> None:
+ return self._rewriteLast(value, 4)
+
+ def _write(self, value: int, field_size: int) -> None:
+ bytes_written = self.f.write(
+ struct.pack(self.endian + self._fmt(field_size), value)
+ )
+ self._verify_bytes_written(bytes_written, field_size)
+
+ def writeShort(self, value: int) -> None:
+ self._write(value, 2)
+
+ def writeLong(self, value: int) -> None:
+ self._write(value, 4)
+
+ def close(self) -> None:
+ self.finalize()
+ if self.close_fp:
+ self.f.close()
+
+ def fixIFD(self) -> None:
+ num_tags = self._read(8 if self._bigtiff else 2)
+
+ for i in range(num_tags):
+ tag, field_type, count = struct.unpack(
+ self.tagFormat, self.f.read(12 if self._bigtiff else 8)
+ )
+
+ field_size = self.fieldSizes[field_type]
+ total_size = field_size * count
+ fmt_size = 8 if self._bigtiff else 4
+ is_local = total_size <= fmt_size
+ if not is_local:
+ offset = self._read(fmt_size) + self.offsetOfNewPage
+ self._rewriteLast(offset, fmt_size)
+
+ if tag in self.Tags:
+ cur_pos = self.f.tell()
+
+ logger.debug(
+ "fixIFD: %s (%d) - type: %s (%d) - type size: %d - count: %d",
+ TiffTags.lookup(tag).name,
+ tag,
+ TYPES.get(field_type, "unknown"),
+ field_type,
+ field_size,
+ count,
+ )
+
+ if is_local:
+ self._fixOffsets(count, field_size)
+ self.f.seek(cur_pos + fmt_size)
+ else:
+ self.f.seek(offset)
+ self._fixOffsets(count, field_size)
+ self.f.seek(cur_pos)
+
+ elif is_local:
+ # skip the locally stored value that is not an offset
+ self.f.seek(fmt_size, os.SEEK_CUR)
+
+ def _fixOffsets(self, count: int, field_size: int) -> None:
+ for i in range(count):
+ offset = self._read(field_size)
+ offset += self.offsetOfNewPage
+
+ new_field_size = 0
+ if self._bigtiff and field_size in (2, 4) and offset >= 2**32:
+ # offset is now too large - we must convert long to long8
+ new_field_size = 8
+ elif field_size == 2 and offset >= 2**16:
+ # offset is now too large - we must convert short to long
+ new_field_size = 4
+ if new_field_size:
+ if count != 1:
+ msg = "not implemented"
+ raise RuntimeError(msg) # XXX TODO
+
+ # simple case - the offset is just one and therefore it is
+ # local (not referenced with another offset)
+ self._rewriteLast(offset, field_size, new_field_size)
+ # Move back past the new offset, past 'count', and before 'field_type'
+ rewind = -new_field_size - 4 - 2
+ self.f.seek(rewind, os.SEEK_CUR)
+ self.writeShort(new_field_size) # rewrite the type
+ self.f.seek(2 - rewind, os.SEEK_CUR)
+ else:
+ self._rewriteLast(offset, field_size)
+
+ def fixOffsets(
+ self, count: int, isShort: bool = False, isLong: bool = False
+ ) -> None:
+ if isShort:
+ field_size = 2
+ elif isLong:
+ field_size = 4
+ else:
+ field_size = 0
+ return self._fixOffsets(count, field_size)
+
+
+def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ append_images = list(im.encoderinfo.get("append_images", []))
+ if not hasattr(im, "n_frames") and not append_images:
+ return _save(im, fp, filename)
+
+ cur_idx = im.tell()
+ try:
+ with AppendingTiffWriter(fp) as tf:
+ for ims in [im] + append_images:
+ encoderinfo = ims._attach_default_encoderinfo(im)
+ if not hasattr(ims, "encoderconfig"):
+ ims.encoderconfig = ()
+ nfr = getattr(ims, "n_frames", 1)
+
+ for idx in range(nfr):
+ ims.seek(idx)
+ ims.load()
+ _save(ims, tf, filename)
+ tf.newFrame()
+ ims.encoderinfo = encoderinfo
+ finally:
+ im.seek(cur_idx)
+
+
+#
+# --------------------------------------------------------------------
+# Register
+
+Image.register_open(TiffImageFile.format, TiffImageFile, _accept)
+Image.register_save(TiffImageFile.format, _save)
+Image.register_save_all(TiffImageFile.format, _save_all)
+
+Image.register_extensions(TiffImageFile.format, [".tif", ".tiff"])
+
+Image.register_mime(TiffImageFile.format, "image/tiff")
diff --git a/venv/Lib/site-packages/PIL/TiffTags.py b/venv/Lib/site-packages/PIL/TiffTags.py
new file mode 100644
index 0000000..613a3b7
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/TiffTags.py
@@ -0,0 +1,566 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# TIFF tags
+#
+# This module provides clear-text names for various well-known
+# TIFF tags. the TIFF codec works just fine without it.
+#
+# Copyright (c) Secret Labs AB 1999.
+#
+# See the README file for information on usage and redistribution.
+#
+
+##
+# This module provides constants and clear-text names for various
+# well-known TIFF tags.
+##
+from __future__ import annotations
+
+from typing import NamedTuple
+
+
+class _TagInfo(NamedTuple):
+ value: int | None
+ name: str
+ type: int | None
+ length: int | None
+ enum: dict[str, int]
+
+
+class TagInfo(_TagInfo):
+ __slots__: list[str] = []
+
+ def __new__(
+ cls,
+ value: int | None = None,
+ name: str = "unknown",
+ type: int | None = None,
+ length: int | None = None,
+ enum: dict[str, int] | None = None,
+ ) -> TagInfo:
+ return super().__new__(cls, value, name, type, length, enum or {})
+
+ def cvt_enum(self, value: str) -> int | str:
+ # Using get will call hash(value), which can be expensive
+ # for some types (e.g. Fraction). Since self.enum is rarely
+ # used, it's usually better to test it first.
+ return self.enum.get(value, value) if self.enum else value
+
+
+def lookup(tag: int, group: int | None = None) -> TagInfo:
+ """
+ :param tag: Integer tag number
+ :param group: Which :py:data:`~PIL.TiffTags.TAGS_V2_GROUPS` to look in
+
+ .. versionadded:: 8.3.0
+
+ :returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible,
+ otherwise just populating the value and name from ``TAGS``.
+ If the tag is not recognized, "unknown" is returned for the name
+
+ """
+
+ if group is not None:
+ info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None
+ else:
+ info = TAGS_V2.get(tag)
+ return info or TagInfo(tag, TAGS.get(tag, "unknown"))
+
+
+##
+# Map tag numbers to tag info.
+#
+# id: (Name, Type, Length[, enum_values])
+#
+# The length here differs from the length in the tiff spec. For
+# numbers, the tiff spec is for the number of fields returned. We
+# agree here. For string-like types, the tiff spec uses the length of
+# field in bytes. In Pillow, we are using the number of expected
+# fields, in general 1 for string-like types.
+
+
+BYTE = 1
+ASCII = 2
+SHORT = 3
+LONG = 4
+RATIONAL = 5
+SIGNED_BYTE = 6
+UNDEFINED = 7
+SIGNED_SHORT = 8
+SIGNED_LONG = 9
+SIGNED_RATIONAL = 10
+FLOAT = 11
+DOUBLE = 12
+IFD = 13
+LONG8 = 16
+
+_tags_v2: dict[int, tuple[str, int, int] | tuple[str, int, int, dict[str, int]]] = {
+ 254: ("NewSubfileType", LONG, 1),
+ 255: ("SubfileType", SHORT, 1),
+ 256: ("ImageWidth", LONG, 1),
+ 257: ("ImageLength", LONG, 1),
+ 258: ("BitsPerSample", SHORT, 0),
+ 259: (
+ "Compression",
+ SHORT,
+ 1,
+ {
+ "Uncompressed": 1,
+ "CCITT 1d": 2,
+ "Group 3 Fax": 3,
+ "Group 4 Fax": 4,
+ "LZW": 5,
+ "JPEG": 6,
+ "PackBits": 32773,
+ },
+ ),
+ 262: (
+ "PhotometricInterpretation",
+ SHORT,
+ 1,
+ {
+ "WhiteIsZero": 0,
+ "BlackIsZero": 1,
+ "RGB": 2,
+ "RGB Palette": 3,
+ "Transparency Mask": 4,
+ "CMYK": 5,
+ "YCbCr": 6,
+ "CieLAB": 8,
+ "CFA": 32803, # TIFF/EP, Adobe DNG
+ "LinearRaw": 32892, # Adobe DNG
+ },
+ ),
+ 263: ("Threshholding", SHORT, 1),
+ 264: ("CellWidth", SHORT, 1),
+ 265: ("CellLength", SHORT, 1),
+ 266: ("FillOrder", SHORT, 1),
+ 269: ("DocumentName", ASCII, 1),
+ 270: ("ImageDescription", ASCII, 1),
+ 271: ("Make", ASCII, 1),
+ 272: ("Model", ASCII, 1),
+ 273: ("StripOffsets", LONG, 0),
+ 274: ("Orientation", SHORT, 1),
+ 277: ("SamplesPerPixel", SHORT, 1),
+ 278: ("RowsPerStrip", LONG, 1),
+ 279: ("StripByteCounts", LONG, 0),
+ 280: ("MinSampleValue", SHORT, 0),
+ 281: ("MaxSampleValue", SHORT, 0),
+ 282: ("XResolution", RATIONAL, 1),
+ 283: ("YResolution", RATIONAL, 1),
+ 284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}),
+ 285: ("PageName", ASCII, 1),
+ 286: ("XPosition", RATIONAL, 1),
+ 287: ("YPosition", RATIONAL, 1),
+ 288: ("FreeOffsets", LONG, 1),
+ 289: ("FreeByteCounts", LONG, 1),
+ 290: ("GrayResponseUnit", SHORT, 1),
+ 291: ("GrayResponseCurve", SHORT, 0),
+ 292: ("T4Options", LONG, 1),
+ 293: ("T6Options", LONG, 1),
+ 296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}),
+ 297: ("PageNumber", SHORT, 2),
+ 301: ("TransferFunction", SHORT, 0),
+ 305: ("Software", ASCII, 1),
+ 306: ("DateTime", ASCII, 1),
+ 315: ("Artist", ASCII, 1),
+ 316: ("HostComputer", ASCII, 1),
+ 317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}),
+ 318: ("WhitePoint", RATIONAL, 2),
+ 319: ("PrimaryChromaticities", RATIONAL, 6),
+ 320: ("ColorMap", SHORT, 0),
+ 321: ("HalftoneHints", SHORT, 2),
+ 322: ("TileWidth", LONG, 1),
+ 323: ("TileLength", LONG, 1),
+ 324: ("TileOffsets", LONG, 0),
+ 325: ("TileByteCounts", LONG, 0),
+ 330: ("SubIFDs", LONG, 0),
+ 332: ("InkSet", SHORT, 1),
+ 333: ("InkNames", ASCII, 1),
+ 334: ("NumberOfInks", SHORT, 1),
+ 336: ("DotRange", SHORT, 0),
+ 337: ("TargetPrinter", ASCII, 1),
+ 338: ("ExtraSamples", SHORT, 0),
+ 339: ("SampleFormat", SHORT, 0),
+ 340: ("SMinSampleValue", DOUBLE, 0),
+ 341: ("SMaxSampleValue", DOUBLE, 0),
+ 342: ("TransferRange", SHORT, 6),
+ 347: ("JPEGTables", UNDEFINED, 1),
+ # obsolete JPEG tags
+ 512: ("JPEGProc", SHORT, 1),
+ 513: ("JPEGInterchangeFormat", LONG, 1),
+ 514: ("JPEGInterchangeFormatLength", LONG, 1),
+ 515: ("JPEGRestartInterval", SHORT, 1),
+ 517: ("JPEGLosslessPredictors", SHORT, 0),
+ 518: ("JPEGPointTransforms", SHORT, 0),
+ 519: ("JPEGQTables", LONG, 0),
+ 520: ("JPEGDCTables", LONG, 0),
+ 521: ("JPEGACTables", LONG, 0),
+ 529: ("YCbCrCoefficients", RATIONAL, 3),
+ 530: ("YCbCrSubSampling", SHORT, 2),
+ 531: ("YCbCrPositioning", SHORT, 1),
+ 532: ("ReferenceBlackWhite", RATIONAL, 6),
+ 700: ("XMP", BYTE, 0),
+ # Four private SGI tags
+ 32995: ("Matteing", SHORT, 1),
+ 32996: ("DataType", SHORT, 0),
+ 32997: ("ImageDepth", LONG, 1),
+ 32998: ("TileDepth", LONG, 1),
+ 33432: ("Copyright", ASCII, 1),
+ 33723: ("IptcNaaInfo", UNDEFINED, 1),
+ 34377: ("PhotoshopInfo", BYTE, 0),
+ # FIXME add more tags here
+ 34665: ("ExifIFD", LONG, 1),
+ 34675: ("ICCProfile", UNDEFINED, 1),
+ 34853: ("GPSInfoIFD", LONG, 1),
+ 36864: ("ExifVersion", UNDEFINED, 1),
+ 37724: ("ImageSourceData", UNDEFINED, 1),
+ 40965: ("InteroperabilityIFD", LONG, 1),
+ 41730: ("CFAPattern", UNDEFINED, 1),
+ # MPInfo
+ 45056: ("MPFVersion", UNDEFINED, 1),
+ 45057: ("NumberOfImages", LONG, 1),
+ 45058: ("MPEntry", UNDEFINED, 1),
+ 45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check
+ 45060: ("TotalFrames", LONG, 1),
+ 45313: ("MPIndividualNum", LONG, 1),
+ 45569: ("PanOrientation", LONG, 1),
+ 45570: ("PanOverlap_H", RATIONAL, 1),
+ 45571: ("PanOverlap_V", RATIONAL, 1),
+ 45572: ("BaseViewpointNum", LONG, 1),
+ 45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1),
+ 45574: ("BaselineLength", RATIONAL, 1),
+ 45575: ("VerticalDivergence", SIGNED_RATIONAL, 1),
+ 45576: ("AxisDistance_X", SIGNED_RATIONAL, 1),
+ 45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1),
+ 45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1),
+ 45579: ("YawAngle", SIGNED_RATIONAL, 1),
+ 45580: ("PitchAngle", SIGNED_RATIONAL, 1),
+ 45581: ("RollAngle", SIGNED_RATIONAL, 1),
+ 40960: ("FlashPixVersion", UNDEFINED, 1),
+ 50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}),
+ 50780: ("BestQualityScale", RATIONAL, 1),
+ 50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one
+ 50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006
+}
+_tags_v2_groups = {
+ # ExifIFD
+ 34665: {
+ 36864: ("ExifVersion", UNDEFINED, 1),
+ 40960: ("FlashPixVersion", UNDEFINED, 1),
+ 40965: ("InteroperabilityIFD", LONG, 1),
+ 41730: ("CFAPattern", UNDEFINED, 1),
+ },
+ # GPSInfoIFD
+ 34853: {
+ 0: ("GPSVersionID", BYTE, 4),
+ 1: ("GPSLatitudeRef", ASCII, 2),
+ 2: ("GPSLatitude", RATIONAL, 3),
+ 3: ("GPSLongitudeRef", ASCII, 2),
+ 4: ("GPSLongitude", RATIONAL, 3),
+ 5: ("GPSAltitudeRef", BYTE, 1),
+ 6: ("GPSAltitude", RATIONAL, 1),
+ 7: ("GPSTimeStamp", RATIONAL, 3),
+ 8: ("GPSSatellites", ASCII, 0),
+ 9: ("GPSStatus", ASCII, 2),
+ 10: ("GPSMeasureMode", ASCII, 2),
+ 11: ("GPSDOP", RATIONAL, 1),
+ 12: ("GPSSpeedRef", ASCII, 2),
+ 13: ("GPSSpeed", RATIONAL, 1),
+ 14: ("GPSTrackRef", ASCII, 2),
+ 15: ("GPSTrack", RATIONAL, 1),
+ 16: ("GPSImgDirectionRef", ASCII, 2),
+ 17: ("GPSImgDirection", RATIONAL, 1),
+ 18: ("GPSMapDatum", ASCII, 0),
+ 19: ("GPSDestLatitudeRef", ASCII, 2),
+ 20: ("GPSDestLatitude", RATIONAL, 3),
+ 21: ("GPSDestLongitudeRef", ASCII, 2),
+ 22: ("GPSDestLongitude", RATIONAL, 3),
+ 23: ("GPSDestBearingRef", ASCII, 2),
+ 24: ("GPSDestBearing", RATIONAL, 1),
+ 25: ("GPSDestDistanceRef", ASCII, 2),
+ 26: ("GPSDestDistance", RATIONAL, 1),
+ 27: ("GPSProcessingMethod", UNDEFINED, 0),
+ 28: ("GPSAreaInformation", UNDEFINED, 0),
+ 29: ("GPSDateStamp", ASCII, 11),
+ 30: ("GPSDifferential", SHORT, 1),
+ },
+ # InteroperabilityIFD
+ 40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)},
+}
+
+# Legacy Tags structure
+# these tags aren't included above, but were in the previous versions
+TAGS: dict[int | tuple[int, int], str] = {
+ 347: "JPEGTables",
+ 700: "XMP",
+ # Additional Exif Info
+ 32932: "Wang Annotation",
+ 33434: "ExposureTime",
+ 33437: "FNumber",
+ 33445: "MD FileTag",
+ 33446: "MD ScalePixel",
+ 33447: "MD ColorTable",
+ 33448: "MD LabName",
+ 33449: "MD SampleInfo",
+ 33450: "MD PrepDate",
+ 33451: "MD PrepTime",
+ 33452: "MD FileUnits",
+ 33550: "ModelPixelScaleTag",
+ 33723: "IptcNaaInfo",
+ 33918: "INGR Packet Data Tag",
+ 33919: "INGR Flag Registers",
+ 33920: "IrasB Transformation Matrix",
+ 33922: "ModelTiepointTag",
+ 34264: "ModelTransformationTag",
+ 34377: "PhotoshopInfo",
+ 34735: "GeoKeyDirectoryTag",
+ 34736: "GeoDoubleParamsTag",
+ 34737: "GeoAsciiParamsTag",
+ 34850: "ExposureProgram",
+ 34852: "SpectralSensitivity",
+ 34855: "ISOSpeedRatings",
+ 34856: "OECF",
+ 34864: "SensitivityType",
+ 34865: "StandardOutputSensitivity",
+ 34866: "RecommendedExposureIndex",
+ 34867: "ISOSpeed",
+ 34868: "ISOSpeedLatitudeyyy",
+ 34869: "ISOSpeedLatitudezzz",
+ 34908: "HylaFAX FaxRecvParams",
+ 34909: "HylaFAX FaxSubAddress",
+ 34910: "HylaFAX FaxRecvTime",
+ 36864: "ExifVersion",
+ 36867: "DateTimeOriginal",
+ 36868: "DateTimeDigitized",
+ 37121: "ComponentsConfiguration",
+ 37122: "CompressedBitsPerPixel",
+ 37724: "ImageSourceData",
+ 37377: "ShutterSpeedValue",
+ 37378: "ApertureValue",
+ 37379: "BrightnessValue",
+ 37380: "ExposureBiasValue",
+ 37381: "MaxApertureValue",
+ 37382: "SubjectDistance",
+ 37383: "MeteringMode",
+ 37384: "LightSource",
+ 37385: "Flash",
+ 37386: "FocalLength",
+ 37396: "SubjectArea",
+ 37500: "MakerNote",
+ 37510: "UserComment",
+ 37520: "SubSec",
+ 37521: "SubSecTimeOriginal",
+ 37522: "SubsecTimeDigitized",
+ 40960: "FlashPixVersion",
+ 40961: "ColorSpace",
+ 40962: "PixelXDimension",
+ 40963: "PixelYDimension",
+ 40964: "RelatedSoundFile",
+ 40965: "InteroperabilityIFD",
+ 41483: "FlashEnergy",
+ 41484: "SpatialFrequencyResponse",
+ 41486: "FocalPlaneXResolution",
+ 41487: "FocalPlaneYResolution",
+ 41488: "FocalPlaneResolutionUnit",
+ 41492: "SubjectLocation",
+ 41493: "ExposureIndex",
+ 41495: "SensingMethod",
+ 41728: "FileSource",
+ 41729: "SceneType",
+ 41730: "CFAPattern",
+ 41985: "CustomRendered",
+ 41986: "ExposureMode",
+ 41987: "WhiteBalance",
+ 41988: "DigitalZoomRatio",
+ 41989: "FocalLengthIn35mmFilm",
+ 41990: "SceneCaptureType",
+ 41991: "GainControl",
+ 41992: "Contrast",
+ 41993: "Saturation",
+ 41994: "Sharpness",
+ 41995: "DeviceSettingDescription",
+ 41996: "SubjectDistanceRange",
+ 42016: "ImageUniqueID",
+ 42032: "CameraOwnerName",
+ 42033: "BodySerialNumber",
+ 42034: "LensSpecification",
+ 42035: "LensMake",
+ 42036: "LensModel",
+ 42037: "LensSerialNumber",
+ 42112: "GDAL_METADATA",
+ 42113: "GDAL_NODATA",
+ 42240: "Gamma",
+ 50215: "Oce Scanjob Description",
+ 50216: "Oce Application Selector",
+ 50217: "Oce Identification Number",
+ 50218: "Oce ImageLogic Characteristics",
+ # Adobe DNG
+ 50706: "DNGVersion",
+ 50707: "DNGBackwardVersion",
+ 50708: "UniqueCameraModel",
+ 50709: "LocalizedCameraModel",
+ 50710: "CFAPlaneColor",
+ 50711: "CFALayout",
+ 50712: "LinearizationTable",
+ 50713: "BlackLevelRepeatDim",
+ 50714: "BlackLevel",
+ 50715: "BlackLevelDeltaH",
+ 50716: "BlackLevelDeltaV",
+ 50717: "WhiteLevel",
+ 50718: "DefaultScale",
+ 50719: "DefaultCropOrigin",
+ 50720: "DefaultCropSize",
+ 50721: "ColorMatrix1",
+ 50722: "ColorMatrix2",
+ 50723: "CameraCalibration1",
+ 50724: "CameraCalibration2",
+ 50725: "ReductionMatrix1",
+ 50726: "ReductionMatrix2",
+ 50727: "AnalogBalance",
+ 50728: "AsShotNeutral",
+ 50729: "AsShotWhiteXY",
+ 50730: "BaselineExposure",
+ 50731: "BaselineNoise",
+ 50732: "BaselineSharpness",
+ 50733: "BayerGreenSplit",
+ 50734: "LinearResponseLimit",
+ 50735: "CameraSerialNumber",
+ 50736: "LensInfo",
+ 50737: "ChromaBlurRadius",
+ 50738: "AntiAliasStrength",
+ 50740: "DNGPrivateData",
+ 50778: "CalibrationIlluminant1",
+ 50779: "CalibrationIlluminant2",
+ 50784: "Alias Layer Metadata",
+}
+
+TAGS_V2: dict[int, TagInfo] = {}
+TAGS_V2_GROUPS: dict[int, dict[int, TagInfo]] = {}
+
+
+def _populate() -> None:
+ for k, v in _tags_v2.items():
+ # Populate legacy structure.
+ TAGS[k] = v[0]
+ if len(v) == 4:
+ for sk, sv in v[3].items():
+ TAGS[(k, sv)] = sk
+
+ TAGS_V2[k] = TagInfo(k, *v)
+
+ for group, tags in _tags_v2_groups.items():
+ TAGS_V2_GROUPS[group] = {k: TagInfo(k, *v) for k, v in tags.items()}
+
+
+_populate()
+##
+# Map type numbers to type names -- defined in ImageFileDirectory.
+
+TYPES: dict[int, str] = {}
+
+#
+# These tags are handled by default in libtiff, without
+# adding to the custom dictionary. From tif_dir.c, searching for
+# case TIFFTAG in the _TIFFVSetField function:
+# Line: item.
+# 148: case TIFFTAG_SUBFILETYPE:
+# 151: case TIFFTAG_IMAGEWIDTH:
+# 154: case TIFFTAG_IMAGELENGTH:
+# 157: case TIFFTAG_BITSPERSAMPLE:
+# 181: case TIFFTAG_COMPRESSION:
+# 202: case TIFFTAG_PHOTOMETRIC:
+# 205: case TIFFTAG_THRESHHOLDING:
+# 208: case TIFFTAG_FILLORDER:
+# 214: case TIFFTAG_ORIENTATION:
+# 221: case TIFFTAG_SAMPLESPERPIXEL:
+# 228: case TIFFTAG_ROWSPERSTRIP:
+# 238: case TIFFTAG_MINSAMPLEVALUE:
+# 241: case TIFFTAG_MAXSAMPLEVALUE:
+# 244: case TIFFTAG_SMINSAMPLEVALUE:
+# 247: case TIFFTAG_SMAXSAMPLEVALUE:
+# 250: case TIFFTAG_XRESOLUTION:
+# 256: case TIFFTAG_YRESOLUTION:
+# 262: case TIFFTAG_PLANARCONFIG:
+# 268: case TIFFTAG_XPOSITION:
+# 271: case TIFFTAG_YPOSITION:
+# 274: case TIFFTAG_RESOLUTIONUNIT:
+# 280: case TIFFTAG_PAGENUMBER:
+# 284: case TIFFTAG_HALFTONEHINTS:
+# 288: case TIFFTAG_COLORMAP:
+# 294: case TIFFTAG_EXTRASAMPLES:
+# 298: case TIFFTAG_MATTEING:
+# 305: case TIFFTAG_TILEWIDTH:
+# 316: case TIFFTAG_TILELENGTH:
+# 327: case TIFFTAG_TILEDEPTH:
+# 333: case TIFFTAG_DATATYPE:
+# 344: case TIFFTAG_SAMPLEFORMAT:
+# 361: case TIFFTAG_IMAGEDEPTH:
+# 364: case TIFFTAG_SUBIFD:
+# 376: case TIFFTAG_YCBCRPOSITIONING:
+# 379: case TIFFTAG_YCBCRSUBSAMPLING:
+# 383: case TIFFTAG_TRANSFERFUNCTION:
+# 389: case TIFFTAG_REFERENCEBLACKWHITE:
+# 393: case TIFFTAG_INKNAMES:
+
+# Following pseudo-tags are also handled by default in libtiff:
+# TIFFTAG_JPEGQUALITY 65537
+
+# some of these are not in our TAGS_V2 dict and were included from tiff.h
+
+# This list also exists in encode.c
+LIBTIFF_CORE = {
+ 255,
+ 256,
+ 257,
+ 258,
+ 259,
+ 262,
+ 263,
+ 266,
+ 274,
+ 277,
+ 278,
+ 280,
+ 281,
+ 340,
+ 341,
+ 282,
+ 283,
+ 284,
+ 286,
+ 287,
+ 296,
+ 297,
+ 321,
+ 320,
+ 338,
+ 32995,
+ 322,
+ 323,
+ 32998,
+ 32996,
+ 339,
+ 32997,
+ 330,
+ 531,
+ 530,
+ 301,
+ 532,
+ 333,
+ # as above
+ 269, # this has been in our tests forever, and works
+ 65537,
+}
+
+LIBTIFF_CORE.remove(255) # We don't have support for subfiletypes
+LIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff
+LIBTIFF_CORE.remove(323) # Tiled images
+
+# Note to advanced users: There may be combinations of these
+# parameters and values that when added properly, will work and
+# produce valid tiff images that may work in your application.
+# It is safe to add and remove tags from this set from Pillow's point
+# of view so long as you test against libtiff.
diff --git a/venv/Lib/site-packages/PIL/WalImageFile.py b/venv/Lib/site-packages/PIL/WalImageFile.py
new file mode 100644
index 0000000..fb3e1c0
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/WalImageFile.py
@@ -0,0 +1,128 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# WAL file handling
+#
+# History:
+# 2003-04-23 fl created
+#
+# Copyright (c) 2003 by Fredrik Lundh.
+#
+# See the README file for information on usage and redistribution.
+#
+
+"""
+This reader is based on the specification available from:
+https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml
+and has been tested with a few sample files found using google.
+
+.. note::
+ This format cannot be automatically recognized, so the reader
+ is not registered for use with :py:func:`PIL.Image.open()`.
+ To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead.
+"""
+from __future__ import annotations
+
+from typing import IO
+
+from . import Image, ImageFile
+from ._binary import i32le as i32
+from ._typing import StrOrBytesPath
+
+
+class WalImageFile(ImageFile.ImageFile):
+ format = "WAL"
+ format_description = "Quake2 Texture"
+
+ def _open(self) -> None:
+ self._mode = "P"
+
+ # read header fields
+ assert self.fp is not None
+ header = self.fp.read(32 + 24 + 32 + 12)
+ self._size = i32(header, 32), i32(header, 36)
+ Image._decompression_bomb_check(self.size)
+
+ # load pixel data
+ offset = i32(header, 40)
+ self.fp.seek(offset)
+
+ # strings are null-terminated
+ self.info["name"] = header[:32].split(b"\0", 1)[0]
+ if next_name := header[56 : 56 + 32].split(b"\0", 1)[0]:
+ self.info["next_name"] = next_name
+
+ def load(self) -> Image.core.PixelAccess | None:
+ if self._im is None:
+ assert self.fp is not None
+ self.im = Image.core.new(self.mode, self.size)
+ self.frombytes(self.fp.read(self.size[0] * self.size[1]))
+ self.putpalette(quake2palette)
+ return Image.Image.load(self)
+
+
+def open(filename: StrOrBytesPath | IO[bytes]) -> WalImageFile:
+ """
+ Load texture from a Quake2 WAL texture file.
+
+ By default, a Quake2 standard palette is attached to the texture.
+ To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
+
+ :param filename: WAL file name, or an opened file handle.
+ :returns: An image instance.
+ """
+ return WalImageFile(filename)
+
+
+quake2palette = (
+ # default palette taken from piffo 0.93 by Hans Häggström
+ b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e"
+ b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f"
+ b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c"
+ b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b"
+ b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10"
+ b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07"
+ b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f"
+ b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16"
+ b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d"
+ b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31"
+ b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28"
+ b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07"
+ b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27"
+ b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b"
+ b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01"
+ b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21"
+ b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14"
+ b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07"
+ b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14"
+ b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f"
+ b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34"
+ b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d"
+ b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14"
+ b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01"
+ b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24"
+ b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10"
+ b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01"
+ b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27"
+ b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c"
+ b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a"
+ b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26"
+ b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d"
+ b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01"
+ b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20"
+ b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17"
+ b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07"
+ b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25"
+ b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c"
+ b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01"
+ b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23"
+ b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f"
+ b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b"
+ b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37"
+ b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b"
+ b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01"
+ b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10"
+ b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b"
+ b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20"
+)
diff --git a/venv/Lib/site-packages/PIL/WebPImagePlugin.py b/venv/Lib/site-packages/PIL/WebPImagePlugin.py
new file mode 100644
index 0000000..e20e40d
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/WebPImagePlugin.py
@@ -0,0 +1,317 @@
+from __future__ import annotations
+
+from io import BytesIO
+
+from . import Image, ImageFile
+
+try:
+ from . import _webp
+
+ SUPPORTED = True
+except ImportError:
+ SUPPORTED = False
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from typing import IO, Any
+
+_VP8_MODES_BY_IDENTIFIER = {
+ b"VP8 ": "RGB",
+ b"VP8X": "RGBA",
+ b"VP8L": "RGBA", # lossless
+}
+
+
+def _accept(prefix: bytes) -> bool | str:
+ is_riff_file_format = prefix.startswith(b"RIFF")
+ is_webp_file = prefix[8:12] == b"WEBP"
+ is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER
+
+ if is_riff_file_format and is_webp_file and is_valid_vp8_mode:
+ if not SUPPORTED:
+ return (
+ "image file could not be identified because WEBP support not installed"
+ )
+ return True
+ return False
+
+
+class WebPImageFile(ImageFile.ImageFile):
+ format = "WEBP"
+ format_description = "WebP image"
+ __loaded = 0
+ __logical_frame = 0
+
+ def _open(self) -> None:
+ # Use the newer AnimDecoder API to parse the (possibly) animated file,
+ # and access muxed chunks like ICC/EXIF/XMP.
+ assert self.fp is not None
+ self._decoder = _webp.WebPAnimDecoder(self.fp.read())
+
+ # Get info from decoder
+ self._size, self.info["loop"], bgcolor, self.n_frames, self.rawmode = (
+ self._decoder.get_info()
+ )
+ self.info["background"] = (
+ (bgcolor >> 16) & 0xFF, # R
+ (bgcolor >> 8) & 0xFF, # G
+ bgcolor & 0xFF, # B
+ (bgcolor >> 24) & 0xFF, # A
+ )
+ self.is_animated = self.n_frames > 1
+ self._mode = "RGB" if self.rawmode == "RGBX" else self.rawmode
+
+ # Attempt to read ICC / EXIF / XMP chunks from file
+ for key, chunk_name in {
+ "icc_profile": "ICCP",
+ "exif": "EXIF",
+ "xmp": "XMP ",
+ }.items():
+ if value := self._decoder.get_chunk(chunk_name):
+ self.info[key] = value
+
+ # Initialize seek state
+ self._reset(reset=False)
+
+ def _getexif(self) -> dict[int, Any] | None:
+ if "exif" not in self.info:
+ return None
+ return self.getexif()._get_merged_dict()
+
+ def seek(self, frame: int) -> None:
+ if not self._seek_check(frame):
+ return
+
+ # Set logical frame to requested position
+ self.__logical_frame = frame
+
+ def _reset(self, reset: bool = True) -> None:
+ if reset:
+ self._decoder.reset()
+ self.__physical_frame = 0
+ self.__loaded = -1
+ self.__timestamp = 0
+
+ def _get_next(self) -> tuple[bytes, int, int]:
+ # Get next frame
+ ret = self._decoder.get_next()
+ self.__physical_frame += 1
+
+ # Check if an error occurred
+ if ret is None:
+ self._reset() # Reset just to be safe
+ self.seek(0)
+ msg = "failed to decode next frame in WebP file"
+ raise EOFError(msg)
+
+ # Compute duration
+ data, timestamp = ret
+ duration = timestamp - self.__timestamp
+ self.__timestamp = timestamp
+
+ # libwebp gives frame end, adjust to start of frame
+ timestamp -= duration
+ return data, timestamp, duration
+
+ def _seek(self, frame: int) -> None:
+ if self.__physical_frame == frame:
+ return # Nothing to do
+ if frame < self.__physical_frame:
+ self._reset() # Rewind to beginning
+ while self.__physical_frame < frame:
+ self._get_next() # Advance to the requested frame
+
+ def load(self) -> Image.core.PixelAccess | None:
+ if self.__loaded != self.__logical_frame:
+ self._seek(self.__logical_frame)
+
+ # We need to load the image data for this frame
+ data, self.info["timestamp"], self.info["duration"] = self._get_next()
+ self.__loaded = self.__logical_frame
+
+ # Set tile
+ if self.fp and self._exclusive_fp:
+ self.fp.close()
+ self.fp = BytesIO(data)
+ self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.rawmode)]
+
+ return super().load()
+
+ def load_seek(self, pos: int) -> None:
+ pass
+
+ def tell(self) -> int:
+ return self.__logical_frame
+
+
+def _convert_frame(im: Image.Image) -> Image.Image:
+ # Make sure image mode is supported
+ if im.mode not in ("RGBX", "RGBA", "RGB"):
+ im = im.convert("RGBA" if im.has_transparency_data else "RGB")
+ return im
+
+
+def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ encoderinfo = im.encoderinfo.copy()
+ append_images = list(encoderinfo.get("append_images", []))
+
+ # If total frame count is 1, then save using the legacy API, which
+ # will preserve non-alpha modes
+ total = 0
+ for ims in [im] + append_images:
+ total += getattr(ims, "n_frames", 1)
+ if total == 1:
+ _save(im, fp, filename)
+ return
+
+ background: int | tuple[int, ...] = (0, 0, 0, 0)
+ if "background" in encoderinfo:
+ background = encoderinfo["background"]
+ elif "background" in im.info:
+ background = im.info["background"]
+ if isinstance(background, int):
+ # GifImagePlugin stores a global color table index in
+ # info["background"]. So it must be converted to an RGBA value
+ palette = im.getpalette()
+ if palette:
+ r, g, b = palette[background * 3 : (background + 1) * 3]
+ background = (r, g, b, 255)
+ else:
+ background = (background, background, background, 255)
+
+ duration = im.encoderinfo.get("duration", im.info.get("duration", 0))
+ loop = im.encoderinfo.get("loop", 0)
+ minimize_size = im.encoderinfo.get("minimize_size", False)
+ kmin = im.encoderinfo.get("kmin", None)
+ kmax = im.encoderinfo.get("kmax", None)
+ allow_mixed = im.encoderinfo.get("allow_mixed", False)
+ verbose = False
+ lossless = im.encoderinfo.get("lossless", False)
+ quality = im.encoderinfo.get("quality", 80)
+ alpha_quality = im.encoderinfo.get("alpha_quality", 100)
+ method = im.encoderinfo.get("method", 0)
+ icc_profile = im.encoderinfo.get("icc_profile") or ""
+ exif = im.encoderinfo.get("exif", "")
+ if isinstance(exif, Image.Exif):
+ exif = exif.tobytes()
+ xmp = im.encoderinfo.get("xmp", "")
+ if allow_mixed:
+ lossless = False
+
+ # Sensible keyframe defaults are from gif2webp.c script
+ if kmin is None:
+ kmin = 9 if lossless else 3
+ if kmax is None:
+ kmax = 17 if lossless else 5
+
+ # Validate background color
+ if (
+ not isinstance(background, (list, tuple))
+ or len(background) != 4
+ or not all(0 <= v < 256 for v in background)
+ ):
+ msg = f"Background color is not an RGBA tuple clamped to (0-255): {background}"
+ raise OSError(msg)
+
+ # Convert to packed uint
+ bg_r, bg_g, bg_b, bg_a = background
+ background = (bg_a << 24) | (bg_r << 16) | (bg_g << 8) | (bg_b << 0)
+
+ # Setup the WebP animation encoder
+ enc = _webp.WebPAnimEncoder(
+ im.size,
+ background,
+ loop,
+ minimize_size,
+ kmin,
+ kmax,
+ allow_mixed,
+ verbose,
+ )
+
+ # Add each frame
+ frame_idx = 0
+ timestamp = 0
+ cur_idx = im.tell()
+ try:
+ for ims in [im] + append_images:
+ # Get number of frames in this image
+ nfr = getattr(ims, "n_frames", 1)
+
+ for idx in range(nfr):
+ ims.seek(idx)
+
+ frame = _convert_frame(ims)
+
+ # Append the frame to the animation encoder
+ enc.add(
+ frame.getim(),
+ round(timestamp),
+ lossless,
+ quality,
+ alpha_quality,
+ method,
+ )
+
+ # Update timestamp and frame index
+ if isinstance(duration, (list, tuple)):
+ timestamp += duration[frame_idx]
+ else:
+ timestamp += duration
+ frame_idx += 1
+
+ finally:
+ im.seek(cur_idx)
+
+ # Force encoder to flush frames
+ enc.add(None, round(timestamp), lossless, quality, alpha_quality, 0)
+
+ # Get the final output from the encoder
+ data = enc.assemble(icc_profile, exif, xmp)
+ if data is None:
+ msg = "cannot write file as WebP (encoder returned None)"
+ raise OSError(msg)
+
+ fp.write(data)
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ lossless = im.encoderinfo.get("lossless", False)
+ quality = im.encoderinfo.get("quality", 80)
+ alpha_quality = im.encoderinfo.get("alpha_quality", 100)
+ icc_profile = im.encoderinfo.get("icc_profile") or ""
+ exif = im.encoderinfo.get("exif", b"")
+ if isinstance(exif, Image.Exif):
+ exif = exif.tobytes()
+ if exif.startswith(b"Exif\x00\x00"):
+ exif = exif[6:]
+ xmp = im.encoderinfo.get("xmp", "")
+ method = im.encoderinfo.get("method", 4)
+ exact = 1 if im.encoderinfo.get("exact") else 0
+
+ im = _convert_frame(im)
+
+ data = _webp.WebPEncode(
+ im.getim(),
+ lossless,
+ float(quality),
+ float(alpha_quality),
+ icc_profile,
+ method,
+ exact,
+ exif,
+ xmp,
+ )
+ if data is None:
+ msg = "cannot write file as WebP (encoder returned None)"
+ raise OSError(msg)
+
+ fp.write(data)
+
+
+Image.register_open(WebPImageFile.format, WebPImageFile, _accept)
+if SUPPORTED:
+ Image.register_save(WebPImageFile.format, _save)
+ Image.register_save_all(WebPImageFile.format, _save_all)
+ Image.register_extension(WebPImageFile.format, ".webp")
+ Image.register_mime(WebPImageFile.format, "image/webp")
diff --git a/venv/Lib/site-packages/PIL/WmfImagePlugin.py b/venv/Lib/site-packages/PIL/WmfImagePlugin.py
new file mode 100644
index 0000000..3ae8624
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/WmfImagePlugin.py
@@ -0,0 +1,188 @@
+#
+# The Python Imaging Library
+# $Id$
+#
+# WMF stub codec
+#
+# history:
+# 1996-12-14 fl Created
+# 2004-02-22 fl Turned into a stub driver
+# 2004-02-23 fl Added EMF support
+#
+# Copyright (c) Secret Labs AB 1997-2004. All rights reserved.
+# Copyright (c) Fredrik Lundh 1996.
+#
+# See the README file for information on usage and redistribution.
+#
+# WMF/EMF reference documentation:
+# https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-WMF/[MS-WMF].pdf
+# http://wvware.sourceforge.net/caolan/index.html
+# http://wvware.sourceforge.net/caolan/ora-wmf.html
+from __future__ import annotations
+
+from typing import IO
+
+from . import Image, ImageFile
+from ._binary import i16le as word
+from ._binary import si16le as short
+from ._binary import si32le as _long
+
+_handler = None
+
+
+def register_handler(handler: ImageFile.StubHandler | None) -> None:
+ """
+ Install application-specific WMF image handler.
+
+ :param handler: Handler object.
+ """
+ global _handler
+ _handler = handler
+
+
+if hasattr(Image.core, "drawwmf"):
+ # install default handler (windows only)
+
+ class WmfHandler(ImageFile.StubHandler):
+ def open(self, im: ImageFile.StubImageFile) -> None:
+ im._mode = "RGB"
+ self.bbox = im.info["wmf_bbox"]
+
+ def load(self, im: ImageFile.StubImageFile) -> Image.Image:
+ assert im.fp is not None
+ im.fp.seek(0) # rewind
+ return Image.frombytes(
+ "RGB",
+ im.size,
+ Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
+ "raw",
+ "BGR",
+ (im.size[0] * 3 + 3) & -4,
+ -1,
+ )
+
+ register_handler(WmfHandler())
+
+#
+# --------------------------------------------------------------------
+# Read WMF file
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00"))
+
+
+##
+# Image plugin for Windows metafiles.
+
+
+class WmfStubImageFile(ImageFile.StubImageFile):
+ format = "WMF"
+ format_description = "Windows Metafile"
+
+ def _open(self) -> None:
+ # check placeable header
+ assert self.fp is not None
+ s = self.fp.read(44)
+
+ if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"):
+ # placeable windows metafile
+
+ # get units per inch
+ inch = word(s, 14)
+ if inch == 0:
+ msg = "Invalid inch"
+ raise ValueError(msg)
+ self._inch: tuple[float, float] = inch, inch
+
+ # get bounding box
+ x0 = short(s, 6)
+ y0 = short(s, 8)
+ x1 = short(s, 10)
+ y1 = short(s, 12)
+
+ # normalize size to 72 dots per inch
+ self.info["dpi"] = 72
+ size = (
+ (x1 - x0) * self.info["dpi"] // inch,
+ (y1 - y0) * self.info["dpi"] // inch,
+ )
+
+ self.info["wmf_bbox"] = x0, y0, x1, y1
+
+ # sanity check (standard metafile header)
+ if s[22:26] != b"\x01\x00\t\x00":
+ msg = "Unsupported WMF file format"
+ raise SyntaxError(msg)
+
+ elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF":
+ # enhanced metafile
+
+ # get bounding box
+ x0 = _long(s, 8)
+ y0 = _long(s, 12)
+ x1 = _long(s, 16)
+ y1 = _long(s, 20)
+
+ # get frame (in 0.01 millimeter units)
+ frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36)
+
+ size = x1 - x0, y1 - y0
+
+ # calculate dots per inch from bbox and frame
+ xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0])
+ ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1])
+
+ self.info["wmf_bbox"] = x0, y0, x1, y1
+
+ if xdpi == ydpi:
+ self.info["dpi"] = xdpi
+ else:
+ self.info["dpi"] = xdpi, ydpi
+ self._inch = xdpi, ydpi
+
+ else:
+ msg = "Unsupported file format"
+ raise SyntaxError(msg)
+
+ self._mode = "RGB"
+ self._size = size
+
+ loader = self._load()
+ if loader:
+ loader.open(self)
+
+ def _load(self) -> ImageFile.StubHandler | None:
+ return _handler
+
+ def load(
+ self, dpi: float | tuple[float, float] | None = None
+ ) -> Image.core.PixelAccess | None:
+ if dpi is not None:
+ self.info["dpi"] = dpi
+ x0, y0, x1, y1 = self.info["wmf_bbox"]
+ if not isinstance(dpi, tuple):
+ dpi = dpi, dpi
+ self._size = (
+ int((x1 - x0) * dpi[0] / self._inch[0]),
+ int((y1 - y0) * dpi[1] / self._inch[1]),
+ )
+ return super().load()
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if _handler is None or not hasattr(_handler, "save"):
+ msg = "WMF save handler not installed"
+ raise OSError(msg)
+ _handler.save(im, fp, filename)
+
+
+#
+# --------------------------------------------------------------------
+# Registry stuff
+
+
+Image.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept)
+Image.register_save(WmfStubImageFile.format, _save)
+
+Image.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"])
diff --git a/venv/Lib/site-packages/PIL/XVThumbImagePlugin.py b/venv/Lib/site-packages/PIL/XVThumbImagePlugin.py
new file mode 100644
index 0000000..192c041
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/XVThumbImagePlugin.py
@@ -0,0 +1,83 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# XV Thumbnail file handler by Charles E. "Gene" Cash
+# (gcash@magicnet.net)
+#
+# see xvcolor.c and xvbrowse.c in the sources to John Bradley's XV,
+# available from ftp://ftp.cis.upenn.edu/pub/xv/
+#
+# history:
+# 98-08-15 cec created (b/w only)
+# 98-12-09 cec added color palette
+# 98-12-28 fl added to PIL (with only a few very minor modifications)
+#
+# To do:
+# FIXME: make save work (this requires quantization support)
+#
+from __future__ import annotations
+
+from . import Image, ImageFile, ImagePalette
+from ._binary import o8
+
+_MAGIC = b"P7 332"
+
+# standard color palette for thumbnails (RGB332)
+PALETTE = b""
+for r in range(8):
+ for g in range(8):
+ for b in range(4):
+ PALETTE = PALETTE + (
+ o8((r * 255) // 7) + o8((g * 255) // 7) + o8((b * 255) // 3)
+ )
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(_MAGIC)
+
+
+##
+# Image plugin for XV thumbnail images.
+
+
+class XVThumbImageFile(ImageFile.ImageFile):
+ format = "XVThumb"
+ format_description = "XV thumbnail image"
+
+ def _open(self) -> None:
+ # check magic
+ assert self.fp is not None
+
+ if not _accept(self.fp.read(6)):
+ msg = "not an XV thumbnail file"
+ raise SyntaxError(msg)
+
+ # Skip to beginning of next line
+ self.fp.readline()
+
+ # skip info comments
+ while True:
+ s = self.fp.readline()
+ if not s:
+ msg = "Unexpected EOF reading XV thumbnail file"
+ raise SyntaxError(msg)
+ if s[0] != 35: # ie. when not a comment: '#'
+ break
+
+ # parse header line (already read)
+ w, h = s.strip().split(maxsplit=2)[:2]
+
+ self._mode = "P"
+ self._size = int(w), int(h)
+
+ self.palette = ImagePalette.raw("RGB", PALETTE)
+
+ self.tile = [
+ ImageFile._Tile("raw", (0, 0) + self.size, self.fp.tell(), self.mode)
+ ]
+
+
+# --------------------------------------------------------------------
+
+Image.register_open(XVThumbImageFile.format, XVThumbImageFile, _accept)
diff --git a/venv/Lib/site-packages/PIL/XbmImagePlugin.py b/venv/Lib/site-packages/PIL/XbmImagePlugin.py
new file mode 100644
index 0000000..1e57aa1
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/XbmImagePlugin.py
@@ -0,0 +1,98 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# XBM File handling
+#
+# History:
+# 1995-09-08 fl Created
+# 1996-11-01 fl Added save support
+# 1997-07-07 fl Made header parser more tolerant
+# 1997-07-22 fl Fixed yet another parser bug
+# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
+# 2001-05-13 fl Added hotspot handling (based on code from Bernhard Herzog)
+# 2004-02-24 fl Allow some whitespace before first #define
+#
+# Copyright (c) 1997-2004 by Secret Labs AB
+# Copyright (c) 1996-1997 by Fredrik Lundh
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import re
+from typing import IO
+
+from . import Image, ImageFile
+
+# XBM header
+xbm_head = re.compile(
+ rb"\s*#define[ \t]+.*_width[ \t]+(?P[0-9]+)[\r\n]+"
+ b"#define[ \t]+.*_height[ \t]+(?P[0-9]+)[\r\n]+"
+ b"(?P"
+ b"#define[ \t]+[^_]*_x_hot[ \t]+(?P[0-9]+)[\r\n]+"
+ b"#define[ \t]+[^_]*_y_hot[ \t]+(?P[0-9]+)[\r\n]+"
+ b")?"
+ rb"[\000-\377]*_bits\[]"
+)
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.lstrip().startswith(b"#define")
+
+
+##
+# Image plugin for X11 bitmaps.
+
+
+class XbmImageFile(ImageFile.ImageFile):
+ format = "XBM"
+ format_description = "X11 Bitmap"
+
+ def _open(self) -> None:
+ assert self.fp is not None
+
+ m = xbm_head.match(self.fp.read(512))
+
+ if not m:
+ msg = "not a XBM file"
+ raise SyntaxError(msg)
+
+ xsize = int(m.group("width"))
+ ysize = int(m.group("height"))
+
+ if m.group("hotspot"):
+ self.info["hotspot"] = (int(m.group("xhot")), int(m.group("yhot")))
+
+ self._mode = "1"
+ self._size = xsize, ysize
+
+ self.tile = [ImageFile._Tile("xbm", (0, 0) + self.size, m.end())]
+
+
+def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
+ if im.mode != "1":
+ msg = f"cannot write mode {im.mode} as XBM"
+ raise OSError(msg)
+
+ fp.write(f"#define im_width {im.size[0]}\n".encode("ascii"))
+ fp.write(f"#define im_height {im.size[1]}\n".encode("ascii"))
+
+ hotspot = im.encoderinfo.get("hotspot")
+ if hotspot:
+ fp.write(f"#define im_x_hot {hotspot[0]}\n".encode("ascii"))
+ fp.write(f"#define im_y_hot {hotspot[1]}\n".encode("ascii"))
+
+ fp.write(b"static char im_bits[] = {\n")
+
+ ImageFile._save(im, fp, [ImageFile._Tile("xbm", (0, 0) + im.size)])
+
+ fp.write(b"};\n")
+
+
+Image.register_open(XbmImageFile.format, XbmImageFile, _accept)
+Image.register_save(XbmImageFile.format, _save)
+
+Image.register_extension(XbmImageFile.format, ".xbm")
+
+Image.register_mime(XbmImageFile.format, "image/xbm")
diff --git a/venv/Lib/site-packages/PIL/XpmImagePlugin.py b/venv/Lib/site-packages/PIL/XpmImagePlugin.py
new file mode 100644
index 0000000..3be240f
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/XpmImagePlugin.py
@@ -0,0 +1,157 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# XPM File handling
+#
+# History:
+# 1996-12-29 fl Created
+# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)
+#
+# Copyright (c) Secret Labs AB 1997-2001.
+# Copyright (c) Fredrik Lundh 1996-2001.
+#
+# See the README file for information on usage and redistribution.
+#
+from __future__ import annotations
+
+import re
+
+from . import Image, ImageFile, ImagePalette
+from ._binary import o8
+
+# XPM header
+xpm_head = re.compile(b'"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)')
+
+
+def _accept(prefix: bytes) -> bool:
+ return prefix.startswith(b"/* XPM */")
+
+
+##
+# Image plugin for X11 pixel maps.
+
+
+class XpmImageFile(ImageFile.ImageFile):
+ format = "XPM"
+ format_description = "X11 Pixel Map"
+
+ def _open(self) -> None:
+ assert self.fp is not None
+ if not _accept(self.fp.read(9)):
+ msg = "not an XPM file"
+ raise SyntaxError(msg)
+
+ # skip forward to next string
+ while True:
+ line = self.fp.readline()
+ if not line:
+ msg = "broken XPM file"
+ raise SyntaxError(msg)
+ m = xpm_head.match(line)
+ if m:
+ break
+
+ self._size = int(m.group(1)), int(m.group(2))
+
+ palette_length = int(m.group(3))
+ bpp = int(m.group(4))
+
+ #
+ # load palette description
+
+ palette = {}
+
+ for _ in range(palette_length):
+ line = self.fp.readline().rstrip()
+
+ c = line[1 : bpp + 1]
+ s = line[bpp + 1 : -2].split()
+
+ for i in range(0, len(s), 2):
+ if s[i] == b"c":
+ # process colour key
+ rgb = s[i + 1]
+ if rgb == b"None":
+ self.info["transparency"] = c
+ elif rgb.startswith(b"#"):
+ rgb_int = int(rgb[1:], 16)
+ palette[c] = (
+ o8((rgb_int >> 16) & 255)
+ + o8((rgb_int >> 8) & 255)
+ + o8(rgb_int & 255)
+ )
+ else:
+ # unknown colour
+ msg = "cannot read this XPM file"
+ raise ValueError(msg)
+ break
+
+ else:
+ # missing colour key
+ msg = "cannot read this XPM file"
+ raise ValueError(msg)
+
+ args: tuple[int, dict[bytes, bytes] | tuple[bytes, ...]]
+ if palette_length > 256:
+ self._mode = "RGB"
+ args = (bpp, palette)
+ else:
+ self._mode = "P"
+ self.palette = ImagePalette.raw("RGB", b"".join(palette.values()))
+ args = (bpp, tuple(palette.keys()))
+
+ self.tile = [ImageFile._Tile("xpm", (0, 0) + self.size, self.fp.tell(), args)]
+
+ def load_read(self, read_bytes: int) -> bytes:
+ #
+ # load all image data in one chunk
+
+ xsize, ysize = self.size
+
+ assert self.fp is not None
+ s = [self.fp.readline()[1 : xsize + 1].ljust(xsize) for i in range(ysize)]
+
+ return b"".join(s)
+
+
+class XpmDecoder(ImageFile.PyDecoder):
+ _pulls_fd = True
+
+ def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
+ assert self.fd is not None
+
+ data = bytearray()
+ bpp, palette = self.args
+ dest_length = self.state.xsize * self.state.ysize
+ if self.mode == "RGB":
+ dest_length *= 3
+ pixel_header = False
+ while len(data) < dest_length:
+ line = self.fd.readline()
+ if not line:
+ break
+ if line.rstrip() == b"/* pixels */" and not pixel_header:
+ pixel_header = True
+ continue
+ line = b'"'.join(line.split(b'"')[1:-1])
+ for i in range(0, len(line), bpp):
+ key = line[i : i + bpp]
+ if self.mode == "RGB":
+ data += palette[key]
+ else:
+ data += o8(palette.index(key))
+ self.set_as_raw(bytes(data))
+ return -1, 0
+
+
+#
+# Registry
+
+
+Image.register_open(XpmImageFile.format, XpmImageFile, _accept)
+Image.register_decoder("xpm", XpmDecoder)
+
+Image.register_extension(XpmImageFile.format, ".xpm")
+
+Image.register_mime(XpmImageFile.format, "image/xpm")
diff --git a/venv/Lib/site-packages/PIL/__init__.py b/venv/Lib/site-packages/PIL/__init__.py
new file mode 100644
index 0000000..6e4c23f
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/__init__.py
@@ -0,0 +1,87 @@
+"""Pillow (Fork of the Python Imaging Library)
+
+Pillow is the friendly PIL fork by Jeffrey A. Clark and contributors.
+ https://github.com/python-pillow/Pillow/
+
+Pillow is forked from PIL 1.1.7.
+
+PIL is the Python Imaging Library by Fredrik Lundh and contributors.
+Copyright (c) 1999 by Secret Labs AB.
+
+Use PIL.__version__ for this Pillow version.
+
+;-)
+"""
+
+from __future__ import annotations
+
+from . import _version
+
+# VERSION was removed in Pillow 6.0.0.
+# PILLOW_VERSION was removed in Pillow 9.0.0.
+# Use __version__ instead.
+__version__ = _version.__version__
+del _version
+
+
+_plugins = [
+ "AvifImagePlugin",
+ "BlpImagePlugin",
+ "BmpImagePlugin",
+ "BufrStubImagePlugin",
+ "CurImagePlugin",
+ "DcxImagePlugin",
+ "DdsImagePlugin",
+ "EpsImagePlugin",
+ "FitsImagePlugin",
+ "FliImagePlugin",
+ "FpxImagePlugin",
+ "FtexImagePlugin",
+ "GbrImagePlugin",
+ "GifImagePlugin",
+ "GribStubImagePlugin",
+ "Hdf5StubImagePlugin",
+ "IcnsImagePlugin",
+ "IcoImagePlugin",
+ "ImImagePlugin",
+ "ImtImagePlugin",
+ "IptcImagePlugin",
+ "JpegImagePlugin",
+ "Jpeg2KImagePlugin",
+ "McIdasImagePlugin",
+ "MicImagePlugin",
+ "MpegImagePlugin",
+ "MpoImagePlugin",
+ "MspImagePlugin",
+ "PalmImagePlugin",
+ "PcdImagePlugin",
+ "PcxImagePlugin",
+ "PdfImagePlugin",
+ "PixarImagePlugin",
+ "PngImagePlugin",
+ "PpmImagePlugin",
+ "PsdImagePlugin",
+ "QoiImagePlugin",
+ "SgiImagePlugin",
+ "SpiderImagePlugin",
+ "SunImagePlugin",
+ "TgaImagePlugin",
+ "TiffImagePlugin",
+ "WebPImagePlugin",
+ "WmfImagePlugin",
+ "XbmImagePlugin",
+ "XpmImagePlugin",
+ "XVThumbImagePlugin",
+]
+
+
+class UnidentifiedImageError(OSError):
+ """
+ Raised in :py:meth:`PIL.Image.open` if an image cannot be opened and identified.
+
+ If a PNG image raises this error, setting :data:`.ImageFile.LOAD_TRUNCATED_IMAGES`
+ to true may allow the image to be opened after all. The setting will ignore missing
+ data and checksum failures.
+ """
+
+ pass
diff --git a/venv/Lib/site-packages/PIL/__main__.py b/venv/Lib/site-packages/PIL/__main__.py
new file mode 100644
index 0000000..043156e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/__main__.py
@@ -0,0 +1,7 @@
+from __future__ import annotations
+
+import sys
+
+from .features import pilinfo
+
+pilinfo(supported_formats="--report" not in sys.argv)
diff --git a/venv/Lib/site-packages/PIL/__pycache__/AvifImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/AvifImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..6e7a4f1
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/AvifImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/BdfFontFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/BdfFontFile.cpython-312.pyc
new file mode 100644
index 0000000..fa135d2
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/BdfFontFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/BlpImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/BlpImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..18f93fd
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/BlpImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/BmpImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/BmpImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..d9f3f32
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/BmpImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/BufrStubImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/BufrStubImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..1d83e60
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/BufrStubImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ContainerIO.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ContainerIO.cpython-312.pyc
new file mode 100644
index 0000000..9a40051
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ContainerIO.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/CurImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/CurImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..f5b8958
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/CurImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/DcxImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/DcxImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..9c2361c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/DcxImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/DdsImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/DdsImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..da5126b
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/DdsImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/EpsImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/EpsImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..d15eb72
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/EpsImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ExifTags.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ExifTags.cpython-312.pyc
new file mode 100644
index 0000000..88a6e7f
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ExifTags.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/FitsImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/FitsImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..4817d5f
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/FitsImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/FliImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/FliImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..88a4abb
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/FliImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/FontFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/FontFile.cpython-312.pyc
new file mode 100644
index 0000000..feebeb7
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/FontFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/FpxImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/FpxImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..90e0810
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/FpxImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/FtexImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/FtexImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..304d7dc
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/FtexImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/GbrImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/GbrImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..554d211
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/GbrImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/GdImageFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/GdImageFile.cpython-312.pyc
new file mode 100644
index 0000000..7c92365
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/GdImageFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/GifImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/GifImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..88ffe3f
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/GifImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/GimpGradientFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/GimpGradientFile.cpython-312.pyc
new file mode 100644
index 0000000..5c333e2
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/GimpGradientFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/GimpPaletteFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/GimpPaletteFile.cpython-312.pyc
new file mode 100644
index 0000000..d4ec75c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/GimpPaletteFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/GribStubImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/GribStubImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..3f55a95
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/GribStubImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/Hdf5StubImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/Hdf5StubImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..2651b6a
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/Hdf5StubImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/IcnsImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/IcnsImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..a6d446a
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/IcnsImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/IcoImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/IcoImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..fce6958
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/IcoImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..402e2c9
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/Image.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/Image.cpython-312.pyc
new file mode 100644
index 0000000..b1496ad
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/Image.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageChops.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageChops.cpython-312.pyc
new file mode 100644
index 0000000..50b4a2a
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageChops.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageCms.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageCms.cpython-312.pyc
new file mode 100644
index 0000000..318c87a
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageCms.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageColor.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageColor.cpython-312.pyc
new file mode 100644
index 0000000..17ea92e
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageColor.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageDraw.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageDraw.cpython-312.pyc
new file mode 100644
index 0000000..3173cf5
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageDraw.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageDraw2.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageDraw2.cpython-312.pyc
new file mode 100644
index 0000000..c39a7c2
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageDraw2.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageEnhance.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageEnhance.cpython-312.pyc
new file mode 100644
index 0000000..160d0d6
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageEnhance.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageFile.cpython-312.pyc
new file mode 100644
index 0000000..8dccaf0
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageFilter.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageFilter.cpython-312.pyc
new file mode 100644
index 0000000..d7a92bb
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageFilter.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageFont.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageFont.cpython-312.pyc
new file mode 100644
index 0000000..a5b5373
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageFont.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageGrab.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageGrab.cpython-312.pyc
new file mode 100644
index 0000000..d142646
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageGrab.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageMath.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageMath.cpython-312.pyc
new file mode 100644
index 0000000..063392c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageMath.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageMode.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageMode.cpython-312.pyc
new file mode 100644
index 0000000..6a65bba
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageMode.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageMorph.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageMorph.cpython-312.pyc
new file mode 100644
index 0000000..ed93379
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageMorph.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageOps.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageOps.cpython-312.pyc
new file mode 100644
index 0000000..b3390b6
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageOps.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImagePalette.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImagePalette.cpython-312.pyc
new file mode 100644
index 0000000..00ef20e
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImagePalette.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImagePath.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImagePath.cpython-312.pyc
new file mode 100644
index 0000000..e8e3003
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImagePath.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageQt.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageQt.cpython-312.pyc
new file mode 100644
index 0000000..1052de2
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageQt.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageSequence.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageSequence.cpython-312.pyc
new file mode 100644
index 0000000..a9d70ee
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageSequence.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageShow.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageShow.cpython-312.pyc
new file mode 100644
index 0000000..ea7fc24
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageShow.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageStat.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageStat.cpython-312.pyc
new file mode 100644
index 0000000..c873956
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageStat.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageText.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageText.cpython-312.pyc
new file mode 100644
index 0000000..990bee6
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageText.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageTk.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageTk.cpython-312.pyc
new file mode 100644
index 0000000..b433e72
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageTk.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageTransform.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageTransform.cpython-312.pyc
new file mode 100644
index 0000000..c1e7a18
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageTransform.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImageWin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImageWin.cpython-312.pyc
new file mode 100644
index 0000000..9148e6c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImageWin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/ImtImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/ImtImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..96387b9
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/ImtImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/IptcImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/IptcImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..34e725a
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/IptcImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/Jpeg2KImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/Jpeg2KImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..77094b7
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/Jpeg2KImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/JpegImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/JpegImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..790b2f9
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/JpegImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/JpegPresets.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/JpegPresets.cpython-312.pyc
new file mode 100644
index 0000000..bd9c425
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/JpegPresets.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/McIdasImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/McIdasImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..a94ea62
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/McIdasImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/MicImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/MicImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..6cd2b7c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/MicImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/MpegImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/MpegImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..6ce3b6c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/MpegImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/MpoImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/MpoImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..e6d010b
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/MpoImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/MspImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/MspImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..82475d2
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/MspImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PSDraw.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PSDraw.cpython-312.pyc
new file mode 100644
index 0000000..4deeff5
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PSDraw.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PaletteFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PaletteFile.cpython-312.pyc
new file mode 100644
index 0000000..3a5365e
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PaletteFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PalmImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PalmImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..b13ad73
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PalmImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PcdImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PcdImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..cb36818
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PcdImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PcfFontFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PcfFontFile.cpython-312.pyc
new file mode 100644
index 0000000..356995b
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PcfFontFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PcxImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PcxImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..e4d0a38
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PcxImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PdfImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PdfImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..29bd43e
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PdfImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PdfParser.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PdfParser.cpython-312.pyc
new file mode 100644
index 0000000..c3d145b
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PdfParser.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PixarImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PixarImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..a83264e
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PixarImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PngImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PngImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..ba91ceb
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PngImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PpmImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PpmImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..752a356
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PpmImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/PsdImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/PsdImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..21c9db2
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/PsdImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/QoiImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/QoiImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..5e83af3
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/QoiImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/SgiImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/SgiImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..6c57eb3
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/SgiImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/SpiderImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/SpiderImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..dd669f5
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/SpiderImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/SunImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/SunImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..b1af32c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/SunImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/TarIO.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/TarIO.cpython-312.pyc
new file mode 100644
index 0000000..789dd33
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/TarIO.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/TgaImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/TgaImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..ed15da8
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/TgaImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/TiffImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/TiffImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..bc869cc
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/TiffImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/TiffTags.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/TiffTags.cpython-312.pyc
new file mode 100644
index 0000000..a0d2538
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/TiffTags.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/WalImageFile.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/WalImageFile.cpython-312.pyc
new file mode 100644
index 0000000..218872a
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/WalImageFile.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/WebPImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/WebPImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..773916c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/WebPImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/WmfImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/WmfImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..1d061ed
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/WmfImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/XVThumbImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/XVThumbImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..cab96b0
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/XVThumbImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/XbmImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/XbmImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..c53dfeb
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/XbmImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/XpmImagePlugin.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/XpmImagePlugin.cpython-312.pyc
new file mode 100644
index 0000000..4a3b62c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/XpmImagePlugin.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/__init__.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000..8cd322c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/__init__.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/__main__.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/__main__.cpython-312.pyc
new file mode 100644
index 0000000..8e21158
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/__main__.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/_binary.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/_binary.cpython-312.pyc
new file mode 100644
index 0000000..985ecd7
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/_binary.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/_deprecate.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/_deprecate.cpython-312.pyc
new file mode 100644
index 0000000..95c9194
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/_deprecate.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/_tkinter_finder.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/_tkinter_finder.cpython-312.pyc
new file mode 100644
index 0000000..da317f9
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/_tkinter_finder.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/_typing.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/_typing.cpython-312.pyc
new file mode 100644
index 0000000..f00ec22
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/_typing.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/_util.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/_util.cpython-312.pyc
new file mode 100644
index 0000000..b28fd58
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/_util.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/_version.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/_version.cpython-312.pyc
new file mode 100644
index 0000000..58bedb1
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/_version.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/features.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/features.cpython-312.pyc
new file mode 100644
index 0000000..846ba0c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/features.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/__pycache__/report.cpython-312.pyc b/venv/Lib/site-packages/PIL/__pycache__/report.cpython-312.pyc
new file mode 100644
index 0000000..a0e386d
Binary files /dev/null and b/venv/Lib/site-packages/PIL/__pycache__/report.cpython-312.pyc differ
diff --git a/venv/Lib/site-packages/PIL/_avif.cp312-win_amd64.pyd b/venv/Lib/site-packages/PIL/_avif.cp312-win_amd64.pyd
new file mode 100644
index 0000000..394db75
Binary files /dev/null and b/venv/Lib/site-packages/PIL/_avif.cp312-win_amd64.pyd differ
diff --git a/venv/Lib/site-packages/PIL/_avif.pyi b/venv/Lib/site-packages/PIL/_avif.pyi
new file mode 100644
index 0000000..e27843e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_avif.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name: str) -> Any: ...
diff --git a/venv/Lib/site-packages/PIL/_binary.py b/venv/Lib/site-packages/PIL/_binary.py
new file mode 100644
index 0000000..4594ccc
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_binary.py
@@ -0,0 +1,112 @@
+#
+# The Python Imaging Library.
+# $Id$
+#
+# Binary input/output support routines.
+#
+# Copyright (c) 1997-2003 by Secret Labs AB
+# Copyright (c) 1995-2003 by Fredrik Lundh
+# Copyright (c) 2012 by Brian Crowell
+#
+# See the README file for information on usage and redistribution.
+#
+
+
+"""Binary input/output support routines."""
+from __future__ import annotations
+
+from struct import pack, unpack_from
+
+
+def i8(c: bytes) -> int:
+ return c[0]
+
+
+def o8(i: int) -> bytes:
+ return bytes((i & 255,))
+
+
+# Input, le = little endian, be = big endian
+def i16le(c: bytes, o: int = 0) -> int:
+ """
+ Converts a 2-bytes (16 bits) string to an unsigned integer.
+
+ :param c: string containing bytes to convert
+ :param o: offset of bytes to convert in string
+ """
+ return unpack_from(" int:
+ """
+ Converts a 2-bytes (16 bits) string to a signed integer.
+
+ :param c: string containing bytes to convert
+ :param o: offset of bytes to convert in string
+ """
+ return unpack_from(" int:
+ """
+ Converts a 2-bytes (16 bits) string to a signed integer, big endian.
+
+ :param c: string containing bytes to convert
+ :param o: offset of bytes to convert in string
+ """
+ return unpack_from(">h", c, o)[0]
+
+
+def i32le(c: bytes, o: int = 0) -> int:
+ """
+ Converts a 4-bytes (32 bits) string to an unsigned integer.
+
+ :param c: string containing bytes to convert
+ :param o: offset of bytes to convert in string
+ """
+ return unpack_from(" int:
+ """
+ Converts a 4-bytes (32 bits) string to a signed integer.
+
+ :param c: string containing bytes to convert
+ :param o: offset of bytes to convert in string
+ """
+ return unpack_from(" int:
+ """
+ Converts a 4-bytes (32 bits) string to a signed integer, big endian.
+
+ :param c: string containing bytes to convert
+ :param o: offset of bytes to convert in string
+ """
+ return unpack_from(">i", c, o)[0]
+
+
+def i16be(c: bytes, o: int = 0) -> int:
+ return unpack_from(">H", c, o)[0]
+
+
+def i32be(c: bytes, o: int = 0) -> int:
+ return unpack_from(">I", c, o)[0]
+
+
+# Output, le = little endian, be = big endian
+def o16le(i: int) -> bytes:
+ return pack(" bytes:
+ return pack(" bytes:
+ return pack(">H", i)
+
+
+def o32be(i: int) -> bytes:
+ return pack(">I", i)
diff --git a/venv/Lib/site-packages/PIL/_deprecate.py b/venv/Lib/site-packages/PIL/_deprecate.py
new file mode 100644
index 0000000..711c62a
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_deprecate.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+import warnings
+
+from . import __version__
+
+
+def deprecate(
+ deprecated: str,
+ when: int | None,
+ replacement: str | None = None,
+ *,
+ action: str | None = None,
+ plural: bool = False,
+ stacklevel: int = 3,
+) -> None:
+ """
+ Deprecations helper.
+
+ :param deprecated: Name of thing to be deprecated.
+ :param when: Pillow major version to be removed in.
+ :param replacement: Name of replacement.
+ :param action: Instead of "replacement", give a custom call to action
+ e.g. "Upgrade to new thing".
+ :param plural: if the deprecated thing is plural, needing "are" instead of "is".
+
+ Usually of the form:
+
+ "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd).
+ Use [replacement] instead."
+
+ You can leave out the replacement sentence:
+
+ "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd)"
+
+ Or with another call to action:
+
+ "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd).
+ [action]."
+ """
+
+ is_ = "are" if plural else "is"
+
+ if when is None:
+ removed = "a future version"
+ elif when <= int(__version__.split(".")[0]):
+ msg = f"{deprecated} {is_} deprecated and should be removed."
+ raise RuntimeError(msg)
+ elif when == 13:
+ removed = "Pillow 13 (2026-10-15)"
+ elif when == 14:
+ removed = "Pillow 14 (2027-10-15)"
+ else:
+ msg = f"Unknown removal version: {when}. Update {__name__}?"
+ raise ValueError(msg)
+
+ if replacement and action:
+ msg = "Use only one of 'replacement' and 'action'"
+ raise ValueError(msg)
+
+ if replacement:
+ action = f". Use {replacement} instead."
+ elif action:
+ action = f". {action.rstrip('.')}."
+ else:
+ action = ""
+
+ warnings.warn(
+ f"{deprecated} {is_} deprecated and will be removed in {removed}{action}",
+ DeprecationWarning,
+ stacklevel=stacklevel,
+ )
diff --git a/venv/Lib/site-packages/PIL/_imaging.cp312-win_amd64.pyd b/venv/Lib/site-packages/PIL/_imaging.cp312-win_amd64.pyd
new file mode 100644
index 0000000..cb0bd1f
Binary files /dev/null and b/venv/Lib/site-packages/PIL/_imaging.cp312-win_amd64.pyd differ
diff --git a/venv/Lib/site-packages/PIL/_imaging.pyi b/venv/Lib/site-packages/PIL/_imaging.pyi
new file mode 100644
index 0000000..81028a5
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_imaging.pyi
@@ -0,0 +1,31 @@
+from typing import Any
+
+class ImagingCore:
+ def __getitem__(self, index: int) -> float | tuple[int, ...] | None: ...
+ def __getattr__(self, name: str) -> Any: ...
+
+class ImagingFont:
+ def __getattr__(self, name: str) -> Any: ...
+
+class ImagingDraw:
+ def __getattr__(self, name: str) -> Any: ...
+
+class PixelAccess:
+ def __getitem__(self, xy: tuple[int, int]) -> float | tuple[int, ...]: ...
+ def __setitem__(
+ self, xy: tuple[int, int], color: float | tuple[int, ...]
+ ) -> None: ...
+
+class ImagingDecoder:
+ def __getattr__(self, name: str) -> Any: ...
+
+class ImagingEncoder:
+ def __getattr__(self, name: str) -> Any: ...
+
+class _Outline:
+ def close(self) -> None: ...
+ def __getattr__(self, name: str) -> Any: ...
+
+def font(image: ImagingCore, glyphdata: bytes) -> ImagingFont: ...
+def outline() -> _Outline: ...
+def __getattr__(name: str) -> Any: ...
diff --git a/venv/Lib/site-packages/PIL/_imagingcms.cp312-win_amd64.pyd b/venv/Lib/site-packages/PIL/_imagingcms.cp312-win_amd64.pyd
new file mode 100644
index 0000000..5646c4e
Binary files /dev/null and b/venv/Lib/site-packages/PIL/_imagingcms.cp312-win_amd64.pyd differ
diff --git a/venv/Lib/site-packages/PIL/_imagingcms.pyi b/venv/Lib/site-packages/PIL/_imagingcms.pyi
new file mode 100644
index 0000000..4fc0d60
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_imagingcms.pyi
@@ -0,0 +1,143 @@
+import datetime
+import sys
+from typing import Literal, SupportsFloat, TypeAlias, TypedDict
+
+from ._typing import CapsuleType
+
+littlecms_version: str | None
+
+_Tuple3f: TypeAlias = tuple[float, float, float]
+_Tuple2x3f: TypeAlias = tuple[_Tuple3f, _Tuple3f]
+_Tuple3x3f: TypeAlias = tuple[_Tuple3f, _Tuple3f, _Tuple3f]
+
+class _IccMeasurementCondition(TypedDict):
+ observer: int
+ backing: _Tuple3f
+ geo: str
+ flare: float
+ illuminant_type: str
+
+class _IccViewingCondition(TypedDict):
+ illuminant: _Tuple3f
+ surround: _Tuple3f
+ illuminant_type: str
+
+class CmsProfile:
+ @property
+ def rendering_intent(self) -> int: ...
+ @property
+ def creation_date(self) -> datetime.datetime | None: ...
+ @property
+ def copyright(self) -> str | None: ...
+ @property
+ def target(self) -> str | None: ...
+ @property
+ def manufacturer(self) -> str | None: ...
+ @property
+ def model(self) -> str | None: ...
+ @property
+ def profile_description(self) -> str | None: ...
+ @property
+ def screening_description(self) -> str | None: ...
+ @property
+ def viewing_condition(self) -> str | None: ...
+ @property
+ def version(self) -> float: ...
+ @property
+ def icc_version(self) -> int: ...
+ @property
+ def attributes(self) -> int: ...
+ @property
+ def header_flags(self) -> int: ...
+ @property
+ def header_manufacturer(self) -> str: ...
+ @property
+ def header_model(self) -> str: ...
+ @property
+ def device_class(self) -> str: ...
+ @property
+ def connection_space(self) -> str: ...
+ @property
+ def xcolor_space(self) -> str: ...
+ @property
+ def profile_id(self) -> bytes: ...
+ @property
+ def is_matrix_shaper(self) -> bool: ...
+ @property
+ def technology(self) -> str | None: ...
+ @property
+ def colorimetric_intent(self) -> str | None: ...
+ @property
+ def perceptual_rendering_intent_gamut(self) -> str | None: ...
+ @property
+ def saturation_rendering_intent_gamut(self) -> str | None: ...
+ @property
+ def red_colorant(self) -> _Tuple2x3f | None: ...
+ @property
+ def green_colorant(self) -> _Tuple2x3f | None: ...
+ @property
+ def blue_colorant(self) -> _Tuple2x3f | None: ...
+ @property
+ def red_primary(self) -> _Tuple2x3f | None: ...
+ @property
+ def green_primary(self) -> _Tuple2x3f | None: ...
+ @property
+ def blue_primary(self) -> _Tuple2x3f | None: ...
+ @property
+ def media_white_point_temperature(self) -> float | None: ...
+ @property
+ def media_white_point(self) -> _Tuple2x3f | None: ...
+ @property
+ def media_black_point(self) -> _Tuple2x3f | None: ...
+ @property
+ def luminance(self) -> _Tuple2x3f | None: ...
+ @property
+ def chromatic_adaptation(self) -> tuple[_Tuple3x3f, _Tuple3x3f] | None: ...
+ @property
+ def chromaticity(self) -> _Tuple3x3f | None: ...
+ @property
+ def colorant_table(self) -> list[str] | None: ...
+ @property
+ def colorant_table_out(self) -> list[str] | None: ...
+ @property
+ def intent_supported(self) -> dict[int, tuple[bool, bool, bool]] | None: ...
+ @property
+ def clut(self) -> dict[int, tuple[bool, bool, bool]] | None: ...
+ @property
+ def icc_measurement_condition(self) -> _IccMeasurementCondition | None: ...
+ @property
+ def icc_viewing_condition(self) -> _IccViewingCondition | None: ...
+ def is_intent_supported(self, intent: int, direction: int, /) -> int: ...
+
+class CmsTransform:
+ def apply(self, id_in: CapsuleType, id_out: CapsuleType) -> int: ...
+
+def profile_open(profile: str, /) -> CmsProfile: ...
+def profile_frombytes(profile: bytes, /) -> CmsProfile: ...
+def profile_tobytes(profile: CmsProfile, /) -> bytes: ...
+def buildTransform(
+ input_profile: CmsProfile,
+ output_profile: CmsProfile,
+ in_mode: str,
+ out_mode: str,
+ rendering_intent: int = 0,
+ cms_flags: int = 0,
+ /,
+) -> CmsTransform: ...
+def buildProofTransform(
+ input_profile: CmsProfile,
+ output_profile: CmsProfile,
+ proof_profile: CmsProfile,
+ in_mode: str,
+ out_mode: str,
+ rendering_intent: int = 0,
+ proof_intent: int = 0,
+ cms_flags: int = 0,
+ /,
+) -> CmsTransform: ...
+def createProfile(
+ color_space: Literal["LAB", "XYZ", "sRGB"], color_temp: SupportsFloat = 0.0, /
+) -> CmsProfile: ...
+
+if sys.platform == "win32":
+ def get_display_profile_win32(handle: int = 0, is_dc: int = 0, /) -> str | None: ...
diff --git a/venv/Lib/site-packages/PIL/_imagingft.cp312-win_amd64.pyd b/venv/Lib/site-packages/PIL/_imagingft.cp312-win_amd64.pyd
new file mode 100644
index 0000000..bb2609c
Binary files /dev/null and b/venv/Lib/site-packages/PIL/_imagingft.cp312-win_amd64.pyd differ
diff --git a/venv/Lib/site-packages/PIL/_imagingft.pyi b/venv/Lib/site-packages/PIL/_imagingft.pyi
new file mode 100644
index 0000000..2136810
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_imagingft.pyi
@@ -0,0 +1,70 @@
+from collections.abc import Callable
+from typing import Any
+
+from . import ImageFont, _imaging
+
+class Font:
+ @property
+ def family(self) -> str | None: ...
+ @property
+ def style(self) -> str | None: ...
+ @property
+ def ascent(self) -> int: ...
+ @property
+ def descent(self) -> int: ...
+ @property
+ def height(self) -> int: ...
+ @property
+ def x_ppem(self) -> int: ...
+ @property
+ def y_ppem(self) -> int: ...
+ @property
+ def glyphs(self) -> int: ...
+ def render(
+ self,
+ string: str | bytes,
+ fill: Callable[[int, int], _imaging.ImagingCore],
+ mode: str,
+ dir: str | None,
+ features: list[str] | None,
+ lang: str | None,
+ stroke_width: float,
+ stroke_filled: bool,
+ anchor: str | None,
+ foreground_ink_long: int,
+ start: tuple[float, float],
+ /,
+ ) -> tuple[_imaging.ImagingCore, tuple[int, int]]: ...
+ def getsize(
+ self,
+ string: str | bytes | bytearray,
+ mode: str,
+ dir: str | None,
+ features: list[str] | None,
+ lang: str | None,
+ anchor: str | None,
+ /,
+ ) -> tuple[tuple[int, int], tuple[int, int]]: ...
+ def getlength(
+ self,
+ string: str | bytes,
+ mode: str,
+ dir: str | None,
+ features: list[str] | None,
+ lang: str | None,
+ /,
+ ) -> float: ...
+ def getvarnames(self) -> list[bytes]: ...
+ def getvaraxes(self) -> list[ImageFont.Axis]: ...
+ def setvarname(self, instance_index: int, /) -> None: ...
+ def setvaraxes(self, axes: list[float], /) -> None: ...
+
+def getfont(
+ filename: str | bytes,
+ size: float,
+ index: int,
+ encoding: str,
+ font_bytes: bytes,
+ layout_engine: int,
+) -> Font: ...
+def __getattr__(name: str) -> Any: ...
diff --git a/venv/Lib/site-packages/PIL/_imagingmath.cp312-win_amd64.pyd b/venv/Lib/site-packages/PIL/_imagingmath.cp312-win_amd64.pyd
new file mode 100644
index 0000000..fa932ce
Binary files /dev/null and b/venv/Lib/site-packages/PIL/_imagingmath.cp312-win_amd64.pyd differ
diff --git a/venv/Lib/site-packages/PIL/_imagingmath.pyi b/venv/Lib/site-packages/PIL/_imagingmath.pyi
new file mode 100644
index 0000000..e27843e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_imagingmath.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name: str) -> Any: ...
diff --git a/venv/Lib/site-packages/PIL/_imagingmorph.cp312-win_amd64.pyd b/venv/Lib/site-packages/PIL/_imagingmorph.cp312-win_amd64.pyd
new file mode 100644
index 0000000..3a27ecf
Binary files /dev/null and b/venv/Lib/site-packages/PIL/_imagingmorph.cp312-win_amd64.pyd differ
diff --git a/venv/Lib/site-packages/PIL/_imagingmorph.pyi b/venv/Lib/site-packages/PIL/_imagingmorph.pyi
new file mode 100644
index 0000000..e27843e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_imagingmorph.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name: str) -> Any: ...
diff --git a/venv/Lib/site-packages/PIL/_imagingtk.cp312-win_amd64.pyd b/venv/Lib/site-packages/PIL/_imagingtk.cp312-win_amd64.pyd
new file mode 100644
index 0000000..2cf632f
Binary files /dev/null and b/venv/Lib/site-packages/PIL/_imagingtk.cp312-win_amd64.pyd differ
diff --git a/venv/Lib/site-packages/PIL/_imagingtk.pyi b/venv/Lib/site-packages/PIL/_imagingtk.pyi
new file mode 100644
index 0000000..e27843e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_imagingtk.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name: str) -> Any: ...
diff --git a/venv/Lib/site-packages/PIL/_tkinter_finder.py b/venv/Lib/site-packages/PIL/_tkinter_finder.py
new file mode 100644
index 0000000..9c01430
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_tkinter_finder.py
@@ -0,0 +1,20 @@
+"""Find compiled module linking to Tcl / Tk libraries"""
+
+from __future__ import annotations
+
+import sys
+import tkinter
+
+tk = getattr(tkinter, "_tkinter")
+
+try:
+ if hasattr(sys, "pypy_find_executable"):
+ TKINTER_LIB = tk.tklib_cffi.__file__
+ else:
+ TKINTER_LIB = tk.__file__
+except AttributeError:
+ # _tkinter may be compiled directly into Python, in which case __file__ is
+ # not available. load_tkinter_funcs will check the binary first in any case.
+ TKINTER_LIB = None
+
+tk_version = str(tkinter.TkVersion)
diff --git a/venv/Lib/site-packages/PIL/_typing.py b/venv/Lib/site-packages/PIL/_typing.py
new file mode 100644
index 0000000..a941f89
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_typing.py
@@ -0,0 +1,45 @@
+from __future__ import annotations
+
+import os
+import sys
+from collections.abc import Sequence
+from typing import Any, Protocol, TypeVar
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from numbers import _IntegralLike as IntegralLike
+
+ try:
+ import numpy.typing as npt
+
+ NumpyArray = npt.NDArray[Any]
+ except ImportError:
+ pass
+
+if sys.version_info >= (3, 13):
+ from types import CapsuleType
+else:
+ CapsuleType = object
+
+if sys.version_info >= (3, 12):
+ from collections.abc import Buffer
+else:
+ Buffer = Any
+
+
+_Ink = float | tuple[int, ...] | str
+
+Coords = Sequence[float] | Sequence[Sequence[float]]
+
+
+_T_co = TypeVar("_T_co", covariant=True)
+
+
+class SupportsRead(Protocol[_T_co]):
+ def read(self, length: int = ..., /) -> _T_co: ...
+
+
+StrOrBytesPath = str | bytes | os.PathLike[str] | os.PathLike[bytes]
+
+
+__all__ = ["Buffer", "IntegralLike", "StrOrBytesPath", "SupportsRead"]
diff --git a/venv/Lib/site-packages/PIL/_util.py b/venv/Lib/site-packages/PIL/_util.py
new file mode 100644
index 0000000..b1fa6a0
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_util.py
@@ -0,0 +1,29 @@
+from __future__ import annotations
+
+import os
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+ from typing import Any, NoReturn, TypeGuard
+
+ from ._typing import StrOrBytesPath
+
+
+def is_path(f: Any) -> TypeGuard[StrOrBytesPath]:
+ return isinstance(f, (bytes, str, os.PathLike))
+
+
+class DeferredError:
+ def __init__(self, ex: BaseException):
+ self.ex = ex
+
+ def __getattr__(self, elt: str) -> NoReturn:
+ raise self.ex
+
+ @staticmethod
+ def new(ex: BaseException) -> Any:
+ """
+ Creates an object that raises the wrapped exception ``ex`` when used,
+ and casts it to :py:obj:`~typing.Any` type.
+ """
+ return DeferredError(ex)
diff --git a/venv/Lib/site-packages/PIL/_version.py b/venv/Lib/site-packages/PIL/_version.py
new file mode 100644
index 0000000..b32ff44
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_version.py
@@ -0,0 +1,4 @@
+# Master version for Pillow
+from __future__ import annotations
+
+__version__ = "12.1.0"
diff --git a/venv/Lib/site-packages/PIL/_webp.cp312-win_amd64.pyd b/venv/Lib/site-packages/PIL/_webp.cp312-win_amd64.pyd
new file mode 100644
index 0000000..5f1d989
Binary files /dev/null and b/venv/Lib/site-packages/PIL/_webp.cp312-win_amd64.pyd differ
diff --git a/venv/Lib/site-packages/PIL/_webp.pyi b/venv/Lib/site-packages/PIL/_webp.pyi
new file mode 100644
index 0000000..e27843e
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/_webp.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name: str) -> Any: ...
diff --git a/venv/Lib/site-packages/PIL/features.py b/venv/Lib/site-packages/PIL/features.py
new file mode 100644
index 0000000..ff32c25
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/features.py
@@ -0,0 +1,343 @@
+from __future__ import annotations
+
+import collections
+import os
+import sys
+import warnings
+from typing import IO
+
+import PIL
+
+from . import Image
+
+modules = {
+ "pil": ("PIL._imaging", "PILLOW_VERSION"),
+ "tkinter": ("PIL._tkinter_finder", "tk_version"),
+ "freetype2": ("PIL._imagingft", "freetype2_version"),
+ "littlecms2": ("PIL._imagingcms", "littlecms_version"),
+ "webp": ("PIL._webp", "webpdecoder_version"),
+ "avif": ("PIL._avif", "libavif_version"),
+}
+
+
+def check_module(feature: str) -> bool:
+ """
+ Checks if a module is available.
+
+ :param feature: The module to check for.
+ :returns: ``True`` if available, ``False`` otherwise.
+ :raises ValueError: If the module is not defined in this version of Pillow.
+ """
+ if feature not in modules:
+ msg = f"Unknown module {feature}"
+ raise ValueError(msg)
+
+ module, ver = modules[feature]
+
+ try:
+ __import__(module)
+ return True
+ except ModuleNotFoundError:
+ return False
+ except ImportError as ex:
+ warnings.warn(str(ex))
+ return False
+
+
+def version_module(feature: str) -> str | None:
+ """
+ :param feature: The module to check for.
+ :returns:
+ The loaded version number as a string, or ``None`` if unknown or not available.
+ :raises ValueError: If the module is not defined in this version of Pillow.
+ """
+ if not check_module(feature):
+ return None
+
+ module, ver = modules[feature]
+
+ return getattr(__import__(module, fromlist=[ver]), ver)
+
+
+def get_supported_modules() -> list[str]:
+ """
+ :returns: A list of all supported modules.
+ """
+ return [f for f in modules if check_module(f)]
+
+
+codecs = {
+ "jpg": ("jpeg", "jpeglib"),
+ "jpg_2000": ("jpeg2k", "jp2klib"),
+ "zlib": ("zip", "zlib"),
+ "libtiff": ("libtiff", "libtiff"),
+}
+
+
+def check_codec(feature: str) -> bool:
+ """
+ Checks if a codec is available.
+
+ :param feature: The codec to check for.
+ :returns: ``True`` if available, ``False`` otherwise.
+ :raises ValueError: If the codec is not defined in this version of Pillow.
+ """
+ if feature not in codecs:
+ msg = f"Unknown codec {feature}"
+ raise ValueError(msg)
+
+ codec, lib = codecs[feature]
+
+ return f"{codec}_encoder" in dir(Image.core)
+
+
+def version_codec(feature: str) -> str | None:
+ """
+ :param feature: The codec to check for.
+ :returns:
+ The version number as a string, or ``None`` if not available.
+ Checked at compile time for ``jpg``, run-time otherwise.
+ :raises ValueError: If the codec is not defined in this version of Pillow.
+ """
+ if not check_codec(feature):
+ return None
+
+ codec, lib = codecs[feature]
+
+ version = getattr(Image.core, f"{lib}_version")
+
+ if feature == "libtiff":
+ return version.split("\n")[0].split("Version ")[1]
+
+ return version
+
+
+def get_supported_codecs() -> list[str]:
+ """
+ :returns: A list of all supported codecs.
+ """
+ return [f for f in codecs if check_codec(f)]
+
+
+features: dict[str, tuple[str, str, str | None]] = {
+ "raqm": ("PIL._imagingft", "HAVE_RAQM", "raqm_version"),
+ "fribidi": ("PIL._imagingft", "HAVE_FRIBIDI", "fribidi_version"),
+ "harfbuzz": ("PIL._imagingft", "HAVE_HARFBUZZ", "harfbuzz_version"),
+ "libjpeg_turbo": ("PIL._imaging", "HAVE_LIBJPEGTURBO", "libjpeg_turbo_version"),
+ "mozjpeg": ("PIL._imaging", "HAVE_MOZJPEG", "libjpeg_turbo_version"),
+ "zlib_ng": ("PIL._imaging", "HAVE_ZLIBNG", "zlib_ng_version"),
+ "libimagequant": ("PIL._imaging", "HAVE_LIBIMAGEQUANT", "imagequant_version"),
+ "xcb": ("PIL._imaging", "HAVE_XCB", None),
+}
+
+
+def check_feature(feature: str) -> bool | None:
+ """
+ Checks if a feature is available.
+
+ :param feature: The feature to check for.
+ :returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown.
+ :raises ValueError: If the feature is not defined in this version of Pillow.
+ """
+ if feature not in features:
+ msg = f"Unknown feature {feature}"
+ raise ValueError(msg)
+
+ module, flag, ver = features[feature]
+
+ try:
+ imported_module = __import__(module, fromlist=["PIL"])
+ return getattr(imported_module, flag)
+ except ModuleNotFoundError:
+ return None
+ except ImportError as ex:
+ warnings.warn(str(ex))
+ return None
+
+
+def version_feature(feature: str) -> str | None:
+ """
+ :param feature: The feature to check for.
+ :returns: The version number as a string, or ``None`` if not available.
+ :raises ValueError: If the feature is not defined in this version of Pillow.
+ """
+ if not check_feature(feature):
+ return None
+
+ module, flag, ver = features[feature]
+
+ if ver is None:
+ return None
+
+ return getattr(__import__(module, fromlist=[ver]), ver)
+
+
+def get_supported_features() -> list[str]:
+ """
+ :returns: A list of all supported features.
+ """
+ return [f for f in features if check_feature(f)]
+
+
+def check(feature: str) -> bool | None:
+ """
+ :param feature: A module, codec, or feature name.
+ :returns:
+ ``True`` if the module, codec, or feature is available,
+ ``False`` or ``None`` otherwise.
+ """
+
+ if feature in modules:
+ return check_module(feature)
+ if feature in codecs:
+ return check_codec(feature)
+ if feature in features:
+ return check_feature(feature)
+ warnings.warn(f"Unknown feature '{feature}'.", stacklevel=2)
+ return False
+
+
+def version(feature: str) -> str | None:
+ """
+ :param feature:
+ The module, codec, or feature to check for.
+ :returns:
+ The version number as a string, or ``None`` if unknown or not available.
+ """
+ if feature in modules:
+ return version_module(feature)
+ if feature in codecs:
+ return version_codec(feature)
+ if feature in features:
+ return version_feature(feature)
+ return None
+
+
+def get_supported() -> list[str]:
+ """
+ :returns: A list of all supported modules, features, and codecs.
+ """
+
+ ret = get_supported_modules()
+ ret.extend(get_supported_features())
+ ret.extend(get_supported_codecs())
+ return ret
+
+
+def pilinfo(out: IO[str] | None = None, supported_formats: bool = True) -> None:
+ """
+ Prints information about this installation of Pillow.
+ This function can be called with ``python3 -m PIL``.
+ It can also be called with ``python3 -m PIL.report`` or ``python3 -m PIL --report``
+ to have "supported_formats" set to ``False``, omitting the list of all supported
+ image file formats.
+
+ :param out:
+ The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
+ :param supported_formats:
+ If ``True``, a list of all supported image file formats will be printed.
+ """
+
+ if out is None:
+ out = sys.stdout
+
+ Image.init()
+
+ print("-" * 68, file=out)
+ print(f"Pillow {PIL.__version__}", file=out)
+ py_version_lines = sys.version.splitlines()
+ print(f"Python {py_version_lines[0].strip()}", file=out)
+ for py_version in py_version_lines[1:]:
+ print(f" {py_version.strip()}", file=out)
+ print("-" * 68, file=out)
+ print(f"Python executable is {sys.executable or 'unknown'}", file=out)
+ if sys.prefix != sys.base_prefix:
+ print(f"Environment Python files loaded from {sys.prefix}", file=out)
+ print(f"System Python files loaded from {sys.base_prefix}", file=out)
+ print("-" * 68, file=out)
+ print(
+ f"Python Pillow modules loaded from {os.path.dirname(Image.__file__)}",
+ file=out,
+ )
+ print(
+ f"Binary Pillow modules loaded from {os.path.dirname(Image.core.__file__)}",
+ file=out,
+ )
+ print("-" * 68, file=out)
+
+ for name, feature in [
+ ("pil", "PIL CORE"),
+ ("tkinter", "TKINTER"),
+ ("freetype2", "FREETYPE2"),
+ ("littlecms2", "LITTLECMS2"),
+ ("webp", "WEBP"),
+ ("avif", "AVIF"),
+ ("jpg", "JPEG"),
+ ("jpg_2000", "OPENJPEG (JPEG2000)"),
+ ("zlib", "ZLIB (PNG/ZIP)"),
+ ("libtiff", "LIBTIFF"),
+ ("raqm", "RAQM (Bidirectional Text)"),
+ ("libimagequant", "LIBIMAGEQUANT (Quantization method)"),
+ ("xcb", "XCB (X protocol)"),
+ ]:
+ if check(name):
+ v: str | None = None
+ if name == "jpg":
+ libjpeg_turbo_version = version_feature("libjpeg_turbo")
+ if libjpeg_turbo_version is not None:
+ v = "mozjpeg" if check_feature("mozjpeg") else "libjpeg-turbo"
+ v += " " + libjpeg_turbo_version
+ if v is None:
+ v = version(name)
+ if v is not None:
+ version_static = name in ("pil", "jpg")
+ if name == "littlecms2":
+ # this check is also in src/_imagingcms.c:setup_module()
+ version_static = tuple(int(x) for x in v.split(".")) < (2, 7)
+ t = "compiled for" if version_static else "loaded"
+ if name == "zlib":
+ zlib_ng_version = version_feature("zlib_ng")
+ if zlib_ng_version is not None:
+ v += ", compiled for zlib-ng " + zlib_ng_version
+ elif name == "raqm":
+ for f in ("fribidi", "harfbuzz"):
+ v2 = version_feature(f)
+ if v2 is not None:
+ v += f", {f} {v2}"
+ print("---", feature, "support ok,", t, v, file=out)
+ else:
+ print("---", feature, "support ok", file=out)
+ else:
+ print("***", feature, "support not installed", file=out)
+ print("-" * 68, file=out)
+
+ if supported_formats:
+ extensions = collections.defaultdict(list)
+ for ext, i in Image.EXTENSION.items():
+ extensions[i].append(ext)
+
+ for i in sorted(Image.ID):
+ line = f"{i}"
+ if i in Image.MIME:
+ line = f"{line} {Image.MIME[i]}"
+ print(line, file=out)
+
+ if i in extensions:
+ print(
+ "Extensions: {}".format(", ".join(sorted(extensions[i]))), file=out
+ )
+
+ features = []
+ if i in Image.OPEN:
+ features.append("open")
+ if i in Image.SAVE:
+ features.append("save")
+ if i in Image.SAVE_ALL:
+ features.append("save_all")
+ if i in Image.DECODERS:
+ features.append("decode")
+ if i in Image.ENCODERS:
+ features.append("encode")
+
+ print("Features: {}".format(", ".join(features)), file=out)
+ print("-" * 68, file=out)
diff --git a/venv/Lib/site-packages/PIL/py.typed b/venv/Lib/site-packages/PIL/py.typed
new file mode 100644
index 0000000..e69de29
diff --git a/venv/Lib/site-packages/PIL/report.py b/venv/Lib/site-packages/PIL/report.py
new file mode 100644
index 0000000..d2815e8
--- /dev/null
+++ b/venv/Lib/site-packages/PIL/report.py
@@ -0,0 +1,5 @@
+from __future__ import annotations
+
+from .features import pilinfo
+
+pilinfo(supported_formats=False)
diff --git a/venv/Lib/site-packages/pillow-12.1.0.dist-info/INSTALLER b/venv/Lib/site-packages/pillow-12.1.0.dist-info/INSTALLER
new file mode 100644
index 0000000..a1b589e
--- /dev/null
+++ b/venv/Lib/site-packages/pillow-12.1.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/Lib/site-packages/pillow-12.1.0.dist-info/METADATA b/venv/Lib/site-packages/pillow-12.1.0.dist-info/METADATA
new file mode 100644
index 0000000..c147a64
--- /dev/null
+++ b/venv/Lib/site-packages/pillow-12.1.0.dist-info/METADATA
@@ -0,0 +1,175 @@
+Metadata-Version: 2.4
+Name: pillow
+Version: 12.1.0
+Summary: Python Imaging Library (fork)
+Author-email: "Jeffrey A. Clark"
+License-Expression: MIT-CMU
+Project-URL: Changelog, https://github.com/python-pillow/Pillow/releases
+Project-URL: Documentation, https://pillow.readthedocs.io
+Project-URL: Funding, https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pypi-pillow&utm_medium=pypi
+Project-URL: Homepage, https://python-pillow.github.io
+Project-URL: Mastodon, https://fosstodon.org/@pillow
+Project-URL: Release notes, https://pillow.readthedocs.io/en/stable/releasenotes/index.html
+Project-URL: Source, https://github.com/python-pillow/Pillow
+Keywords: Imaging
+Classifier: Development Status :: 6 - Mature
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Multimedia :: Graphics
+Classifier: Topic :: Multimedia :: Graphics :: Capture :: Digital Camera
+Classifier: Topic :: Multimedia :: Graphics :: Capture :: Screen Capture
+Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
+Classifier: Topic :: Multimedia :: Graphics :: Viewers
+Classifier: Typing :: Typed
+Requires-Python: >=3.10
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Provides-Extra: docs
+Requires-Dist: furo; extra == "docs"
+Requires-Dist: olefile; extra == "docs"
+Requires-Dist: sphinx>=8.2; extra == "docs"
+Requires-Dist: sphinx-autobuild; extra == "docs"
+Requires-Dist: sphinx-copybutton; extra == "docs"
+Requires-Dist: sphinx-inline-tabs; extra == "docs"
+Requires-Dist: sphinxext-opengraph; extra == "docs"
+Provides-Extra: fpx
+Requires-Dist: olefile; extra == "fpx"
+Provides-Extra: mic
+Requires-Dist: olefile; extra == "mic"
+Provides-Extra: test-arrow
+Requires-Dist: arro3-compute; extra == "test-arrow"
+Requires-Dist: arro3-core; extra == "test-arrow"
+Requires-Dist: nanoarrow; extra == "test-arrow"
+Requires-Dist: pyarrow; extra == "test-arrow"
+Provides-Extra: tests
+Requires-Dist: check-manifest; extra == "tests"
+Requires-Dist: coverage>=7.4.2; extra == "tests"
+Requires-Dist: defusedxml; extra == "tests"
+Requires-Dist: markdown2; extra == "tests"
+Requires-Dist: olefile; extra == "tests"
+Requires-Dist: packaging; extra == "tests"
+Requires-Dist: pyroma>=5; extra == "tests"
+Requires-Dist: pytest; extra == "tests"
+Requires-Dist: pytest-cov; extra == "tests"
+Requires-Dist: pytest-timeout; extra == "tests"
+Requires-Dist: pytest-xdist; extra == "tests"
+Requires-Dist: trove-classifiers>=2024.10.12; extra == "tests"
+Provides-Extra: xmp
+Requires-Dist: defusedxml; extra == "xmp"
+Dynamic: license-file
+
+
+
+
+
+# Pillow
+
+## Python Imaging Library (Fork)
+
+Pillow is the friendly PIL fork by [Jeffrey A. Clark and
+contributors](https://github.com/python-pillow/Pillow/graphs/contributors).
+PIL is the Python Imaging Library by Fredrik Lundh and contributors.
+As of 2019, Pillow development is
+[supported by Tidelift](https://tidelift.com/subscription/pkg/pypi-pillow?utm_source=pypi-pillow&utm_medium=readme&utm_campaign=enterprise).
+
+
+
+ | docs |
+
+
+ |
+
+
+ | tests |
+
+
+
+
+
+
+
+
+
+ |
+
+
+ | package |
+
+
+
+
+
+
+ |
+
+
+ | social |
+
+
+
+ |
+
+
+
+## Overview
+
+The Python Imaging Library adds image processing capabilities to your Python interpreter.
+
+This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities.
+
+The core image library is designed for fast access to data stored in a few basic pixel formats. It should provide a solid foundation for a general image processing tool.
+
+## More information
+
+- [Documentation](https://pillow.readthedocs.io/)
+ - [Installation](https://pillow.readthedocs.io/en/latest/installation/basic-installation.html)
+ - [Handbook](https://pillow.readthedocs.io/en/latest/handbook/index.html)
+- [Contribute](https://github.com/python-pillow/Pillow/blob/main/.github/CONTRIBUTING.md)
+ - [Issues](https://github.com/python-pillow/Pillow/issues)
+ - [Pull requests](https://github.com/python-pillow/Pillow/pulls)
+- [Release notes](https://pillow.readthedocs.io/en/stable/releasenotes/index.html)
+- [Changelog](https://github.com/python-pillow/Pillow/releases)
+ - [Pre-fork](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst#pre-fork)
+
+## Report a vulnerability
+
+To report a security vulnerability, please follow the procedure described in the [Tidelift security policy](https://tidelift.com/docs/security).
diff --git a/venv/Lib/site-packages/pillow-12.1.0.dist-info/RECORD b/venv/Lib/site-packages/pillow-12.1.0.dist-info/RECORD
new file mode 100644
index 0000000..f66bbc7
--- /dev/null
+++ b/venv/Lib/site-packages/pillow-12.1.0.dist-info/RECORD
@@ -0,0 +1,219 @@
+PIL/AvifImagePlugin.py,sha256=YCw3mGsZiu8LDpu8eUZuf4o-7nuPTOW6CFA6FIPkWTM,9323
+PIL/BdfFontFile.py,sha256=bApbMl2vYRceQKIkSDFa002Ywr9laVrp2NGK9xzlS_8,3407
+PIL/BlpImagePlugin.py,sha256=EpHoVShYXypqxnEoiSShngD7CPhCeY8efwSH1G5lnXk,17066
+PIL/BmpImagePlugin.py,sha256=NMzi6fiFZSUxIuYQRIoOWUotdPXpXZS8zWBybS3Kd-w,20442
+PIL/BufrStubImagePlugin.py,sha256=uU9nG6QHnuKeqZKd8nARlWPU6oa215Y1DXlmdqKbnMI,1841
+PIL/ContainerIO.py,sha256=I6yO_YFEEqMKA1ckgEEzF2r_Ik5p_GjM-RrWOJYjSlY,4777
+PIL/CurImagePlugin.py,sha256=O_bFtW82YhAM8_F8tpr3O5UrzKPPyiV9S2zjV9QwqaI,1866
+PIL/DcxImagePlugin.py,sha256=L21c3gVX6IPmk4zuf_ltt3mAeRfcuCCcXhkCVpued2U,2264
+PIL/DdsImagePlugin.py,sha256=2JxzvTsnaiaE5xWE-bUjNjuuN6HjhCaVuozY74Ml9YU,19556
+PIL/EpsImagePlugin.py,sha256=5cHzzxj1vUffcLYr-MEO5Tk1zTeLY4M_tMN8bwDUxpo,17107
+PIL/ExifTags.py,sha256=xG6PuZIJSXk7bfkBfXh11YgKlWVkF1HWQ_I7XywFBMs,10313
+PIL/FitsImagePlugin.py,sha256=v4peLA6wIdySjHBzDMzVI5UWx8zr0jI2A3qYZSaMixs,4796
+PIL/FliImagePlugin.py,sha256=L1vf4QjsaMV0eRQTmfy1wnqJ9l9hGV5lvTILW7znzD8,5113
+PIL/FontFile.py,sha256=iLSV32yQetLnE4SgG8HnHb2FdqkqFBjY9n--E6u5UE0,3711
+PIL/FpxImagePlugin.py,sha256=4NAdiIuZ_VF6OXraYCt12vzQqEhEJSu7s3aaMlxDFpQ,7622
+PIL/FtexImagePlugin.py,sha256=-zKvvhMTczUe3o0f4HpDC9_DK6lKHT5LABf0r5-3l-4,3685
+PIL/GbrImagePlugin.py,sha256=Ib_y35ZzNOmMqG2SuOyjxRh3Oxt42QpcEcgLa6BhmtA,3156
+PIL/GdImageFile.py,sha256=LjMalK77Vw9U5pBH4KQlbi2PaIr73u9DqtxN58O1rBs,2890
+PIL/GifImagePlugin.py,sha256=1RCh0bWIxh_VcF8ztTlzfBHthuzEoLylrWE9QRpnDSU,43521
+PIL/GimpGradientFile.py,sha256=kbXZojJsokKBAgd_KOX9LAk2aabIIWJpdwZ16eKvxTc,4135
+PIL/GimpPaletteFile.py,sha256=EmBHcQ9ExC4f47taD7S7G6VaMkr9HjynlV8NdTXV5iQ,1935
+PIL/GribStubImagePlugin.py,sha256=Nyp5h5l-fwgBg6KBYXB6wqxZWAIz6Q-2e2sTelDbfu0,1870
+PIL/Hdf5StubImagePlugin.py,sha256=oCnXpfLPCRzc5vra6YcbH9vHLXy_iQWbja1d0Pl-SgM,1852
+PIL/IcnsImagePlugin.py,sha256=WW6GT0jcYcG_M7t-ab2xSb9SMJCvjsp51lIvfgSSvGE,12842
+PIL/IcoImagePlugin.py,sha256=DZoBj2zKv76Sk96PKq8el9aZAM2J3wULVqPeono_0z0,13499
+PIL/ImImagePlugin.py,sha256=X9iBSQ4x7rauxbOIn72j7v6TAUgZldpYD5cAc6Z1MNA,11992
+PIL/Image.py,sha256=Ry-wtI-imqrosqofZIAHl5-ORJC5eY0bjIdwlWUCP-w,153145
+PIL/ImageChops.py,sha256=hZ8EPUPlQIzugsEedV8trkKX0jBCDGb6Cszma6ZeMZQ,8257
+PIL/ImageCms.py,sha256=5rDN-FiLHebKlWP2kN6jbvDEF9jcb3somkBaDX8dFbs,41752
+PIL/ImageColor.py,sha256=KV-u7HnZWrrL3zuBAOLqerI-7vFcXTxdLeoaYVjsnwI,9761
+PIL/ImageDraw.py,sha256=-CJ7HMpnvaj2WynZ8OaUoN5jC2Qz_RiGeoV4YgIESeE,37323
+PIL/ImageDraw2.py,sha256=_e6I2nPxeiZwjOjBEJzUvxoyAklzmc-xF6R8z8ieOAA,7470
+PIL/ImageEnhance.py,sha256=ugDU0sljaR_zaTibtumlTvf-qFH1x1W6l2QMpc386XU,3740
+PIL/ImageFile.py,sha256=E8DXKovcC9h3lhATOkteYTsvz4_2uw0eWz4PlgVsFCE,30910
+PIL/ImageFilter.py,sha256=n3aT1MkbKrqGPeoSuqxmWliVqhkhOgLZ3ixjLn8vqK8,19336
+PIL/ImageFont.py,sha256=GnOo5yNj0DDRdIpyXEI-0lHktGvpgAzF7W9sEwKZiiI,64573
+PIL/ImageGrab.py,sha256=VKmorGPVfWYGNOIcYSEzLsAiOFvAhNN2EQULC4loomY,7974
+PIL/ImageMath.py,sha256=xhGBhvet2v7bgyLRl_adzVWnmZ7zVcbT8d1q1cpJHFI,10683
+PIL/ImageMode.py,sha256=ULkA-jsCgGwxVjr2LPSP42dDmj6nWaQk9L4UKj7KfSg,2480
+PIL/ImageMorph.py,sha256=Vr1QQB5vGYpGVffRGJQod4H7_AlQmO3l-BlhpaYeDyI,10673
+PIL/ImageOps.py,sha256=0Qc0PTg5r8t8JSgaKkzd-cjYMGtMUUMSBkXmmaJm-JU,26313
+PIL/ImagePalette.py,sha256=twVKqJFi6SEys_r7bVuhaaoPTdi3Kmjc2lHAQcCAZNs,9379
+PIL/ImagePath.py,sha256=ZnnJuvQNtbKRhCmr61TEmEh1vVV5_90WMEPL8Opy5l8,391
+PIL/ImageQt.py,sha256=SpxHePgWh5gdjVIGNC4GG5v9V3smQm_nPiJDcrhnHXc,6903
+PIL/ImageSequence.py,sha256=guZHUdpWrznzZkcY0OYpDzuF0uFXlCEu260oP-7e_fI,2341
+PIL/ImageShow.py,sha256=TqO6nzj5EMwp5dExag3jhBJXdHojccnFx59LOnMQao0,10468
+PIL/ImageStat.py,sha256=W0uUa8YNC6vhowlerSzZIwE7Ru-Kp2rWuqGNLBFLZyo,5662
+PIL/ImageText.py,sha256=YhgNTRumUFlkkklHZqLl58TyRCY2BkFRPewQXmL3yDQ,12440
+PIL/ImageTk.py,sha256=Tx0zf9kTaBuAGvZuo0JAHrNbk3n6ewr4ZndWnWxZK0Q,8398
+PIL/ImageTransform.py,sha256=Zu6oySXENtq712-nkqFLqafYPviRAgsgkzfLWG0K3V8,4052
+PIL/ImageWin.py,sha256=b-fO6kn4icHpy-zk-Xg-nO382zPXl-MKjZcs3vAXl1Q,8332
+PIL/ImtImagePlugin.py,sha256=r-ZDz3Xji6EBF8eUnK6iuCEZEtllp0xLRSIQ0_h14UE,2768
+PIL/IptcImagePlugin.py,sha256=Agv0WZN3tQWP5X9f_tkoFFKgv7BTdnkQ_AK328VxdGM,6812
+PIL/Jpeg2KImagePlugin.py,sha256=Lji_F42Lk5gIiKSnkDbyI11mp38aVg8uImFIWuaMSgk,14450
+PIL/JpegImagePlugin.py,sha256=Bv1zgkVZCBUzmEYMJaGZsT60Imrr62eZ8zrKrW6zLf0,32438
+PIL/JpegPresets.py,sha256=UUIsKzvyzdPzsndODd90eu_luMqauG1PJh10UOuQvmg,12621
+PIL/McIdasImagePlugin.py,sha256=P9d1kr4Ste0QVkxfqix31sfGD8sWn-eVmYK0wg6DvIw,1955
+PIL/MicImagePlugin.py,sha256=uCxGM4llIFPjfu2Kji-zSnPacnqiGUZGqs_Dtb3JktI,2702
+PIL/MpegImagePlugin.py,sha256=kem9zofsBtIq6xlMJcsFkOXTcJCPEICk9lchTfR9pDI,2094
+PIL/MpoImagePlugin.py,sha256=zec5axNlRwIWfX1-ZXzDi1u6AcSJUGbBPsPis54TXaU,6996
+PIL/MspImagePlugin.py,sha256=W8ruM60OZUbiPuUBQ7BBkFzkl1fiaPEvsvRMyNrg18A,6092
+PIL/PSDraw.py,sha256=uAr-Mg5j9_G3RLwWx4_J1wutJg_DVeDAE4qWd3Mvi9U,7155
+PIL/PaletteFile.py,sha256=QdEa99jLC-PPhEqGy6_4fDua8TzKSSUzkAeYcClFX7M,1270
+PIL/PalmImagePlugin.py,sha256=fNIhWH06V35uLgwIHUMMc_2xumelIEJsmCwhw2whBxI,8965
+PIL/PcdImagePlugin.py,sha256=gZsCcXDIqEVTK2z-GWKptT25pFU1AUOgpr3J06cjPCg,1842
+PIL/PcfFontFile.py,sha256=LaEuaKkGaahzjCkS7P7JbdoO4XQB9x7Njc3xdvAbokg,7481
+PIL/PcxImagePlugin.py,sha256=OiNiWX24k5atXZJNbS0XLxp-EiklJAwyuZKuk9jxqKE,6473
+PIL/PdfImagePlugin.py,sha256=gJMr0sSEWzyn7LnK5P5WQI995Cu_l-W3T8FX4jVgYf8,9632
+PIL/PdfParser.py,sha256=0jyauisa3VbAXxintmxjbSdw7m1xuaAQbit-9ytu_BM,39071
+PIL/PixarImagePlugin.py,sha256=-RnuJSGhGF8MsUsiHZq3VzBxV-BNnK35kBjJfhYzwXs,1830
+PIL/PngImagePlugin.py,sha256=JDJQ7Efeqkgvg8Ye7ciq7PQxayguHDAxldkCADUr8ws,53285
+PIL/PpmImagePlugin.py,sha256=WhtClGFMAO8VZZU9mFBZfMj7DbkytZ8XP7nQbVtZN5U,12766
+PIL/PsdImagePlugin.py,sha256=fDKVzMolUjVlAgS9eZpBZg53D6nuQQWKCmYlEWThslc,9054
+PIL/QoiImagePlugin.py,sha256=XKWT6v5f7l_3WmTWxbmmNWsMkzl5j-Uh5pnJwV2ybFg,8842
+PIL/SgiImagePlugin.py,sha256=w1xV4-ELYBHKL_AaGf9oJSYJzBwTpdJ-rNPqiArKgGs,6620
+PIL/SpiderImagePlugin.py,sha256=J3VxtBF-SqeYieu87IWKO34JXRhnRcLodTmT5J_Qsck,10638
+PIL/SunImagePlugin.py,sha256=YKYEvuG4QUkies34OKtXWKTYSZ8U3qzcE_vdTrOuRsw,4734
+PIL/TarIO.py,sha256=K6tLkFDcaar3vb6EyYb7G4oVEB41x_LMuGJeUT9w5DQ,1503
+PIL/TgaImagePlugin.py,sha256=OMvZn_xKjB1dZ1_4MkOquzJBHpSUIpAf5mUEJZiLBTI,7244
+PIL/TiffImagePlugin.py,sha256=lCVGTYQHxNxjcKcEmk2NmAgoheHroJ9NONncOXAeEU0,87340
+PIL/TiffTags.py,sha256=FsdqbIQJOI7ihG7MZ_K4YUQDZ4zo-raYbihVDe42U9E,17772
+PIL/WalImageFile.py,sha256=paHkgmmgW2_LXggPSTxhPiRxW-6B2wBKRW3GFO70Pck,5889
+PIL/WebPImagePlugin.py,sha256=mqdblF3URZ_V2dijWXtloM328_Ja-txMUervzEVI0Wk,10171
+PIL/WmfImagePlugin.py,sha256=i8w7nN1KC1TbGiz04PlN1hw3bERdK39dYkJ-xLQdCpY,5504
+PIL/XVThumbImagePlugin.py,sha256=OEtEhQgCLLgvx8J1iI911TMzjJ5iTlOOqQpLQx1bzQ4,2209
+PIL/XbmImagePlugin.py,sha256=wc0NpfTzlShx9Ymi0zwo0aVZjDa4_B7NEiG2TgCO65Q,2767
+PIL/XpmImagePlugin.py,sha256=wYf7Q7TGo4JL6n5ouQx8pbTMnMZVshgp-xwoAMZEUKg,4557
+PIL/__init__.py,sha256=Z-sXBmtIAVmDwqwBdI6L4RWjWxcgVvQ3v4SG0NxKeWU,2118
+PIL/__main__.py,sha256=X8eIpGlmHfnp7zazp5mdav228Itcf2lkiMP0tLU6X9c,140
+PIL/__pycache__/AvifImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/BdfFontFile.cpython-312.pyc,,
+PIL/__pycache__/BlpImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/BmpImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/BufrStubImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/ContainerIO.cpython-312.pyc,,
+PIL/__pycache__/CurImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/DcxImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/DdsImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/EpsImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/ExifTags.cpython-312.pyc,,
+PIL/__pycache__/FitsImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/FliImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/FontFile.cpython-312.pyc,,
+PIL/__pycache__/FpxImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/FtexImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/GbrImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/GdImageFile.cpython-312.pyc,,
+PIL/__pycache__/GifImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/GimpGradientFile.cpython-312.pyc,,
+PIL/__pycache__/GimpPaletteFile.cpython-312.pyc,,
+PIL/__pycache__/GribStubImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/Hdf5StubImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/IcnsImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/IcoImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/ImImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/Image.cpython-312.pyc,,
+PIL/__pycache__/ImageChops.cpython-312.pyc,,
+PIL/__pycache__/ImageCms.cpython-312.pyc,,
+PIL/__pycache__/ImageColor.cpython-312.pyc,,
+PIL/__pycache__/ImageDraw.cpython-312.pyc,,
+PIL/__pycache__/ImageDraw2.cpython-312.pyc,,
+PIL/__pycache__/ImageEnhance.cpython-312.pyc,,
+PIL/__pycache__/ImageFile.cpython-312.pyc,,
+PIL/__pycache__/ImageFilter.cpython-312.pyc,,
+PIL/__pycache__/ImageFont.cpython-312.pyc,,
+PIL/__pycache__/ImageGrab.cpython-312.pyc,,
+PIL/__pycache__/ImageMath.cpython-312.pyc,,
+PIL/__pycache__/ImageMode.cpython-312.pyc,,
+PIL/__pycache__/ImageMorph.cpython-312.pyc,,
+PIL/__pycache__/ImageOps.cpython-312.pyc,,
+PIL/__pycache__/ImagePalette.cpython-312.pyc,,
+PIL/__pycache__/ImagePath.cpython-312.pyc,,
+PIL/__pycache__/ImageQt.cpython-312.pyc,,
+PIL/__pycache__/ImageSequence.cpython-312.pyc,,
+PIL/__pycache__/ImageShow.cpython-312.pyc,,
+PIL/__pycache__/ImageStat.cpython-312.pyc,,
+PIL/__pycache__/ImageText.cpython-312.pyc,,
+PIL/__pycache__/ImageTk.cpython-312.pyc,,
+PIL/__pycache__/ImageTransform.cpython-312.pyc,,
+PIL/__pycache__/ImageWin.cpython-312.pyc,,
+PIL/__pycache__/ImtImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/IptcImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/Jpeg2KImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/JpegImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/JpegPresets.cpython-312.pyc,,
+PIL/__pycache__/McIdasImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/MicImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/MpegImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/MpoImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/MspImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/PSDraw.cpython-312.pyc,,
+PIL/__pycache__/PaletteFile.cpython-312.pyc,,
+PIL/__pycache__/PalmImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/PcdImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/PcfFontFile.cpython-312.pyc,,
+PIL/__pycache__/PcxImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/PdfImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/PdfParser.cpython-312.pyc,,
+PIL/__pycache__/PixarImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/PngImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/PpmImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/PsdImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/QoiImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/SgiImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/SpiderImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/SunImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/TarIO.cpython-312.pyc,,
+PIL/__pycache__/TgaImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/TiffImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/TiffTags.cpython-312.pyc,,
+PIL/__pycache__/WalImageFile.cpython-312.pyc,,
+PIL/__pycache__/WebPImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/WmfImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/XVThumbImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/XbmImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/XpmImagePlugin.cpython-312.pyc,,
+PIL/__pycache__/__init__.cpython-312.pyc,,
+PIL/__pycache__/__main__.cpython-312.pyc,,
+PIL/__pycache__/_binary.cpython-312.pyc,,
+PIL/__pycache__/_deprecate.cpython-312.pyc,,
+PIL/__pycache__/_tkinter_finder.cpython-312.pyc,,
+PIL/__pycache__/_typing.cpython-312.pyc,,
+PIL/__pycache__/_util.cpython-312.pyc,,
+PIL/__pycache__/_version.cpython-312.pyc,,
+PIL/__pycache__/features.cpython-312.pyc,,
+PIL/__pycache__/report.cpython-312.pyc,,
+PIL/_avif.cp312-win_amd64.pyd,sha256=Vt65LbBJif7PyPWIebJOqQcNpVETUa7AWelQicRFv40,7834112
+PIL/_avif.pyi,sha256=zD8vAoPC8aEIVjfckLtFskRW5saiVel3-sJUA2pHaGc,66
+PIL/_binary.py,sha256=cb9p-_mwzBYumlVsWbnoTWsrLo59towA6atLOZvjO3w,2662
+PIL/_deprecate.py,sha256=UirDlwsyef6u6sL_rlE3mnKtRf1mavmnhkt_1PA7Q8A,2106
+PIL/_imaging.cp312-win_amd64.pyd,sha256=P6RIJRFtlzBIHA1f_TSOLYwDxWAC1HtfO9iaThK9bzQ,2588160
+PIL/_imaging.pyi,sha256=jSRG3q1dwiBMqOwIhLtTBe3LMKwsi3YkTcDfsKV32E0,924
+PIL/_imagingcms.cp312-win_amd64.pyd,sha256=g0K2LR6FYnL-Wezzy4JRk7VekR5LoR-rNGXJLS9EEFI,269824
+PIL/_imagingcms.pyi,sha256=5_SDKe7KwT9ab5EeG-wn6F5sv_fs0o212xoPBm3H-Io,4576
+PIL/_imagingft.cp312-win_amd64.pyd,sha256=L6MCmoS60xRT3UCpTULGjaNepakotTE62KrIcQZeYNQ,2170368
+PIL/_imagingft.pyi,sha256=U1rpwqQX1hULvTAo8fY0_IrXng-VPuCXVaWBUj2p1z0,1903
+PIL/_imagingmath.cp312-win_amd64.pyd,sha256=NTzbD5DGn3xWYoWX8mXdKOpuqY47MiMZJQYZnRI3CsI,25088
+PIL/_imagingmath.pyi,sha256=zD8vAoPC8aEIVjfckLtFskRW5saiVel3-sJUA2pHaGc,66
+PIL/_imagingmorph.cp312-win_amd64.pyd,sha256=TrI_4nK_Fvk3y2UGrdAaIUAenc_-qTDBCpJe3_G1SLM,13824
+PIL/_imagingmorph.pyi,sha256=zD8vAoPC8aEIVjfckLtFskRW5saiVel3-sJUA2pHaGc,66
+PIL/_imagingtk.cp312-win_amd64.pyd,sha256=L7gkiD6-Tdn3JwO-Wb5fFnnKrn_cgTBEn_kiLtAhpNg,14848
+PIL/_imagingtk.pyi,sha256=zD8vAoPC8aEIVjfckLtFskRW5saiVel3-sJUA2pHaGc,66
+PIL/_tkinter_finder.py,sha256=H1Uw3dV7gWHIj_osUnJFxWh1aRsQ2MdKpNP3vQwQcW0,558
+PIL/_typing.py,sha256=t-MVS5f_pRdL-M072YZqlXFB_D8z1KOl8EcKsT_d9s4,964
+PIL/_util.py,sha256=eP8IfmWJmbE_PqbUJb4qTqGNLi4zT0TTadrrqmykg7Y,713
+PIL/_version.py,sha256=c98gZU4emt6sNtCLY_9UhrF4HWnVoO6DZPkCV4k9Ik0,91
+PIL/_webp.cp312-win_amd64.pyd,sha256=vzGK_OwJkqyz6J0cjvIPWudQ0oCycZRsX42yPX2_UYQ,410112
+PIL/_webp.pyi,sha256=zD8vAoPC8aEIVjfckLtFskRW5saiVel3-sJUA2pHaGc,66
+PIL/features.py,sha256=y_elNCzgB6RgMP9AMf3CdOP3jdoN4ho4vxoSKzg6eWc,11118
+PIL/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+PIL/report.py,sha256=6m7NOv1a24577ZiJoxX89ip5JeOgf2O1F95f6-1K5aM,105
+pillow-12.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pillow-12.1.0.dist-info/METADATA,sha256=w7MYfUpI2Mgk_IAgQJk4CP8nbcg8QKGUZoyP1gIVfu8,8983
+pillow-12.1.0.dist-info/RECORD,,
+pillow-12.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pillow-12.1.0.dist-info/WHEEL,sha256=8UP9x9puWI0P1V_d7K2oMTBqfeLNm21CTzZ_Ptr0NXU,101
+pillow-12.1.0.dist-info/licenses/LICENSE,sha256=km31-IinM3_UEmpDUgLt8oRzEr6BoWffkabXDPo_LtM,78078
+pillow-12.1.0.dist-info/top_level.txt,sha256=riZqrk-hyZqh5f1Z0Zwii3dKfxEsByhu9cU9IODF-NY,4
+pillow-12.1.0.dist-info/zip-safe,sha256=frcCV1k9oG9oKj3dpUqdJg1PxRT2RSN_XKdLCPjaYaY,2
diff --git a/venv/Lib/site-packages/pillow-12.1.0.dist-info/REQUESTED b/venv/Lib/site-packages/pillow-12.1.0.dist-info/REQUESTED
new file mode 100644
index 0000000..e69de29
diff --git a/venv/Lib/site-packages/pillow-12.1.0.dist-info/WHEEL b/venv/Lib/site-packages/pillow-12.1.0.dist-info/WHEEL
new file mode 100644
index 0000000..10ac2c2
--- /dev/null
+++ b/venv/Lib/site-packages/pillow-12.1.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: false
+Tag: cp312-cp312-win_amd64
+
diff --git a/venv/Lib/site-packages/pillow-12.1.0.dist-info/licenses/LICENSE b/venv/Lib/site-packages/pillow-12.1.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000..19bfa3c
--- /dev/null
+++ b/venv/Lib/site-packages/pillow-12.1.0.dist-info/licenses/LICENSE
@@ -0,0 +1,1617 @@
+The Python Imaging Library (PIL) is
+
+ Copyright © 1997-2011 by Secret Labs AB
+ Copyright © 1995-2011 by Fredrik Lundh and contributors
+
+Pillow is the friendly PIL fork. It is
+
+ Copyright © 2010 by Jeffrey A. Clark and contributors
+
+Like PIL, Pillow is licensed under the open source MIT-CMU License:
+
+By obtaining, using, and/or copying this software and/or its associated
+documentation, you agree that you have read, understood, and will comply
+with the following terms and conditions:
+
+Permission to use, copy, modify and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appears in all copies, and that
+both that copyright notice and this permission notice appear in supporting
+documentation, and that the name of Secret Labs AB or the author not be
+used in advertising or publicity pertaining to distribution of the software
+without specific, written prior permission.
+
+SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
+SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,
+INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+
+===== brotli-1.2.0 =====
+
+Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+===== freetype-2.14.1 =====
+
+FREETYPE LICENSES
+-----------------
+
+The FreeType 2 font engine is copyrighted work and cannot be used
+legally without a software license. In order to make this project
+usable to a vast majority of developers, we distribute it under two
+mutually exclusive open-source licenses.
+
+This means that *you* must choose *one* of the two licenses described
+below, then obey all its terms and conditions when using FreeType 2 in
+any of your projects or products.
+
+ - The FreeType License, found in the file `docs/FTL.TXT`, which is
+ similar to the original BSD license *with* an advertising clause
+ that forces you to explicitly cite the FreeType project in your
+ product's documentation. All details are in the license file.
+ This license is suited to products which don't use the GNU General
+ Public License.
+
+ Note that this license is compatible to the GNU General Public
+ License version 3, but not version 2.
+
+ - The GNU General Public License version 2, found in
+ `docs/GPLv2.TXT` (any later version can be used also), for
+ programs which already use the GPL. Note that the FTL is
+ incompatible with GPLv2 due to its advertisement clause.
+
+The contributed BDF and PCF drivers come with a license similar to
+that of the X Window System. It is compatible to the above two
+licenses (see files `src/bdf/README` and `src/pcf/README`). The same
+holds for the source code files `src/base/fthash.c` and
+`include/freetype/internal/fthash.h`; they were part of the BDF driver
+in earlier FreeType versions.
+
+The gzip module uses the zlib license (see `src/gzip/zlib.h`) which
+too is compatible to the above two licenses.
+
+The files `src/autofit/ft-hb-ft.c`, `src/autofit/ft-hb-decls.h`,
+`src/autofit/ft-hb-types.h`, and `src/autofit/hb-script-list.h`
+contain code taken (almost) verbatim from the HarfBuzz library, which
+uses the 'Old MIT' license compatible to the above two licenses.
+
+The MD5 checksum support (only used for debugging in development
+builds) is in the public domain.
+
+
+--- end of LICENSE.TXT ---
+ The FreeType Project LICENSE
+ ----------------------------
+
+ 2006-Jan-27
+
+ Copyright 1996-2002, 2006 by
+ David Turner, Robert Wilhelm, and Werner Lemberg
+
+
+
+Introduction
+============
+
+ The FreeType Project is distributed in several archive packages;
+ some of them may contain, in addition to the FreeType font engine,
+ various tools and contributions which rely on, or relate to, the
+ FreeType Project.
+
+ This license applies to all files found in such packages, and
+ which do not fall under their own explicit license. The license
+ affects thus the FreeType font engine, the test programs,
+ documentation and makefiles, at the very least.
+
+ This license was inspired by the BSD, Artistic, and IJG
+ (Independent JPEG Group) licenses, which all encourage inclusion
+ and use of free software in commercial and freeware products
+ alike. As a consequence, its main points are that:
+
+ o We don't promise that this software works. However, we will be
+ interested in any kind of bug reports. (`as is' distribution)
+
+ o You can use this software for whatever you want, in parts or
+ full form, without having to pay us. (`royalty-free' usage)
+
+ o You may not pretend that you wrote this software. If you use
+ it, or only parts of it, in a program, you must acknowledge
+ somewhere in your documentation that you have used the
+ FreeType code. (`credits')
+
+ We specifically permit and encourage the inclusion of this
+ software, with or without modifications, in commercial products.
+ We disclaim all warranties covering The FreeType Project and
+ assume no liability related to The FreeType Project.
+
+
+ Finally, many people asked us for a preferred form for a
+ credit/disclaimer to use in compliance with this license. We thus
+ encourage you to use the following text:
+
+ """
+ Portions of this software are copyright © The FreeType
+ Project (https://freetype.org). All rights reserved.
+ """
+
+ Please replace with the value from the FreeType version you
+ actually use.
+
+
+Legal Terms
+===========
+
+0. Definitions
+--------------
+
+ Throughout this license, the terms `package', `FreeType Project',
+ and `FreeType archive' refer to the set of files originally
+ distributed by the authors (David Turner, Robert Wilhelm, and
+ Werner Lemberg) as the `FreeType Project', be they named as alpha,
+ beta or final release.
+
+ `You' refers to the licensee, or person using the project, where
+ `using' is a generic term including compiling the project's source
+ code as well as linking it to form a `program' or `executable'.
+ This program is referred to as `a program using the FreeType
+ engine'.
+
+ This license applies to all files distributed in the original
+ FreeType Project, including all source code, binaries and
+ documentation, unless otherwise stated in the file in its
+ original, unmodified form as distributed in the original archive.
+ If you are unsure whether or not a particular file is covered by
+ this license, you must contact us to verify this.
+
+ The FreeType Project is copyright (C) 1996-2000 by David Turner,
+ Robert Wilhelm, and Werner Lemberg. All rights reserved except as
+ specified below.
+
+1. No Warranty
+--------------
+
+ THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
+ BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO
+ USE, OF THE FREETYPE PROJECT.
+
+2. Redistribution
+-----------------
+
+ This license grants a worldwide, royalty-free, perpetual and
+ irrevocable right and license to use, execute, perform, compile,
+ display, copy, create derivative works of, distribute and
+ sublicense the FreeType Project (in both source and object code
+ forms) and derivative works thereof for any purpose; and to
+ authorize others to exercise some or all of the rights granted
+ herein, subject to the following conditions:
+
+ o Redistribution of source code must retain this license file
+ (`FTL.TXT') unaltered; any additions, deletions or changes to
+ the original files must be clearly indicated in accompanying
+ documentation. The copyright notices of the unaltered,
+ original files must be preserved in all copies of source
+ files.
+
+ o Redistribution in binary form must provide a disclaimer that
+ states that the software is based in part of the work of the
+ FreeType Team, in the distribution documentation. We also
+ encourage you to put an URL to the FreeType web page in your
+ documentation, though this isn't mandatory.
+
+ These conditions apply to any software derived from or based on
+ the FreeType Project, not just the unmodified files. If you use
+ our work, you must acknowledge us. However, no fee need be paid
+ to us.
+
+3. Advertising
+--------------
+
+ Neither the FreeType authors and contributors nor you shall use
+ the name of the other for commercial, advertising, or promotional
+ purposes without specific prior written permission.
+
+ We suggest, but do not require, that you use one or more of the
+ following phrases to refer to this software in your documentation
+ or advertising materials: `FreeType Project', `FreeType Engine',
+ `FreeType library', or `FreeType Distribution'.
+
+ As you have not signed this license, you are not required to
+ accept it. However, as the FreeType Project is copyrighted
+ material, only this license, or another one contracted with the
+ authors, grants you the right to use, distribute, and modify it.
+ Therefore, by using, distributing, or modifying the FreeType
+ Project, you indicate that you understand and accept all the terms
+ of this license.
+
+4. Contacts
+-----------
+
+ There are two mailing lists related to FreeType:
+
+ o freetype@nongnu.org
+
+ Discusses general use and applications of FreeType, as well as
+ future and wanted additions to the library and distribution.
+ If you are looking for support, start in this list if you
+ haven't found anything to help you in the documentation.
+
+ o freetype-devel@nongnu.org
+
+ Discusses bugs, as well as engine internals, design issues,
+ specific licenses, porting, etc.
+
+ Our home page can be found at
+
+ https://freetype.org
+
+
+--- end of FTL.TXT ---
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ , 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
+
+===== harfbuzz-12.3.0 =====
+
+HarfBuzz is licensed under the so-called "Old MIT" license. Details follow.
+For parts of HarfBuzz that are licensed under different licenses see individual
+files names COPYING in subdirectories where applicable.
+
+Copyright © 2010-2022 Google, Inc.
+Copyright © 2015-2020 Ebrahim Byagowi
+Copyright © 2019,2020 Facebook, Inc.
+Copyright © 2012,2015 Mozilla Foundation
+Copyright © 2011 Codethink Limited
+Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies)
+Copyright © 2009 Keith Stribley
+Copyright © 2011 Martin Hosken and SIL International
+Copyright © 2007 Chris Wilson
+Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod
+Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc.
+Copyright © 1998-2005 David Turner and Werner Lemberg
+Copyright © 2016 Igalia S.L.
+Copyright © 2022 Matthias Clasen
+Copyright © 2018,2021 Khaled Hosny
+Copyright © 2018,2019,2020 Adobe, Inc
+Copyright © 2013-2015 Alexei Podtelezhnikov
+
+For full copyright notices consult the individual files in the package.
+
+
+Permission is hereby granted, without written agreement and without
+license or royalty fees, to use, copy, modify, and distribute this
+software and its documentation for any purpose, provided that the
+above copyright notice and the following two paragraphs appear in
+all copies of this software.
+
+IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
+DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
+BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
+ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
+PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+
+===== lcms2-2.17 =====
+
+MIT License
+
+Copyright (c) 2023 Marti Maria Saguer
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject
+to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+===== libavif-1.3.0 =====
+
+Copyright 2019 Joe Drago. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+
+Files: src/obu.c
+
+Copyright © 2018-2019, VideoLAN and dav1d authors
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+
+Files: third_party/iccjpeg/*
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-2013, Thomas G. Lane, Guido Vollbeding.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+
+The Unix configuration script "configure" was produced with GNU Autoconf.
+It is copyright by the Free Software Foundation but is freely distributable.
+The same holds for its supporting scripts (config.guess, config.sub,
+ltmain.sh). Another support script, install-sh, is copyright by X Consortium
+but is also freely distributable.
+
+The IJG distribution formerly included code to read and write GIF files.
+To avoid entanglement with the Unisys LZW patent, GIF reading support has
+been removed altogether, and the GIF writer has been simplified to produce
+"uncompressed GIFs". This technique does not use the LZW algorithm; the
+resulting GIF files are larger than usual, but are readable by all standard
+GIF decoders.
+
+We are required to state that
+ "The Graphics Interchange Format(c) is the Copyright property of
+ CompuServe Incorporated. GIF(sm) is a Service Mark property of
+ CompuServe Incorporated."
+
+------------------------------------------------------------------------------
+
+Files: contrib/gdk-pixbuf/*
+
+Copyright 2020 Emmanuel Gil Peyrot. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+
+Files: android_jni/gradlew*
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+------------------------------------------------------------------------------
+
+Files: third_party/libyuv/*
+
+Copyright 2011 The LibYuv Project Authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+ * Neither the name of Google nor the names of its contributors may
+ be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+===== libjpeg-turbo-3.1.3 =====
+
+LEGAL ISSUES
+============
+
+In plain English:
+
+1. We don't promise that this software works. (But if you find any bugs,
+ please let us know!)
+2. You can use this software for whatever you want. You don't have to pay us.
+3. You may not pretend that you wrote this software. If you use it in a
+ program, you must acknowledge somewhere in your documentation that
+ you've used the IJG code.
+
+In legalese:
+
+The authors make NO WARRANTY or representation, either express or implied,
+with respect to this software, its quality, accuracy, merchantability, or
+fitness for a particular purpose. This software is provided "AS IS", and you,
+its user, assume the entire risk as to its quality and accuracy.
+
+This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
+All Rights Reserved except as specified below.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+software (or portions thereof) for any purpose, without fee, subject to these
+conditions:
+(1) If any part of the source code for this software is distributed, then this
+README file must be included, with this copyright and no-warranty notice
+unaltered; and any additions, deletions, or changes to the original files
+must be clearly indicated in accompanying documentation.
+(2) If only executable code is distributed, then the accompanying
+documentation must state that "this software is based in part on the work of
+the Independent JPEG Group".
+(3) Permission for use of this software is granted only if the user accepts
+full responsibility for any undesirable consequences; the authors accept
+NO LIABILITY for damages of any kind.
+
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library. If you use our work, you ought to
+acknowledge us.
+
+Permission is NOT granted for the use of any IJG author's name or company name
+in advertising or publicity relating to this software or products derived from
+it. This software may be referred to only as "the Independent JPEG Group's
+software".
+
+We specifically permit and encourage the use of this software as the basis of
+commercial products, provided that all warranty or liability claims are
+assumed by the product vendor.
+
+libjpeg-turbo Licenses
+======================
+
+libjpeg-turbo is covered by two compatible BSD-style open source licenses:
+
+- The IJG (Independent JPEG Group) License, which is listed in
+ [README.ijg](README.ijg)
+
+ This license applies to the libjpeg API library and associated programs,
+ including any code inherited from libjpeg and any modifications to that
+ code. Note that the libjpeg-turbo SIMD source code bears the
+ [zlib License](https://opensource.org/licenses/Zlib), but in the context of
+ the overall libjpeg API library, the terms of the zlib License are subsumed
+ by the terms of the IJG License.
+
+- The Modified (3-clause) BSD License, which is listed below
+
+ This license applies to the TurboJPEG API library and associated programs, as
+ well as the build system. Note that the TurboJPEG API library wraps the
+ libjpeg API library, so in the context of the overall TurboJPEG API library,
+ both the terms of the IJG License and the terms of the Modified (3-clause)
+ BSD License apply.
+
+
+Complying with the libjpeg-turbo Licenses
+=========================================
+
+This section provides a roll-up of the libjpeg-turbo licensing terms, to the
+best of our understanding. This is not a license in and of itself. It is
+intended solely for clarification.
+
+1. If you are distributing a modified version of the libjpeg-turbo source,
+ then:
+
+ 1. You cannot alter or remove any existing copyright or license notices
+ from the source.
+
+ **Origin**
+ - Clause 1 of the IJG License
+ - Clause 1 of the Modified BSD License
+ - Clauses 1 and 3 of the zlib License
+
+ 2. You must add your own copyright notice to the header of each source
+ file you modified, so others can tell that you modified that file. (If
+ there is not an existing copyright header in that file, then you can
+ simply add a notice stating that you modified the file.)
+
+ **Origin**
+ - Clause 1 of the IJG License
+ - Clause 2 of the zlib License
+
+ 3. You must include the IJG README file, and you must not alter any of the
+ copyright or license text in that file.
+
+ **Origin**
+ - Clause 1 of the IJG License
+
+2. If you are distributing only libjpeg-turbo binaries without the source, or
+ if you are distributing an application that statically links with
+ libjpeg-turbo, then:
+
+ 1. Your product documentation must include a message stating:
+
+ This software is based in part on the work of the Independent JPEG
+ Group.
+
+ **Origin**
+ - Clause 2 of the IJG license
+
+ 2. If your binary distribution includes or uses the TurboJPEG API, then
+ your product documentation must include the text of the Modified BSD
+ License (see below.)
+
+ **Origin**
+ - Clause 2 of the Modified BSD License
+
+3. You cannot use the name of the IJG or The libjpeg-turbo Project or the
+ contributors thereof in advertising, publicity, etc.
+
+ **Origin**
+ - IJG License
+ - Clause 3 of the Modified BSD License
+
+4. The IJG and The libjpeg-turbo Project do not warrant libjpeg-turbo to be
+ free of defects, nor do we accept any liability for undesirable
+ consequences resulting from your use of the software.
+
+ **Origin**
+ - IJG License
+ - Modified BSD License
+ - zlib License
+
+
+The Modified (3-clause) BSD License
+===================================
+
+Copyright (C)2009-2025 D. R. Commander. All Rights Reserved.
+Copyright (C)2015 Viktor Szathmáry. All Rights Reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+- Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+- Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+- Neither the name of the libjpeg-turbo Project nor the names of its
+ contributors may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+
+Why Two Licenses?
+=================
+
+The zlib License could have been used instead of the Modified (3-clause) BSD
+License, and since the IJG License effectively subsumes the distribution
+conditions of the zlib License, this would have effectively placed
+libjpeg-turbo binary distributions under the IJG License. However, the IJG
+License specifically refers to the Independent JPEG Group and does not extend
+attribution and endorsement protections to other entities. Thus, it was
+desirable to choose a license that granted us the same protections for new code
+that were granted to the IJG for code derived from their software.
+
+===== libpng-1.6.53 =====
+
+COPYRIGHT NOTICE, DISCLAIMER, and LICENSE
+=========================================
+
+PNG Reference Library License version 2
+---------------------------------------
+
+ * Copyright (c) 1995-2025 The PNG Reference Library Authors.
+ * Copyright (c) 2018-2025 Cosmin Truta.
+ * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson.
+ * Copyright (c) 1996-1997 Andreas Dilger.
+ * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
+
+The software is supplied "as is", without warranty of any kind,
+express or implied, including, without limitation, the warranties
+of merchantability, fitness for a particular purpose, title, and
+non-infringement. In no event shall the Copyright owners, or
+anyone distributing the software, be liable for any damages or
+other liability, whether in contract, tort or otherwise, arising
+from, out of, or in connection with the software, or the use or
+other dealings in the software, even if advised of the possibility
+of such damage.
+
+Permission is hereby granted to use, copy, modify, and distribute
+this software, or portions hereof, for any purpose, without fee,
+subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you
+ must not claim that you wrote the original software. If you
+ use this software in a product, an acknowledgment in the product
+ documentation would be appreciated, but is not required.
+
+ 2. Altered source versions must be plainly marked as such, and must
+ not be misrepresented as being the original software.
+
+ 3. This Copyright notice may not be removed or altered from any
+ source or altered source distribution.
+
+
+PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35)
+-----------------------------------------------------------------------
+
+libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are
+Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are
+derived from libpng-1.0.6, and are distributed according to the same
+disclaimer and license as libpng-1.0.6 with the following individuals
+added to the list of Contributing Authors:
+
+ Simon-Pierre Cadieux
+ Eric S. Raymond
+ Mans Rullgard
+ Cosmin Truta
+ Gilles Vollant
+ James Yu
+ Mandar Sahastrabuddhe
+ Google Inc.
+ Vadim Barkov
+
+and with the following additions to the disclaimer:
+
+ There is no warranty against interference with your enjoyment of
+ the library or against infringement. There is no warranty that our
+ efforts or the library will fulfill any of your particular purposes
+ or needs. This library is provided with all faults, and the entire
+ risk of satisfactory quality, performance, accuracy, and effort is
+ with the user.
+
+Some files in the "contrib" directory and some configure-generated
+files that are distributed with libpng have other copyright owners, and
+are released under other open source licenses.
+
+libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
+Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
+libpng-0.96, and are distributed according to the same disclaimer and
+license as libpng-0.96, with the following individuals added to the
+list of Contributing Authors:
+
+ Tom Lane
+ Glenn Randers-Pehrson
+ Willem van Schaik
+
+libpng versions 0.89, June 1996, through 0.96, May 1997, are
+Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
+and are distributed according to the same disclaimer and license as
+libpng-0.88, with the following individuals added to the list of
+Contributing Authors:
+
+ John Bowler
+ Kevin Bracey
+ Sam Bushell
+ Magnus Holmgren
+ Greg Roelofs
+ Tom Tanner
+
+Some files in the "scripts" directory have other copyright owners,
+but are released under this license.
+
+libpng versions 0.5, May 1995, through 0.88, January 1996, are
+Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
+
+For the purposes of this copyright and license, "Contributing Authors"
+is defined as the following set of individuals:
+
+ Andreas Dilger
+ Dave Martindale
+ Guy Eric Schalnat
+ Paul Schmidt
+ Tim Wegner
+
+The PNG Reference Library is supplied "AS IS". The Contributing
+Authors and Group 42, Inc. disclaim all warranties, expressed or
+implied, including, without limitation, the warranties of
+merchantability and of fitness for any purpose. The Contributing
+Authors and Group 42, Inc. assume no liability for direct, indirect,
+incidental, special, exemplary, or consequential damages, which may
+result from the use of the PNG Reference Library, even if advised of
+the possibility of such damage.
+
+Permission is hereby granted to use, copy, modify, and distribute this
+source code, or portions hereof, for any purpose, without fee, subject
+to the following restrictions:
+
+ 1. The origin of this source code must not be misrepresented.
+
+ 2. Altered versions must be plainly marked as such and must not
+ be misrepresented as being the original source.
+
+ 3. This Copyright notice may not be removed or altered from any
+ source or altered source distribution.
+
+The Contributing Authors and Group 42, Inc. specifically permit,
+without fee, and encourage the use of this source code as a component
+to supporting the PNG file format in commercial products. If you use
+this source code in a product, acknowledgment is not required but would
+be appreciated.
+
+===== libwebp-1.6.0 =====
+
+Copyright (c) 2010, Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+ * Neither the name of Google nor the names of its contributors may
+ be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+===== openjpeg-2.5.4 =====
+
+/*
+ * The copyright in this software is being made available under the 2-clauses
+ * BSD License, included below. This software may be subject to other third
+ * party and contributor rights, including patent rights, and no such rights
+ * are granted under this license.
+ *
+ * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
+ * Copyright (c) 2002-2014, Professor Benoit Macq
+ * Copyright (c) 2003-2014, Antonin Descampe
+ * Copyright (c) 2003-2009, Francois-Olivier Devaux
+ * Copyright (c) 2005, Herve Drolon, FreeImage Team
+ * Copyright (c) 2002-2003, Yannick Verschueren
+ * Copyright (c) 2001-2003, David Janssens
+ * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
+ * Copyright (c) 2012, CS Systemes d'Information, France
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+===== tiff-4.7.1 =====
+
+# LibTIFF license
+
+Copyright © 1988-1997 Sam Leffler\
+Copyright © 1991-1997 Silicon Graphics, Inc.
+
+Permission to use, copy, modify, distribute, and sell this software and
+its documentation for any purpose is hereby granted without fee, provided
+that (i) the above copyright notices and this permission notice appear in
+all copies of the software and related documentation, and (ii) the names of
+Sam Leffler and Silicon Graphics may not be used in any advertising or
+publicity relating to the software without the specific, prior written
+permission of Sam Leffler and Silicon Graphics.
+
+THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
+EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
+WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+
+IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
+ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
+OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
+LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
+OF THIS SOFTWARE.
+
+# Lempel-Ziv & Welch Compression (tif_lzw.c) license
+The code of tif_lzw.c is derived from the compress program whose code is
+derived from software contributed to Berkeley by James A. Woods,
+derived from original work by Spencer Thomas and Joseph Orost.
+
+The original Berkeley copyright notice appears below in its entirety:
+
+Copyright (c) 1985, 1986 The Regents of the University of California.
+All rights reserved.
+
+This code is derived from software contributed to Berkeley by
+James A. Woods, derived from original work by Spencer Thomas
+and Joseph Orost.
+
+Redistribution and use in source and binary forms are permitted
+provided that the above copyright notice and this paragraph are
+duplicated in all such forms and that any documentation,
+advertising materials, and other materials related to such
+distribution and use acknowledge that the software was developed
+by the University of California, Berkeley. The name of the
+University may not be used to endorse or promote products derived
+from this software without specific prior written permission.
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+
+===== xz-5.8.2 =====
+
+
+XZ Utils Licensing
+==================
+
+ Different licenses apply to different files in this package. Here
+ is a summary of which licenses apply to which parts of this package:
+
+ - liblzma is under the BSD Zero Clause License (0BSD).
+
+ - The command line tools xz, xzdec, lzmadec, and lzmainfo are
+ under 0BSD except that, on systems that don't have a usable
+ getopt_long, GNU getopt_long is compiled and linked in from the
+ 'lib' directory. The getopt_long code is under GNU LGPLv2.1+.
+
+ - The scripts to grep, diff, and view compressed files have been
+ adapted from GNU gzip. These scripts (xzgrep, xzdiff, xzless,
+ and xzmore) are under GNU GPLv2+. The man pages of the scripts
+ are under 0BSD; they aren't based on the man pages of GNU gzip.
+
+ - Most of the XZ Utils specific documentation that is in
+ plain text files (like README, INSTALL, PACKAGERS, NEWS,
+ and ChangeLog) are under 0BSD unless stated otherwise in
+ the file itself. The files xz-file-format.txt and
+ lzma-file-format.xt are in the public domain but may
+ be distributed under the terms of 0BSD too.
+
+ - Translated messages and man pages are under 0BSD except that
+ some old translations are in the public domain.
+
+ - Test files and test code in the 'tests' directory, and
+ debugging utilities in the 'debug' directory are under
+ the BSD Zero Clause License (0BSD).
+
+ - The GNU Autotools based build system contains files that are
+ under GNU GPLv2+, GNU GPLv3+, and a few permissive licenses.
+ These files don't affect the licensing of the binaries being
+ built.
+
+ - The 'extra' directory contains files that are under various
+ free software licenses. These aren't built or installed as
+ part of XZ Utils.
+
+ The following command may be helpful in finding per-file license
+ information. It works on xz.git and on a clean file tree extracted
+ from a release tarball.
+
+ sh build-aux/license-check.sh -v
+
+ For the files under the BSD Zero Clause License (0BSD), if
+ a copyright notice is needed, the following is sufficient:
+
+ Copyright (C) The XZ Utils authors and contributors
+
+ If you copy significant amounts of 0BSD-licensed code from XZ Utils
+ into your project, acknowledging this somewhere in your software is
+ polite (especially if it is proprietary, non-free software), but
+ it is not legally required by the license terms. Here is an example
+ of a good notice to put into "about box" or into documentation:
+
+ This software includes code from XZ Utils .
+
+ The following license texts are included in the following files:
+ - COPYING.0BSD: BSD Zero Clause License
+ - COPYING.LGPLv2.1: GNU Lesser General Public License version 2.1
+ - COPYING.GPLv2: GNU General Public License version 2
+ - COPYING.GPLv3: GNU General Public License version 3
+
+ If you have questions, don't hesitate to ask for more information.
+ The contact information is in the README file.
+
+
+===== zlib-ng-2.3.2 =====
+
+(C) 1995-2024 Jean-loup Gailly and Mark Adler
+
+This software is provided 'as-is', without any express or implied
+warranty. In no event will the authors be held liable for any damages
+arising from the use of this software.
+
+Permission is granted to anyone to use this software for any purpose,
+including commercial applications, and to alter it and redistribute it
+freely, subject to the following restrictions:
+
+1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+
+2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+
+3. This notice may not be removed or altered from any source distribution.
diff --git a/venv/Lib/site-packages/pillow-12.1.0.dist-info/top_level.txt b/venv/Lib/site-packages/pillow-12.1.0.dist-info/top_level.txt
new file mode 100644
index 0000000..b338169
--- /dev/null
+++ b/venv/Lib/site-packages/pillow-12.1.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+PIL
diff --git a/venv/Lib/site-packages/pillow-12.1.0.dist-info/zip-safe b/venv/Lib/site-packages/pillow-12.1.0.dist-info/zip-safe
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/venv/Lib/site-packages/pillow-12.1.0.dist-info/zip-safe
@@ -0,0 +1 @@
+