id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
167,765
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath The provided code snippet includes necessary dependencies for implementing the `composite` function. Write a Python function `def composite(image1, image2, mask)` to solve the following problem: Create composite image by blending images using a transparency mask. :param image1: The first image. :param image2: The second image. Must have the same mode and size as the first image. :param mask: A mask image. This image can have mode "1", "L", or "RGBA", and must have the same size as the other two images. Here is the function: def composite(image1, image2, mask): """ Create composite image by blending images using a transparency mask. :param image1: The first image. :param image2: The second image. Must have the same mode and size as the first image. :param mask: A mask image. This image can have mode "1", "L", or "RGBA", and must have the same size as the other two images. """ image = image2.copy() image.paste(image1, None, mask) return image
Create composite image by blending images using a transparency mask. :param image1: The first image. :param image2: The second image. Must have the same mode and size as the first image. :param mask: A mask image. This image can have mode "1", "L", or "RGBA", and must have the same size as the other two images.
167,766
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath The provided code snippet includes necessary dependencies for implementing the `eval` function. Write a Python function `def eval(image, *args)` to solve the following problem: Applies the function (which should take one argument) to each pixel in the given image. If the image has more than one band, the same function is applied to each band. Note that the function is evaluated once for each possible pixel value, so you cannot use random components or other generators. :param image: The input image. :param function: A function object, taking one integer argument. :returns: An :py:class:`~PIL.Image.Image` object. Here is the function: def eval(image, *args): """ Applies the function (which should take one argument) to each pixel in the given image. If the image has more than one band, the same function is applied to each band. Note that the function is evaluated once for each possible pixel value, so you cannot use random components or other generators. :param image: The input image. :param function: A function object, taking one integer argument. :returns: An :py:class:`~PIL.Image.Image` object. """ return image.point(args[0])
Applies the function (which should take one argument) to each pixel in the given image. If the image has more than one band, the same function is applied to each band. Note that the function is evaluated once for each possible pixel value, so you cannot use random components or other generators. :param image: The input image. :param function: A function object, taking one integer argument. :returns: An :py:class:`~PIL.Image.Image` object.
167,767
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath ID = [] OPEN = {} The provided code snippet includes necessary dependencies for implementing the `register_open` function. Write a Python function `def register_open(id, factory, accept=None)` to solve the following problem: Register an image file plugin. This function should not be used in application code. :param id: An image format identifier. :param factory: An image file factory method. :param accept: An optional function that can be used to quickly reject images having another format. Here is the function: def register_open(id, factory, accept=None): """ Register an image file plugin. This function should not be used in application code. :param id: An image format identifier. :param factory: An image file factory method. :param accept: An optional function that can be used to quickly reject images having another format. """ id = id.upper() ID.append(id) OPEN[id] = factory, accept
Register an image file plugin. This function should not be used in application code. :param id: An image format identifier. :param factory: An image file factory method. :param accept: An optional function that can be used to quickly reject images having another format.
167,768
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath MIME = {} The provided code snippet includes necessary dependencies for implementing the `register_mime` function. Write a Python function `def register_mime(id, mimetype)` to solve the following problem: Registers an image MIME type. This function should not be used in application code. :param id: An image format identifier. :param mimetype: The image MIME type for this format. Here is the function: def register_mime(id, mimetype): """ Registers an image MIME type. This function should not be used in application code. :param id: An image format identifier. :param mimetype: The image MIME type for this format. """ MIME[id.upper()] = mimetype
Registers an image MIME type. This function should not be used in application code. :param id: An image format identifier. :param mimetype: The image MIME type for this format.
167,769
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath SAVE = {} The provided code snippet includes necessary dependencies for implementing the `register_save` function. Write a Python function `def register_save(id, driver)` to solve the following problem: Registers an image save function. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format. Here is the function: def register_save(id, driver): """ Registers an image save function. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format. """ SAVE[id.upper()] = driver
Registers an image save function. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format.
167,770
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath SAVE_ALL = {} The provided code snippet includes necessary dependencies for implementing the `register_save_all` function. Write a Python function `def register_save_all(id, driver)` to solve the following problem: Registers an image function to save all the frames of a multiframe format. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format. Here is the function: def register_save_all(id, driver): """ Registers an image function to save all the frames of a multiframe format. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format. """ SAVE_ALL[id.upper()] = driver
Registers an image function to save all the frames of a multiframe format. This function should not be used in application code. :param id: An image format identifier. :param driver: A function to save images in this format.
167,771
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath def register_extension(id, extension): """ Registers an image extension. This function should not be used in application code. :param id: An image format identifier. :param extension: An extension used for this format. """ EXTENSION[extension.lower()] = id.upper() The provided code snippet includes necessary dependencies for implementing the `register_extensions` function. Write a Python function `def register_extensions(id, extensions)` to solve the following problem: Registers image extensions. This function should not be used in application code. :param id: An image format identifier. :param extensions: A list of extensions used for this format. Here is the function: def register_extensions(id, extensions): """ Registers image extensions. This function should not be used in application code. :param id: An image format identifier. :param extensions: A list of extensions used for this format. """ for extension in extensions: register_extension(id, extension)
Registers image extensions. This function should not be used in application code. :param id: An image format identifier. :param extensions: A list of extensions used for this format.
167,772
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath EXTENSION = {} def init(): """ Explicitly initializes the Python Imaging Library. This function loads all available file format drivers. """ global _initialized if _initialized >= 2: return 0 for plugin in _plugins: try: logger.debug("Importing %s", plugin) __import__(f"PIL.{plugin}", globals(), locals(), []) except ImportError as e: logger.debug("Image: failed to import %s: %s", plugin, e) if OPEN or SAVE: _initialized = 2 return 1 The provided code snippet includes necessary dependencies for implementing the `registered_extensions` function. Write a Python function `def registered_extensions()` to solve the following problem: Returns a dictionary containing all file extensions belonging to registered plugins Here is the function: def registered_extensions(): """ Returns a dictionary containing all file extensions belonging to registered plugins """ if not EXTENSION: init() return EXTENSION
Returns a dictionary containing all file extensions belonging to registered plugins
167,773
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath DECODERS = {} The provided code snippet includes necessary dependencies for implementing the `register_decoder` function. Write a Python function `def register_decoder(name, decoder)` to solve the following problem: Registers an image decoder. This function should not be used in application code. :param name: The name of the decoder :param decoder: A callable(mode, args) that returns an ImageFile.PyDecoder object .. versionadded:: 4.1.0 Here is the function: def register_decoder(name, decoder): """ Registers an image decoder. This function should not be used in application code. :param name: The name of the decoder :param decoder: A callable(mode, args) that returns an ImageFile.PyDecoder object .. versionadded:: 4.1.0 """ DECODERS[name] = decoder
Registers an image decoder. This function should not be used in application code. :param name: The name of the decoder :param decoder: A callable(mode, args) that returns an ImageFile.PyDecoder object .. versionadded:: 4.1.0
167,774
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath ENCODERS = {} The provided code snippet includes necessary dependencies for implementing the `register_encoder` function. Write a Python function `def register_encoder(name, encoder)` to solve the following problem: Registers an image encoder. This function should not be used in application code. :param name: The name of the encoder :param encoder: A callable(mode, args) that returns an ImageFile.PyEncoder object .. versionadded:: 4.1.0 Here is the function: def register_encoder(name, encoder): """ Registers an image encoder. This function should not be used in application code. :param name: The name of the encoder :param encoder: A callable(mode, args) that returns an ImageFile.PyEncoder object .. versionadded:: 4.1.0 """ ENCODERS[name] = encoder
Registers an image encoder. This function should not be used in application code. :param name: The name of the encoder :param encoder: A callable(mode, args) that returns an ImageFile.PyEncoder object .. versionadded:: 4.1.0
167,775
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath def _show(image, **options): from . import ImageShow ImageShow.show(image, **options)
null
167,776
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None def close(self): """ 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: if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = deferred_error(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.readonly == other.readonly and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is :data:`NONE`, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA": # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and palette != ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size. """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): if self._exif is None: self._exif = Exif() exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation="([0-9])"', xmp_tags) if match: self._exif[0x0112] = int(match[1]) return self._exif def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError("cannot determine region size; use 4-item box") box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode") return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: raise ValueError("illegal image mode") from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[oldPosition * 3 : oldPosition * 3 + 3] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette("RGB", palette=mapping_palette * 3) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = NEAREST if self.mode in ["LA", "RGBA"] and resample != NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else ROTATE_270) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif isPath(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and isPath(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) finally: # do what we can to clean up if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: raise ValueError(f'The image has no channel "{channel}"') from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: raise ValueError("missing method data") im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == MESH: # list of quads for box, quad in data: im.__transformer(box, self, QUAD, quad, resample, fillcolor is None) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer(self, box, image, method, data, resample=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `effect_mandelbrot` function. Write a Python function `def effect_mandelbrot(size, extent, quality)` to solve the following problem: Generate a Mandelbrot set covering the given extent. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param extent: The extent to cover, as a 4-tuple: (x0, y0, x1, y2). :param quality: Quality. Here is the function: def effect_mandelbrot(size, extent, quality): """ Generate a Mandelbrot set covering the given extent. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param extent: The extent to cover, as a 4-tuple: (x0, y0, x1, y2). :param quality: Quality. """ return Image()._new(core.effect_mandelbrot(size, extent, quality))
Generate a Mandelbrot set covering the given extent. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param extent: The extent to cover, as a 4-tuple: (x0, y0, x1, y2). :param quality: Quality.
167,777
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None def close(self): """ 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: if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = deferred_error(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.readonly == other.readonly and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is :data:`NONE`, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA": # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and palette != ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size. """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): if self._exif is None: self._exif = Exif() exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation="([0-9])"', xmp_tags) if match: self._exif[0x0112] = int(match[1]) return self._exif def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError("cannot determine region size; use 4-item box") box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode") return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: raise ValueError("illegal image mode") from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[oldPosition * 3 : oldPosition * 3 + 3] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette("RGB", palette=mapping_palette * 3) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = NEAREST if self.mode in ["LA", "RGBA"] and resample != NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else ROTATE_270) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif isPath(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and isPath(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) finally: # do what we can to clean up if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: raise ValueError(f'The image has no channel "{channel}"') from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: raise ValueError("missing method data") im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == MESH: # list of quads for box, quad in data: im.__transformer(box, self, QUAD, quad, resample, fillcolor is None) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer(self, box, image, method, data, resample=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `effect_noise` function. Write a Python function `def effect_noise(size, sigma)` to solve the following problem: Generate Gaussian noise centered around 128. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param sigma: Standard deviation of noise. Here is the function: def effect_noise(size, sigma): """ Generate Gaussian noise centered around 128. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param sigma: Standard deviation of noise. """ return Image()._new(core.effect_noise(size, sigma))
Generate Gaussian noise centered around 128. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param sigma: Standard deviation of noise.
167,778
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None def close(self): """ 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: if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = deferred_error(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.readonly == other.readonly and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is :data:`NONE`, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA": # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and palette != ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size. """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): if self._exif is None: self._exif = Exif() exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation="([0-9])"', xmp_tags) if match: self._exif[0x0112] = int(match[1]) return self._exif def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError("cannot determine region size; use 4-item box") box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode") return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: raise ValueError("illegal image mode") from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[oldPosition * 3 : oldPosition * 3 + 3] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette("RGB", palette=mapping_palette * 3) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = NEAREST if self.mode in ["LA", "RGBA"] and resample != NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else ROTATE_270) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif isPath(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and isPath(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) finally: # do what we can to clean up if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: raise ValueError(f'The image has no channel "{channel}"') from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: raise ValueError("missing method data") im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == MESH: # list of quads for box, quad in data: im.__transformer(box, self, QUAD, quad, resample, fillcolor is None) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer(self, box, image, method, data, resample=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `linear_gradient` function. Write a Python function `def linear_gradient(mode)` to solve the following problem: Generate 256x256 linear gradient from black to white, top to bottom. :param mode: Input mode. Here is the function: def linear_gradient(mode): """ Generate 256x256 linear gradient from black to white, top to bottom. :param mode: Input mode. """ return Image()._new(core.linear_gradient(mode))
Generate 256x256 linear gradient from black to white, top to bottom. :param mode: Input mode.
167,779
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None def close(self): """ 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: if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = deferred_error(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.readonly == other.readonly and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is :data:`NONE`, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA": # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and palette != ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size. """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): if self._exif is None: self._exif = Exif() exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation="([0-9])"', xmp_tags) if match: self._exif[0x0112] = int(match[1]) return self._exif def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError("cannot determine region size; use 4-item box") box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode") return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: raise ValueError("illegal image mode") from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[oldPosition * 3 : oldPosition * 3 + 3] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette("RGB", palette=mapping_palette * 3) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = NEAREST if self.mode in ["LA", "RGBA"] and resample != NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else ROTATE_270) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif isPath(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and isPath(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) finally: # do what we can to clean up if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: raise ValueError(f'The image has no channel "{channel}"') from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: raise ValueError("missing method data") im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == MESH: # list of quads for box, quad in data: im.__transformer(box, self, QUAD, quad, resample, fillcolor is None) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer(self, box, image, method, data, resample=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `radial_gradient` function. Write a Python function `def radial_gradient(mode)` to solve the following problem: Generate 256x256 radial gradient from black to white, centre to edge. :param mode: Input mode. Here is the function: def radial_gradient(mode): """ Generate 256x256 radial gradient from black to white, centre to edge. :param mode: Input mode. """ return Image()._new(core.radial_gradient(mode))
Generate 256x256 radial gradient from black to white, centre to edge. :param mode: Input mode.
167,780
import atexit import builtins import io import logging import math import numbers import os import re import struct import sys import tempfile import warnings from collections.abc import Callable, MutableMapping from pathlib import Path from . import ImageMode, TiffTags, UnidentifiedImageError, __version__, _plugins from ._binary import i32le from ._util import deferred_error, isPath def _apply_env_variables(env=None): if env is None: env = os.environ for var_name, setter in [ ("PILLOW_ALIGNMENT", core.set_alignment), ("PILLOW_BLOCK_SIZE", core.set_block_size), ("PILLOW_BLOCKS_MAX", core.set_blocks_max), ]: if var_name not in env: continue var = env[var_name].lower() units = 1 for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]: if var.endswith(postfix): units = mul var = var[: -len(postfix)] try: var = int(var) * units except ValueError: warnings.warn(f"{var_name} is not int") continue try: setter(var) except ValueError as e: warnings.warn(f"{var_name}: {e}")
null
167,781
import olefile from . import Image, ImageFile from ._binary import i32le as i32 def _accept(prefix): return prefix[:8] == olefile.MAGIC
null
167,782
import collections import os import sys import warnings import PIL from . import Image def get_supported_modules(): """ :returns: A list of all supported modules. """ return [f for f in modules if check_module(f)] def get_supported_codecs(): """ :returns: A list of all supported codecs. """ return [f for f in codecs if check_codec(f)] def get_supported_features(): """ :returns: A list of all supported features. """ return [f for f in features if check_feature(f)] The provided code snippet includes necessary dependencies for implementing the `get_supported` function. Write a Python function `def get_supported()` to solve the following problem: :returns: A list of all supported modules, features, and codecs. Here is the function: def get_supported(): """ :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
:returns: A list of all supported modules, features, and codecs.
167,783
import collections import os import sys import warnings import PIL from . import Image features = { "webp_anim": ("PIL._webp", "HAVE_WEBPANIM", None), "webp_mux": ("PIL._webp", "HAVE_WEBPMUX", None), "transp_webp": ("PIL._webp", "HAVE_TRANSPARENCY", 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"), "libimagequant": ("PIL._imaging", "HAVE_LIBIMAGEQUANT", "imagequant_version"), "xcb": ("PIL._imaging", "HAVE_XCB", None), } def check_feature(feature): """ 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: raise ValueError(f"Unknown feature {feature}") module, flag, ver = features[feature] try: imported_module = __import__(module, fromlist=["PIL"]) return getattr(imported_module, flag) except ImportError: return None def version_feature(feature): """ :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 check(feature): """ :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): """ :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 class Image: """ This class represents an image object. To create :py:class:`~PIL.Image.Image` objects, use the appropriate factory functions. There's hardly ever any reason to call the Image constructor directly. * :py:func:`~PIL.Image.open` * :py:func:`~PIL.Image.new` * :py:func:`~PIL.Image.frombytes` """ format = None format_description = None _close_exclusive_fp_after_loading = True def __init__(self): # FIXME: take "new" parameters / other image? # FIXME: turn mode and size into delegating properties? self.im = None self.mode = "" self._size = (0, 0) self.palette = None self.info = {} self._category = 0 self.readonly = 0 self.pyaccess = None self._exif = None def __getattr__(self, name): if name == "category": warnings.warn( "Image categories are deprecated and will be removed in Pillow 10 " "(2023-07-01). Use is_animated instead.", DeprecationWarning, stacklevel=2, ) return self._category raise AttributeError(name) def width(self): return self.size[0] def height(self): return self.size[1] def size(self): return self._size def _new(self, im): new = Image() new.im = im new.mode = im.mode new._size = im.size if im.mode in ("P", "PA"): if self.palette: new.palette = self.palette.copy() else: from . import ImagePalette new.palette = ImagePalette.ImagePalette() new.info = self.info.copy() return new # Context manager support def __enter__(self): return self def __exit__(self, *args): if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False): if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None def close(self): """ 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: if hasattr(self, "_close__fp"): self._close__fp() if self.fp: self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg) if getattr(self, "map", None): self.map = None # Instead of simply setting to None, we're setting up a # deferred error that will better explain that the core image # object is gone. self.im = deferred_error(ValueError("Operation on closed image")) def _copy(self): self.load() self.im = self.im.copy() self.pyaccess = None self.readonly = 0 def _ensure_mutable(self): if self.readonly: self._copy() else: self.load() def _dump(self, file=None, format=None, **options): suffix = "" if format: suffix = "." + format if not file: f, filename = tempfile.mkstemp(suffix) os.close(f) else: filename = file if not filename.endswith(suffix): filename = filename + suffix self.load() if not format or format == "PPM": self.im.save_ppm(filename) else: self.save(filename, format, **options) return filename def __eq__(self, other): return ( self.__class__ is other.__class__ and self.mode == other.mode and self.size == other.size and self.info == other.info and self._category == other._category and self.readonly == other.readonly and self.getpalette() == other.getpalette() and self.tobytes() == other.tobytes() ) def __repr__(self): return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % ( self.__class__.__module__, self.__class__.__name__, self.mode, self.size[0], self.size[1], id(self), ) def _repr_png_(self): """iPython display hook support :returns: png version of the image as bytes """ b = io.BytesIO() try: self.save(b, "PNG") except Exception as e: raise ValueError("Could not save to PNG for display") from e return b.getvalue() class _ArrayData: def __init__(self, new): self.__array_interface__ = new def __array__(self, dtype=None): # numpy array interface support import numpy as np new = {} shape, typestr = _conv_type_shape(self) new["shape"] = shape new["typestr"] = typestr new["version"] = 3 if self.mode == "1": # Binary images need to be extended from bits to bytes # See: https://github.com/python-pillow/Pillow/issues/350 new["data"] = self.tobytes("raw", "L") else: new["data"] = self.tobytes() return np.array(self._ArrayData(new), dtype) def __getstate__(self): return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()] def __setstate__(self, state): Image.__init__(self) self.tile = [] info, mode, size, palette, data = state self.info = info self.mode = mode self._size = size self.im = core.new(mode, size) if mode in ("L", "LA", "P", "PA") and palette: self.putpalette(palette) self.frombytes(data) def tobytes(self, encoder_name="raw", *args): """ Return image as a bytes object. .. warning:: This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use :meth:`~.save`, with a BytesIO parameter for in-memory data. :param encoder_name: What encoder to use. The default is to use the standard "raw" encoder. :param args: Extra arguments to the encoder. :returns: A :py:class:`bytes` object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] if encoder_name == "raw" and args == (): args = self.mode self.load() # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im) bufsize = max(65536, self.size[0] * 4) # see RawEncode.c data = [] while True: l, s, d = e.encode(bufsize) data.append(d) if s: break if s < 0: raise RuntimeError(f"encoder error {s} in tobytes") return b"".join(data) def tobitmap(self, name="image"): """ Returns the image converted to an X11 bitmap. .. note:: This method only works for mode "1" images. :param name: The name prefix to use for the bitmap variables. :returns: A string containing an X11 bitmap. :raises ValueError: If the mode is not "1" """ self.load() if self.mode != "1": raise ValueError("not a bitmap") data = self.tobytes("xbm") return b"".join( [ f"#define {name}_width {self.size[0]}\n".encode("ascii"), f"#define {name}_height {self.size[1]}\n".encode("ascii"), f"static char {name}_bits[] = {{\n".encode("ascii"), data, b"};", ] ) def frombytes(self, data, decoder_name="raw", *args): """ Loads this image with pixel data from a bytes object. This method is similar to the :py:func:`~PIL.Image.frombytes` function, but loads data into this image instead of creating a new image object. """ # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] # default format if decoder_name == "raw" and args == (): args = self.mode # unpack data d = _getdecoder(self.mode, decoder_name, args) d.setimage(self.im) s = d.decode(data) if s[0] >= 0: raise ValueError("not enough image data") if s[1] != 0: raise ValueError("cannot decode image data") def load(self): """ Allocates storage for the image and loads the pixel data. In normal cases, you don't need to call this method, since the Image class automatically loads an opened image when it is accessed for the first time. If the file associated with the image was opened by Pillow, then this method will close it. The exception to this is if the image has multiple frames, in which case the file will be left open for seek operations. See :ref:`file-handling` for more information. :returns: An image access object. :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess` """ if self.im and self.palette and self.palette.dirty: # realize palette mode, arr = self.palette.getdata() if mode == "RGBA": mode = "RGB" self.info["transparency"] = arr[3::4] arr = bytes( value for (index, value) in enumerate(arr) if index % 4 != 3 ) palette_length = self.im.putpalette(mode, arr) self.palette.dirty = 0 self.palette.rawmode = None if "transparency" in self.info and mode in ("LA", "PA"): if isinstance(self.info["transparency"], int): self.im.putpalettealpha(self.info["transparency"], 0) else: self.im.putpalettealphas(self.info["transparency"]) self.palette.mode = "RGBA" else: self.palette.mode = "RGB" self.palette.palette = self.im.getpalette()[: palette_length * 3] if self.im: if cffi and USE_CFFI_ACCESS: if self.pyaccess: return self.pyaccess from . import PyAccess self.pyaccess = PyAccess.new(self, self.readonly) if self.pyaccess: return self.pyaccess return self.im.pixel_access(self.readonly) def verify(self): """ Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file. """ pass def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256): """ Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. The current version supports all possible conversions between "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L" and "RGB". When translating a color image to greyscale (mode "L"), the library uses the ITU-R 601-2 luma transform:: L = R * 299/1000 + G * 587/1000 + B * 114/1000 The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels. If dither is :data:`NONE`, all values larger than 127 are set to 255 (white), all other values to 0 (black). To use other thresholds, use the :py:meth:`~PIL.Image.Image.point` method. When converting from "RGBA" to "P" without a ``matrix`` argument, this passes the operation to :py:meth:`~PIL.Image.Image.quantize`, and ``dither`` and ``palette`` are ignored. :param mode: The requested mode. See: :ref:`concept-modes`. :param matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Note that this is not used when ``matrix`` is supplied. :param palette: Palette to use when converting from mode "RGB" to "P". Available palettes are :data:`WEB` or :data:`ADAPTIVE`. :param colors: Number of colors to use for the :data:`ADAPTIVE` palette. Defaults to 256. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() has_transparency = self.info.get("transparency") is not None if not mode and self.mode == "P": # determine default mode if self.palette: mode = self.palette.mode else: mode = "RGB" if mode == "RGB" and has_transparency: mode = "RGBA" if not mode or (mode == self.mode and not matrix): return self.copy() if matrix: # matrix conversion if mode not in ("L", "RGB"): raise ValueError("illegal conversion") im = self.im.convert_matrix(mode, matrix) new = self._new(im) if has_transparency and self.im.bands == 3: transparency = new.info["transparency"] def convert_transparency(m, v): v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5 return max(0, min(255, int(v))) if mode == "L": transparency = convert_transparency(matrix, transparency) elif len(mode) == 3: transparency = tuple( convert_transparency(matrix[i * 4 : i * 4 + 4], transparency) for i in range(0, len(transparency)) ) new.info["transparency"] = transparency return new if mode == "P" and self.mode == "RGBA": return self.quantize(colors) trns = None delete_trns = False # transparency handling if has_transparency: if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA": # Use transparent conversion to promote from transparent # color to an alpha channel. new_im = self._new( self.im.convert_transparent(mode, self.info["transparency"]) ) del new_im.info["transparency"] return new_im elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"): t = self.info["transparency"] if isinstance(t, bytes): # Dragons. This can't be represented by a single color warnings.warn( "Palette images with Transparency expressed in bytes should be " "converted to RGBA images" ) delete_trns = True else: # get the new transparency color. # use existing conversions trns_im = Image()._new(core.new(self.mode, (1, 1))) if self.mode == "P": trns_im.putpalette(self.palette) if isinstance(t, tuple): err = "Couldn't allocate a palette color for transparency" try: t = trns_im.palette.getcolor(t, self) except ValueError as e: if str(e) == "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency t = None else: raise ValueError(err) from e if t is None: trns = None else: trns_im.putpixel((0, 0), t) if mode in ("L", "RGB"): trns_im = trns_im.convert(mode) else: # can't just retrieve the palette number, got to do it # after quantization. trns_im = trns_im.convert("RGB") trns = trns_im.getpixel((0, 0)) elif self.mode == "P" and mode in ("LA", "PA", "RGBA"): t = self.info["transparency"] delete_trns = True if isinstance(t, bytes): self.im.putpalettealphas(t) elif isinstance(t, int): self.im.putpalettealpha(t, 0) else: raise ValueError("Transparency for P mode should be bytes or int") if mode == "P" and palette == ADAPTIVE: im = self.im.quantize(colors) new = self._new(im) from . import ImagePalette new.palette = ImagePalette.ImagePalette("RGB", new.im.getpalette("RGB")) if delete_trns: # This could possibly happen if we requantize to fewer colors. # The transparency would be totally off in that case. del new.info["transparency"] if trns is not None: try: new.info["transparency"] = new.palette.getcolor(trns, new) except Exception: # if we can't make a transparent color, don't leave the old # transparency hanging around to mess us up. del new.info["transparency"] warnings.warn("Couldn't allocate palette entry for transparency") return new # colorspace conversion if dither is None: dither = FLOYDSTEINBERG try: im = self.im.convert(mode, dither) except ValueError: try: # normalize source image and try again im = self.im.convert(getmodebase(self.mode)) im = im.convert(mode, dither) except KeyError as e: raise ValueError("illegal conversion") from e new_im = self._new(im) if mode == "P" and palette != ADAPTIVE: from . import ImagePalette new_im.palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3) if delete_trns: # crash fail if we leave a bytes transparency in an rgb/l mode. del new_im.info["transparency"] if trns is not None: if new_im.mode == "P": try: new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im) except ValueError as e: del new_im.info["transparency"] if str(e) != "cannot allocate more than 256 colors": # If all 256 colors are in use, # then there is no need for transparency warnings.warn( "Couldn't allocate palette entry for transparency" ) else: new_im.info["transparency"] = trns return new_im def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1): """ Convert the image to 'P' mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: :data:`MEDIANCUT` (median cut), :data:`MAXCOVERAGE` (maximum coverage), :data:`FASTOCTREE` (fast octree), :data:`LIBIMAGEQUANT` (libimagequant; check support using :py:func:`PIL.features.check_feature` with ``feature="libimagequant"``). By default, :data:`MEDIANCUT` will be used. The exception to this is RGBA images. :data:`MEDIANCUT` and :data:`MAXCOVERAGE` do not support RGBA images, so :data:`FASTOCTREE` is used by default instead. :param kmeans: Integer :param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`. :param dither: Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default). Default: 1 (legacy setting) :returns: A new image """ self.load() if method is None: # defaults: method = MEDIANCUT if self.mode == "RGBA": method = FASTOCTREE if self.mode == "RGBA" and method not in (FASTOCTREE, LIBIMAGEQUANT): # Caller specified an invalid mode. raise ValueError( "Fast Octree (method == 2) and libimagequant (method == 3) " "are the only valid methods for quantizing RGBA images" ) if palette: # use palette from reference image palette.load() if palette.mode != "P": raise ValueError("bad mode for palette image") if self.mode != "RGB" and self.mode != "L": raise ValueError( "only RGB or L mode images can be quantized to a palette" ) im = self.im.convert("P", dither, palette.im) new_im = self._new(im) new_im.palette = palette.palette.copy() return new_im im = self._new(self.im.quantize(colors, method, kmeans)) from . import ImagePalette mode = im.im.getpalettemode() palette = im.im.getpalette(mode, mode)[: colors * len(mode)] im.palette = ImagePalette.ImagePalette(mode, palette) return im def copy(self): """ Copies this image. Use this method if you wish to paste things into an image, but still retain the original. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() return self._new(self.im.copy()) __copy__ = copy def crop(self, box=None): """ Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. Note: Prior to Pillow 3.4.0, this was a lazy operation. :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :rtype: :py:class:`~PIL.Image.Image` :returns: An :py:class:`~PIL.Image.Image` object. """ if box is None: return self.copy() self.load() return self._new(self._crop(self.im, box)) def _crop(self, im, box): """ Returns a rectangular region from the core image object im. This is equivalent to calling im.crop((x0, y0, x1, y1)), but includes additional sanity checks. :param im: a core image object :param box: The crop rectangle, as a (left, upper, right, lower)-tuple. :returns: A core image object. """ x0, y0, x1, y1 = map(int, map(round, box)) absolute_values = (abs(x1 - x0), abs(y1 - y0)) _decompression_bomb_check(absolute_values) return im.crop((x0, y0, x1, y1)) def draft(self, mode, size): """ Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a color JPEG to greyscale while loading it. If any changes are made, returns a tuple with the chosen ``mode`` and ``box`` with coordinates of the original image within the altered one. Note that this method modifies the :py:class:`~PIL.Image.Image` object in place. If the image has already been loaded, this method has no effect. Note: This method is not implemented for most images. It is currently implemented only for JPEG and MPO images. :param mode: The requested mode. :param size: The requested size. """ pass def _expand(self, xmargin, ymargin=None): if ymargin is None: ymargin = xmargin self.load() return self._new(self.im.expand(xmargin, ymargin, 0)) def filter(self, filter): """ Filters this image using the given filter. For a list of available filters, see the :py:mod:`~PIL.ImageFilter` module. :param filter: Filter kernel. :returns: An :py:class:`~PIL.Image.Image` object.""" from . import ImageFilter self.load() if isinstance(filter, Callable): filter = filter() if not hasattr(filter, "filter"): raise TypeError( "filter argument should be ImageFilter.Filter instance or class" ) multiband = isinstance(filter, ImageFilter.MultibandFilter) if self.im.bands == 1 or multiband: return self._new(filter.filter(self.im)) ims = [] for c in range(self.im.bands): ims.append(self._new(filter.filter(self.im.getband(c)))) return merge(self.mode, ims) def getbands(self): """ Returns a tuple containing the name of each band in this image. For example, ``getbands`` on an RGB image returns ("R", "G", "B"). :returns: A tuple containing band names. :rtype: tuple """ return ImageMode.getmode(self.mode).bands def getbbox(self): """ Calculates the bounding box of the non-zero regions in the image. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this method returns None. """ self.load() return self.im.getbbox() def getcolors(self, maxcolors=256): """ Returns a list of colors used in this image. The colors will be in the image's mode. For example, an RGB image will return a tuple of (red, green, blue) color values, and a P image will return the index of the color in the palette. :param maxcolors: Maximum number of colors. If this number is exceeded, this method returns None. The default limit is 256 colors. :returns: An unsorted list of (count, pixel) values. """ self.load() if self.mode in ("1", "L", "P"): h = self.im.histogram() out = [] for i in range(256): if h[i]: out.append((h[i], i)) if len(out) > maxcolors: return None return out return self.im.getcolors(maxcolors) def getdata(self, band=None): """ Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use ``list(im.getdata())``. :param band: What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the "R" band from an "RGB" image). :returns: A sequence-like object. """ self.load() if band is not None: return self.im.getband(band) return self.im # could be abused def getextrema(self): """ Gets the the minimum and maximum pixel values for each band in the image. :returns: For a single-band image, a 2-tuple containing the minimum and maximum pixel value. For a multi-band image, a tuple containing one 2-tuple for each band. """ self.load() if self.im.bands > 1: extrema = [] for i in range(self.im.bands): extrema.append(self.im.getband(i).getextrema()) return tuple(extrema) return self.im.getextrema() def _getxmp(self, xmp_tags): def get_name(tag): return tag.split("}")[1] def get_value(element): value = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} else: root = ElementTree.fromstring(xmp_tags) return {get_name(root.tag): get_value(root)} def getexif(self): if self._exif is None: self._exif = Exif() exif_info = self.info.get("exif") if exif_info is None: if "Raw profile type exif" in self.info: exif_info = bytes.fromhex( "".join(self.info["Raw profile type exif"].split("\n")[3:]) ) elif hasattr(self, "tag_v2"): self._exif.endian = self.tag_v2._endian self._exif.load_from_fp(self.fp, self.tag_v2._offset) if exif_info is not None: self._exif.load(exif_info) # XMP tags if 0x0112 not in self._exif: xmp_tags = self.info.get("XML:com.adobe.xmp") if xmp_tags: match = re.search(r'tiff:Orientation="([0-9])"', xmp_tags) if match: self._exif[0x0112] = int(match[1]) return self._exif def getim(self): """ Returns a capsule that points to the internal image memory. :returns: A capsule object. """ self.load() return self.im.ptr def getpalette(self): """ Returns the image palette as a list. :returns: A list of color values [r, g, b, ...], or None if the image has no palette. """ self.load() try: return list(self.im.getpalette()) except ValueError: return None # no palette def getpixel(self, xy): """ Returns the pixel value at a given position. :param xy: The coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. """ self.load() if self.pyaccess: return self.pyaccess.getpixel(xy) return self.im.getpixel(xy) def getprojection(self): """ Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. """ self.load() x, y = self.im.getprojection() return list(x), list(y) def histogram(self, mask=None, extrema=None): """ Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an "RGB" image contains 768 values). A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A list containing pixel counts. """ self.load() if mask: mask.load() return self.im.histogram((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.histogram(extrema) return self.im.histogram() def entropy(self, mask=None, extrema=None): """ Calculates and returns the entropy for the image. A bilevel image (mode "1") is treated as a greyscale ("L") image by this method. If a mask is provided, the method employs the histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). :param mask: An optional mask. :param extrema: An optional tuple of manually-specified extrema. :returns: A float value representing the image entropy """ self.load() if mask: mask.load() return self.im.entropy((0, 0), mask.im) if self.mode in ("I", "F"): if extrema is None: extrema = self.getextrema() return self.im.entropy(extrema) return self.im.entropy() def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError("cannot determine region size; use 4-item box") box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box) def alpha_composite(self, im, dest=(0, 0), source=(0, 0)): """'In-place' analog of Image.alpha_composite. Composites an image onto this image. :param im: image to composite over this one :param dest: Optional 2 tuple (left, top) specifying the upper left corner in this (destination) image. :param source: Optional 2 (left, top) tuple for the upper left corner in the overlay source image, or 4 tuple (left, top, right, bottom) for the bounds of the source rectangle Performance Note: Not currently implemented in-place in the core layer. """ if not isinstance(source, (list, tuple)): raise ValueError("Source must be a tuple") if not isinstance(dest, (list, tuple)): raise ValueError("Destination must be a tuple") if not len(source) in (2, 4): raise ValueError("Source must be a 2 or 4-tuple") if not len(dest) == 2: raise ValueError("Destination must be a 2-tuple") if min(source) < 0: raise ValueError("Source must be non-negative") if len(source) == 2: source = source + im.size # over image, crop if it's not the whole thing. if source == (0, 0) + im.size: overlay = im else: overlay = im.crop(source) # target for the paste box = dest + (dest[0] + overlay.width, dest[1] + overlay.height) # destination image. don't copy if we're using the whole image. if box == (0, 0) + self.size: background = self else: background = self.crop(box) result = alpha_composite(background, overlay) self.paste(result, box) def point(self, lut, mode=None): """ Maps this image through a lookup table or function. :param lut: A lookup table, containing 256 (or 65536 if self.mode=="I" and mode == "L") values per band in the image. A function can be used instead, it should take a single argument. The function is called once for each possible pixel value, and the resulting table is applied to all bands of the image. It may also be an :py:class:`~PIL.Image.ImagePointHandler` object:: class Example(Image.ImagePointHandler): def point(self, data): # Return result :param mode: Output mode (default is same as input). In the current version, this can only be used if the source image has mode "L" or "P", and the output has mode "1" or the source image mode is "I" and the output mode is "L". :returns: An :py:class:`~PIL.Image.Image` object. """ self.load() if isinstance(lut, ImagePointHandler): return lut.point(self) if callable(lut): # if it isn't a list, it should be a function if self.mode in ("I", "I;16", "F"): # check if the function can be used with point_transform # UNDONE wiredfool -- I think this prevents us from ever doing # a gamma function point transform on > 8bit images. scale, offset = _getscaleoffset(lut) return self._new(self.im.point_transform(scale, offset)) # for other modes, convert the function to a table lut = [lut(i) for i in range(256)] * self.im.bands if self.mode == "F": # FIXME: _imaging returns a confusing error message for this case raise ValueError("point operation not supported for this mode") return self._new(self.im.point(lut, mode)) def putalpha(self, alpha): """ Adds or replaces the alpha layer in this image. If the image does not have an alpha layer, it's converted to "LA" or "RGBA". The new layer must be either "L" or "1". :param alpha: The new alpha layer. This can either be an "L" or "1" image having the same size as this image, or an integer or other color value. """ self._ensure_mutable() if self.mode not in ("LA", "PA", "RGBA"): # attempt to promote self to a matching alpha mode try: mode = getmodebase(self.mode) + "A" try: self.im.setmode(mode) except (AttributeError, ValueError) as e: # do things the hard way im = self.im.convert(mode) if im.mode not in ("LA", "PA", "RGBA"): raise ValueError from e # sanity check self.im = im self.pyaccess = None self.mode = self.im.mode except KeyError as e: raise ValueError("illegal image mode") from e if self.mode in ("LA", "PA"): band = 1 else: band = 3 if isImageType(alpha): # alpha layer if alpha.mode not in ("1", "L"): raise ValueError("illegal image mode") alpha.load() if alpha.mode == "1": alpha = alpha.convert("L") else: # constant alpha try: self.im.fillband(band, alpha) except (AttributeError, ValueError): # do things the hard way alpha = new("L", self.size, alpha) else: return self.im.putband(alpha.im, band) def putdata(self, data, scale=1.0, offset=0.0): """ Copies pixel data from a flattened sequence object into the image. The values should start at the upper left corner (0, 0), continue to the end of the line, followed directly by the first value of the second line, and so on. Data will be read until either the image or the sequence ends. The scale and offset values are used to adjust the sequence values: **pixel = value*scale + offset**. :param data: A flattened sequence object. :param scale: An optional scale value. The default is 1.0. :param offset: An optional offset value. The default is 0.0. """ self._ensure_mutable() self.im.putdata(data, scale, offset) def putpalette(self, data, rawmode="RGB"): """ Attaches a palette to this image. The image must be a "P", "PA", "L" or "LA" image. The palette sequence must contain at most 256 colors, made up of one integer value for each channel in the raw mode. For example, if the raw mode is "RGB", then it can contain at most 768 values, made up of red, green and blue values for the corresponding pixel index in the 256 colors. If the raw mode is "RGBA", then it can contain at most 1024 values, containing red, green, blue and alpha values. Alternatively, an 8-bit string may be used instead of an integer sequence. :param data: A palette sequence (either a list or a string). :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode that can be transformed to "RGB" (e.g. "R", "BGR;15", "RGBA;L"). """ from . import ImagePalette if self.mode not in ("L", "LA", "P", "PA"): raise ValueError("illegal image mode") if isinstance(data, ImagePalette.ImagePalette): palette = ImagePalette.raw(data.rawmode, data.palette) else: if not isinstance(data, bytes): data = bytes(data) palette = ImagePalette.raw(rawmode, data) self.mode = "PA" if "A" in self.mode else "P" self.palette = palette self.palette.mode = "RGB" self.load() # install new palette def putpixel(self, xy, value): """ Modifies the pixel at the given position. The color is given as a single numerical value for single-band images, and a tuple for multi-band images. In addition to this, RGB and RGBA tuples are accepted for P images. Note that this method is relatively slow. For more extensive changes, use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw` module instead. See: * :py:meth:`~PIL.Image.Image.paste` * :py:meth:`~PIL.Image.Image.putdata` * :py:mod:`~PIL.ImageDraw` :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param value: The pixel value. """ if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode == "P" and isinstance(value, (list, tuple)) and len(value) in [3, 4] ): # RGB or RGBA value for a P image value = self.palette.getcolor(value, self) return self.im.putpixel(xy, value) def remap_palette(self, dest_map, source_palette=None): """ Rewrites the image to reorder the palette. :param dest_map: A list of indexes into the original palette. e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))`` is the identity transform. :param source_palette: Bytes or None. :returns: An :py:class:`~PIL.Image.Image` object. """ from . import ImagePalette if self.mode not in ("L", "P"): raise ValueError("illegal image mode") if source_palette is None: if self.mode == "P": self.load() source_palette = self.im.getpalette("RGB")[:768] else: # L-mode source_palette = bytearray(i // 3 for i in range(768)) palette_bytes = b"" new_positions = [0] * 256 # pick only the used colors from the palette for i, oldPosition in enumerate(dest_map): palette_bytes += source_palette[oldPosition * 3 : oldPosition * 3 + 3] new_positions[oldPosition] = i # replace the palette color id of all pixel with the new id # Palette images are [0..255], mapped through a 1 or 3 # byte/color map. We need to remap the whole image # from palette 1 to palette 2. New_positions is # an array of indexes into palette 1. Palette 2 is # palette 1 with any holes removed. # We're going to leverage the convert mechanism to use the # C code to remap the image from palette 1 to palette 2, # by forcing the source image into 'L' mode and adding a # mapping 'L' mode palette, then converting back to 'L' # sans palette thus converting the image bytes, then # assigning the optimized RGB palette. # perf reference, 9500x4000 gif, w/~135 colors # 14 sec prepatch, 1 sec postpatch with optimization forced. mapping_palette = bytearray(new_positions) m_im = self.copy() m_im.mode = "P" m_im.palette = ImagePalette.ImagePalette("RGB", palette=mapping_palette * 3) # possibly set palette dirty, then # m_im.putpalette(mapping_palette, 'L') # converts to 'P' # or just force it. # UNDONE -- this is part of the general issue with palettes m_im.im.putpalette("RGB;L", m_im.palette.tobytes()) m_im = m_im.convert("L") # Internally, we require 768 bytes for a palette. new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00" m_im.putpalette(new_palette_bytes) m_im.palette = ImagePalette.ImagePalette("RGB", palette=palette_bytes) return m_im def _get_safe_box(self, size, resample, box): """Expands the box so it includes adjacent pixels that may be used by resampling with the given resampling filter. """ filter_support = _filters_support[resample] - 0.5 scale_x = (box[2] - box[0]) / size[0] scale_y = (box[3] - box[1]) / size[1] support_x = filter_support * scale_x support_y = filter_support * scale_y return ( max(0, int(box[0] - support_x)), max(0, int(box[1] - support_y)), min(self.size[0], math.ceil(box[2] + support_x)), min(self.size[1], math.ceil(box[3] + support_y)), ) def resize(self, size, resample=None, box=None, reducing_gap=None): """ Returns a resized copy of this image. :param size: The requested size in pixels, as a 2-tuple: (width, height). :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If the image has mode "1" or "P", it is always set to :py:data:`PIL.Image.NEAREST`. If the image mode specifies a number of bits, such as "I;16", then the default filter is :py:data:`PIL.Image.NEAREST`. Otherwise, the default filter is :py:data:`PIL.Image.BICUBIC`. See: :ref:`concept-filters`. :param box: An optional 4-tuple of floats providing the source image region to be scaled. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce`. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is None (no optimization). :returns: An :py:class:`~PIL.Image.Image` object. """ if resample is None: type_special = ";" in self.mode resample = NEAREST if type_special else BICUBIC elif resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING): message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (LANCZOS, "Image.LANCZOS"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), (BOX, "Image.BOX"), (HAMMING, "Image.HAMMING"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) if reducing_gap is not None and reducing_gap < 1.0: raise ValueError("reducing_gap must be 1.0 or greater") size = tuple(size) if box is None: box = (0, 0) + self.size else: box = tuple(box) if self.size == size and box == (0, 0) + self.size: return self.copy() if self.mode in ("1", "P"): resample = NEAREST if self.mode in ["LA", "RGBA"] and resample != NEAREST: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.resize(size, resample, box) return im.convert(self.mode) self.load() if reducing_gap is not None and resample != NEAREST: factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1 factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1 if factor_x > 1 or factor_y > 1: reduce_box = self._get_safe_box(size, resample, box) factor = (factor_x, factor_y) if callable(self.reduce): self = self.reduce(factor, box=reduce_box) else: self = Image.reduce(self, factor, box=reduce_box) box = ( (box[0] - reduce_box[0]) / factor_x, (box[1] - reduce_box[1]) / factor_y, (box[2] - reduce_box[0]) / factor_x, (box[3] - reduce_box[1]) / factor_y, ) return self._new(self.im.resize(size, resample, box)) def reduce(self, factor, box=None): """ Returns a copy of the image reduced ``factor`` times. If the size of the image is not dividable by ``factor``, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within ``(0, 0, width, height)`` rectangle. If omitted or ``None``, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box)) def rotate( self, angle, resample=NEAREST, expand=0, center=None, translate=None, fillcolor=None, ): """ Returns a rotated copy of this image. This method returns a copy of this image, rotated the given number of degrees counter clockwise around its centre. :param angle: In degrees counter clockwise. :param resample: An optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See :ref:`concept-filters`. :param expand: Optional expansion flag. If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. :param center: Optional center of rotation (a 2-tuple). Origin is the upper left corner. Default is the center of the image. :param translate: An optional post-rotate translation (a 2-tuple). :param fillcolor: An optional color for area outside the rotated image. :returns: An :py:class:`~PIL.Image.Image` object. """ angle = angle % 360.0 # Fast paths regardless of filter, as long as we're not # translating or changing the center. if not (center or translate): if angle == 0: return self.copy() if angle == 180: return self.transpose(ROTATE_180) if angle in (90, 270) and (expand or self.width == self.height): return self.transpose(ROTATE_90 if angle == 90 else ROTATE_270) # Calculate the affine matrix. Note that this is the reverse # transformation (from destination image to source) because we # want to interpolate the (discrete) destination pixel from # the local area around the (floating) source pixel. # The matrix we actually want (note that it operates from the right): # (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx) # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy) # (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1) # The reverse matrix is thus: # (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx) # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty) # (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1) # In any case, the final translation may be updated at the end to # compensate for the expand flag. w, h = self.size if translate is None: post_trans = (0, 0) else: post_trans = translate if center is None: # FIXME These should be rounded to ints? rotn_center = (w / 2.0, h / 2.0) else: rotn_center = center angle = -math.radians(angle) matrix = [ round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0, ] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return a * x + b * y + c, d * x + e * y + f matrix[2], matrix[5] = transform( -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix ) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] if expand: # calculate output size xx = [] yy = [] for x, y in ((0, 0), (w, 0), (w, h), (0, h)): x, y = transform(x, y, matrix) xx.append(x) yy.append(y) nw = math.ceil(max(xx)) - math.floor(min(xx)) nh = math.ceil(max(yy)) - math.floor(min(yy)) # We multiply a translation matrix from the right. Because of its # special form, this is the same as taking the image of the # translation vector as new translation vector. matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix) w, h = nw, nh return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor) def save(self, fp, format=None, **params): """ Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognise an option, it is silently ignored. The available options are described in the :doc:`image format documentation <../handbook/image-file-formats>` for each writer. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the ``seek``, ``tell``, and ``write`` methods, and be opened in binary mode. :param fp: A filename (string), pathlib.Path object or file object. :param format: Optional format override. If omitted, the format to use is determined from the filename extension. If a file object was used instead of a filename, this parameter should always be used. :param params: Extra parameters to the image writer. :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ filename = "" open_fp = False if isinstance(fp, Path): filename = str(fp) open_fp = True elif isPath(fp): filename = fp open_fp = True elif fp == sys.stdout: try: fp = sys.stdout.buffer except AttributeError: pass if not filename and hasattr(fp, "name") and isPath(fp.name): # only set the name for metadata purposes filename = fp.name # may mutate self! self._ensure_mutable() save_all = params.pop("save_all", False) self.encoderinfo = params self.encoderconfig = () preinit() ext = os.path.splitext(filename)[1].lower() if not format: if ext not in EXTENSION: init() try: format = EXTENSION[ext] except KeyError as e: raise ValueError(f"unknown file extension: {ext}") from e if format.upper() not in SAVE: init() if save_all: save_handler = SAVE_ALL[format.upper()] else: save_handler = SAVE[format.upper()] if open_fp: if params.get("append", False): # Open also for reading ("+"), because TIFF save_all # writer needs to go back and edit the written data. fp = builtins.open(filename, "r+b") else: fp = builtins.open(filename, "w+b") try: save_handler(self, fp, filename) finally: # do what we can to clean up if open_fp: fp.close() def seek(self, frame): """ Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an ``EOFError`` exception. When a sequence file is opened, the library automatically seeks to frame 0. See :py:meth:`~PIL.Image.Image.tell`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :param frame: Frame number, starting at 0. :exception EOFError: If the call attempts to seek beyond the end of the sequence. """ # overridden by file handlers if frame != 0: raise EOFError def show(self, title=None): """ Displays this image. This method is mainly intended for debugging purposes. This method calls :py:func:`PIL.ImageShow.show` internally. You can use :py:func:`PIL.ImageShow.register` to override its default behaviour. The image is first saved to a temporary file. By default, it will be in PNG format. On Unix, the image is then opened using the **display**, **eog** or **xv** utility, depending on which one can be found. On macOS, the image is opened with the native Preview application. On Windows, the image is opened with the standard PNG display utility. :param title: Optional title to use for the image window, where possible. """ _show(self, title=title) def split(self): """ Split this image into individual bands. This method returns a tuple of individual image bands from an image. For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). If you need only one band, :py:meth:`~PIL.Image.Image.getchannel` method can be more convenient and faster. :returns: A tuple containing bands. """ self.load() if self.im.bands == 1: ims = [self.copy()] else: ims = map(self._new, self.im.split()) return tuple(ims) def getchannel(self, channel): """ Returns an image containing a single channel of the source image. :param channel: What channel to return. Could be index (0 for "R" channel of "RGB") or channel name ("A" for alpha channel of "RGBA"). :returns: An image in "L" mode. .. versionadded:: 4.3.0 """ self.load() if isinstance(channel, str): try: channel = self.getbands().index(channel) except ValueError as e: raise ValueError(f'The image has no channel "{channel}"') from e return self._new(self.im.getband(channel)) def tell(self): """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0): """ Make this image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the :py:meth:`~PIL.Image.Image.draft` method to configure the file reader (where applicable), and finally resizes the image. Note that this function modifies the :py:class:`~PIL.Image.Image` object in place. If you need to use the full resolution image as well, apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original image. :param size: Requested size. :param resample: Optional resampling filter. This can be one of :py:data:`PIL.Image.NEAREST`, :py:data:`PIL.Image.BOX`, :py:data:`PIL.Image.BILINEAR`, :py:data:`PIL.Image.HAMMING`, :py:data:`PIL.Image.BICUBIC` or :py:data:`PIL.Image.LANCZOS`. If omitted, it defaults to :py:data:`PIL.Image.BICUBIC`. (was :py:data:`PIL.Image.NEAREST` prior to version 2.5.0). See: :ref:`concept-filters`. :param reducing_gap: Apply optimization by resizing the image in two steps. First, reducing the image by integer times using :py:meth:`~PIL.Image.Image.reduce` or :py:meth:`~PIL.Image.Image.draft` for JPEG images. Second, resizing using regular resampling. The last step changes size no less than by ``reducing_gap`` times. ``reducing_gap`` may be None (no first step is performed) or should be greater than 1.0. The bigger ``reducing_gap``, the closer the result to the fair resampling. The smaller ``reducing_gap``, the faster resizing. With ``reducing_gap`` greater or equal to 3.0, the result is indistinguishable from fair resampling in most cases. The default value is 2.0 (very close to fair resampling while still being faster in many cases). :returns: None """ x, y = map(math.floor, size) if x >= self.width and y >= self.height: return def round_aspect(number, key): return max(min(math.floor(number), math.ceil(number), key=key), 1) # preserve aspect ratio aspect = self.width / self.height if x / y >= aspect: x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y)) else: y = round_aspect( x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n) ) size = (x, y) box = None if reducing_gap is not None: res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap)) if res is not None: box = res[1] if self.size != size: im = self.resize(size, resample, box=box, reducing_gap=reducing_gap) self.im = im.im self._size = size self.mode = self.im.mode self.readonly = 0 self.pyaccess = None # FIXME: the different transform methods need further explanation # instead of bloating the method docs, add a separate chapter. def transform( self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None ): """ Transforms this image. This method creates a new image with the given size, and the same mode as the original, and copies data to the new image using the given transform. :param size: The output size. :param method: The transformation method. This is one of :py:data:`PIL.Image.EXTENT` (cut out a rectangular subregion), :py:data:`PIL.Image.AFFINE` (affine transform), :py:data:`PIL.Image.PERSPECTIVE` (perspective transform), :py:data:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or :py:data:`PIL.Image.MESH` (map a number of source quadrilaterals in one operation). It may also be an :py:class:`~PIL.Image.ImageTransformHandler` object:: class Example(Image.ImageTransformHandler): def transform(self, size, data, resample, fill=1): # Return result It may also be an object with a ``method.getdata`` method that returns a tuple supplying new ``method`` and ``data`` values:: class Example: def getdata(self): method = Image.EXTENT data = (0, 0, 100, 100) return method, data :param data: Extra data to the transformation method. :param resample: Optional resampling filter. It can be one of :py:data:`PIL.Image.NEAREST` (use nearest neighbour), :py:data:`PIL.Image.BILINEAR` (linear interpolation in a 2x2 environment), or :py:data:`PIL.Image.BICUBIC` (cubic spline interpolation in a 4x4 environment). If omitted, or if the image has mode "1" or "P", it is set to :py:data:`PIL.Image.NEAREST`. See: :ref:`concept-filters`. :param fill: If ``method`` is an :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of the arguments passed to it. Otherwise, it is unused. :param fillcolor: Optional fill color for the area outside the transform in the output image. :returns: An :py:class:`~PIL.Image.Image` object. """ if self.mode in ("LA", "RGBA") and resample != NEAREST: return ( self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode]) .transform(size, method, data, resample, fill, fillcolor) .convert(self.mode) ) if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): # compatibility w. old-style transform objects method, data = method.getdata() if data is None: raise ValueError("missing method data") im = new(self.mode, size, fillcolor) if self.mode == "P" and self.palette: im.palette = self.palette.copy() im.info = self.info.copy() if method == MESH: # list of quads for box, quad in data: im.__transformer(box, self, QUAD, quad, resample, fillcolor is None) else: im.__transformer( (0, 0) + size, self, method, data, resample, fillcolor is None ) return im def __transformer(self, box, image, method, data, resample=NEAREST, fill=1): w = box[2] - box[0] h = box[3] - box[1] if method == AFFINE: data = data[0:6] elif method == EXTENT: # convert extent to an affine transform x0, y0, x1, y1 = data xs = (x1 - x0) / w ys = (y1 - y0) / h method = AFFINE data = (xs, 0, x0, 0, ys, y0) elif method == PERSPECTIVE: data = data[0:8] elif method == QUAD: # quadrilateral warp. data specifies the four corners # given as NW, SW, SE, and NE. nw = data[0:2] sw = data[2:4] se = data[4:6] ne = data[6:8] x0, y0 = nw As = 1.0 / w At = 1.0 / h data = ( x0, (ne[0] - x0) * As, (sw[0] - x0) * At, (se[0] - sw[0] - ne[0] + x0) * As * At, y0, (ne[1] - y0) * As, (sw[1] - y0) * At, (se[1] - sw[1] - ne[1] + y0) * As * At, ) else: raise ValueError("unknown transformation method") if resample not in (NEAREST, BILINEAR, BICUBIC): if resample in (BOX, HAMMING, LANCZOS): message = { BOX: "Image.BOX", HAMMING: "Image.HAMMING", LANCZOS: "Image.LANCZOS/Image.ANTIALIAS", }[resample] + f" ({resample}) cannot be used." else: message = f"Unknown resampling filter ({resample})." filters = [ f"{filter[1]} ({filter[0]})" for filter in ( (NEAREST, "Image.NEAREST"), (BILINEAR, "Image.BILINEAR"), (BICUBIC, "Image.BICUBIC"), ) ] raise ValueError( message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1] ) image.load() self.load() if image.mode in ("1", "P"): resample = NEAREST self.im.transform2(box, image.im, method, data, resample, fill) def transpose(self, method): """ Transpose image (flip or rotate in 90 degree steps) :param method: One of :py:data:`PIL.Image.FLIP_LEFT_RIGHT`, :py:data:`PIL.Image.FLIP_TOP_BOTTOM`, :py:data:`PIL.Image.ROTATE_90`, :py:data:`PIL.Image.ROTATE_180`, :py:data:`PIL.Image.ROTATE_270`, :py:data:`PIL.Image.TRANSPOSE` or :py:data:`PIL.Image.TRANSVERSE`. :returns: Returns a flipped or rotated copy of this image. """ self.load() return self._new(self.im.transpose(method)) def effect_spread(self, distance): """ Randomly spread pixels in an image. :param distance: Distance to spread pixels. """ self.load() return self._new(self.im.effect_spread(distance)) def toqimage(self): """Returns a QImage copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqimage(self) def toqpixmap(self): """Returns a QPixmap copy of this image""" from . import ImageQt if not ImageQt.qt_is_installed: raise ImportError("Qt bindings are not installed") return ImageQt.toqpixmap(self) The provided code snippet includes necessary dependencies for implementing the `pilinfo` function. Write a Python function `def pilinfo(out=None, supported_formats=True)` to solve the following problem: Prints information about this installation of Pillow. This function can be called with ``python3 -m PIL``. :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. Here is the function: def pilinfo(out=None, supported_formats=True): """ Prints information about this installation of Pillow. This function can be called with ``python3 -m PIL``. :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 = sys.version.splitlines() print(f"Python {py_version[0].strip()}", file=out) for py_version in py_version[1:]: print(f" {py_version.strip()}", file=out) print("-" * 68, file=out) print( f"Python modules loaded from {os.path.dirname(Image.__file__)}", file=out, ) print( f"Binary 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"), ("transp_webp", "WEBP Transparency"), ("webp_mux", "WEBPMUX"), ("webp_anim", "WEBP Animation"), ("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): if name == "jpg" and check_feature("libjpeg_turbo"): v = "libjpeg-turbo " + version_feature("libjpeg_turbo") else: 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 == "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)
Prints information about this installation of Pillow. This function can be called with ``python3 -m PIL``. :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.
167,784
from inspect import signature from typing import List, Type from beanie.migrations.controllers.base import BaseMigrationController from beanie.odm.documents import Document class BaseMigrationController(ABC): def __init__(self, function): self.function = function async def run(self, session): pass def models(self) -> List[Type[Document]]: pass class Document( LazyModel, SettersInterface, InheritanceInterface, FindInterface, AggregateInterface, OtherGettersInterface, ): """ Document Mapping class. Fields: - `id` - MongoDB document ObjectID "_id" field. Mapped to the PydanticObjectId class """ if IS_PYDANTIC_V2: model_config = ConfigDict( json_schema_extra=json_schema_extra, populate_by_name=True, alias_generator=document_alias_generator, ) else: class Config: json_encoders = {ObjectId: str} allow_population_by_field_name = True fields = {"id": "_id"} schema_extra = staticmethod(json_schema_extra) id: Optional[PydanticObjectId] = Field( default=None, description="MongoDB document ObjectID" ) # State revision_id: Optional[UUID] = Field(default=None, exclude=True) _saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None) _previous_saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None) # Relations _link_fields: ClassVar[Optional[Dict[str, LinkInfo]]] = None # Cache _cache: ClassVar[Optional[LRUCache]] = None # Settings _document_settings: ClassVar[Optional[DocumentSettings]] = None # Database _database_major_version: ClassVar[int] = 4 def __init__(self, *args, **kwargs) -> None: super(Document, self).__init__(*args, **kwargs) self.get_motor_collection() def _fill_back_refs(cls, values): if cls._link_fields: for field_name, link_info in cls._link_fields.items(): if ( link_info.link_type in [LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT] and field_name not in values ): values[field_name] = BackLink[link_info.document_class]( link_info.document_class ) if ( link_info.link_type in [LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST] and field_name not in values ): values[field_name] = [ BackLink[link_info.document_class]( link_info.document_class ) ] return values if IS_PYDANTIC_V2: def fill_back_refs(cls, values): return cls._fill_back_refs(values) else: def fill_back_refs(cls, values): return cls._fill_back_refs(values) async def get( cls: Type["DocType"], document_id: Any, session: Optional[ClientSession] = None, ignore_cache: bool = False, fetch_links: bool = False, with_children: bool = False, nesting_depth: Optional[int] = None, nesting_depths_per_field: Optional[Dict[str, int]] = None, **pymongo_kwargs, ) -> Optional["DocType"]: """ Get document by id, returns None if document does not exist :param document_id: PydanticObjectId - document id :param session: Optional[ClientSession] - pymongo session :param ignore_cache: bool - ignore cache (if it is turned on) :param **pymongo_kwargs: pymongo native parameters for find operation :return: Union["Document", None] """ if not isinstance( document_id, extract_id_class(get_field_type(get_model_fields(cls)["id"])), ): document_id = parse_object_as( get_field_type(get_model_fields(cls)["id"]), document_id ) return await cls.find_one( {"_id": document_id}, session=session, ignore_cache=ignore_cache, fetch_links=fetch_links, with_children=with_children, nesting_depth=nesting_depth, nesting_depths_per_field=nesting_depths_per_field, **pymongo_kwargs, ) async def sync(self, merge_strategy: MergeStrategy = MergeStrategy.remote): """ Sync the document with the database :param merge_strategy: MergeStrategy - how to merge the document :return: None """ if ( merge_strategy == MergeStrategy.local and self.get_settings().use_state_management is False ): raise ValueError( "State management must be turned on to use local merge strategy" ) if self.id is None: raise DocumentWasNotSaved document = await self.find_one({"_id": self.id}) if document is None: raise DocumentNotFound if merge_strategy == MergeStrategy.local: original_changes = self.get_changes() new_state = document.get_saved_state() if new_state is None: raise DocumentWasNotSaved changes_to_apply = self._collect_updates( new_state, original_changes ) merge_models(self, document) apply_changes(changes_to_apply, self) elif merge_strategy == MergeStrategy.remote: merge_models(self, document) else: raise ValueError("Invalid merge strategy") async def insert( self: DocType, *, link_rule: WriteRules = WriteRules.DO_NOTHING, session: Optional[ClientSession] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> DocType: """ Insert the document (self) to the collection :return: Document """ if self.get_settings().use_revision: self.revision_id = uuid4() if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, ]: if isinstance(value, Document): await value.save(link_rule=WriteRules.WRITE) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.save(link_rule=WriteRules.WRITE) for obj in value if isinstance(obj, Document) ] ) result = await self.get_motor_collection().insert_one( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls ), session=session, ) new_id = result.inserted_id if not isinstance( new_id, extract_id_class(get_field_type(get_model_fields(self)["id"])), ): new_id = parse_object_as( get_field_type(get_model_fields(self)["id"]), new_id ) self.id = new_id return self async def create( self: DocType, session: Optional[ClientSession] = None, ) -> DocType: """ The same as self.insert() :return: Document """ return await self.insert(session=session) async def insert_one( cls: Type[DocType], document: DocType, session: Optional[ClientSession] = None, bulk_writer: Optional["BulkWriter"] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ) -> Optional[DocType]: """ Insert one document to the collection :param document: Document - document to insert :param session: ClientSession - pymongo session :param bulk_writer: "BulkWriter" - Beanie bulk writer :param link_rule: InsertRules - hot to manage link fields :return: DocType """ if not isinstance(document, cls): raise TypeError( "Inserting document must be of the original document class" ) if bulk_writer is None: return await document.insert(link_rule=link_rule, session=session) else: if link_rule == WriteRules.WRITE: raise NotSupported( "Cascade insert with bulk writing not supported" ) bulk_writer.add_operation( Operation( operation=InsertOne, first_query=get_dict( document, to_db=True, keep_nulls=document.get_settings().keep_nulls, ), object_class=type(document), ) ) return None async def insert_many( cls: Type[DocType], documents: Iterable[DocType], session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, **pymongo_kwargs, ) -> InsertManyResult: """ Insert many documents to the collection :param documents: List["Document"] - documents to insert :param session: ClientSession - pymongo session :param link_rule: InsertRules - how to manage link fields :return: InsertManyResult """ if link_rule == WriteRules.WRITE: raise NotSupported( "Cascade insert not supported for insert many method" ) documents_list = [ get_dict( document, to_db=True, keep_nulls=document.get_settings().keep_nulls, ) for document in documents ] return await cls.get_motor_collection().insert_many( documents_list, session=session, **pymongo_kwargs ) async def replace( self: DocType, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> DocType: """ Fully update the document in the database :param session: Optional[ClientSession] - pymongo session. :param ignore_revision: bool - do force replace. Used when revision based protection is turned on. :param bulk_writer: "BulkWriter" - Beanie bulk writer :return: self """ if self.id is None: raise ValueError("Document must have an id") if bulk_writer is not None and link_rule != WriteRules.DO_NOTHING: raise NotSupported if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.replace( link_rule=link_rule, bulk_writer=bulk_writer, ignore_revision=ignore_revision, session=session, ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.replace( link_rule=link_rule, bulk_writer=bulk_writer, ignore_revision=ignore_revision, session=session, ) for obj in value if isinstance(obj, Document) ] ) use_revision_id = self.get_settings().use_revision find_query: Dict[str, Any] = {"_id": self.id} if use_revision_id and not ignore_revision: find_query["revision_id"] = self.revision_id self.revision_id = uuid4() try: await self.find_one(find_query).replace_one( self, session=session, bulk_writer=bulk_writer, ) except DocumentNotFound: if use_revision_id and not ignore_revision: raise RevisionIdWasChanged else: raise DocumentNotFound return self async def save( self: DocType, session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ignore_revision: bool = False, **kwargs, ) -> None: """ Update an existing model in the database or insert it if it does not yet exist. :param session: Optional[ClientSession] - pymongo session. :param link_rule: WriteRules - rules how to deal with links on writing :param ignore_revision: bool - do force save. :return: None """ if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.save( link_rule=link_rule, session=session ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.save( link_rule=link_rule, session=session ) for obj in value if isinstance(obj, Document) ] ) if self.get_settings().keep_nulls is False: return await self.update( SetOperator( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, ) ), Unset(get_top_level_nones(self)), session=session, ignore_revision=ignore_revision, upsert=True, **kwargs, ) else: return await self.update( SetOperator( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, ) ), session=session, ignore_revision=ignore_revision, upsert=True, **kwargs, ) async def save_changes( self, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> None: """ Save changes. State management usage must be turned on :param ignore_revision: bool - ignore revision id, if revision is turned on :param bulk_writer: "BulkWriter" - Beanie bulk writer :return: None """ if not self.is_changed: return None changes = self.get_changes() if self.get_settings().keep_nulls is False: return await self.update( SetOperator(changes), Unset(get_top_level_nones(self)), ignore_revision=ignore_revision, session=session, bulk_writer=bulk_writer, ) else: return await self.set( changes, # type: ignore #TODO fix typing ignore_revision=ignore_revision, session=session, bulk_writer=bulk_writer, ) async def replace_many( cls: Type[DocType], documents: List[DocType], session: Optional[ClientSession] = None, ) -> None: """ Replace list of documents :param documents: List["Document"] :param session: Optional[ClientSession] - pymongo session. :return: None """ ids_list = [document.id for document in documents] if await cls.find(In(cls.id, ids_list)).count() != len(ids_list): raise ReplaceError( "Some of the documents are not exist in the collection" ) async with BulkWriter(session=session) as bulk_writer: for document in documents: await document.replace( bulk_writer=bulk_writer, session=session ) async def update( self, *args, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, skip_sync: Optional[bool] = None, **pymongo_kwargs, ) -> DocType: """ Partially update the document in the database :param args: *Union[dict, Mapping] - the modifications to apply. :param session: ClientSession - pymongo session. :param ignore_revision: bool - force update. Will update even if revision id is not the same, as stored :param bulk_writer: "BulkWriter" - Beanie bulk writer :param pymongo_kwargs: pymongo native parameters for update operation :return: None """ arguments = list(args) if skip_sync is not None: raise DeprecationWarning( "skip_sync parameter is not supported. The document get synced always using atomic operation." ) use_revision_id = self.get_settings().use_revision if self.id is not None: find_query: Dict[str, Any] = {"_id": self.id} else: find_query = {"_id": PydanticObjectId()} if use_revision_id and not ignore_revision: find_query["revision_id"] = self.revision_id if use_revision_id: new_revision_id = uuid4() arguments.append(SetRevisionId(new_revision_id)) try: result = await self.find_one(find_query).update( *arguments, session=session, response_type=UpdateResponse.NEW_DOCUMENT, bulk_writer=bulk_writer, **pymongo_kwargs, ) except DuplicateKeyError: raise RevisionIdWasChanged if bulk_writer is None: if use_revision_id and not ignore_revision and result is None: raise RevisionIdWasChanged merge_models(self, result) return self def update_all( cls, *args: Union[dict, Mapping], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, **pymongo_kwargs, ) -> UpdateMany: """ Partially update all the documents :param args: *Union[dict, Mapping] - the modifications to apply. :param session: ClientSession - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param **pymongo_kwargs: pymongo native parameters for find operation :return: UpdateMany query """ return cls.find_all().update_many( *args, session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) def set( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Set values Example: ```python class Sample(Document): one: int await Document.find(Sample.one == 1).set({Sample.one: 100}) ``` Uses [Set operator](operators/update.md#set) :param expression: Dict[Union[ExpressionField, str], Any] - keys and values to set :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( SetOperator(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) def current_date( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Set current date Uses [CurrentDate operator](operators/update.md#currentdate) :param expression: Dict[Union[ExpressionField, str], Any] :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( CurrentDate(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) def inc( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Increment Example: ```python class Sample(Document): one: int await Document.find(Sample.one == 1).inc({Sample.one: 100}) ``` Uses [Inc operator](operators/update.md#inc) :param expression: Dict[Union[ExpressionField, str], Any] :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( Inc(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) async def delete( self, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, link_rule: DeleteRules = DeleteRules.DO_NOTHING, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, **pymongo_kwargs, ) -> Optional[DeleteResult]: """ Delete the document :param session: Optional[ClientSession] - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param link_rule: DeleteRules - rules for link fields :param **pymongo_kwargs: pymongo native parameters for delete operation :return: Optional[DeleteResult] - pymongo DeleteResult instance. """ if link_rule == DeleteRules.DELETE_LINKS: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.delete( link_rule=DeleteRules.DELETE_LINKS, **pymongo_kwargs, ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.delete( link_rule=DeleteRules.DELETE_LINKS, **pymongo_kwargs, ) for obj in value if isinstance(obj, Document) ] ) return await self.find_one({"_id": self.id}).delete( session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) async def delete_all( cls, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, **pymongo_kwargs, ) -> Optional[DeleteResult]: """ Delete all the documents :param session: Optional[ClientSession] - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param **pymongo_kwargs: pymongo native parameters for delete operation :return: Optional[DeleteResult] - pymongo DeleteResult instance. """ return await cls.find_all().delete( session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) # State management def use_state_management(cls) -> bool: """ Is state management turned on :return: bool """ return cls.get_settings().use_state_management def state_management_save_previous(cls) -> bool: """ Should we save the previous state after a commit to database :return: bool """ return cls.get_settings().state_management_save_previous def state_management_replace_objects(cls) -> bool: """ Should objects be replaced when using state management :return: bool """ return cls.get_settings().state_management_replace_objects def _save_state(self) -> None: """ Save current document state. Internal method :return: None """ if self.use_state_management() and self.id is not None: if self.state_management_save_previous(): self._previous_saved_state = self._saved_state self._saved_state = get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ) def get_saved_state(self) -> Optional[Dict[str, Any]]: """ Saved state getter. It is protected property. :return: Optional[Dict[str, Any]] - saved state """ return self._saved_state def get_previous_saved_state(self) -> Optional[Dict[str, Any]]: """ Previous state getter. It is a protected property. :return: Optional[Dict[str, Any]] - previous state """ return self._previous_saved_state def is_changed(self) -> bool: if self._saved_state == get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ): return False return True def has_changed(self) -> bool: if ( self._previous_saved_state is None or self._previous_saved_state == self._saved_state ): return False return True def _collect_updates( self, old_dict: Dict[str, Any], new_dict: Dict[str, Any] ) -> Dict[str, Any]: """ Compares old_dict with new_dict and returns field paths that have been updated Args: old_dict: dict1 new_dict: dict2 Returns: dictionary with updates """ updates = {} if old_dict.keys() - new_dict.keys(): updates = new_dict else: for field_name, field_value in new_dict.items(): if field_value != old_dict.get(field_name): if not self.state_management_replace_objects() and ( isinstance(field_value, dict) and isinstance(old_dict.get(field_name), dict) ): if old_dict.get(field_name) is None: updates[field_name] = field_value elif isinstance(field_value, dict) and isinstance( old_dict.get(field_name), dict ): field_data = self._collect_updates( old_dict.get(field_name), # type: ignore field_value, ) for k, v in field_data.items(): updates[f"{field_name}.{k}"] = v else: updates[field_name] = field_value return updates def get_changes(self) -> Dict[str, Any]: return self._collect_updates( self._saved_state, # type: ignore get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ), ) def get_previous_changes(self) -> Dict[str, Any]: if self._previous_saved_state is None: return {} return self._collect_updates( self._previous_saved_state, self._saved_state, # type: ignore ) def rollback(self) -> None: if self.is_changed: for key, value in self._saved_state.items(): # type: ignore if key == "_id": setattr(self, "id", value) else: setattr(self, key, value) # Other def get_settings(cls) -> DocumentSettings: """ Get document settings, which was created on the initialization step :return: DocumentSettings class """ if cls._document_settings is None: raise CollectionWasNotInitialized return cls._document_settings async def inspect_collection( cls, session: Optional[ClientSession] = None ) -> InspectionResult: """ Check, if documents, stored in the MongoDB collection are compatible with the Document schema :return: InspectionResult """ inspection_result = InspectionResult() async for json_document in cls.get_motor_collection().find( {}, session=session ): try: parse_model(cls, json_document) except ValidationError as e: if inspection_result.status == InspectionStatuses.OK: inspection_result.status = InspectionStatuses.FAIL inspection_result.errors.append( InspectionError( document_id=json_document["_id"], error=str(e) ) ) return inspection_result def check_hidden_fields(cls): hidden_fields = [ (name, field) for name, field in get_model_fields(cls).items() if get_extra_field_info(field, "hidden") is True ] if not hidden_fields: return warnings.warn( f"{cls.__name__}: 'hidden=True' is deprecated, please use 'exclude=True'", DeprecationWarning, ) if IS_PYDANTIC_V2: for name, field in hidden_fields: field.exclude = True del field.json_schema_extra["hidden"] cls.model_rebuild(force=True) else: for name, field in hidden_fields: field.field_info.exclude = True del field.field_info.extra["hidden"] cls.__exclude_fields__[name] = True async def validate_self(self, *args, **kwargs): # TODO: it can be sync, but needs some actions controller improvements if self.get_settings().validate_on_save: new_model = parse_model(self.__class__, get_model_dump(self)) merge_models(self, new_model) def to_ref(self): if self.id is None: raise DocumentWasNotSaved("Can not create dbref without id") return DBRef(self.get_motor_collection().name, self.id) async def fetch_link(self, field: Union[str, Any]): ref_obj = getattr(self, field, None) if isinstance(ref_obj, Link): value = await ref_obj.fetch(fetch_links=True) setattr(self, field, value) if isinstance(ref_obj, list) and ref_obj: values = await Link.fetch_list(ref_obj, fetch_links=True) setattr(self, field, values) async def fetch_all_links(self): coros = [] link_fields = self.get_link_fields() if link_fields is not None: for ref in link_fields.values(): coros.append(self.fetch_link(ref.field_name)) # TODO lists await asyncio.gather(*coros) def get_link_fields(cls) -> Optional[Dict[str, LinkInfo]]: return cls._link_fields def get_model_type(cls) -> ModelType: return ModelType.Document async def distinct( cls, key: str, filter: Optional[Mapping[str, Any]] = None, session: Optional[ClientSession] = None, **kwargs: Any, ) -> list: return await cls.get_motor_collection().distinct( key, filter, session, **kwargs ) def link_from_id(cls, id: Any): ref = DBRef(id=id, collection=cls.get_collection_name()) return Link(ref, document_class=cls) def free_fall_migration(document_models: List[Type[Document]]): class FreeFallMigrationController(BaseMigrationController): def __init__(self, function): self.function = function self.function_signature = signature(function) self.document_models = document_models def __call__(self, *args, **kwargs): pass @property def models(self) -> List[Type[Document]]: return self.document_models async def run(self, session): function_kwargs = {"session": session} if "self" in self.function_signature.parameters: function_kwargs["self"] = None await self.function(**function_kwargs) return FreeFallMigrationController
null
167,785
import asyncio from inspect import isclass, signature from typing import List, Optional, Type, Union from beanie.migrations.controllers.base import BaseMigrationController from beanie.migrations.utils import update_dict from beanie.odm.documents import Document from beanie.odm.utils.pydantic import parse_model class DummyOutput: def __init__(self): super(DummyOutput, self).__setattr__("_internal_structure_dict", {}) def __setattr__(self, key, value): self._internal_structure_dict[key] = value def __getattr__(self, item): try: return self._internal_structure_dict[item] except KeyError: self._internal_structure_dict[item] = DummyOutput() return self._internal_structure_dict[item] def dict(self, to_parse: Optional[Union[dict, "DummyOutput"]] = None): if to_parse is None: to_parse = self input_dict = ( to_parse._internal_structure_dict if isinstance(to_parse, DummyOutput) else to_parse ) result_dict = {} for key, value in input_dict.items(): if isinstance(value, (DummyOutput, dict)): result_dict[key] = self.dict(to_parse=value) else: result_dict[key] = value return result_dict class BaseMigrationController(ABC): def __init__(self, function): self.function = function async def run(self, session): pass def models(self) -> List[Type[Document]]: pass def update_dict(d, u): for k, v in u.items(): if isinstance(v, dict): d[k] = update_dict(d.get(k, {}), v) else: d[k] = v return d class Document( LazyModel, SettersInterface, InheritanceInterface, FindInterface, AggregateInterface, OtherGettersInterface, ): """ Document Mapping class. Fields: - `id` - MongoDB document ObjectID "_id" field. Mapped to the PydanticObjectId class """ if IS_PYDANTIC_V2: model_config = ConfigDict( json_schema_extra=json_schema_extra, populate_by_name=True, alias_generator=document_alias_generator, ) else: class Config: json_encoders = {ObjectId: str} allow_population_by_field_name = True fields = {"id": "_id"} schema_extra = staticmethod(json_schema_extra) id: Optional[PydanticObjectId] = Field( default=None, description="MongoDB document ObjectID" ) # State revision_id: Optional[UUID] = Field(default=None, exclude=True) _saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None) _previous_saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None) # Relations _link_fields: ClassVar[Optional[Dict[str, LinkInfo]]] = None # Cache _cache: ClassVar[Optional[LRUCache]] = None # Settings _document_settings: ClassVar[Optional[DocumentSettings]] = None # Database _database_major_version: ClassVar[int] = 4 def __init__(self, *args, **kwargs) -> None: super(Document, self).__init__(*args, **kwargs) self.get_motor_collection() def _fill_back_refs(cls, values): if cls._link_fields: for field_name, link_info in cls._link_fields.items(): if ( link_info.link_type in [LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT] and field_name not in values ): values[field_name] = BackLink[link_info.document_class]( link_info.document_class ) if ( link_info.link_type in [LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST] and field_name not in values ): values[field_name] = [ BackLink[link_info.document_class]( link_info.document_class ) ] return values if IS_PYDANTIC_V2: def fill_back_refs(cls, values): return cls._fill_back_refs(values) else: def fill_back_refs(cls, values): return cls._fill_back_refs(values) async def get( cls: Type["DocType"], document_id: Any, session: Optional[ClientSession] = None, ignore_cache: bool = False, fetch_links: bool = False, with_children: bool = False, nesting_depth: Optional[int] = None, nesting_depths_per_field: Optional[Dict[str, int]] = None, **pymongo_kwargs, ) -> Optional["DocType"]: """ Get document by id, returns None if document does not exist :param document_id: PydanticObjectId - document id :param session: Optional[ClientSession] - pymongo session :param ignore_cache: bool - ignore cache (if it is turned on) :param **pymongo_kwargs: pymongo native parameters for find operation :return: Union["Document", None] """ if not isinstance( document_id, extract_id_class(get_field_type(get_model_fields(cls)["id"])), ): document_id = parse_object_as( get_field_type(get_model_fields(cls)["id"]), document_id ) return await cls.find_one( {"_id": document_id}, session=session, ignore_cache=ignore_cache, fetch_links=fetch_links, with_children=with_children, nesting_depth=nesting_depth, nesting_depths_per_field=nesting_depths_per_field, **pymongo_kwargs, ) async def sync(self, merge_strategy: MergeStrategy = MergeStrategy.remote): """ Sync the document with the database :param merge_strategy: MergeStrategy - how to merge the document :return: None """ if ( merge_strategy == MergeStrategy.local and self.get_settings().use_state_management is False ): raise ValueError( "State management must be turned on to use local merge strategy" ) if self.id is None: raise DocumentWasNotSaved document = await self.find_one({"_id": self.id}) if document is None: raise DocumentNotFound if merge_strategy == MergeStrategy.local: original_changes = self.get_changes() new_state = document.get_saved_state() if new_state is None: raise DocumentWasNotSaved changes_to_apply = self._collect_updates( new_state, original_changes ) merge_models(self, document) apply_changes(changes_to_apply, self) elif merge_strategy == MergeStrategy.remote: merge_models(self, document) else: raise ValueError("Invalid merge strategy") async def insert( self: DocType, *, link_rule: WriteRules = WriteRules.DO_NOTHING, session: Optional[ClientSession] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> DocType: """ Insert the document (self) to the collection :return: Document """ if self.get_settings().use_revision: self.revision_id = uuid4() if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, ]: if isinstance(value, Document): await value.save(link_rule=WriteRules.WRITE) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.save(link_rule=WriteRules.WRITE) for obj in value if isinstance(obj, Document) ] ) result = await self.get_motor_collection().insert_one( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls ), session=session, ) new_id = result.inserted_id if not isinstance( new_id, extract_id_class(get_field_type(get_model_fields(self)["id"])), ): new_id = parse_object_as( get_field_type(get_model_fields(self)["id"]), new_id ) self.id = new_id return self async def create( self: DocType, session: Optional[ClientSession] = None, ) -> DocType: """ The same as self.insert() :return: Document """ return await self.insert(session=session) async def insert_one( cls: Type[DocType], document: DocType, session: Optional[ClientSession] = None, bulk_writer: Optional["BulkWriter"] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ) -> Optional[DocType]: """ Insert one document to the collection :param document: Document - document to insert :param session: ClientSession - pymongo session :param bulk_writer: "BulkWriter" - Beanie bulk writer :param link_rule: InsertRules - hot to manage link fields :return: DocType """ if not isinstance(document, cls): raise TypeError( "Inserting document must be of the original document class" ) if bulk_writer is None: return await document.insert(link_rule=link_rule, session=session) else: if link_rule == WriteRules.WRITE: raise NotSupported( "Cascade insert with bulk writing not supported" ) bulk_writer.add_operation( Operation( operation=InsertOne, first_query=get_dict( document, to_db=True, keep_nulls=document.get_settings().keep_nulls, ), object_class=type(document), ) ) return None async def insert_many( cls: Type[DocType], documents: Iterable[DocType], session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, **pymongo_kwargs, ) -> InsertManyResult: """ Insert many documents to the collection :param documents: List["Document"] - documents to insert :param session: ClientSession - pymongo session :param link_rule: InsertRules - how to manage link fields :return: InsertManyResult """ if link_rule == WriteRules.WRITE: raise NotSupported( "Cascade insert not supported for insert many method" ) documents_list = [ get_dict( document, to_db=True, keep_nulls=document.get_settings().keep_nulls, ) for document in documents ] return await cls.get_motor_collection().insert_many( documents_list, session=session, **pymongo_kwargs ) async def replace( self: DocType, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> DocType: """ Fully update the document in the database :param session: Optional[ClientSession] - pymongo session. :param ignore_revision: bool - do force replace. Used when revision based protection is turned on. :param bulk_writer: "BulkWriter" - Beanie bulk writer :return: self """ if self.id is None: raise ValueError("Document must have an id") if bulk_writer is not None and link_rule != WriteRules.DO_NOTHING: raise NotSupported if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.replace( link_rule=link_rule, bulk_writer=bulk_writer, ignore_revision=ignore_revision, session=session, ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.replace( link_rule=link_rule, bulk_writer=bulk_writer, ignore_revision=ignore_revision, session=session, ) for obj in value if isinstance(obj, Document) ] ) use_revision_id = self.get_settings().use_revision find_query: Dict[str, Any] = {"_id": self.id} if use_revision_id and not ignore_revision: find_query["revision_id"] = self.revision_id self.revision_id = uuid4() try: await self.find_one(find_query).replace_one( self, session=session, bulk_writer=bulk_writer, ) except DocumentNotFound: if use_revision_id and not ignore_revision: raise RevisionIdWasChanged else: raise DocumentNotFound return self async def save( self: DocType, session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ignore_revision: bool = False, **kwargs, ) -> None: """ Update an existing model in the database or insert it if it does not yet exist. :param session: Optional[ClientSession] - pymongo session. :param link_rule: WriteRules - rules how to deal with links on writing :param ignore_revision: bool - do force save. :return: None """ if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.save( link_rule=link_rule, session=session ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.save( link_rule=link_rule, session=session ) for obj in value if isinstance(obj, Document) ] ) if self.get_settings().keep_nulls is False: return await self.update( SetOperator( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, ) ), Unset(get_top_level_nones(self)), session=session, ignore_revision=ignore_revision, upsert=True, **kwargs, ) else: return await self.update( SetOperator( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, ) ), session=session, ignore_revision=ignore_revision, upsert=True, **kwargs, ) async def save_changes( self, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> None: """ Save changes. State management usage must be turned on :param ignore_revision: bool - ignore revision id, if revision is turned on :param bulk_writer: "BulkWriter" - Beanie bulk writer :return: None """ if not self.is_changed: return None changes = self.get_changes() if self.get_settings().keep_nulls is False: return await self.update( SetOperator(changes), Unset(get_top_level_nones(self)), ignore_revision=ignore_revision, session=session, bulk_writer=bulk_writer, ) else: return await self.set( changes, # type: ignore #TODO fix typing ignore_revision=ignore_revision, session=session, bulk_writer=bulk_writer, ) async def replace_many( cls: Type[DocType], documents: List[DocType], session: Optional[ClientSession] = None, ) -> None: """ Replace list of documents :param documents: List["Document"] :param session: Optional[ClientSession] - pymongo session. :return: None """ ids_list = [document.id for document in documents] if await cls.find(In(cls.id, ids_list)).count() != len(ids_list): raise ReplaceError( "Some of the documents are not exist in the collection" ) async with BulkWriter(session=session) as bulk_writer: for document in documents: await document.replace( bulk_writer=bulk_writer, session=session ) async def update( self, *args, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, skip_sync: Optional[bool] = None, **pymongo_kwargs, ) -> DocType: """ Partially update the document in the database :param args: *Union[dict, Mapping] - the modifications to apply. :param session: ClientSession - pymongo session. :param ignore_revision: bool - force update. Will update even if revision id is not the same, as stored :param bulk_writer: "BulkWriter" - Beanie bulk writer :param pymongo_kwargs: pymongo native parameters for update operation :return: None """ arguments = list(args) if skip_sync is not None: raise DeprecationWarning( "skip_sync parameter is not supported. The document get synced always using atomic operation." ) use_revision_id = self.get_settings().use_revision if self.id is not None: find_query: Dict[str, Any] = {"_id": self.id} else: find_query = {"_id": PydanticObjectId()} if use_revision_id and not ignore_revision: find_query["revision_id"] = self.revision_id if use_revision_id: new_revision_id = uuid4() arguments.append(SetRevisionId(new_revision_id)) try: result = await self.find_one(find_query).update( *arguments, session=session, response_type=UpdateResponse.NEW_DOCUMENT, bulk_writer=bulk_writer, **pymongo_kwargs, ) except DuplicateKeyError: raise RevisionIdWasChanged if bulk_writer is None: if use_revision_id and not ignore_revision and result is None: raise RevisionIdWasChanged merge_models(self, result) return self def update_all( cls, *args: Union[dict, Mapping], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, **pymongo_kwargs, ) -> UpdateMany: """ Partially update all the documents :param args: *Union[dict, Mapping] - the modifications to apply. :param session: ClientSession - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param **pymongo_kwargs: pymongo native parameters for find operation :return: UpdateMany query """ return cls.find_all().update_many( *args, session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) def set( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Set values Example: ```python class Sample(Document): one: int await Document.find(Sample.one == 1).set({Sample.one: 100}) ``` Uses [Set operator](operators/update.md#set) :param expression: Dict[Union[ExpressionField, str], Any] - keys and values to set :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( SetOperator(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) def current_date( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Set current date Uses [CurrentDate operator](operators/update.md#currentdate) :param expression: Dict[Union[ExpressionField, str], Any] :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( CurrentDate(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) def inc( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Increment Example: ```python class Sample(Document): one: int await Document.find(Sample.one == 1).inc({Sample.one: 100}) ``` Uses [Inc operator](operators/update.md#inc) :param expression: Dict[Union[ExpressionField, str], Any] :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( Inc(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) async def delete( self, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, link_rule: DeleteRules = DeleteRules.DO_NOTHING, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, **pymongo_kwargs, ) -> Optional[DeleteResult]: """ Delete the document :param session: Optional[ClientSession] - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param link_rule: DeleteRules - rules for link fields :param **pymongo_kwargs: pymongo native parameters for delete operation :return: Optional[DeleteResult] - pymongo DeleteResult instance. """ if link_rule == DeleteRules.DELETE_LINKS: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.delete( link_rule=DeleteRules.DELETE_LINKS, **pymongo_kwargs, ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.delete( link_rule=DeleteRules.DELETE_LINKS, **pymongo_kwargs, ) for obj in value if isinstance(obj, Document) ] ) return await self.find_one({"_id": self.id}).delete( session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) async def delete_all( cls, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, **pymongo_kwargs, ) -> Optional[DeleteResult]: """ Delete all the documents :param session: Optional[ClientSession] - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param **pymongo_kwargs: pymongo native parameters for delete operation :return: Optional[DeleteResult] - pymongo DeleteResult instance. """ return await cls.find_all().delete( session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) # State management def use_state_management(cls) -> bool: """ Is state management turned on :return: bool """ return cls.get_settings().use_state_management def state_management_save_previous(cls) -> bool: """ Should we save the previous state after a commit to database :return: bool """ return cls.get_settings().state_management_save_previous def state_management_replace_objects(cls) -> bool: """ Should objects be replaced when using state management :return: bool """ return cls.get_settings().state_management_replace_objects def _save_state(self) -> None: """ Save current document state. Internal method :return: None """ if self.use_state_management() and self.id is not None: if self.state_management_save_previous(): self._previous_saved_state = self._saved_state self._saved_state = get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ) def get_saved_state(self) -> Optional[Dict[str, Any]]: """ Saved state getter. It is protected property. :return: Optional[Dict[str, Any]] - saved state """ return self._saved_state def get_previous_saved_state(self) -> Optional[Dict[str, Any]]: """ Previous state getter. It is a protected property. :return: Optional[Dict[str, Any]] - previous state """ return self._previous_saved_state def is_changed(self) -> bool: if self._saved_state == get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ): return False return True def has_changed(self) -> bool: if ( self._previous_saved_state is None or self._previous_saved_state == self._saved_state ): return False return True def _collect_updates( self, old_dict: Dict[str, Any], new_dict: Dict[str, Any] ) -> Dict[str, Any]: """ Compares old_dict with new_dict and returns field paths that have been updated Args: old_dict: dict1 new_dict: dict2 Returns: dictionary with updates """ updates = {} if old_dict.keys() - new_dict.keys(): updates = new_dict else: for field_name, field_value in new_dict.items(): if field_value != old_dict.get(field_name): if not self.state_management_replace_objects() and ( isinstance(field_value, dict) and isinstance(old_dict.get(field_name), dict) ): if old_dict.get(field_name) is None: updates[field_name] = field_value elif isinstance(field_value, dict) and isinstance( old_dict.get(field_name), dict ): field_data = self._collect_updates( old_dict.get(field_name), # type: ignore field_value, ) for k, v in field_data.items(): updates[f"{field_name}.{k}"] = v else: updates[field_name] = field_value return updates def get_changes(self) -> Dict[str, Any]: return self._collect_updates( self._saved_state, # type: ignore get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ), ) def get_previous_changes(self) -> Dict[str, Any]: if self._previous_saved_state is None: return {} return self._collect_updates( self._previous_saved_state, self._saved_state, # type: ignore ) def rollback(self) -> None: if self.is_changed: for key, value in self._saved_state.items(): # type: ignore if key == "_id": setattr(self, "id", value) else: setattr(self, key, value) # Other def get_settings(cls) -> DocumentSettings: """ Get document settings, which was created on the initialization step :return: DocumentSettings class """ if cls._document_settings is None: raise CollectionWasNotInitialized return cls._document_settings async def inspect_collection( cls, session: Optional[ClientSession] = None ) -> InspectionResult: """ Check, if documents, stored in the MongoDB collection are compatible with the Document schema :return: InspectionResult """ inspection_result = InspectionResult() async for json_document in cls.get_motor_collection().find( {}, session=session ): try: parse_model(cls, json_document) except ValidationError as e: if inspection_result.status == InspectionStatuses.OK: inspection_result.status = InspectionStatuses.FAIL inspection_result.errors.append( InspectionError( document_id=json_document["_id"], error=str(e) ) ) return inspection_result def check_hidden_fields(cls): hidden_fields = [ (name, field) for name, field in get_model_fields(cls).items() if get_extra_field_info(field, "hidden") is True ] if not hidden_fields: return warnings.warn( f"{cls.__name__}: 'hidden=True' is deprecated, please use 'exclude=True'", DeprecationWarning, ) if IS_PYDANTIC_V2: for name, field in hidden_fields: field.exclude = True del field.json_schema_extra["hidden"] cls.model_rebuild(force=True) else: for name, field in hidden_fields: field.field_info.exclude = True del field.field_info.extra["hidden"] cls.__exclude_fields__[name] = True async def validate_self(self, *args, **kwargs): # TODO: it can be sync, but needs some actions controller improvements if self.get_settings().validate_on_save: new_model = parse_model(self.__class__, get_model_dump(self)) merge_models(self, new_model) def to_ref(self): if self.id is None: raise DocumentWasNotSaved("Can not create dbref without id") return DBRef(self.get_motor_collection().name, self.id) async def fetch_link(self, field: Union[str, Any]): ref_obj = getattr(self, field, None) if isinstance(ref_obj, Link): value = await ref_obj.fetch(fetch_links=True) setattr(self, field, value) if isinstance(ref_obj, list) and ref_obj: values = await Link.fetch_list(ref_obj, fetch_links=True) setattr(self, field, values) async def fetch_all_links(self): coros = [] link_fields = self.get_link_fields() if link_fields is not None: for ref in link_fields.values(): coros.append(self.fetch_link(ref.field_name)) # TODO lists await asyncio.gather(*coros) def get_link_fields(cls) -> Optional[Dict[str, LinkInfo]]: return cls._link_fields def get_model_type(cls) -> ModelType: return ModelType.Document async def distinct( cls, key: str, filter: Optional[Mapping[str, Any]] = None, session: Optional[ClientSession] = None, **kwargs: Any, ) -> list: return await cls.get_motor_collection().distinct( key, filter, session, **kwargs ) def link_from_id(cls, id: Any): ref = DBRef(id=id, collection=cls.get_collection_name()) return Link(ref, document_class=cls) def parse_model(model_type: Type[BaseModel], data: Any): if IS_PYDANTIC_V2: return model_type.model_validate(data) else: return model_type.parse_obj(data) def iterative_migration( document_models: Optional[List[Type[Document]]] = None, batch_size: int = 10000, ): class IterativeMigration(BaseMigrationController): def __init__(self, function): self.function = function self.function_signature = signature(function) input_signature = self.function_signature.parameters.get( "input_document" ) if input_signature is None: raise RuntimeError("input_signature must not be None") self.input_document_model: Type[ Document ] = input_signature.annotation output_signature = self.function_signature.parameters.get( "output_document" ) if output_signature is None: raise RuntimeError("output_signature must not be None") self.output_document_model: Type[ Document ] = output_signature.annotation if ( not isclass(self.input_document_model) or not issubclass(self.input_document_model, Document) or not isclass(self.output_document_model) or not issubclass(self.output_document_model, Document) ): raise TypeError( "input_document and output_document " "must have annotation of Document subclass" ) self.batch_size = batch_size def __call__(self, *args, **kwargs): pass @property def models(self) -> List[Type[Document]]: preset_models = document_models if preset_models is None: preset_models = [] return preset_models + [ self.input_document_model, self.output_document_model, ] async def run(self, session): output_documents = [] all_migration_ops = [] async for input_document in self.input_document_model.find_all( session=session ): output = DummyOutput() function_kwargs = { "input_document": input_document, "output_document": output, } if "self" in self.function_signature.parameters: function_kwargs["self"] = None await self.function(**function_kwargs) output_dict = input_document.dict() update_dict(output_dict, output.dict()) output_document = parse_model( self.output_document_model, output_dict ) output_documents.append(output_document) if len(output_documents) == self.batch_size: all_migration_ops.append( self.output_document_model.replace_many( documents=output_documents, session=session ) ) output_documents = [] if output_documents: all_migration_ops.append( self.output_document_model.replace_many( documents=output_documents, session=session ) ) await asyncio.gather(*all_migration_ops) return IterativeMigration
null
167,786
import pydantic def is_second_version() -> bool: return int(pydantic.VERSION.split(".")[0]) >= 2
null
167,787
import asyncio import logging import os import shutil from datetime import datetime from pathlib import Path from typing import Any import click import toml from beanie.migrations import template from beanie.migrations.database import DBHandler from beanie.migrations.models import RunningDirections, RunningMode from beanie.migrations.runner import MigrationNode def migrations(): pass
null
167,788
import asyncio import logging import os import shutil from datetime import datetime from pathlib import Path from typing import Any import click import toml from beanie.migrations import template from beanie.migrations.database import DBHandler from beanie.migrations.models import RunningDirections, RunningMode from beanie.migrations.runner import MigrationNode class MigrationSettings: def __init__(self, **kwargs): def get_env_value(field_name) -> Any: def get_from_toml(field_name) -> Any: async def run_migrate(settings: MigrationSettings): def migrate( direction, distance, connection_uri, database_name, path, allow_index_dropping, use_transaction, ): settings_kwargs = {} if direction: settings_kwargs["direction"] = direction if distance: settings_kwargs["distance"] = distance if connection_uri: settings_kwargs["connection_uri"] = connection_uri if database_name: settings_kwargs["database_name"] = database_name if path: settings_kwargs["path"] = path if allow_index_dropping: settings_kwargs["allow_index_dropping"] = allow_index_dropping settings_kwargs["use_transaction"] = use_transaction settings = MigrationSettings(**settings_kwargs) asyncio.run(run_migrate(settings))
null
167,789
import asyncio import logging import os import shutil from datetime import datetime from pathlib import Path from typing import Any import click import toml from beanie.migrations import template from beanie.migrations.database import DBHandler from beanie.migrations.models import RunningDirections, RunningMode from beanie.migrations.runner import MigrationNode def new_migration(name, path): path = Path(path) ts_string = datetime.now().strftime("%Y%m%d%H%M%S") file_name = f"{ts_string}_{name}.py" shutil.copy(template.__file__, path / file_name)
null
167,790
import asyncio import inspect from enum import Enum from functools import wraps from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union, ) class EventTypes(str, Enum): INSERT = "INSERT" REPLACE = "REPLACE" SAVE = "SAVE" SAVE_CHANGES = "SAVE_CHANGES" VALIDATE_ON_SAVE = "VALIDATE_ON_SAVE" DELETE = "DELETE" UPDATE = "UPDATE" class ActionDirections(str, Enum): # TODO think about this name BEFORE = "BEFORE" AFTER = "AFTER" def register_action( event_types: Tuple[Union[List[EventTypes], EventTypes]], action_direction: ActionDirections, ): """ Decorator. Base registration method. Used inside `before_event` and `after_event` :param event_types: Union[List[EventTypes], EventTypes] - event types :param action_direction: ActionDirections - before or after :return: """ final_event_types = [] for event_type in event_types: if isinstance(event_type, list): final_event_types.extend(event_type) else: final_event_types.append(event_type) def decorator(f): f.has_action = True f.event_types = final_event_types f.action_direction = action_direction return f return decorator The provided code snippet includes necessary dependencies for implementing the `before_event` function. Write a Python function `def before_event(*args: Union[List[EventTypes], EventTypes])` to solve the following problem: Decorator. It adds action, which should run before mentioned one or many events happen :param args: Union[List[EventTypes], EventTypes] - event types :return: None Here is the function: def before_event(*args: Union[List[EventTypes], EventTypes]): """ Decorator. It adds action, which should run before mentioned one or many events happen :param args: Union[List[EventTypes], EventTypes] - event types :return: None """ return register_action( action_direction=ActionDirections.BEFORE, event_types=args # type: ignore )
Decorator. It adds action, which should run before mentioned one or many events happen :param args: Union[List[EventTypes], EventTypes] - event types :return: None
167,791
import asyncio import inspect from enum import Enum from functools import wraps from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union, ) class EventTypes(str, Enum): INSERT = "INSERT" REPLACE = "REPLACE" SAVE = "SAVE" SAVE_CHANGES = "SAVE_CHANGES" VALIDATE_ON_SAVE = "VALIDATE_ON_SAVE" DELETE = "DELETE" UPDATE = "UPDATE" class ActionDirections(str, Enum): # TODO think about this name BEFORE = "BEFORE" AFTER = "AFTER" def register_action( event_types: Tuple[Union[List[EventTypes], EventTypes]], action_direction: ActionDirections, ): """ Decorator. Base registration method. Used inside `before_event` and `after_event` :param event_types: Union[List[EventTypes], EventTypes] - event types :param action_direction: ActionDirections - before or after :return: """ final_event_types = [] for event_type in event_types: if isinstance(event_type, list): final_event_types.extend(event_type) else: final_event_types.append(event_type) def decorator(f): f.has_action = True f.event_types = final_event_types f.action_direction = action_direction return f return decorator The provided code snippet includes necessary dependencies for implementing the `after_event` function. Write a Python function `def after_event(*args: Union[List[EventTypes], EventTypes])` to solve the following problem: Decorator. It adds action, which should run after mentioned one or many events happen :param args: Union[List[EventTypes], EventTypes] - event types :return: None Here is the function: def after_event(*args: Union[List[EventTypes], EventTypes]): """ Decorator. It adds action, which should run after mentioned one or many events happen :param args: Union[List[EventTypes], EventTypes] - event types :return: None """ return register_action( action_direction=ActionDirections.AFTER, event_types=args # type: ignore )
Decorator. It adds action, which should run after mentioned one or many events happen :param args: Union[List[EventTypes], EventTypes] - event types :return: None
167,792
import asyncio import inspect from enum import Enum from functools import wraps from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union, ) class EventTypes(str, Enum): INSERT = "INSERT" REPLACE = "REPLACE" SAVE = "SAVE" SAVE_CHANGES = "SAVE_CHANGES" VALIDATE_ON_SAVE = "VALIDATE_ON_SAVE" DELETE = "DELETE" UPDATE = "UPDATE" class ActionDirections(str, Enum): # TODO think about this name BEFORE = "BEFORE" AFTER = "AFTER" class ActionRegistry: _actions: Dict[ Type["Document"], Dict[EventTypes, Dict[ActionDirections, List[Callable[..., Any]]]], ] = {} def clean_actions(cls, document_class: Type["Document"]): if cls._actions.get(document_class) is not None: del cls._actions[document_class] def add_action( cls, document_class: Type["Document"], event_types: List[EventTypes], action_direction: ActionDirections, funct: Callable, ): """ Add action to the action registry :param document_class: document class :param event_types: List[EventTypes] :param action_direction: ActionDirections - before or after :param funct: Callable - function """ if cls._actions.get(document_class) is None: cls._actions[document_class] = { action_type: { action_direction: [] for action_direction in ActionDirections } for action_type in EventTypes } for event_type in event_types: cls._actions[document_class][event_type][action_direction].append( funct ) def get_action_list( cls, document_class: Type["Document"], event_type: EventTypes, action_direction: ActionDirections, ) -> List[Callable]: """ Get stored action list :param document_class: Type - document class :param event_type: EventTypes - type of needed event :param action_direction: ActionDirections - before or after :return: List[Callable] - list of stored methods """ if document_class not in cls._actions: return [] return cls._actions[document_class][event_type][action_direction] async def run_actions( cls, instance: "Document", event_type: EventTypes, action_direction: ActionDirections, exclude: List[Union[ActionDirections, str]], ): """ Run actions :param instance: Document - object of the Document subclass :param event_type: EventTypes - event types :param action_direction: ActionDirections - before or after """ if action_direction in exclude: return document_class = instance.__class__ actions_list = cls.get_action_list( document_class, event_type, action_direction ) coros = [] for action in actions_list: if action.__name__ in exclude: continue if inspect.iscoroutinefunction(action): coros.append(action(instance)) elif inspect.isfunction(action): action(instance) await asyncio.gather(*coros) The provided code snippet includes necessary dependencies for implementing the `wrap_with_actions` function. Write a Python function `def wrap_with_actions(event_type: EventTypes)` to solve the following problem: Helper function to wrap Document methods with before and after event listeners :param event_type: EventTypes - event types :return: None Here is the function: def wrap_with_actions(event_type: EventTypes): """ Helper function to wrap Document methods with before and after event listeners :param event_type: EventTypes - event types :return: None """ def decorator(f: Callable): @wraps(f) async def wrapper( self, *args, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, **kwargs, ): if skip_actions is None: skip_actions = [] await ActionRegistry.run_actions( self, event_type=event_type, action_direction=ActionDirections.BEFORE, exclude=skip_actions, ) result = await f(self, *args, skip_actions=skip_actions, **kwargs) await ActionRegistry.run_actions( self, event_type=event_type, action_direction=ActionDirections.AFTER, exclude=skip_actions, ) return result return wrapper return decorator
Helper function to wrap Document methods with before and after event listeners :param event_type: EventTypes - event types :return: None
167,793
from typing import Any import bson import pydantic from typing_extensions import Annotated from beanie.odm.utils.pydantic import IS_PYDANTIC_V2 def _to_bson_binary(value: Any) -> bson.Binary: return value if isinstance(value, bson.Binary) else bson.Binary(value)
null
167,794
import asyncio import warnings from enum import Enum from typing import ( Any, ClassVar, Dict, Iterable, List, Mapping, Optional, Type, TypeVar, Union, ) from uuid import UUID, uuid4 from bson import DBRef, ObjectId from lazy_model import LazyModel from pydantic import ( ConfigDict, Field, PrivateAttr, ValidationError, ) from pydantic.class_validators import root_validator from pydantic.main import BaseModel from pymongo import InsertOne from pymongo.client_session import ClientSession from pymongo.errors import DuplicateKeyError from pymongo.results import ( DeleteResult, InsertManyResult, ) from beanie.exceptions import ( CollectionWasNotInitialized, DocumentNotFound, DocumentWasNotSaved, NotSupported, ReplaceError, RevisionIdWasChanged, ) from beanie.odm.actions import ( ActionDirections, EventTypes, wrap_with_actions, ) from beanie.odm.bulk import BulkWriter, Operation from beanie.odm.cache import LRUCache from beanie.odm.fields import ( BackLink, DeleteRules, ExpressionField, Link, LinkInfo, LinkTypes, PydanticObjectId, WriteRules, ) from beanie.odm.interfaces.aggregate import AggregateInterface from beanie.odm.interfaces.detector import ModelType from beanie.odm.interfaces.find import FindInterface from beanie.odm.interfaces.getters import OtherGettersInterface from beanie.odm.interfaces.inheritance import InheritanceInterface from beanie.odm.interfaces.setters import SettersInterface from beanie.odm.models import ( InspectionError, InspectionResult, InspectionStatuses, ) from beanie.odm.operators.find.comparison import In from beanie.odm.operators.update.general import ( CurrentDate, Inc, SetRevisionId, Unset, ) from beanie.odm.operators.update.general import ( Set as SetOperator, ) from beanie.odm.queries.update import UpdateMany, UpdateResponse from beanie.odm.settings.document import DocumentSettings from beanie.odm.utils.dump import get_dict, get_top_level_nones from beanie.odm.utils.parsing import apply_changes, merge_models from beanie.odm.utils.pydantic import ( IS_PYDANTIC_V2, get_extra_field_info, get_field_type, get_model_dump, get_model_fields, parse_model, parse_object_as, ) from beanie.odm.utils.self_validation import validate_self_before from beanie.odm.utils.state import ( previous_saved_state_needed, save_state_after, saved_state_needed, ) from beanie.odm.utils.typing import extract_id_class if IS_PYDANTIC_V2: from pydantic import model_validator IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2 if IS_PYDANTIC_V2: from pydantic import TypeAdapter else: from pydantic import parse_obj_as def get_model_fields(model): if IS_PYDANTIC_V2: return model.model_fields else: return model.__fields__ def json_schema_extra(schema: Dict[str, Any], model: Type["Document"]) -> None: # remove excluded fields from the json schema properties = schema.get("properties") if not properties: return for k, field in get_model_fields(model).items(): k = field.alias or k if k not in properties: continue field_info = field if IS_PYDANTIC_V2 else field.field_info if field_info.exclude: del properties[k]
null
167,795
import asyncio import warnings from enum import Enum from typing import ( Any, ClassVar, Dict, Iterable, List, Mapping, Optional, Type, TypeVar, Union, ) from uuid import UUID, uuid4 from bson import DBRef, ObjectId from lazy_model import LazyModel from pydantic import ( ConfigDict, Field, PrivateAttr, ValidationError, ) from pydantic.class_validators import root_validator from pydantic.main import BaseModel from pymongo import InsertOne from pymongo.client_session import ClientSession from pymongo.errors import DuplicateKeyError from pymongo.results import ( DeleteResult, InsertManyResult, ) from beanie.exceptions import ( CollectionWasNotInitialized, DocumentNotFound, DocumentWasNotSaved, NotSupported, ReplaceError, RevisionIdWasChanged, ) from beanie.odm.actions import ( ActionDirections, EventTypes, wrap_with_actions, ) from beanie.odm.bulk import BulkWriter, Operation from beanie.odm.cache import LRUCache from beanie.odm.fields import ( BackLink, DeleteRules, ExpressionField, Link, LinkInfo, LinkTypes, PydanticObjectId, WriteRules, ) from beanie.odm.interfaces.aggregate import AggregateInterface from beanie.odm.interfaces.detector import ModelType from beanie.odm.interfaces.find import FindInterface from beanie.odm.interfaces.getters import OtherGettersInterface from beanie.odm.interfaces.inheritance import InheritanceInterface from beanie.odm.interfaces.setters import SettersInterface from beanie.odm.models import ( InspectionError, InspectionResult, InspectionStatuses, ) from beanie.odm.operators.find.comparison import In from beanie.odm.operators.update.general import ( CurrentDate, Inc, SetRevisionId, Unset, ) from beanie.odm.operators.update.general import ( Set as SetOperator, ) from beanie.odm.queries.update import UpdateMany, UpdateResponse from beanie.odm.settings.document import DocumentSettings from beanie.odm.utils.dump import get_dict, get_top_level_nones from beanie.odm.utils.parsing import apply_changes, merge_models from beanie.odm.utils.pydantic import ( IS_PYDANTIC_V2, get_extra_field_info, get_field_type, get_model_dump, get_model_fields, parse_model, parse_object_as, ) from beanie.odm.utils.self_validation import validate_self_before from beanie.odm.utils.state import ( previous_saved_state_needed, save_state_after, saved_state_needed, ) from beanie.odm.utils.typing import extract_id_class def document_alias_generator(s: str) -> str: if s == "id": return "_id" return s
null
167,796
import asyncio import sys from collections import OrderedDict from dataclasses import dataclass from enum import Enum from typing import ( TYPE_CHECKING, Any, Dict, Generic, List, Optional, Type, TypeVar, Union, ) from typing import OrderedDict as OrderedDictType from typing import Tuple from bson import DBRef, ObjectId from bson.errors import InvalidId from pydantic import BaseModel from pymongo import ASCENDING, IndexModel from beanie.odm.enums import SortDirection from beanie.odm.operators.find.comparison import ( GT, GTE, LT, LTE, NE, Eq, In, ) from beanie.odm.registry import DocsRegistry from beanie.odm.utils.parsing import parse_obj from beanie.odm.utils.pydantic import ( IS_PYDANTIC_V2, get_field_type, get_model_fields, parse_object_as, ) if IS_PYDANTIC_V2: from pydantic import ( GetCoreSchemaHandler, GetJsonSchemaHandler, TypeAdapter, ) from pydantic.json_schema import JsonSchemaValue from pydantic_core import CoreSchema, core_schema from pydantic_core.core_schema import ( ValidationInfo, simple_ser_schema, str_schema, ) else: from pydantic.fields import ModelField # type: ignore from pydantic.json import ENCODERS_BY_TYPE class IndexedAnnotation: _indexed: Tuple[int, Dict[str, Any]] if not IS_PYDANTIC_V2: ENCODERS_BY_TYPE[ PydanticObjectId ] = str # it is a workaround to force pydantic make json schema for this field if not IS_PYDANTIC_V2: ENCODERS_BY_TYPE[Link] = lambda o: o.to_dict() if not IS_PYDANTIC_V2: ENCODERS_BY_TYPE[BackLink] = lambda o: o.to_dict() IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2 if IS_PYDANTIC_V2: from pydantic import TypeAdapter else: from pydantic import parse_obj_as The provided code snippet includes necessary dependencies for implementing the `Indexed` function. Write a Python function `def Indexed(typ=None, index_type=ASCENDING, **kwargs)` to solve the following problem: If `typ` is defined, returns a subclass of `typ` with an extra attribute `_indexed` as a tuple: - Index 0: `index_type` such as `pymongo.ASCENDING` - Index 1: `kwargs` passed to `IndexModel` When instantiated the type of the result will actually be `typ`. When `typ` is not defined, returns an `IndexedAnnotation` instance, to be used as metadata in `Annotated` fields. Example: ```py # Both fields would have the same behavior class MyModel(BaseModel): field1: Indexed(str, unique=True) field2: Annotated[str, Indexed(unique=True)] ``` Here is the function: def Indexed(typ=None, index_type=ASCENDING, **kwargs): """ If `typ` is defined, returns a subclass of `typ` with an extra attribute `_indexed` as a tuple: - Index 0: `index_type` such as `pymongo.ASCENDING` - Index 1: `kwargs` passed to `IndexModel` When instantiated the type of the result will actually be `typ`. When `typ` is not defined, returns an `IndexedAnnotation` instance, to be used as metadata in `Annotated` fields. Example: ```py # Both fields would have the same behavior class MyModel(BaseModel): field1: Indexed(str, unique=True) field2: Annotated[str, Indexed(unique=True)] ``` """ if typ is None: return IndexedAnnotation(_indexed=(index_type, kwargs)) class NewType(typ): _indexed = (index_type, kwargs) def __new__(cls, *args, **kwargs): return typ.__new__(typ, *args, **kwargs) if IS_PYDANTIC_V2: @classmethod def __get_pydantic_core_schema__( cls, _source_type: Any, _handler: GetCoreSchemaHandler ) -> core_schema.CoreSchema: custom_type = getattr( typ, "__get_pydantic_core_schema__", None ) if custom_type is not None: return custom_type(_source_type, _handler) return core_schema.no_info_after_validator_function( lambda v: v, simple_ser_schema(typ.__name__), ) NewType.__name__ = f"Indexed {typ.__name__}" return NewType
If `typ` is defined, returns a subclass of `typ` with an extra attribute `_indexed` as a tuple: - Index 0: `index_type` such as `pymongo.ASCENDING` - Index 1: `kwargs` passed to `IndexModel` When instantiated the type of the result will actually be `typ`. When `typ` is not defined, returns an `IndexedAnnotation` instance, to be used as metadata in `Annotated` fields. Example: ```py # Both fields would have the same behavior class MyModel(BaseModel): field1: Indexed(str, unique=True) field2: Annotated[str, Indexed(unique=True)] ```
167,797
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type from beanie.odm.fields import LinkInfo, LinkTypes def construct_query( link_info: LinkInfo, queries: List, database_major_version: int, current_depth: Optional[int] = None, ): if link_info.is_fetchable is False or ( current_depth is not None and current_depth <= 0 ): return if link_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, ]: if database_major_version >= 5 or link_info.nested_links is None: lookup_steps = [ { "$lookup": { "from": link_info.document_class.get_motor_collection().name, # type: ignore "localField": f"{link_info.lookup_field_name}.$id", "foreignField": "_id", "as": f"_link_{link_info.field_name}", } }, { "$unwind": { "path": f"$_link_{link_info.field_name}", "preserveNullAndEmptyArrays": True, } }, { "$set": { link_info.field_name: { "$cond": { "if": { "$ifNull": [ f"$_link_{link_info.field_name}", False, ] }, "then": f"$_link_{link_info.field_name}", "else": f"${link_info.field_name}", } } } }, {"$unset": f"_link_{link_info.field_name}"}, ] # type: ignore new_depth = ( current_depth - 1 if current_depth is not None else None ) if link_info.nested_links is not None: lookup_steps[0]["$lookup"]["pipeline"] = [] # type: ignore for nested_link in link_info.nested_links: construct_query( link_info=link_info.nested_links[nested_link], queries=lookup_steps[0]["$lookup"]["pipeline"], # type: ignore database_major_version=database_major_version, current_depth=new_depth, ) queries += lookup_steps else: lookup_steps = [ { "$lookup": { "from": link_info.document_class.get_motor_collection().name, # type: ignore "let": { "link_id": f"${link_info.lookup_field_name}.$id" }, "as": f"_link_{link_info.field_name}", "pipeline": [ { "$match": { "$expr": {"$eq": ["$_id", "$$link_id"]} } }, ], } }, { "$unwind": { "path": f"$_link_{link_info.field_name}", "preserveNullAndEmptyArrays": True, } }, { "$set": { link_info.field_name: { "$cond": { "if": { "$ifNull": [ f"$_link_{link_info.field_name}", False, ] }, "then": f"$_link_{link_info.field_name}", "else": f"${link_info.field_name}", } } } }, {"$unset": f"_link_{link_info.field_name}"}, ] new_depth = ( current_depth - 1 if current_depth is not None else None ) for nested_link in link_info.nested_links: construct_query( link_info=link_info.nested_links[nested_link], queries=lookup_steps[0]["$lookup"]["pipeline"], # type: ignore database_major_version=database_major_version, current_depth=new_depth, ) queries += lookup_steps elif link_info.link_type in [ LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if database_major_version >= 5 or link_info.nested_links is None: lookup_steps = [ { "$lookup": { "from": link_info.document_class.get_motor_collection().name, # type: ignore "localField": "_id", "foreignField": f"{link_info.lookup_field_name}.$id", "as": f"_link_{link_info.field_name}", } }, { "$unwind": { "path": f"$_link_{link_info.field_name}", "preserveNullAndEmptyArrays": True, } }, { "$set": { link_info.field_name: { "$cond": { "if": { "$ifNull": [ f"$_link_{link_info.field_name}", False, ] }, "then": f"$_link_{link_info.field_name}", "else": f"${link_info.field_name}", } } } }, {"$unset": f"_link_{link_info.field_name}"}, ] # type: ignore new_depth = ( current_depth - 1 if current_depth is not None else None ) if link_info.nested_links is not None: lookup_steps[0]["$lookup"]["pipeline"] = [] # type: ignore for nested_link in link_info.nested_links: construct_query( link_info=link_info.nested_links[nested_link], queries=lookup_steps[0]["$lookup"]["pipeline"], # type: ignore database_major_version=database_major_version, current_depth=new_depth, ) queries += lookup_steps else: lookup_steps = [ { "$lookup": { "from": link_info.document_class.get_motor_collection().name, # type: ignore "let": {"link_id": "$_id"}, "as": f"_link_{link_info.field_name}", "pipeline": [ { "$match": { "$expr": { "$eq": [ f"${link_info.lookup_field_name}.$id", "$$link_id", ] } } }, ], } }, { "$unwind": { "path": f"$_link_{link_info.field_name}", "preserveNullAndEmptyArrays": True, } }, { "$set": { link_info.field_name: { "$cond": { "if": { "$ifNull": [ f"$_link_{link_info.field_name}", False, ] }, "then": f"$_link_{link_info.field_name}", "else": f"${link_info.field_name}", } } } }, {"$unset": f"_link_{link_info.field_name}"}, ] new_depth = ( current_depth - 1 if current_depth is not None else None ) for nested_link in link_info.nested_links: construct_query( link_info=link_info.nested_links[nested_link], queries=lookup_steps[0]["$lookup"]["pipeline"], # type: ignore database_major_version=database_major_version, current_depth=new_depth, ) queries += lookup_steps elif link_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, ]: if database_major_version >= 5 or link_info.nested_links is None: queries.append( { "$lookup": { "from": link_info.document_class.get_motor_collection().name, # type: ignore "localField": f"{link_info.lookup_field_name}.$id", "foreignField": "_id", "as": link_info.field_name, } } ) new_depth = ( current_depth - 1 if current_depth is not None else None ) if link_info.nested_links is not None: queries[-1]["$lookup"]["pipeline"] = [] for nested_link in link_info.nested_links: construct_query( link_info=link_info.nested_links[nested_link], queries=queries[-1]["$lookup"]["pipeline"], database_major_version=database_major_version, current_depth=new_depth, ) else: lookup_step = { "$lookup": { "from": link_info.document_class.get_motor_collection().name, # type: ignore "let": {"link_id": f"${link_info.lookup_field_name}.$id"}, "as": link_info.field_name, "pipeline": [ {"$match": {"$expr": {"$in": ["$_id", "$$link_id"]}}}, ], } } new_depth = ( current_depth - 1 if current_depth is not None else None ) for nested_link in link_info.nested_links: construct_query( link_info=link_info.nested_links[nested_link], queries=lookup_step["$lookup"]["pipeline"], database_major_version=database_major_version, current_depth=new_depth, ) queries.append(lookup_step) elif link_info.link_type in [ LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if database_major_version >= 5 or link_info.nested_links is None: queries.append( { "$lookup": { "from": link_info.document_class.get_motor_collection().name, # type: ignore "localField": "_id", "foreignField": f"{link_info.lookup_field_name}.$id", "as": link_info.field_name, } } ) new_depth = ( current_depth - 1 if current_depth is not None else None ) if link_info.nested_links is not None: queries[-1]["$lookup"]["pipeline"] = [] for nested_link in link_info.nested_links: construct_query( link_info=link_info.nested_links[nested_link], queries=queries[-1]["$lookup"]["pipeline"], database_major_version=database_major_version, current_depth=new_depth, ) else: lookup_step = { "$lookup": { "from": link_info.document_class.get_motor_collection().name, # type: ignore "let": {"link_id": "$_id"}, "as": link_info.field_name, "pipeline": [ { "$match": { "$expr": { "$in": [ "$$link_id", f"${link_info.lookup_field_name}.$id", ] } } } ], } } new_depth = ( current_depth - 1 if current_depth is not None else None ) for nested_link in link_info.nested_links: construct_query( link_info=link_info.nested_links[nested_link], queries=lookup_step["$lookup"]["pipeline"], database_major_version=database_major_version, current_depth=new_depth, ) queries.append(lookup_step) return queries def construct_lookup_queries( cls: Type["Document"], nesting_depth: Optional[int] = None, nesting_depths_per_field: Optional[Dict[str, int]] = None, ) -> List[Dict[str, Any]]: queries: List = [] link_fields = cls.get_link_fields() if link_fields is not None: for link_info in link_fields.values(): final_nesting_depth = ( nesting_depths_per_field.get(link_info.field_name, None) if nesting_depths_per_field is not None else None ) if final_nesting_depth is None: final_nesting_depth = nesting_depth construct_query( link_info=link_info, queries=queries, database_major_version=cls._database_major_version, current_depth=final_nesting_depth, ) return queries
null
167,798
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type from beanie.odm.fields import LinkInfo, LinkTypes The provided code snippet includes necessary dependencies for implementing the `split_text_query` function. Write a Python function `def split_text_query( query: Dict[str, Any] ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]` to solve the following problem: Divide query into text and non-text matches :param query: Dict[str, Any] - query dict :return: Tuple[Dict[str, Any], Dict[str, Any]] - text and non-text queries, respectively Here is the function: def split_text_query( query: Dict[str, Any] ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: """Divide query into text and non-text matches :param query: Dict[str, Any] - query dict :return: Tuple[Dict[str, Any], Dict[str, Any]] - text and non-text queries, respectively """ root_text_query_args: Dict[str, Any] = query.get("$text", None) root_non_text_queries: Dict[str, Any] = { k: v for k, v in query.items() if k not in {"$text", "$and"} } text_queries: List[Dict[str, Any]] = ( [{"$text": root_text_query_args}] if root_text_query_args else [] ) non_text_queries: List[Dict[str, Any]] = ( [root_non_text_queries] if root_non_text_queries else [] ) for match_case in query.get("$and", []): if "$text" in match_case: text_queries.append(match_case) else: non_text_queries.append(match_case) return text_queries, non_text_queries
Divide query into text and non-text matches :param query: Dict[str, Any] - query dict :return: Tuple[Dict[str, Any], Dict[str, Any]] - text and non-text queries, respectively
167,799
import asyncio import sys from beanie.odm.utils.pydantic import ( IS_PYDANTIC_V2, get_extra_field_info, get_model_fields, parse_model, ) from beanie.odm.utils.typing import get_index_attributes import importlib import inspect from typing import ( # type: ignore List, Optional, Type, Union, _GenericAlias, ) from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase from pydantic import BaseModel from pydantic.fields import FieldInfo from pymongo import IndexModel from beanie.exceptions import Deprecation, MongoDBVersionError from beanie.odm.actions import ActionRegistry from beanie.odm.cache import LRUCache from beanie.odm.documents import DocType, Document from beanie.odm.fields import ( BackLink, ExpressionField, Link, LinkInfo, LinkTypes, ) from beanie.odm.interfaces.detector import ModelType from beanie.odm.registry import DocsRegistry from beanie.odm.settings.document import DocumentSettings, IndexModelField from beanie.odm.settings.union_doc import UnionDocSettings from beanie.odm.settings.view import ViewSettings from beanie.odm.union_doc import UnionDoc from beanie.odm.views import View class Initializer: def __init__( self, database: AsyncIOMotorDatabase = None, connection_string: Optional[str] = None, document_models: Optional[ List[Union[Type["DocType"], Type["View"], str]] ] = None, allow_index_dropping: bool = False, recreate_views: bool = False, multiprocessing_mode: bool = False, ): """ Beanie initializer :param database: AsyncIOMotorDatabase - motor database instance :param connection_string: str - MongoDB connection string :param document_models: List[Union[Type[DocType], str]] - model classes or strings with dot separated paths :param allow_index_dropping: bool - if index dropping is allowed. Default False :param recreate_views: bool - if views should be recreated. Default False :param multiprocessing_mode: bool - if multiprocessing mode is on it will patch the motor client to use process's event loop. :return: None """ self.inited_classes: List[Type] = [] self.allow_index_dropping = allow_index_dropping self.recreate_views = recreate_views self.models_with_updated_forward_refs: List[Type[BaseModel]] = [] if (connection_string is None and database is None) or ( connection_string is not None and database is not None ): raise ValueError( "connection_string parameter or database parameter must be set" ) if document_models is None: raise ValueError("document_models parameter must be set") if connection_string is not None: database = AsyncIOMotorClient( connection_string ).get_default_database() self.database: AsyncIOMotorDatabase = database if multiprocessing_mode: self.database.client.get_io_loop = asyncio.get_running_loop sort_order = { ModelType.UnionDoc: 0, ModelType.Document: 1, ModelType.View: 2, } self.document_models: List[Union[Type[DocType], Type[View]]] = [ self.get_model(model) if isinstance(model, str) else model for model in document_models ] self.fill_docs_registry() self.document_models.sort( key=lambda val: sort_order[val.get_model_type()] ) def __await__(self): for model in self.document_models: yield from self.init_class(model).__await__() # General def fill_docs_registry(self): for model in self.document_models: module = inspect.getmodule(model) members = inspect.getmembers(module) for name, obj in members: if inspect.isclass(obj) and issubclass(obj, BaseModel): DocsRegistry.register(name, obj) def get_model(dot_path: str) -> Type["DocType"]: """ Get the model by the path in format bar.foo.Model :param dot_path: str - dot seprated path to the model :return: Type[DocType] - class of the model """ module_name, class_name = None, None try: module_name, class_name = dot_path.rsplit(".", 1) return getattr(importlib.import_module(module_name), class_name) except ValueError: raise ValueError( f"'{dot_path}' doesn't have '.' path, eg. path.to.your.model.class" ) except AttributeError: raise AttributeError( f"module '{module_name}' has no class called '{class_name}'" ) def init_settings( self, cls: Union[Type[Document], Type[View], Type[UnionDoc]] ): """ Init Settings :param cls: Union[Type[Document], Type[View], Type[UnionDoc]] - Class to init settings :return: None """ settings_class = getattr(cls, "Settings", None) settings_vars = ( {} if settings_class is None else dict(vars(settings_class)) ) if issubclass(cls, Document): cls._document_settings = parse_model( DocumentSettings, settings_vars ) if issubclass(cls, View): cls._settings = parse_model(ViewSettings, settings_vars) if issubclass(cls, UnionDoc): cls._settings = parse_model(UnionDocSettings, settings_vars) if not IS_PYDANTIC_V2: def update_forward_refs(self, cls: Type[BaseModel]): """ Update forward refs :param cls: Type[BaseModel] - class to update forward refs :return: None """ if cls not in self.models_with_updated_forward_refs: cls.update_forward_refs() self.models_with_updated_forward_refs.append(cls) # General. Relations def detect_link( self, field: FieldInfo, field_name: str ) -> Optional[LinkInfo]: """ It detects link and returns LinkInfo if any found. :param field: ModelField :return: Optional[LinkInfo] """ origin = get_origin(field.annotation) args = get_args(field.annotation) classes = [ Link, BackLink, ] for cls in classes: # Check if annotation is one of the custom classes if ( isinstance(field.annotation, _GenericAlias) and field.annotation.__origin__ is cls ): if cls is Link: return LinkInfo( field_name=field_name, lookup_field_name=field_name, document_class=DocsRegistry.evaluate_fr(args[0]), # type: ignore link_type=LinkTypes.DIRECT, ) if cls is BackLink: return LinkInfo( field_name=field_name, lookup_field_name=get_extra_field_info( field, "original_field" ), # type: ignore document_class=DocsRegistry.evaluate_fr(args[0]), # type: ignore link_type=LinkTypes.BACK_DIRECT, ) # Check if annotation is List[custom class] elif ( (origin is List or origin is list) and len(args) == 1 and isinstance(args[0], _GenericAlias) and args[0].__origin__ is cls ): if cls is Link: return LinkInfo( field_name=field_name, lookup_field_name=field_name, document_class=DocsRegistry.evaluate_fr(get_args(args[0])[0]), # type: ignore link_type=LinkTypes.LIST, ) if cls is BackLink: return LinkInfo( field_name=field_name, lookup_field_name=get_extra_field_info( # type: ignore field, "original_field" ), document_class=DocsRegistry.evaluate_fr(get_args(args[0])[0]), # type: ignore link_type=LinkTypes.BACK_LIST, ) # Check if annotation is Optional[custom class] or Optional[List[custom class]] elif origin is Union and len(args) == 2 and args[1] is type(None): optional_origin = get_origin(args[0]) optional_args = get_args(args[0]) if ( isinstance(args[0], _GenericAlias) and args[0].__origin__ is cls ): if cls is Link: return LinkInfo( field_name=field_name, lookup_field_name=field_name, document_class=DocsRegistry.evaluate_fr(optional_args[0]), # type: ignore link_type=LinkTypes.OPTIONAL_DIRECT, ) if cls is BackLink: return LinkInfo( field_name=field_name, lookup_field_name=get_extra_field_info( field, "original_field" ), document_class=DocsRegistry.evaluate_fr(optional_args[0]), # type: ignore link_type=LinkTypes.OPTIONAL_BACK_DIRECT, ) elif ( (optional_origin is List or optional_origin is list) and len(optional_args) == 1 and isinstance(optional_args[0], _GenericAlias) and optional_args[0].__origin__ is cls ): if cls is Link: return LinkInfo( field_name=field_name, lookup_field_name=field_name, document_class=DocsRegistry.evaluate_fr(get_args(optional_args[0])[0]), # type: ignore link_type=LinkTypes.OPTIONAL_LIST, ) if cls is BackLink: return LinkInfo( field_name=field_name, lookup_field_name=get_extra_field_info( field, "original_field" ), document_class=DocsRegistry.evaluate_fr(get_args(optional_args[0])[0]), # type: ignore link_type=LinkTypes.OPTIONAL_BACK_LIST, ) return None def check_nested_links(self, link_info: LinkInfo, current_depth: int): if current_depth == 1: return for k, v in get_model_fields(link_info.document_class).items(): nested_link_info = self.detect_link(v, k) if nested_link_info is None: continue if link_info.nested_links is None: link_info.nested_links = {} link_info.nested_links[k] = nested_link_info new_depth = ( current_depth - 1 if current_depth is not None else None ) self.check_nested_links(nested_link_info, current_depth=new_depth) # Document def set_default_class_vars(cls: Type[Document]): """ Set default class variables. :param cls: Union[Type[Document], Type[View], Type[UnionDoc]] - Class to init settings :return: """ cls._children = dict() cls._parent = None cls._inheritance_inited = False cls._class_id = None cls._link_fields = None def init_cache(cls) -> None: """ Init model's cache :return: None """ if cls.get_settings().use_cache: cls._cache = LRUCache( capacity=cls.get_settings().cache_capacity, expiration_time=cls.get_settings().cache_expiration_time, ) def init_document_fields(self, cls) -> None: """ Init class fields :return: None """ if not IS_PYDANTIC_V2: self.update_forward_refs(cls) if cls._link_fields is None: cls._link_fields = {} for k, v in get_model_fields(cls).items(): path = v.alias or k setattr(cls, k, ExpressionField(path)) link_info = self.detect_link(v, k) depth_level = cls.get_settings().max_nesting_depths_per_field.get( k, None ) if depth_level is None: depth_level = cls.get_settings().max_nesting_depth if link_info is not None: if depth_level > 0 or depth_level is None: cls._link_fields[k] = link_info self.check_nested_links( link_info, current_depth=depth_level ) elif depth_level <= 0: link_info.is_fetchable = False cls._link_fields[k] = link_info cls.check_hidden_fields() def init_actions(cls): """ Init event-based actions """ ActionRegistry.clean_actions(cls) for attr in dir(cls): f = getattr(cls, attr) if inspect.isfunction(f): if hasattr(f, "has_action"): ActionRegistry.add_action( document_class=cls, event_types=f.event_types, # type: ignore action_direction=f.action_direction, # type: ignore funct=f, ) async def init_document_collection(self, cls): """ Init collection for the Document-based class :param cls: :return: """ cls.set_database(self.database) document_settings = cls.get_settings() # register in the Union Doc if document_settings.union_doc is not None: name = cls.get_settings().name or cls.__name__ document_settings.name = document_settings.union_doc.register_doc( name, cls ) document_settings.union_doc_alias = name # set a name if not document_settings.name: document_settings.name = cls.__name__ # check mongodb version fits if ( document_settings.timeseries is not None and cls._database_major_version < 5 ): raise MongoDBVersionError( "Timeseries are supported by MongoDB version 5 and higher" ) # create motor collection if ( document_settings.timeseries is not None and document_settings.name not in await self.database.list_collection_names( authorizedCollections=True, nameOnly=True ) ): collection = await self.database.create_collection( **document_settings.timeseries.build_query( document_settings.name ) ) else: collection = self.database[document_settings.name] cls.set_collection(collection) async def init_indexes(self, cls, allow_index_dropping: bool = False): """ Async indexes initializer """ collection = cls.get_motor_collection() document_settings = cls.get_settings() index_information = await collection.index_information() old_indexes = IndexModelField.from_motor_index_information( index_information ) new_indexes = [] # Indexed field wrapped with Indexed() indexed_fields = ( (k, fvalue, get_index_attributes(fvalue)) for k, fvalue in get_model_fields(cls).items() ) found_indexes = [ IndexModelField( IndexModel( [ ( fvalue.alias or k, indexed_attrs[0], ) ], **indexed_attrs[1], ) ) for k, fvalue, indexed_attrs in indexed_fields if indexed_attrs is not None ] if document_settings.merge_indexes: result: List[IndexModelField] = [] for subclass in reversed(cls.mro()): if issubclass(subclass, Document) and not subclass == Document: if ( subclass not in self.inited_classes and not subclass == cls ): await self.init_class(subclass) if subclass.get_settings().indexes: result = IndexModelField.merge_indexes( result, subclass.get_settings().indexes ) found_indexes = IndexModelField.merge_indexes( found_indexes, result ) else: if document_settings.indexes: found_indexes = IndexModelField.merge_indexes( found_indexes, document_settings.indexes ) new_indexes += found_indexes # delete indexes # Only drop indexes if the user specifically allows for it if allow_index_dropping: for index in IndexModelField.list_difference( old_indexes, new_indexes ): await collection.drop_index(index.name) # create indices if found_indexes: new_indexes += await collection.create_indexes( IndexModelField.list_to_index_model(new_indexes) ) async def init_document(self, cls: Type[Document]) -> Optional[Output]: """ Init Document-based class :param cls: :return: """ if cls is Document: return None # get db version build_info = await self.database.command({"buildInfo": 1}) mongo_version = build_info["version"] cls._database_major_version = int(mongo_version.split(".")[0]) if cls not in self.inited_classes: self.set_default_class_vars(cls) self.init_settings(cls) bases = [b for b in cls.__bases__ if issubclass(b, Document)] if len(bases) > 1: return None parent = bases[0] output = await self.init_document(parent) if cls.get_settings().is_root and ( parent is Document or not parent.get_settings().is_root ): if cls.get_collection_name() is None: cls.set_collection_name(cls.__name__) output = Output( class_name=cls.__name__, collection_name=cls.get_collection_name(), ) cls._class_id = cls.__name__ cls._inheritance_inited = True elif output is not None: output.class_name = f"{output.class_name}.{cls.__name__}" cls._class_id = output.class_name cls.set_collection_name(output.collection_name) parent.add_child(cls._class_id, cls) cls._parent = parent cls._inheritance_inited = True await self.init_document_collection(cls) await self.init_indexes(cls, self.allow_index_dropping) self.init_document_fields(cls) self.init_cache(cls) self.init_actions(cls) self.inited_classes.append(cls) return output else: if cls._inheritance_inited is True: return Output( class_name=cls._class_id, collection_name=cls.get_collection_name(), ) else: return None # Views def init_view_fields(self, cls) -> None: """ Init class fields :return: None """ if cls._link_fields is None: cls._link_fields = {} for k, v in get_model_fields(cls).items(): path = v.alias or k setattr(cls, k, ExpressionField(path)) link_info = self.detect_link(v, k) depth_level = cls.get_settings().max_nesting_depths_per_field.get( k, None ) if depth_level is None: depth_level = cls.get_settings().max_nesting_depth if link_info is not None: if depth_level > 0: cls._link_fields[k] = link_info self.check_nested_links( link_info, current_depth=depth_level ) elif depth_level <= 0: link_info.is_fetchable = False cls._link_fields[k] = link_info def init_view_collection(self, cls): """ Init collection for View :param cls: :return: """ view_settings = cls.get_settings() if view_settings.name is None: view_settings.name = cls.__name__ if inspect.isclass(view_settings.source): view_settings.source = view_settings.source.get_collection_name() view_settings.motor_db = self.database view_settings.motor_collection = self.database[view_settings.name] async def init_view(self, cls: Type[View]): """ Init View-based class :param cls: :return: """ self.init_settings(cls) self.init_view_collection(cls) self.init_view_fields(cls) self.init_cache(cls) collection_names = await self.database.list_collection_names( authorizedCollections=True, nameOnly=True ) if self.recreate_views or cls._settings.name not in collection_names: if cls._settings.name in collection_names: await cls.get_motor_collection().drop() await self.database.command( { "create": cls.get_settings().name, "viewOn": cls.get_settings().source, "pipeline": cls.get_settings().pipeline, } ) # Union Doc async def init_union_doc(self, cls: Type[UnionDoc]): """ Init Union Doc based class :param cls: :return: """ self.init_settings(cls) if cls._settings.name is None: cls._settings.name = cls.__name__ cls._settings.motor_db = self.database cls._settings.motor_collection = self.database[cls._settings.name] cls._is_inited = True # Deprecations def check_deprecations( cls: Union[Type[Document], Type[View], Type[UnionDoc]] ): if hasattr(cls, "Collection"): raise Deprecation( "Collection inner class is not supported more. " "Please use Settings instead. " "https://beanie-odm.dev/tutorial/defining-a-document/#settings" ) # Final async def init_class( self, cls: Union[Type[Document], Type[View], Type[UnionDoc]] ): """ Init Document, View or UnionDoc based class. :param cls: :return: """ self.check_deprecations(cls) if issubclass(cls, Document): await self.init_document(cls) if issubclass(cls, View): await self.init_view(cls) if issubclass(cls, UnionDoc): await self.init_union_doc(cls) if hasattr(cls, "custom_init"): await cls.custom_init() # type: ignore class Document( LazyModel, SettersInterface, InheritanceInterface, FindInterface, AggregateInterface, OtherGettersInterface, ): """ Document Mapping class. Fields: - `id` - MongoDB document ObjectID "_id" field. Mapped to the PydanticObjectId class """ if IS_PYDANTIC_V2: model_config = ConfigDict( json_schema_extra=json_schema_extra, populate_by_name=True, alias_generator=document_alias_generator, ) else: class Config: json_encoders = {ObjectId: str} allow_population_by_field_name = True fields = {"id": "_id"} schema_extra = staticmethod(json_schema_extra) id: Optional[PydanticObjectId] = Field( default=None, description="MongoDB document ObjectID" ) # State revision_id: Optional[UUID] = Field(default=None, exclude=True) _saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None) _previous_saved_state: Optional[Dict[str, Any]] = PrivateAttr(default=None) # Relations _link_fields: ClassVar[Optional[Dict[str, LinkInfo]]] = None # Cache _cache: ClassVar[Optional[LRUCache]] = None # Settings _document_settings: ClassVar[Optional[DocumentSettings]] = None # Database _database_major_version: ClassVar[int] = 4 def __init__(self, *args, **kwargs) -> None: super(Document, self).__init__(*args, **kwargs) self.get_motor_collection() def _fill_back_refs(cls, values): if cls._link_fields: for field_name, link_info in cls._link_fields.items(): if ( link_info.link_type in [LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT] and field_name not in values ): values[field_name] = BackLink[link_info.document_class]( link_info.document_class ) if ( link_info.link_type in [LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST] and field_name not in values ): values[field_name] = [ BackLink[link_info.document_class]( link_info.document_class ) ] return values if IS_PYDANTIC_V2: def fill_back_refs(cls, values): return cls._fill_back_refs(values) else: def fill_back_refs(cls, values): return cls._fill_back_refs(values) async def get( cls: Type["DocType"], document_id: Any, session: Optional[ClientSession] = None, ignore_cache: bool = False, fetch_links: bool = False, with_children: bool = False, nesting_depth: Optional[int] = None, nesting_depths_per_field: Optional[Dict[str, int]] = None, **pymongo_kwargs, ) -> Optional["DocType"]: """ Get document by id, returns None if document does not exist :param document_id: PydanticObjectId - document id :param session: Optional[ClientSession] - pymongo session :param ignore_cache: bool - ignore cache (if it is turned on) :param **pymongo_kwargs: pymongo native parameters for find operation :return: Union["Document", None] """ if not isinstance( document_id, extract_id_class(get_field_type(get_model_fields(cls)["id"])), ): document_id = parse_object_as( get_field_type(get_model_fields(cls)["id"]), document_id ) return await cls.find_one( {"_id": document_id}, session=session, ignore_cache=ignore_cache, fetch_links=fetch_links, with_children=with_children, nesting_depth=nesting_depth, nesting_depths_per_field=nesting_depths_per_field, **pymongo_kwargs, ) async def sync(self, merge_strategy: MergeStrategy = MergeStrategy.remote): """ Sync the document with the database :param merge_strategy: MergeStrategy - how to merge the document :return: None """ if ( merge_strategy == MergeStrategy.local and self.get_settings().use_state_management is False ): raise ValueError( "State management must be turned on to use local merge strategy" ) if self.id is None: raise DocumentWasNotSaved document = await self.find_one({"_id": self.id}) if document is None: raise DocumentNotFound if merge_strategy == MergeStrategy.local: original_changes = self.get_changes() new_state = document.get_saved_state() if new_state is None: raise DocumentWasNotSaved changes_to_apply = self._collect_updates( new_state, original_changes ) merge_models(self, document) apply_changes(changes_to_apply, self) elif merge_strategy == MergeStrategy.remote: merge_models(self, document) else: raise ValueError("Invalid merge strategy") async def insert( self: DocType, *, link_rule: WriteRules = WriteRules.DO_NOTHING, session: Optional[ClientSession] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> DocType: """ Insert the document (self) to the collection :return: Document """ if self.get_settings().use_revision: self.revision_id = uuid4() if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, ]: if isinstance(value, Document): await value.save(link_rule=WriteRules.WRITE) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.save(link_rule=WriteRules.WRITE) for obj in value if isinstance(obj, Document) ] ) result = await self.get_motor_collection().insert_one( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls ), session=session, ) new_id = result.inserted_id if not isinstance( new_id, extract_id_class(get_field_type(get_model_fields(self)["id"])), ): new_id = parse_object_as( get_field_type(get_model_fields(self)["id"]), new_id ) self.id = new_id return self async def create( self: DocType, session: Optional[ClientSession] = None, ) -> DocType: """ The same as self.insert() :return: Document """ return await self.insert(session=session) async def insert_one( cls: Type[DocType], document: DocType, session: Optional[ClientSession] = None, bulk_writer: Optional["BulkWriter"] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ) -> Optional[DocType]: """ Insert one document to the collection :param document: Document - document to insert :param session: ClientSession - pymongo session :param bulk_writer: "BulkWriter" - Beanie bulk writer :param link_rule: InsertRules - hot to manage link fields :return: DocType """ if not isinstance(document, cls): raise TypeError( "Inserting document must be of the original document class" ) if bulk_writer is None: return await document.insert(link_rule=link_rule, session=session) else: if link_rule == WriteRules.WRITE: raise NotSupported( "Cascade insert with bulk writing not supported" ) bulk_writer.add_operation( Operation( operation=InsertOne, first_query=get_dict( document, to_db=True, keep_nulls=document.get_settings().keep_nulls, ), object_class=type(document), ) ) return None async def insert_many( cls: Type[DocType], documents: Iterable[DocType], session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, **pymongo_kwargs, ) -> InsertManyResult: """ Insert many documents to the collection :param documents: List["Document"] - documents to insert :param session: ClientSession - pymongo session :param link_rule: InsertRules - how to manage link fields :return: InsertManyResult """ if link_rule == WriteRules.WRITE: raise NotSupported( "Cascade insert not supported for insert many method" ) documents_list = [ get_dict( document, to_db=True, keep_nulls=document.get_settings().keep_nulls, ) for document in documents ] return await cls.get_motor_collection().insert_many( documents_list, session=session, **pymongo_kwargs ) async def replace( self: DocType, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> DocType: """ Fully update the document in the database :param session: Optional[ClientSession] - pymongo session. :param ignore_revision: bool - do force replace. Used when revision based protection is turned on. :param bulk_writer: "BulkWriter" - Beanie bulk writer :return: self """ if self.id is None: raise ValueError("Document must have an id") if bulk_writer is not None and link_rule != WriteRules.DO_NOTHING: raise NotSupported if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.replace( link_rule=link_rule, bulk_writer=bulk_writer, ignore_revision=ignore_revision, session=session, ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.replace( link_rule=link_rule, bulk_writer=bulk_writer, ignore_revision=ignore_revision, session=session, ) for obj in value if isinstance(obj, Document) ] ) use_revision_id = self.get_settings().use_revision find_query: Dict[str, Any] = {"_id": self.id} if use_revision_id and not ignore_revision: find_query["revision_id"] = self.revision_id self.revision_id = uuid4() try: await self.find_one(find_query).replace_one( self, session=session, bulk_writer=bulk_writer, ) except DocumentNotFound: if use_revision_id and not ignore_revision: raise RevisionIdWasChanged else: raise DocumentNotFound return self async def save( self: DocType, session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ignore_revision: bool = False, **kwargs, ) -> None: """ Update an existing model in the database or insert it if it does not yet exist. :param session: Optional[ClientSession] - pymongo session. :param link_rule: WriteRules - rules how to deal with links on writing :param ignore_revision: bool - do force save. :return: None """ if link_rule == WriteRules.WRITE: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.save( link_rule=link_rule, session=session ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.save( link_rule=link_rule, session=session ) for obj in value if isinstance(obj, Document) ] ) if self.get_settings().keep_nulls is False: return await self.update( SetOperator( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, ) ), Unset(get_top_level_nones(self)), session=session, ignore_revision=ignore_revision, upsert=True, **kwargs, ) else: return await self.update( SetOperator( get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, ) ), session=session, ignore_revision=ignore_revision, upsert=True, **kwargs, ) async def save_changes( self, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> None: """ Save changes. State management usage must be turned on :param ignore_revision: bool - ignore revision id, if revision is turned on :param bulk_writer: "BulkWriter" - Beanie bulk writer :return: None """ if not self.is_changed: return None changes = self.get_changes() if self.get_settings().keep_nulls is False: return await self.update( SetOperator(changes), Unset(get_top_level_nones(self)), ignore_revision=ignore_revision, session=session, bulk_writer=bulk_writer, ) else: return await self.set( changes, # type: ignore #TODO fix typing ignore_revision=ignore_revision, session=session, bulk_writer=bulk_writer, ) async def replace_many( cls: Type[DocType], documents: List[DocType], session: Optional[ClientSession] = None, ) -> None: """ Replace list of documents :param documents: List["Document"] :param session: Optional[ClientSession] - pymongo session. :return: None """ ids_list = [document.id for document in documents] if await cls.find(In(cls.id, ids_list)).count() != len(ids_list): raise ReplaceError( "Some of the documents are not exist in the collection" ) async with BulkWriter(session=session) as bulk_writer: for document in documents: await document.replace( bulk_writer=bulk_writer, session=session ) async def update( self, *args, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, skip_sync: Optional[bool] = None, **pymongo_kwargs, ) -> DocType: """ Partially update the document in the database :param args: *Union[dict, Mapping] - the modifications to apply. :param session: ClientSession - pymongo session. :param ignore_revision: bool - force update. Will update even if revision id is not the same, as stored :param bulk_writer: "BulkWriter" - Beanie bulk writer :param pymongo_kwargs: pymongo native parameters for update operation :return: None """ arguments = list(args) if skip_sync is not None: raise DeprecationWarning( "skip_sync parameter is not supported. The document get synced always using atomic operation." ) use_revision_id = self.get_settings().use_revision if self.id is not None: find_query: Dict[str, Any] = {"_id": self.id} else: find_query = {"_id": PydanticObjectId()} if use_revision_id and not ignore_revision: find_query["revision_id"] = self.revision_id if use_revision_id: new_revision_id = uuid4() arguments.append(SetRevisionId(new_revision_id)) try: result = await self.find_one(find_query).update( *arguments, session=session, response_type=UpdateResponse.NEW_DOCUMENT, bulk_writer=bulk_writer, **pymongo_kwargs, ) except DuplicateKeyError: raise RevisionIdWasChanged if bulk_writer is None: if use_revision_id and not ignore_revision and result is None: raise RevisionIdWasChanged merge_models(self, result) return self def update_all( cls, *args: Union[dict, Mapping], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, **pymongo_kwargs, ) -> UpdateMany: """ Partially update all the documents :param args: *Union[dict, Mapping] - the modifications to apply. :param session: ClientSession - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param **pymongo_kwargs: pymongo native parameters for find operation :return: UpdateMany query """ return cls.find_all().update_many( *args, session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) def set( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Set values Example: ```python class Sample(Document): one: int await Document.find(Sample.one == 1).set({Sample.one: 100}) ``` Uses [Set operator](operators/update.md#set) :param expression: Dict[Union[ExpressionField, str], Any] - keys and values to set :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( SetOperator(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) def current_date( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Set current date Uses [CurrentDate operator](operators/update.md#currentdate) :param expression: Dict[Union[ExpressionField, str], Any] :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( CurrentDate(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) def inc( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): """ Increment Example: ```python class Sample(Document): one: int await Document.find(Sample.one == 1).inc({Sample.one: 100}) ``` Uses [Inc operator](operators/update.md#inc) :param expression: Dict[Union[ExpressionField, str], Any] :param session: Optional[ClientSession] - pymongo session :param bulk_writer: Optional[BulkWriter] - bulk writer :param skip_sync: bool - skip doc syncing. Available for the direct instances only :return: self """ return self.update( Inc(expression), session=session, bulk_writer=bulk_writer, skip_sync=skip_sync, **kwargs, ) async def delete( self, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, link_rule: DeleteRules = DeleteRules.DO_NOTHING, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, **pymongo_kwargs, ) -> Optional[DeleteResult]: """ Delete the document :param session: Optional[ClientSession] - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param link_rule: DeleteRules - rules for link fields :param **pymongo_kwargs: pymongo native parameters for delete operation :return: Optional[DeleteResult] - pymongo DeleteResult instance. """ if link_rule == DeleteRules.DELETE_LINKS: link_fields = self.get_link_fields() if link_fields is not None: for field_info in link_fields.values(): value = getattr(self, field_info.field_name) if field_info.link_type in [ LinkTypes.DIRECT, LinkTypes.OPTIONAL_DIRECT, LinkTypes.BACK_DIRECT, LinkTypes.OPTIONAL_BACK_DIRECT, ]: if isinstance(value, Document): await value.delete( link_rule=DeleteRules.DELETE_LINKS, **pymongo_kwargs, ) if field_info.link_type in [ LinkTypes.LIST, LinkTypes.OPTIONAL_LIST, LinkTypes.BACK_LIST, LinkTypes.OPTIONAL_BACK_LIST, ]: if isinstance(value, List): await asyncio.gather( *[ obj.delete( link_rule=DeleteRules.DELETE_LINKS, **pymongo_kwargs, ) for obj in value if isinstance(obj, Document) ] ) return await self.find_one({"_id": self.id}).delete( session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) async def delete_all( cls, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, **pymongo_kwargs, ) -> Optional[DeleteResult]: """ Delete all the documents :param session: Optional[ClientSession] - pymongo session. :param bulk_writer: "BulkWriter" - Beanie bulk writer :param **pymongo_kwargs: pymongo native parameters for delete operation :return: Optional[DeleteResult] - pymongo DeleteResult instance. """ return await cls.find_all().delete( session=session, bulk_writer=bulk_writer, **pymongo_kwargs ) # State management def use_state_management(cls) -> bool: """ Is state management turned on :return: bool """ return cls.get_settings().use_state_management def state_management_save_previous(cls) -> bool: """ Should we save the previous state after a commit to database :return: bool """ return cls.get_settings().state_management_save_previous def state_management_replace_objects(cls) -> bool: """ Should objects be replaced when using state management :return: bool """ return cls.get_settings().state_management_replace_objects def _save_state(self) -> None: """ Save current document state. Internal method :return: None """ if self.use_state_management() and self.id is not None: if self.state_management_save_previous(): self._previous_saved_state = self._saved_state self._saved_state = get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ) def get_saved_state(self) -> Optional[Dict[str, Any]]: """ Saved state getter. It is protected property. :return: Optional[Dict[str, Any]] - saved state """ return self._saved_state def get_previous_saved_state(self) -> Optional[Dict[str, Any]]: """ Previous state getter. It is a protected property. :return: Optional[Dict[str, Any]] - previous state """ return self._previous_saved_state def is_changed(self) -> bool: if self._saved_state == get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ): return False return True def has_changed(self) -> bool: if ( self._previous_saved_state is None or self._previous_saved_state == self._saved_state ): return False return True def _collect_updates( self, old_dict: Dict[str, Any], new_dict: Dict[str, Any] ) -> Dict[str, Any]: """ Compares old_dict with new_dict and returns field paths that have been updated Args: old_dict: dict1 new_dict: dict2 Returns: dictionary with updates """ updates = {} if old_dict.keys() - new_dict.keys(): updates = new_dict else: for field_name, field_value in new_dict.items(): if field_value != old_dict.get(field_name): if not self.state_management_replace_objects() and ( isinstance(field_value, dict) and isinstance(old_dict.get(field_name), dict) ): if old_dict.get(field_name) is None: updates[field_name] = field_value elif isinstance(field_value, dict) and isinstance( old_dict.get(field_name), dict ): field_data = self._collect_updates( old_dict.get(field_name), # type: ignore field_value, ) for k, v in field_data.items(): updates[f"{field_name}.{k}"] = v else: updates[field_name] = field_value return updates def get_changes(self) -> Dict[str, Any]: return self._collect_updates( self._saved_state, # type: ignore get_dict( self, to_db=True, keep_nulls=self.get_settings().keep_nulls, exclude={"revision_id"}, ), ) def get_previous_changes(self) -> Dict[str, Any]: if self._previous_saved_state is None: return {} return self._collect_updates( self._previous_saved_state, self._saved_state, # type: ignore ) def rollback(self) -> None: if self.is_changed: for key, value in self._saved_state.items(): # type: ignore if key == "_id": setattr(self, "id", value) else: setattr(self, key, value) # Other def get_settings(cls) -> DocumentSettings: """ Get document settings, which was created on the initialization step :return: DocumentSettings class """ if cls._document_settings is None: raise CollectionWasNotInitialized return cls._document_settings async def inspect_collection( cls, session: Optional[ClientSession] = None ) -> InspectionResult: """ Check, if documents, stored in the MongoDB collection are compatible with the Document schema :return: InspectionResult """ inspection_result = InspectionResult() async for json_document in cls.get_motor_collection().find( {}, session=session ): try: parse_model(cls, json_document) except ValidationError as e: if inspection_result.status == InspectionStatuses.OK: inspection_result.status = InspectionStatuses.FAIL inspection_result.errors.append( InspectionError( document_id=json_document["_id"], error=str(e) ) ) return inspection_result def check_hidden_fields(cls): hidden_fields = [ (name, field) for name, field in get_model_fields(cls).items() if get_extra_field_info(field, "hidden") is True ] if not hidden_fields: return warnings.warn( f"{cls.__name__}: 'hidden=True' is deprecated, please use 'exclude=True'", DeprecationWarning, ) if IS_PYDANTIC_V2: for name, field in hidden_fields: field.exclude = True del field.json_schema_extra["hidden"] cls.model_rebuild(force=True) else: for name, field in hidden_fields: field.field_info.exclude = True del field.field_info.extra["hidden"] cls.__exclude_fields__[name] = True async def validate_self(self, *args, **kwargs): # TODO: it can be sync, but needs some actions controller improvements if self.get_settings().validate_on_save: new_model = parse_model(self.__class__, get_model_dump(self)) merge_models(self, new_model) def to_ref(self): if self.id is None: raise DocumentWasNotSaved("Can not create dbref without id") return DBRef(self.get_motor_collection().name, self.id) async def fetch_link(self, field: Union[str, Any]): ref_obj = getattr(self, field, None) if isinstance(ref_obj, Link): value = await ref_obj.fetch(fetch_links=True) setattr(self, field, value) if isinstance(ref_obj, list) and ref_obj: values = await Link.fetch_list(ref_obj, fetch_links=True) setattr(self, field, values) async def fetch_all_links(self): coros = [] link_fields = self.get_link_fields() if link_fields is not None: for ref in link_fields.values(): coros.append(self.fetch_link(ref.field_name)) # TODO lists await asyncio.gather(*coros) def get_link_fields(cls) -> Optional[Dict[str, LinkInfo]]: return cls._link_fields def get_model_type(cls) -> ModelType: return ModelType.Document async def distinct( cls, key: str, filter: Optional[Mapping[str, Any]] = None, session: Optional[ClientSession] = None, **kwargs: Any, ) -> list: return await cls.get_motor_collection().distinct( key, filter, session, **kwargs ) def link_from_id(cls, id: Any): ref = DBRef(id=id, collection=cls.get_collection_name()) return Link(ref, document_class=cls) The provided code snippet includes necessary dependencies for implementing the `init_beanie` function. Write a Python function `async def init_beanie( database: AsyncIOMotorDatabase = None, connection_string: Optional[str] = None, document_models: Optional[ List[Union[Type[Document], Type["View"], str]] ] = None, allow_index_dropping: bool = False, recreate_views: bool = False, multiprocessing_mode: bool = False, )` to solve the following problem: Beanie initialization :param database: AsyncIOMotorDatabase - motor database instance :param connection_string: str - MongoDB connection string :param document_models: List[Union[Type[DocType], str]] - model classes or strings with dot separated paths :param allow_index_dropping: bool - if index dropping is allowed. Default False :param recreate_views: bool - if views should be recreated. Default False :param multiprocessing_mode: bool - if multiprocessing mode is on it will patch the motor client to use process's event loop. Default False :return: None Here is the function: async def init_beanie( database: AsyncIOMotorDatabase = None, connection_string: Optional[str] = None, document_models: Optional[ List[Union[Type[Document], Type["View"], str]] ] = None, allow_index_dropping: bool = False, recreate_views: bool = False, multiprocessing_mode: bool = False, ): """ Beanie initialization :param database: AsyncIOMotorDatabase - motor database instance :param connection_string: str - MongoDB connection string :param document_models: List[Union[Type[DocType], str]] - model classes or strings with dot separated paths :param allow_index_dropping: bool - if index dropping is allowed. Default False :param recreate_views: bool - if views should be recreated. Default False :param multiprocessing_mode: bool - if multiprocessing mode is on it will patch the motor client to use process's event loop. Default False :return: None """ await Initializer( database=database, connection_string=connection_string, document_models=document_models, allow_index_dropping=allow_index_dropping, recreate_views=recreate_views, multiprocessing_mode=multiprocessing_mode, )
Beanie initialization :param database: AsyncIOMotorDatabase - motor database instance :param connection_string: str - MongoDB connection string :param document_models: List[Union[Type[DocType], str]] - model classes or strings with dot separated paths :param allow_index_dropping: bool - if index dropping is allowed. Default False :param recreate_views: bool - if views should be recreated. Default False :param multiprocessing_mode: bool - if multiprocessing mode is on it will patch the motor client to use process's event loop. Default False :return: None
167,800
import inspect import sys from typing import Any, Dict, Optional, Tuple, Type from beanie.odm.fields import IndexedAnnotation from .pydantic import IS_PYDANTIC_V2, get_field_type def extract_id_class(annotation) -> Type[Any]: if get_origin(annotation) is not None: try: annotation = next( arg for arg in get_args(annotation) if arg is not type(None) ) except StopIteration: annotation = None if inspect.isclass(annotation): return annotation raise ValueError("Unknown annotation: {}".format(annotation))
null
167,801
import inspect import sys from typing import Any, Dict, Optional, Tuple, Type from beanie.odm.fields import IndexedAnnotation from .pydantic import IS_PYDANTIC_V2, get_field_type class IndexedAnnotation: _indexed: Tuple[int, Dict[str, Any]] IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2 if IS_PYDANTIC_V2: from pydantic import TypeAdapter else: from pydantic import parse_obj_as def get_field_type(field): if IS_PYDANTIC_V2: return field.annotation else: return field.outer_type_ The provided code snippet includes necessary dependencies for implementing the `get_index_attributes` function. Write a Python function `def get_index_attributes(field) -> Optional[Tuple[int, Dict[str, Any]]]` to solve the following problem: Gets the index attributes from the field, if it is indexed. :param field: The field to get the index attributes from. :return: The index attributes, if the field is indexed. Otherwise, None. Here is the function: def get_index_attributes(field) -> Optional[Tuple[int, Dict[str, Any]]]: """Gets the index attributes from the field, if it is indexed. :param field: The field to get the index attributes from. :return: The index attributes, if the field is indexed. Otherwise, None. """ # For fields that are directly typed with `Indexed()`, the type will have # an `_indexed` attribute. field_type = get_field_type(field) if hasattr(field_type, "_indexed"): return getattr(field_type, "_indexed", None) # For fields that are use `Indexed` within `Annotated`, the field will have # metadata that might contain an `IndexedAnnotation` instance. if IS_PYDANTIC_V2: # In Pydantic 2, the field has a `metadata` attribute with # the annotations. metadata = getattr(field, "metadata", None) elif hasattr(field, "annotation") and hasattr( field.annotation, "__metadata__" ): # In Pydantic 1, the field has an `annotation` attribute with the # type assigned to the field. If the type is annotated, it will # have a `__metadata__` attribute with the annotations. metadata = field.annotation.__metadata__ else: return None if metadata is None: return None try: iter(metadata) except TypeError: return None indexed_annotation = next( ( annotation for annotation in metadata if isinstance(annotation, IndexedAnnotation) ), None, ) return getattr(indexed_annotation, "_indexed", None)
Gets the index attributes from the field, if it is indexed. :param field: The field to get the index attributes from. :return: The index attributes, if the field is indexed. Otherwise, None.
167,802
from collections.abc import Mapping from typing import TYPE_CHECKING, Any, Dict from typing import Mapping as MappingType from beanie.odm.fields import ( ExpressionField, ) class ExpressionField(str): def __getitem__(self, item): def __getattr__(self, item): def __hash__(self): def __eq__(self, other): def __gt__(self, other): def __ge__(self, other): def __lt__(self, other): def __le__(self, other): def __ne__(self, other): def __pos__(self): def __neg__(self): def __copy__(self): def __deepcopy__(self, memo): def convert_ids( query: MappingType[str, Any], doc: "Document", fetch_links: bool ) -> Dict[str, Any]: # TODO add all the cases new_query = {} for k, v in query.items(): k_splitted = k.split(".") if ( isinstance(k, ExpressionField) and doc.get_link_fields() is not None and len(k_splitted) == 2 and k_splitted[0] in doc.get_link_fields().keys() # type: ignore and k_splitted[1] == "id" ): if fetch_links: new_k = f"{k_splitted[0]}._id" else: new_k = f"{k_splitted[0]}.$id" else: new_k = k new_v: Any if isinstance(v, Mapping): new_v = convert_ids(v, doc, fetch_links) elif isinstance(v, list): new_v = [ convert_ids(ele, doc, fetch_links) if isinstance(ele, Mapping) else ele for ele in v ] else: new_v = v new_query[new_k] = new_v return new_query
null
167,803
from typing import Any, Type import pydantic from pydantic import BaseModel IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2 if IS_PYDANTIC_V2: from pydantic import TypeAdapter else: from pydantic import parse_obj_as def parse_object_as(object_type: Type, data: Any): if IS_PYDANTIC_V2: return TypeAdapter(object_type).validate_python(data) else: return parse_obj_as(object_type, data)
null
167,804
from typing import Any, Type import pydantic from pydantic import BaseModel IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2 if IS_PYDANTIC_V2: from pydantic import TypeAdapter else: from pydantic import parse_obj_as def get_extra_field_info(field, parameter: str): if IS_PYDANTIC_V2: if field.json_schema_extra is not None: return field.json_schema_extra.get(parameter) return None else: return field.field_info.extra.get(parameter)
null
167,805
from typing import Any, Type import pydantic from pydantic import BaseModel IS_PYDANTIC_V2 = int(pydantic.VERSION.split(".")[0]) >= 2 if IS_PYDANTIC_V2: from pydantic import TypeAdapter else: from pydantic import parse_obj_as def get_model_dump(model, *args, **kwargs): if IS_PYDANTIC_V2: return model.model_dump(*args, **kwargs) else: return model.dict(*args, **kwargs)
null
167,806
from typing import TYPE_CHECKING, Any, Dict, Type, Union from pydantic import BaseModel from beanie.exceptions import ( ApplyChangesException, DocWasNotRegisteredInUnionClass, UnionHasNoRegisteredDocs, ) from beanie.odm.interfaces.detector import ModelType from beanie.odm.utils.pydantic import get_config_value, parse_model def get_config_value(model, parameter: str): if IS_PYDANTIC_V2: return model.model_config.get(parameter) else: return getattr(model.Config, parameter, None) class Link(Generic[T]): def __init__(self, ref: DBRef, document_class: Type[T]): self.ref = ref self.document_class = document_class async def fetch(self, fetch_links: bool = False) -> Union[T, "Link"]: result = await self.document_class.get( # type: ignore self.ref.id, with_children=True, fetch_links=fetch_links ) return result or self async def fetch_one(cls, link: "Link"): return await link.fetch() async def fetch_list( cls, links: List[Union["Link", "DocType"]], fetch_links: bool = False ): """ Fetch list that contains links and documents :param links: :param fetch_links: :return: """ data = Link.repack_links(links) # type: ignore ids_to_fetch = [] document_class = None for doc_id, link in data.items(): if isinstance(link, Link): if document_class is None: document_class = link.document_class else: if document_class != link.document_class: raise ValueError( "All the links must have the same model class" ) ids_to_fetch.append(link.ref.id) if ids_to_fetch: fetched_models = await document_class.find( # type: ignore In("_id", ids_to_fetch), with_children=True, fetch_links=fetch_links, ).to_list() for model in fetched_models: data[model.id] = model return list(data.values()) def repack_links( links: List[Union["Link", "DocType"]] ) -> OrderedDictType[Any, Any]: result = OrderedDict() for link in links: if isinstance(link, Link): result[link.ref.id] = link else: result[link.id] = link return result async def fetch_many(cls, links: List["Link"]): coros = [] for link in links: coros.append(link.fetch()) return await asyncio.gather(*coros) if IS_PYDANTIC_V2: def serialize(value: Union["Link", BaseModel]): if isinstance(value, Link): return value.to_dict() return value.model_dump() def build_validation(cls, handler, source_type): def validate(v: Union[DBRef, T], validation_info: ValidationInfo): document_class = DocsRegistry.evaluate_fr(get_args(source_type)[0]) # type: ignore # noqa: F821 if isinstance(v, DBRef): return cls(ref=v, document_class=document_class) if isinstance(v, Link): return v if isinstance(v, dict) and v.keys() == {"id", "collection"}: return cls( ref=DBRef( collection=v["collection"], id=TypeAdapter( document_class.model_fields["id"].annotation ).validate_python(v["id"]), ), document_class=document_class, ) if isinstance(v, dict) or isinstance(v, BaseModel): return parse_obj(document_class, v) new_id = TypeAdapter( document_class.model_fields["id"].annotation ).validate_python(v) ref = DBRef( collection=document_class.get_collection_name(), id=new_id ) return cls(ref=ref, document_class=document_class) return validate def __get_pydantic_core_schema__( cls, source_type: Any, handler: GetCoreSchemaHandler ) -> CoreSchema: # type: ignore return core_schema.json_or_python_schema( python_schema=core_schema.general_plain_validator_function( cls.build_validation(handler, source_type) ), json_schema=core_schema.typed_dict_schema( { "id": core_schema.typed_dict_field( core_schema.str_schema() ), "collection": core_schema.typed_dict_field( core_schema.str_schema() ), } ), serialization=core_schema.plain_serializer_function_ser_schema( # type: ignore lambda instance: cls.serialize(instance) # type: ignore ), ) return core_schema.general_plain_validator_function( cls.build_validation(handler, source_type) ) else: def __get_validators__(cls): yield cls.validate def validate(cls, v: Union[DBRef, T], field: ModelField): document_class = field.sub_fields[0].type_ # type: ignore if isinstance(v, DBRef): return cls(ref=v, document_class=document_class) if isinstance(v, Link): return v if isinstance(v, dict) or isinstance(v, BaseModel): return parse_obj(document_class, v) new_id = parse_object_as( get_field_type(get_model_fields(document_class)["id"]), v ) ref = DBRef( collection=document_class.get_collection_name(), id=new_id ) return cls(ref=ref, document_class=document_class) def to_ref(self): return self.ref def to_dict(self): return {"id": str(self.ref.id), "collection": self.ref.collection} The provided code snippet includes necessary dependencies for implementing the `merge_models` function. Write a Python function `def merge_models(left: BaseModel, right: BaseModel) -> None` to solve the following problem: Merge two models :param left: left model :param right: right model :return: None Here is the function: def merge_models(left: BaseModel, right: BaseModel) -> None: """ Merge two models :param left: left model :param right: right model :return: None """ from beanie.odm.fields import Link for k, right_value in right.__iter__(): left_value = getattr(left, k) if isinstance(right_value, BaseModel) and isinstance( left_value, BaseModel ): if get_config_value(left_value, "frozen"): left.__setattr__(k, right_value) else: merge_models(left_value, right_value) continue if isinstance(right_value, list): links_found = False for i in right_value: if isinstance(i, Link): links_found = True break if links_found: continue left.__setattr__(k, right_value) elif not isinstance(right_value, Link): left.__setattr__(k, right_value)
Merge two models :param left: left model :param right: right model :return: None
167,807
from typing import TYPE_CHECKING, Any, Dict, Type, Union from pydantic import BaseModel from beanie.exceptions import ( ApplyChangesException, DocWasNotRegisteredInUnionClass, UnionHasNoRegisteredDocs, ) from beanie.odm.interfaces.detector import ModelType from beanie.odm.utils.pydantic import get_config_value, parse_model class ApplyChangesException(Exception): pass def apply_changes( changes: Dict[str, Any], target: Union[BaseModel, Dict[str, Any]] ): for key, value in changes.items(): if "." in key: key_parts = key.split(".") current_target = target try: for part in key_parts[:-1]: if isinstance(current_target, dict): current_target = current_target[part] elif isinstance(current_target, BaseModel): current_target = getattr(current_target, part) else: raise ApplyChangesException( f"Unexpected type of target: {type(target)}" ) final_key = key_parts[-1] if isinstance(current_target, dict): current_target[final_key] = value elif isinstance(current_target, BaseModel): setattr(current_target, final_key, value) else: raise ApplyChangesException( f"Unexpected type of target: {type(target)}" ) except (KeyError, AttributeError) as e: raise ApplyChangesException( f"Failed to apply change for key '{key}': {e}" ) else: if isinstance(target, dict): target[key] = value elif isinstance(target, BaseModel): setattr(target, key, value) else: raise ApplyChangesException( f"Unexpected type of target: {type(target)}" )
null
167,808
from typing import TYPE_CHECKING, Any, Dict, Type, Union from pydantic import BaseModel from beanie.exceptions import ( ApplyChangesException, DocWasNotRegisteredInUnionClass, UnionHasNoRegisteredDocs, ) from beanie.odm.interfaces.detector import ModelType from beanie.odm.utils.pydantic import get_config_value, parse_model def save_state(item: BaseModel): # type: ignore class UnionHasNoRegisteredDocs(Exception): class DocWasNotRegisteredInUnionClass(Exception): class ModelType(str, Enum): def parse_model(model_type: Type[BaseModel], data: Any): class Document( LazyModel, SettersInterface, InheritanceInterface, FindInterface, AggregateInterface, OtherGettersInterface, ): def __init__(self, *args, **kwargs) -> None: def _fill_back_refs(cls, values): def fill_back_refs(cls, values): def fill_back_refs(cls, values): async def get( cls: Type["DocType"], document_id: Any, session: Optional[ClientSession] = None, ignore_cache: bool = False, fetch_links: bool = False, with_children: bool = False, nesting_depth: Optional[int] = None, nesting_depths_per_field: Optional[Dict[str, int]] = None, **pymongo_kwargs, ) -> Optional["DocType"]: async def sync(self, merge_strategy: MergeStrategy = MergeStrategy.remote): async def insert( self: DocType, *, link_rule: WriteRules = WriteRules.DO_NOTHING, session: Optional[ClientSession] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> DocType: async def create( self: DocType, session: Optional[ClientSession] = None, ) -> DocType: async def insert_one( cls: Type[DocType], document: DocType, session: Optional[ClientSession] = None, bulk_writer: Optional["BulkWriter"] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ) -> Optional[DocType]: async def insert_many( cls: Type[DocType], documents: Iterable[DocType], session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, **pymongo_kwargs, ) -> InsertManyResult: async def replace( self: DocType, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> DocType: async def save( self: DocType, session: Optional[ClientSession] = None, link_rule: WriteRules = WriteRules.DO_NOTHING, ignore_revision: bool = False, **kwargs, ) -> None: async def save_changes( self, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, ) -> None: async def replace_many( cls: Type[DocType], documents: List[DocType], session: Optional[ClientSession] = None, ) -> None: async def update( self, *args, ignore_revision: bool = False, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, skip_sync: Optional[bool] = None, **pymongo_kwargs, ) -> DocType: def update_all( cls, *args: Union[dict, Mapping], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, **pymongo_kwargs, ) -> UpdateMany: def set( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): def current_date( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): def inc( self, expression: Dict[Union[ExpressionField, str], Any], session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, skip_sync: Optional[bool] = None, **kwargs, ): async def delete( self, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, link_rule: DeleteRules = DeleteRules.DO_NOTHING, skip_actions: Optional[List[Union[ActionDirections, str]]] = None, **pymongo_kwargs, ) -> Optional[DeleteResult]: async def delete_all( cls, session: Optional[ClientSession] = None, bulk_writer: Optional[BulkWriter] = None, **pymongo_kwargs, ) -> Optional[DeleteResult]: def use_state_management(cls) -> bool: def state_management_save_previous(cls) -> bool: def state_management_replace_objects(cls) -> bool: def _save_state(self) -> None: def get_saved_state(self) -> Optional[Dict[str, Any]]: def get_previous_saved_state(self) -> Optional[Dict[str, Any]]: def is_changed(self) -> bool: def has_changed(self) -> bool: def _collect_updates( self, old_dict: Dict[str, Any], new_dict: Dict[str, Any] ) -> Dict[str, Any]: def get_changes(self) -> Dict[str, Any]: def get_previous_changes(self) -> Dict[str, Any]: def rollback(self) -> None: def get_settings(cls) -> DocumentSettings: async def inspect_collection( cls, session: Optional[ClientSession] = None ) -> InspectionResult: def check_hidden_fields(cls): async def validate_self(self, *args, **kwargs): def to_ref(self): async def fetch_link(self, field: Union[str, Any]): async def fetch_all_links(self): def get_link_fields(cls) -> Optional[Dict[str, LinkInfo]]: def get_model_type(cls) -> ModelType: async def distinct( cls, key: str, filter: Optional[Mapping[str, Any]] = None, session: Optional[ClientSession] = None, **kwargs: Any, ) -> list: def link_from_id(cls, id: Any): def parse_obj( model: Union[Type[BaseModel], Type["Document"]], data: Any, lazy_parse: bool = False, ) -> BaseModel: if ( hasattr(model, "get_model_type") and model.get_model_type() == ModelType.UnionDoc # type: ignore ): if model._document_models is None: # type: ignore raise UnionHasNoRegisteredDocs if isinstance(data, dict): class_name = data[model.get_settings().class_id] # type: ignore else: class_name = data._class_id if class_name not in model._document_models: # type: ignore raise DocWasNotRegisteredInUnionClass return parse_obj( model=model._document_models[class_name], # type: ignore data=data, lazy_parse=lazy_parse, ) # type: ignore if ( hasattr(model, "get_model_type") and model.get_model_type() == ModelType.Document # type: ignore and model._inheritance_inited # type: ignore ): if isinstance(data, dict): class_name = data.get(model.get_settings().class_id) # type: ignore elif hasattr(data, model.get_settings().class_id): # type: ignore class_name = data._class_id else: class_name = None if model._children and class_name in model._children: # type: ignore return parse_obj( model=model._children[class_name], # type: ignore data=data, lazy_parse=lazy_parse, ) # type: ignore if ( lazy_parse and hasattr(model, "get_model_type") and model.get_model_type() == ModelType.Document # type: ignore ): o = model.lazy_parse(data, {"_id"}) # type: ignore o._saved_state = {"_id": o.id} return o result = parse_model(model, data) save_state(result) return result
null
167,809
from typing import TYPE_CHECKING, Optional, Set from beanie.odm.utils.encoder import Encoder def get_dict( document: "Document", to_db: bool = False, exclude: Optional[Set[str]] = None, keep_nulls: bool = True, ): if exclude is None: exclude = set() if document.id is None: exclude.add("_id") if not document.get_settings().use_revision: exclude.add("revision_id") encoder = Encoder(exclude=exclude, to_db=to_db, keep_nulls=keep_nulls) return encoder.encode(document) def filter_none(d): result = {} for k, v in d.items(): if isinstance(v, dict): filtered = filter_none(v) if filtered: result[k] = filtered elif v is None: result[k] = v return result def get_nulls( document: "Document", exclude: Optional[Set[str]] = None, ): dictionary = get_dict(document, exclude=exclude, keep_nulls=True) return filter_none(dictionary)
null
167,810
from typing import TYPE_CHECKING, Optional, Set from beanie.odm.utils.encoder import Encoder def get_dict( document: "Document", to_db: bool = False, exclude: Optional[Set[str]] = None, keep_nulls: bool = True, ): if exclude is None: exclude = set() if document.id is None: exclude.add("_id") if not document.get_settings().use_revision: exclude.add("revision_id") encoder = Encoder(exclude=exclude, to_db=to_db, keep_nulls=keep_nulls) return encoder.encode(document) def get_top_level_nones( document: "Document", exclude: Optional[Set[str]] = None, ): dictionary = get_dict(document, exclude=exclude, keep_nulls=True) return {k: v for k, v in dictionary.items() if v is None}
null
167,811
from typing import Dict, Optional, Type, TypeVar from pydantic import BaseModel from beanie.odm.interfaces.detector import ModelType from beanie.odm.utils.pydantic import get_config_value, get_model_fields ProjectionModelType = TypeVar("ProjectionModelType", bound=BaseModel) class ModelType(str, Enum): def get_model_fields(model): def get_config_value(model, parameter: str): def get_projection( model: Type[ProjectionModelType], ) -> Optional[Dict[str, int]]: if hasattr(model, "get_model_type") and ( model.get_model_type() == ModelType.UnionDoc # type: ignore or ( # type: ignore model.get_model_type() == ModelType.Document # type: ignore and model._inheritance_inited # type: ignore ) ): # type: ignore return None if hasattr(model, "Settings"): # MyPy checks settings = getattr(model, "Settings") if hasattr(settings, "projection"): return getattr(settings, "projection") if get_config_value(model, "extra") == "allow": return None document_projection: Dict[str, int] = {} for name, field in get_model_fields(model).items(): document_projection[field.alias or name] = 1 return document_projection
null
167,812
from functools import wraps from typing import TYPE_CHECKING, Callable def validate_self_before(f: Callable): @wraps(f) async def wrapper(self: "DocType", *args, **kwargs): await self.validate_self(*args, **kwargs) return await f(self, *args, **kwargs) return wrapper
null
167,813
import inspect from functools import wraps from typing import TYPE_CHECKING, Callable from beanie.exceptions import StateManagementIsTurnedOff, StateNotSaved def check_if_state_saved(self: "DocType"): if not self.use_state_management(): raise StateManagementIsTurnedOff( "State management is turned off for this document" ) if self._saved_state is None: raise StateNotSaved("No state was saved") def saved_state_needed(f: Callable): @wraps(f) def sync_wrapper(self: "DocType", *args, **kwargs): check_if_state_saved(self) return f(self, *args, **kwargs) @wraps(f) async def async_wrapper(self: "DocType", *args, **kwargs): check_if_state_saved(self) return await f(self, *args, **kwargs) if inspect.iscoroutinefunction(f): return async_wrapper return sync_wrapper
null
167,814
import inspect from functools import wraps from typing import TYPE_CHECKING, Callable from beanie.exceptions import StateManagementIsTurnedOff, StateNotSaved def check_if_previous_state_saved(self: "DocType"): if not self.use_state_management(): raise StateManagementIsTurnedOff( "State management is turned off for this document" ) if not self.state_management_save_previous(): raise StateManagementIsTurnedOff( "State management's option to save previous state is turned off for this document" ) def previous_saved_state_needed(f: Callable): @wraps(f) def sync_wrapper(self: "DocType", *args, **kwargs): check_if_previous_state_saved(self) return f(self, *args, **kwargs) @wraps(f) async def async_wrapper(self: "DocType", *args, **kwargs): check_if_previous_state_saved(self) return await f(self, *args, **kwargs) if inspect.iscoroutinefunction(f): return async_wrapper return sync_wrapper
null
167,815
import inspect from functools import wraps from typing import TYPE_CHECKING, Callable from beanie.exceptions import StateManagementIsTurnedOff, StateNotSaved def save_state_after(f: Callable): @wraps(f) async def wrapper(self: "DocType", *args, **kwargs): result = await f(self, *args, **kwargs) self._save_state() return result return wrapper
null
167,816
import dataclasses as dc import datetime import decimal import enum import ipaddress import operator import pathlib import re import uuid from enum import Enum from typing import ( Any, Callable, Container, Iterable, Mapping, MutableMapping, Optional, Tuple, ) import bson import pydantic import beanie from beanie.odm.fields import Link, LinkTypes from beanie.odm.utils.pydantic import IS_PYDANTIC_V2, get_model_fields SingleArgCallable = Callable[[Any], Any] def _get_encoder( obj: Any, custom_encoders: Mapping[type, SingleArgCallable] ) -> Optional[SingleArgCallable]: encoder = custom_encoders.get(type(obj)) if encoder is not None: return encoder for cls, encoder in custom_encoders.items(): if isinstance(obj, cls): return encoder return None
null
167,817
from typing import Optional from fastapi import Depends, HTTPException, Path, Query from starlette import status from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.errors import EntityDoesNotExist from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( DEFAULT_ARTICLES_LIMIT, DEFAULT_ARTICLES_OFFSET, ArticlesFilters, ) from app.resources import strings from app.services.articles import check_user_can_modify_article async def get_article_by_slug_from_path( slug: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> Article: try: return await articles_repo.get_article_by_slug(slug=slug, requested_user=user) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.ARTICLE_DOES_NOT_EXIST_ERROR, ) def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional class Article(IDModelMixin, DateTimeModelMixin, RWModel): slug: str title: str description: str body: str tags: List[str] author: Profile favorited: bool favorites_count: int class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None def check_user_can_modify_article(article: Article, user: User) -> bool: return article.author.username == user.username def check_article_modification_permissions( current_article: Article = Depends(get_article_by_slug_from_path), user: User = Depends(get_current_user_authorizer()), ) -> None: if not check_user_can_modify_article(current_article, user): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=strings.USER_IS_NOT_AUTHOR_OF_ARTICLE, )
null
167,818
from typing import Optional from fastapi import Depends, HTTPException, Path from starlette import status from app.api.dependencies import articles, authentication, database from app.db.errors import EntityDoesNotExist from app.db.repositories.comments import CommentsRepository from app.models.domain.articles import Article from app.models.domain.comments import Comment from app.models.domain.users import User from app.resources import strings from app.services.comments import check_user_can_modify_comment async def get_comment_by_id_from_path( comment_id: int = Path(..., ge=1), article: Article = Depends(articles.get_article_by_slug_from_path), user: Optional[User] = Depends( authentication.get_current_user_authorizer(required=False), ), comments_repo: CommentsRepository = Depends( database.get_repository(CommentsRepository), ), ) -> Comment: try: return await comments_repo.get_comment_by_id( comment_id=comment_id, article=article, user=user, ) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.COMMENT_DOES_NOT_EXIST, ) class Comment(IDModelMixin, DateTimeModelMixin, RWModel): body: str author: Profile class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None def check_user_can_modify_comment(comment: Comment, user: User) -> bool: return comment.author.username == user.username def check_comment_modification_permissions( comment: Comment = Depends(get_comment_by_id_from_path), user: User = Depends(authentication.get_current_user_authorizer()), ) -> None: if not check_user_can_modify_comment(comment, user): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=strings.USER_IS_NOT_AUTHOR_OF_ARTICLE, )
null
167,819
from fastapi import APIRouter, Depends from app.api.dependencies.database import get_repository from app.db.repositories.tags import TagsRepository from app.models.schemas.tags import TagsInList def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class TagsRepository(BaseRepository): async def get_all_tags(self) -> List[str]: tags_row = await queries.get_all_tags(self.connection) return [tag[0] for tag in tags_row] async def create_tags_that_dont_exist(self, *, tags: Sequence[str]) -> None: await queries.create_new_tags(self.connection, [{"tag": tag} for tag in tags]) class TagsInList(BaseModel): tags: List[str] async def get_all_tags( tags_repo: TagsRepository = Depends(get_repository(TagsRepository)), ) -> TagsInList: tags = await tags_repo.get_all_tags() return TagsInList(tags=tags)
null
167,820
from fastapi import APIRouter, Body, Depends, HTTPException from starlette.status import HTTP_400_BAD_REQUEST from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.core.config import get_app_settings from app.core.settings.app import AppSettings from app.db.repositories.users import UsersRepository from app.models.domain.users import User from app.models.schemas.users import UserInResponse, UserInUpdate, UserWithToken from app.resources import strings from app.services import jwt from app.services.authentication import check_email_is_taken, check_username_is_taken def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_app_settings() -> AppSettings: app_env = BaseAppSettings().app_env config = environments[app_env] return config() class AppSettings(BaseAppSettings): debug: bool = False docs_url: str = "/docs" openapi_prefix: str = "" openapi_url: str = "/openapi.json" redoc_url: str = "/redoc" title: str = "FastAPI example application" version: str = "0.0.0" database_url: PostgresDsn max_connection_count: int = 10 min_connection_count: int = 10 secret_key: SecretStr api_prefix: str = "/api" jwt_token_prefix: str = "Token" allowed_hosts: List[str] = ["*"] logging_level: int = logging.INFO loggers: Tuple[str, str] = ("uvicorn.asgi", "uvicorn.access") class Config: validate_assignment = True def fastapi_kwargs(self) -> Dict[str, Any]: return { "debug": self.debug, "docs_url": self.docs_url, "openapi_prefix": self.openapi_prefix, "openapi_url": self.openapi_url, "redoc_url": self.redoc_url, "title": self.title, "version": self.version, } def configure_logging(self) -> None: logging.getLogger().handlers = [InterceptHandler()] for logger_name in self.loggers: logging_logger = logging.getLogger(logger_name) logging_logger.handlers = [InterceptHandler(level=self.logging_level)] logger.configure(handlers=[{"sink": sys.stderr, "level": self.logging_level}]) class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None class UserWithToken(User): token: str class UserInResponse(RWSchema): user: UserWithToken import jwt async def retrieve_current_user( user: User = Depends(get_current_user_authorizer()), settings: AppSettings = Depends(get_app_settings), ) -> UserInResponse: token = jwt.create_access_token_for_user( user, str(settings.secret_key.get_secret_value()), ) return UserInResponse( user=UserWithToken( username=user.username, email=user.email, bio=user.bio, image=user.image, token=token, ), )
null
167,821
from fastapi import APIRouter, Body, Depends, HTTPException from starlette.status import HTTP_400_BAD_REQUEST from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.core.config import get_app_settings from app.core.settings.app import AppSettings from app.db.repositories.users import UsersRepository from app.models.domain.users import User from app.models.schemas.users import UserInResponse, UserInUpdate, UserWithToken from app.resources import strings from app.services import jwt from app.services.authentication import check_email_is_taken, check_username_is_taken def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo def get_app_settings() -> AppSettings: app_env = BaseAppSettings().app_env config = environments[app_env] return config() class AppSettings(BaseAppSettings): debug: bool = False docs_url: str = "/docs" openapi_prefix: str = "" openapi_url: str = "/openapi.json" redoc_url: str = "/redoc" title: str = "FastAPI example application" version: str = "0.0.0" database_url: PostgresDsn max_connection_count: int = 10 min_connection_count: int = 10 secret_key: SecretStr api_prefix: str = "/api" jwt_token_prefix: str = "Token" allowed_hosts: List[str] = ["*"] logging_level: int = logging.INFO loggers: Tuple[str, str] = ("uvicorn.asgi", "uvicorn.access") class Config: validate_assignment = True def fastapi_kwargs(self) -> Dict[str, Any]: return { "debug": self.debug, "docs_url": self.docs_url, "openapi_prefix": self.openapi_prefix, "openapi_url": self.openapi_url, "redoc_url": self.redoc_url, "title": self.title, "version": self.version, } def configure_logging(self) -> None: logging.getLogger().handlers = [InterceptHandler()] for logger_name in self.loggers: logging_logger = logging.getLogger(logger_name) logging_logger.handlers = [InterceptHandler(level=self.logging_level)] logger.configure(handlers=[{"sink": sys.stderr, "level": self.logging_level}]) class UsersRepository(BaseRepository): async def get_user_by_email(self, *, email: str) -> UserInDB: user_row = await queries.get_user_by_email(self.connection, email=email) if user_row: return UserInDB(**user_row) raise EntityDoesNotExist("user with email {0} does not exist".format(email)) async def get_user_by_username(self, *, username: str) -> UserInDB: user_row = await queries.get_user_by_username( self.connection, username=username, ) if user_row: return UserInDB(**user_row) raise EntityDoesNotExist( "user with username {0} does not exist".format(username), ) async def create_user( self, *, username: str, email: str, password: str, ) -> UserInDB: user = UserInDB(username=username, email=email) user.change_password(password) async with self.connection.transaction(): user_row = await queries.create_new_user( self.connection, username=user.username, email=user.email, salt=user.salt, hashed_password=user.hashed_password, ) return user.copy(update=dict(user_row)) async def update_user( # noqa: WPS211 self, *, user: User, username: Optional[str] = None, email: Optional[str] = None, password: Optional[str] = None, bio: Optional[str] = None, image: Optional[str] = None, ) -> UserInDB: user_in_db = await self.get_user_by_username(username=user.username) user_in_db.username = username or user_in_db.username user_in_db.email = email or user_in_db.email user_in_db.bio = bio or user_in_db.bio user_in_db.image = image or user_in_db.image if password: user_in_db.change_password(password) async with self.connection.transaction(): user_in_db.updated_at = await queries.update_user_by_username( self.connection, username=user.username, new_username=user_in_db.username, new_email=user_in_db.email, new_salt=user_in_db.salt, new_password=user_in_db.hashed_password, new_bio=user_in_db.bio, new_image=user_in_db.image, ) return user_in_db class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None class UserInUpdate(BaseModel): username: Optional[str] = None email: Optional[EmailStr] = None password: Optional[str] = None bio: Optional[str] = None image: Optional[HttpUrl] = None class UserWithToken(User): token: str class UserInResponse(RWSchema): user: UserWithToken import jwt async def check_username_is_taken(repo: UsersRepository, username: str) -> bool: try: await repo.get_user_by_username(username=username) except EntityDoesNotExist: return False return True async def check_email_is_taken(repo: UsersRepository, email: str) -> bool: try: await repo.get_user_by_email(email=email) except EntityDoesNotExist: return False return True async def update_current_user( user_update: UserInUpdate = Body(..., embed=True, alias="user"), current_user: User = Depends(get_current_user_authorizer()), users_repo: UsersRepository = Depends(get_repository(UsersRepository)), settings: AppSettings = Depends(get_app_settings), ) -> UserInResponse: if user_update.username and user_update.username != current_user.username: if await check_username_is_taken(users_repo, user_update.username): raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.USERNAME_TAKEN, ) if user_update.email and user_update.email != current_user.email: if await check_email_is_taken(users_repo, user_update.email): raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.EMAIL_TAKEN, ) user = await users_repo.update_user(user=current_user, **user_update.dict()) token = jwt.create_access_token_for_user( user, str(settings.secret_key.get_secret_value()), ) return UserInResponse( user=UserWithToken( username=user.username, email=user.email, bio=user.bio, image=user.image, token=token, ), )
null
167,822
from fastapi import APIRouter, Depends, HTTPException from starlette.status import HTTP_400_BAD_REQUEST from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.api.dependencies.profiles import get_profile_by_username_from_path from app.db.repositories.profiles import ProfilesRepository from app.models.domain.profiles import Profile from app.models.domain.users import User from app.models.schemas.profiles import ProfileInResponse from app.resources import strings async def get_profile_by_username_from_path( username: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), profiles_repo: ProfilesRepository = Depends(get_repository(ProfilesRepository)), ) -> Profile: try: return await profiles_repo.get_profile_by_username( username=username, requested_user=user, ) except EntityDoesNotExist: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail=strings.USER_DOES_NOT_EXIST_ERROR, ) class Profile(RWModel): username: str bio: str = "" image: Optional[str] = None following: bool = False class ProfileInResponse(BaseModel): profile: Profile async def retrieve_profile_by_username( profile: Profile = Depends(get_profile_by_username_from_path), ) -> ProfileInResponse: return ProfileInResponse(profile=profile)
null
167,823
from fastapi import APIRouter, Depends, HTTPException from starlette.status import HTTP_400_BAD_REQUEST from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.api.dependencies.profiles import get_profile_by_username_from_path from app.db.repositories.profiles import ProfilesRepository from app.models.domain.profiles import Profile from app.models.domain.users import User from app.models.schemas.profiles import ProfileInResponse from app.resources import strings def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo async def get_profile_by_username_from_path( username: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), profiles_repo: ProfilesRepository = Depends(get_repository(ProfilesRepository)), ) -> Profile: try: return await profiles_repo.get_profile_by_username( username=username, requested_user=user, ) except EntityDoesNotExist: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail=strings.USER_DOES_NOT_EXIST_ERROR, ) class ProfilesRepository(BaseRepository): def __init__(self, conn: Connection): super().__init__(conn) self._users_repo = UsersRepository(conn) async def get_profile_by_username( self, *, username: str, requested_user: Optional[UserLike], ) -> Profile: user = await self._users_repo.get_user_by_username(username=username) profile = Profile(username=user.username, bio=user.bio, image=user.image) if requested_user: profile.following = await self.is_user_following_for_another_user( target_user=user, requested_user=requested_user, ) return profile async def is_user_following_for_another_user( self, *, target_user: UserLike, requested_user: UserLike, ) -> bool: return ( await queries.is_user_following_for_another( self.connection, follower_username=requested_user.username, following_username=target_user.username, ) )["is_following"] async def add_user_into_followers( self, *, target_user: UserLike, requested_user: UserLike, ) -> None: async with self.connection.transaction(): await queries.subscribe_user_to_another( self.connection, follower_username=requested_user.username, following_username=target_user.username, ) async def remove_user_from_followers( self, *, target_user: UserLike, requested_user: UserLike, ) -> None: async with self.connection.transaction(): await queries.unsubscribe_user_from_another( self.connection, follower_username=requested_user.username, following_username=target_user.username, ) class Profile(RWModel): username: str bio: str = "" image: Optional[str] = None following: bool = False class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None class ProfileInResponse(BaseModel): profile: Profile async def follow_for_user( profile: Profile = Depends(get_profile_by_username_from_path), user: User = Depends(get_current_user_authorizer()), profiles_repo: ProfilesRepository = Depends(get_repository(ProfilesRepository)), ) -> ProfileInResponse: if user.username == profile.username: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.UNABLE_TO_FOLLOW_YOURSELF, ) if profile.following: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.USER_IS_ALREADY_FOLLOWED, ) await profiles_repo.add_user_into_followers( target_user=profile, requested_user=user, ) return ProfileInResponse(profile=profile.copy(update={"following": True}))
null
167,824
from fastapi import APIRouter, Depends, HTTPException from starlette.status import HTTP_400_BAD_REQUEST from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.api.dependencies.profiles import get_profile_by_username_from_path from app.db.repositories.profiles import ProfilesRepository from app.models.domain.profiles import Profile from app.models.domain.users import User from app.models.schemas.profiles import ProfileInResponse from app.resources import strings def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo async def get_profile_by_username_from_path( username: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), profiles_repo: ProfilesRepository = Depends(get_repository(ProfilesRepository)), ) -> Profile: try: return await profiles_repo.get_profile_by_username( username=username, requested_user=user, ) except EntityDoesNotExist: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail=strings.USER_DOES_NOT_EXIST_ERROR, ) class ProfilesRepository(BaseRepository): def __init__(self, conn: Connection): super().__init__(conn) self._users_repo = UsersRepository(conn) async def get_profile_by_username( self, *, username: str, requested_user: Optional[UserLike], ) -> Profile: user = await self._users_repo.get_user_by_username(username=username) profile = Profile(username=user.username, bio=user.bio, image=user.image) if requested_user: profile.following = await self.is_user_following_for_another_user( target_user=user, requested_user=requested_user, ) return profile async def is_user_following_for_another_user( self, *, target_user: UserLike, requested_user: UserLike, ) -> bool: return ( await queries.is_user_following_for_another( self.connection, follower_username=requested_user.username, following_username=target_user.username, ) )["is_following"] async def add_user_into_followers( self, *, target_user: UserLike, requested_user: UserLike, ) -> None: async with self.connection.transaction(): await queries.subscribe_user_to_another( self.connection, follower_username=requested_user.username, following_username=target_user.username, ) async def remove_user_from_followers( self, *, target_user: UserLike, requested_user: UserLike, ) -> None: async with self.connection.transaction(): await queries.unsubscribe_user_from_another( self.connection, follower_username=requested_user.username, following_username=target_user.username, ) class Profile(RWModel): username: str bio: str = "" image: Optional[str] = None following: bool = False class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None class ProfileInResponse(BaseModel): profile: Profile async def unsubscribe_from_user( profile: Profile = Depends(get_profile_by_username_from_path), user: User = Depends(get_current_user_authorizer()), profiles_repo: ProfilesRepository = Depends(get_repository(ProfilesRepository)), ) -> ProfileInResponse: if user.username == profile.username: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.UNABLE_TO_UNSUBSCRIBE_FROM_YOURSELF, ) if not profile.following: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.USER_IS_NOT_FOLLOWED, ) await profiles_repo.remove_user_from_followers( target_user=profile, requested_user=user, ) return ProfileInResponse(profile=profile.copy(update={"following": False}))
null
167,825
from fastapi import APIRouter, Body, Depends, HTTPException from starlette.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST from app.api.dependencies.database import get_repository from app.core.config import get_app_settings from app.core.settings.app import AppSettings from app.db.errors import EntityDoesNotExist from app.db.repositories.users import UsersRepository from app.models.schemas.users import ( UserInCreate, UserInLogin, UserInResponse, UserWithToken, ) from app.resources import strings from app.services import jwt from app.services.authentication import check_email_is_taken, check_username_is_taken def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo def get_app_settings() -> AppSettings: app_env = BaseAppSettings().app_env config = environments[app_env] return config() class AppSettings(BaseAppSettings): debug: bool = False docs_url: str = "/docs" openapi_prefix: str = "" openapi_url: str = "/openapi.json" redoc_url: str = "/redoc" title: str = "FastAPI example application" version: str = "0.0.0" database_url: PostgresDsn max_connection_count: int = 10 min_connection_count: int = 10 secret_key: SecretStr api_prefix: str = "/api" jwt_token_prefix: str = "Token" allowed_hosts: List[str] = ["*"] logging_level: int = logging.INFO loggers: Tuple[str, str] = ("uvicorn.asgi", "uvicorn.access") class Config: validate_assignment = True def fastapi_kwargs(self) -> Dict[str, Any]: return { "debug": self.debug, "docs_url": self.docs_url, "openapi_prefix": self.openapi_prefix, "openapi_url": self.openapi_url, "redoc_url": self.redoc_url, "title": self.title, "version": self.version, } def configure_logging(self) -> None: logging.getLogger().handlers = [InterceptHandler()] for logger_name in self.loggers: logging_logger = logging.getLogger(logger_name) logging_logger.handlers = [InterceptHandler(level=self.logging_level)] logger.configure(handlers=[{"sink": sys.stderr, "level": self.logging_level}]) class EntityDoesNotExist(Exception): """Raised when entity was not found in database.""" class UsersRepository(BaseRepository): async def get_user_by_email(self, *, email: str) -> UserInDB: user_row = await queries.get_user_by_email(self.connection, email=email) if user_row: return UserInDB(**user_row) raise EntityDoesNotExist("user with email {0} does not exist".format(email)) async def get_user_by_username(self, *, username: str) -> UserInDB: user_row = await queries.get_user_by_username( self.connection, username=username, ) if user_row: return UserInDB(**user_row) raise EntityDoesNotExist( "user with username {0} does not exist".format(username), ) async def create_user( self, *, username: str, email: str, password: str, ) -> UserInDB: user = UserInDB(username=username, email=email) user.change_password(password) async with self.connection.transaction(): user_row = await queries.create_new_user( self.connection, username=user.username, email=user.email, salt=user.salt, hashed_password=user.hashed_password, ) return user.copy(update=dict(user_row)) async def update_user( # noqa: WPS211 self, *, user: User, username: Optional[str] = None, email: Optional[str] = None, password: Optional[str] = None, bio: Optional[str] = None, image: Optional[str] = None, ) -> UserInDB: user_in_db = await self.get_user_by_username(username=user.username) user_in_db.username = username or user_in_db.username user_in_db.email = email or user_in_db.email user_in_db.bio = bio or user_in_db.bio user_in_db.image = image or user_in_db.image if password: user_in_db.change_password(password) async with self.connection.transaction(): user_in_db.updated_at = await queries.update_user_by_username( self.connection, username=user.username, new_username=user_in_db.username, new_email=user_in_db.email, new_salt=user_in_db.salt, new_password=user_in_db.hashed_password, new_bio=user_in_db.bio, new_image=user_in_db.image, ) return user_in_db class UserInLogin(RWSchema): email: EmailStr password: str class UserWithToken(User): token: str class UserInResponse(RWSchema): user: UserWithToken import jwt async def login( user_login: UserInLogin = Body(..., embed=True, alias="user"), users_repo: UsersRepository = Depends(get_repository(UsersRepository)), settings: AppSettings = Depends(get_app_settings), ) -> UserInResponse: wrong_login_error = HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.INCORRECT_LOGIN_INPUT, ) try: user = await users_repo.get_user_by_email(email=user_login.email) except EntityDoesNotExist as existence_error: raise wrong_login_error from existence_error if not user.check_password(user_login.password): raise wrong_login_error token = jwt.create_access_token_for_user( user, str(settings.secret_key.get_secret_value()), ) return UserInResponse( user=UserWithToken( username=user.username, email=user.email, bio=user.bio, image=user.image, token=token, ), )
null
167,826
from fastapi import APIRouter, Body, Depends, HTTPException from starlette.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST from app.api.dependencies.database import get_repository from app.core.config import get_app_settings from app.core.settings.app import AppSettings from app.db.errors import EntityDoesNotExist from app.db.repositories.users import UsersRepository from app.models.schemas.users import ( UserInCreate, UserInLogin, UserInResponse, UserWithToken, ) from app.resources import strings from app.services import jwt from app.services.authentication import check_email_is_taken, check_username_is_taken def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo def get_app_settings() -> AppSettings: app_env = BaseAppSettings().app_env config = environments[app_env] return config() class AppSettings(BaseAppSettings): debug: bool = False docs_url: str = "/docs" openapi_prefix: str = "" openapi_url: str = "/openapi.json" redoc_url: str = "/redoc" title: str = "FastAPI example application" version: str = "0.0.0" database_url: PostgresDsn max_connection_count: int = 10 min_connection_count: int = 10 secret_key: SecretStr api_prefix: str = "/api" jwt_token_prefix: str = "Token" allowed_hosts: List[str] = ["*"] logging_level: int = logging.INFO loggers: Tuple[str, str] = ("uvicorn.asgi", "uvicorn.access") class Config: validate_assignment = True def fastapi_kwargs(self) -> Dict[str, Any]: return { "debug": self.debug, "docs_url": self.docs_url, "openapi_prefix": self.openapi_prefix, "openapi_url": self.openapi_url, "redoc_url": self.redoc_url, "title": self.title, "version": self.version, } def configure_logging(self) -> None: logging.getLogger().handlers = [InterceptHandler()] for logger_name in self.loggers: logging_logger = logging.getLogger(logger_name) logging_logger.handlers = [InterceptHandler(level=self.logging_level)] logger.configure(handlers=[{"sink": sys.stderr, "level": self.logging_level}]) class UsersRepository(BaseRepository): async def get_user_by_email(self, *, email: str) -> UserInDB: user_row = await queries.get_user_by_email(self.connection, email=email) if user_row: return UserInDB(**user_row) raise EntityDoesNotExist("user with email {0} does not exist".format(email)) async def get_user_by_username(self, *, username: str) -> UserInDB: user_row = await queries.get_user_by_username( self.connection, username=username, ) if user_row: return UserInDB(**user_row) raise EntityDoesNotExist( "user with username {0} does not exist".format(username), ) async def create_user( self, *, username: str, email: str, password: str, ) -> UserInDB: user = UserInDB(username=username, email=email) user.change_password(password) async with self.connection.transaction(): user_row = await queries.create_new_user( self.connection, username=user.username, email=user.email, salt=user.salt, hashed_password=user.hashed_password, ) return user.copy(update=dict(user_row)) async def update_user( # noqa: WPS211 self, *, user: User, username: Optional[str] = None, email: Optional[str] = None, password: Optional[str] = None, bio: Optional[str] = None, image: Optional[str] = None, ) -> UserInDB: user_in_db = await self.get_user_by_username(username=user.username) user_in_db.username = username or user_in_db.username user_in_db.email = email or user_in_db.email user_in_db.bio = bio or user_in_db.bio user_in_db.image = image or user_in_db.image if password: user_in_db.change_password(password) async with self.connection.transaction(): user_in_db.updated_at = await queries.update_user_by_username( self.connection, username=user.username, new_username=user_in_db.username, new_email=user_in_db.email, new_salt=user_in_db.salt, new_password=user_in_db.hashed_password, new_bio=user_in_db.bio, new_image=user_in_db.image, ) return user_in_db class UserInCreate(UserInLogin): username: str class UserWithToken(User): token: str class UserInResponse(RWSchema): user: UserWithToken import jwt async def check_username_is_taken(repo: UsersRepository, username: str) -> bool: try: await repo.get_user_by_username(username=username) except EntityDoesNotExist: return False return True async def check_email_is_taken(repo: UsersRepository, email: str) -> bool: try: await repo.get_user_by_email(email=email) except EntityDoesNotExist: return False return True async def register( user_create: UserInCreate = Body(..., embed=True, alias="user"), users_repo: UsersRepository = Depends(get_repository(UsersRepository)), settings: AppSettings = Depends(get_app_settings), ) -> UserInResponse: if await check_username_is_taken(users_repo, user_create.username): raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.USERNAME_TAKEN, ) if await check_email_is_taken(users_repo, user_create.email): raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.EMAIL_TAKEN, ) user = await users_repo.create_user(**user_create.dict()) token = jwt.create_access_token_for_user( user, str(settings.secret_key.get_secret_value()), ) return UserInResponse( user=UserWithToken( username=user.username, email=user.email, bio=user.bio, image=user.image, token=token, ), )
null
167,827
from typing import Optional from fastapi import APIRouter, Body, Depends, HTTPException, Response from starlette import status from app.api.dependencies.articles import ( check_article_modification_permissions, get_article_by_slug_from_path, get_articles_filters, ) from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( ArticleForResponse, ArticleInCreate, ArticleInResponse, ArticleInUpdate, ArticlesFilters, ListOfArticlesInResponse, ) from app.resources import strings from app.services.articles import check_article_exists, get_slug_for_article def get_articles_filters( tag: Optional[str] = None, author: Optional[str] = None, favorited: Optional[str] = None, limit: int = Query(DEFAULT_ARTICLES_LIMIT, ge=1), offset: int = Query(DEFAULT_ARTICLES_OFFSET, ge=0), ) -> ArticlesFilters: return ArticlesFilters( tag=tag, author=author, favorited=favorited, limit=limit, offset=offset, ) def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class ArticlesRepository(BaseRepository): # noqa: WPS214 def __init__(self, conn: Connection) -> None: super().__init__(conn) self._profiles_repo = ProfilesRepository(conn) self._tags_repo = TagsRepository(conn) async def create_article( # noqa: WPS211 self, *, slug: str, title: str, description: str, body: str, author: User, tags: Optional[Sequence[str]] = None, ) -> Article: async with self.connection.transaction(): article_row = await queries.create_new_article( self.connection, slug=slug, title=title, description=description, body=body, author_username=author.username, ) if tags: await self._tags_repo.create_tags_that_dont_exist(tags=tags) await self._link_article_with_tags(slug=slug, tags=tags) return await self._get_article_from_db_record( article_row=article_row, slug=slug, author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=author, ) async def update_article( # noqa: WPS211 self, *, article: Article, slug: Optional[str] = None, title: Optional[str] = None, body: Optional[str] = None, description: Optional[str] = None, ) -> Article: updated_article = article.copy(deep=True) updated_article.slug = slug or updated_article.slug updated_article.title = title or article.title updated_article.body = body or article.body updated_article.description = description or article.description async with self.connection.transaction(): updated_article.updated_at = await queries.update_article( self.connection, slug=article.slug, author_username=article.author.username, new_slug=updated_article.slug, new_title=updated_article.title, new_body=updated_article.body, new_description=updated_article.description, ) return updated_article async def delete_article(self, *, article: Article) -> None: async with self.connection.transaction(): await queries.delete_article( self.connection, slug=article.slug, author_username=article.author.username, ) async def filter_articles( # noqa: WPS211 self, *, tag: Optional[str] = None, author: Optional[str] = None, favorited: Optional[str] = None, limit: int = 20, offset: int = 0, requested_user: Optional[User] = None, ) -> List[Article]: query_params: List[Union[str, int]] = [] query_params_count = 0 # fmt: off query = Query.from_( articles, ).select( articles.id, articles.slug, articles.title, articles.description, articles.body, articles.created_at, articles.updated_at, Query.from_( users, ).where( users.id == articles.author_id, ).select( users.username, ).as_( AUTHOR_USERNAME_ALIAS, ), ) # fmt: on if tag: query_params.append(tag) query_params_count += 1 # fmt: off query = query.join( articles_to_tags, ).on( (articles.id == articles_to_tags.article_id) & ( articles_to_tags.tag == Query.from_( tags_table, ).where( tags_table.tag == Parameter(query_params_count), ).select( tags_table.tag, ) ), ) # fmt: on if author: query_params.append(author) query_params_count += 1 # fmt: off query = query.join( users, ).on( (articles.author_id == users.id) & ( users.id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on if favorited: query_params.append(favorited) query_params_count += 1 # fmt: off query = query.join( favorites, ).on( (articles.id == favorites.article_id) & ( favorites.user_id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on query = query.limit(Parameter(query_params_count + 1)).offset( Parameter(query_params_count + 2), ) query_params.extend([limit, offset]) articles_rows = await self.connection.fetch(query.get_sql(), *query_params) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) for article_row in articles_rows ] async def get_articles_for_user_feed( self, *, user: User, limit: int = 20, offset: int = 0, ) -> List[Article]: articles_rows = await queries.get_articles_for_feed( self.connection, follower_username=user.username, limit=limit, offset=offset, ) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=user, ) for article_row in articles_rows ] async def get_article_by_slug( self, *, slug: str, requested_user: Optional[User] = None, ) -> Article: article_row = await queries.get_article_by_slug(self.connection, slug=slug) if article_row: return await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) raise EntityDoesNotExist("article with slug {0} does not exist".format(slug)) async def get_tags_for_article_by_slug(self, *, slug: str) -> List[str]: tag_rows = await queries.get_tags_for_article_by_slug( self.connection, slug=slug, ) return [row["tag"] for row in tag_rows] async def get_favorites_count_for_article_by_slug(self, *, slug: str) -> int: return ( await queries.get_favorites_count_for_article(self.connection, slug=slug) )["favorites_count"] async def is_article_favorited_by_user(self, *, slug: str, user: User) -> bool: return ( await queries.is_article_in_favorites( self.connection, username=user.username, slug=slug, ) )["favorited"] async def add_article_into_favorites(self, *, article: Article, user: User) -> None: await queries.add_article_to_favorites( self.connection, username=user.username, slug=article.slug, ) async def remove_article_from_favorites( self, *, article: Article, user: User, ) -> None: await queries.remove_article_from_favorites( self.connection, username=user.username, slug=article.slug, ) async def _get_article_from_db_record( self, *, article_row: Record, slug: str, author_username: str, requested_user: Optional[User], ) -> Article: return Article( id_=article_row["id"], slug=slug, title=article_row["title"], description=article_row["description"], body=article_row["body"], author=await self._profiles_repo.get_profile_by_username( username=author_username, requested_user=requested_user, ), tags=await self.get_tags_for_article_by_slug(slug=slug), favorites_count=await self.get_favorites_count_for_article_by_slug( slug=slug, ), favorited=await self.is_article_favorited_by_user( slug=slug, user=requested_user, ) if requested_user else False, created_at=article_row["created_at"], updated_at=article_row["updated_at"], ) async def _link_article_with_tags(self, *, slug: str, tags: Sequence[str]) -> None: await queries.add_tags_to_article( self.connection, [{SLUG_ALIAS: slug, "tag": tag} for tag in tags], ) class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None class ArticleForResponse(RWSchema, Article): tags: List[str] = Field(..., alias="tagList") class ListOfArticlesInResponse(RWSchema): articles: List[ArticleForResponse] articles_count: int class ArticlesFilters(BaseModel): tag: Optional[str] = None author: Optional[str] = None favorited: Optional[str] = None limit: int = Field(DEFAULT_ARTICLES_LIMIT, ge=1) offset: int = Field(DEFAULT_ARTICLES_OFFSET, ge=0) async def list_articles( articles_filters: ArticlesFilters = Depends(get_articles_filters), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> ListOfArticlesInResponse: articles = await articles_repo.filter_articles( tag=articles_filters.tag, author=articles_filters.author, favorited=articles_filters.favorited, limit=articles_filters.limit, offset=articles_filters.offset, requested_user=user, ) articles_for_response = [ ArticleForResponse.from_orm(article) for article in articles ] return ListOfArticlesInResponse( articles=articles_for_response, articles_count=len(articles), )
null
167,828
from typing import Optional from fastapi import APIRouter, Body, Depends, HTTPException, Response from starlette import status from app.api.dependencies.articles import ( check_article_modification_permissions, get_article_by_slug_from_path, get_articles_filters, ) from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( ArticleForResponse, ArticleInCreate, ArticleInResponse, ArticleInUpdate, ArticlesFilters, ListOfArticlesInResponse, ) from app.resources import strings from app.services.articles import check_article_exists, get_slug_for_article def get_current_user_authorizer(*, required: bool = True) -> Callable: def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: class ArticlesRepository(BaseRepository): def __init__(self, conn: Connection) -> None: async def create_article( # noqa: WPS211 self, *, slug: str, title: str, description: str, body: str, author: User, tags: Optional[Sequence[str]] = None, ) -> Article: async def update_article( # noqa: WPS211 self, *, article: Article, slug: Optional[str] = None, title: Optional[str] = None, body: Optional[str] = None, description: Optional[str] = None, ) -> Article: async def delete_article(self, *, article: Article) -> None: async def filter_articles( # noqa: WPS211 self, *, tag: Optional[str] = None, author: Optional[str] = None, favorited: Optional[str] = None, limit: int = 20, offset: int = 0, requested_user: Optional[User] = None, ) -> List[Article]: async def get_articles_for_user_feed( self, *, user: User, limit: int = 20, offset: int = 0, ) -> List[Article]: async def get_article_by_slug( self, *, slug: str, requested_user: Optional[User] = None, ) -> Article: async def get_tags_for_article_by_slug(self, *, slug: str) -> List[str]: async def get_favorites_count_for_article_by_slug(self, *, slug: str) -> int: async def is_article_favorited_by_user(self, *, slug: str, user: User) -> bool: async def add_article_into_favorites(self, *, article: Article, user: User) -> None: async def remove_article_from_favorites( self, *, article: Article, user: User, ) -> None: async def _get_article_from_db_record( self, *, article_row: Record, slug: str, author_username: str, requested_user: Optional[User], ) -> Article: async def _link_article_with_tags(self, *, slug: str, tags: Sequence[str]) -> None: class User(RWModel): class ArticleForResponse(RWSchema, Article): class ArticleInResponse(RWSchema): class ArticleInCreate(RWSchema): async def check_article_exists(articles_repo: ArticlesRepository, slug: str) -> bool: def get_slug_for_article(title: str) -> str: async def create_new_article( article_create: ArticleInCreate = Body(..., embed=True, alias="article"), user: User = Depends(get_current_user_authorizer()), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> ArticleInResponse: slug = get_slug_for_article(article_create.title) if await check_article_exists(articles_repo, slug): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=strings.ARTICLE_ALREADY_EXISTS, ) article = await articles_repo.create_article( slug=slug, title=article_create.title, description=article_create.description, body=article_create.body, author=user, tags=article_create.tags, ) return ArticleInResponse(article=ArticleForResponse.from_orm(article))
null
167,829
from typing import Optional from fastapi import APIRouter, Body, Depends, HTTPException, Response from starlette import status from app.api.dependencies.articles import ( check_article_modification_permissions, get_article_by_slug_from_path, get_articles_filters, ) from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( ArticleForResponse, ArticleInCreate, ArticleInResponse, ArticleInUpdate, ArticlesFilters, ListOfArticlesInResponse, ) from app.resources import strings from app.services.articles import check_article_exists, get_slug_for_article async def get_article_by_slug_from_path( slug: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> Article: try: return await articles_repo.get_article_by_slug(slug=slug, requested_user=user) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.ARTICLE_DOES_NOT_EXIST_ERROR, ) class Article(IDModelMixin, DateTimeModelMixin, RWModel): slug: str title: str description: str body: str tags: List[str] author: Profile favorited: bool favorites_count: int class ArticleForResponse(RWSchema, Article): tags: List[str] = Field(..., alias="tagList") class ArticleInResponse(RWSchema): article: ArticleForResponse async def retrieve_article_by_slug( article: Article = Depends(get_article_by_slug_from_path), ) -> ArticleInResponse: return ArticleInResponse(article=ArticleForResponse.from_orm(article))
null
167,830
from typing import Optional from fastapi import APIRouter, Body, Depends, HTTPException, Response from starlette import status from app.api.dependencies.articles import ( check_article_modification_permissions, get_article_by_slug_from_path, get_articles_filters, ) from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( ArticleForResponse, ArticleInCreate, ArticleInResponse, ArticleInUpdate, ArticlesFilters, ListOfArticlesInResponse, ) from app.resources import strings from app.services.articles import check_article_exists, get_slug_for_article async def get_article_by_slug_from_path( slug: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> Article: try: return await articles_repo.get_article_by_slug(slug=slug, requested_user=user) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.ARTICLE_DOES_NOT_EXIST_ERROR, ) def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class ArticlesRepository(BaseRepository): # noqa: WPS214 def __init__(self, conn: Connection) -> None: super().__init__(conn) self._profiles_repo = ProfilesRepository(conn) self._tags_repo = TagsRepository(conn) async def create_article( # noqa: WPS211 self, *, slug: str, title: str, description: str, body: str, author: User, tags: Optional[Sequence[str]] = None, ) -> Article: async with self.connection.transaction(): article_row = await queries.create_new_article( self.connection, slug=slug, title=title, description=description, body=body, author_username=author.username, ) if tags: await self._tags_repo.create_tags_that_dont_exist(tags=tags) await self._link_article_with_tags(slug=slug, tags=tags) return await self._get_article_from_db_record( article_row=article_row, slug=slug, author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=author, ) async def update_article( # noqa: WPS211 self, *, article: Article, slug: Optional[str] = None, title: Optional[str] = None, body: Optional[str] = None, description: Optional[str] = None, ) -> Article: updated_article = article.copy(deep=True) updated_article.slug = slug or updated_article.slug updated_article.title = title or article.title updated_article.body = body or article.body updated_article.description = description or article.description async with self.connection.transaction(): updated_article.updated_at = await queries.update_article( self.connection, slug=article.slug, author_username=article.author.username, new_slug=updated_article.slug, new_title=updated_article.title, new_body=updated_article.body, new_description=updated_article.description, ) return updated_article async def delete_article(self, *, article: Article) -> None: async with self.connection.transaction(): await queries.delete_article( self.connection, slug=article.slug, author_username=article.author.username, ) async def filter_articles( # noqa: WPS211 self, *, tag: Optional[str] = None, author: Optional[str] = None, favorited: Optional[str] = None, limit: int = 20, offset: int = 0, requested_user: Optional[User] = None, ) -> List[Article]: query_params: List[Union[str, int]] = [] query_params_count = 0 # fmt: off query = Query.from_( articles, ).select( articles.id, articles.slug, articles.title, articles.description, articles.body, articles.created_at, articles.updated_at, Query.from_( users, ).where( users.id == articles.author_id, ).select( users.username, ).as_( AUTHOR_USERNAME_ALIAS, ), ) # fmt: on if tag: query_params.append(tag) query_params_count += 1 # fmt: off query = query.join( articles_to_tags, ).on( (articles.id == articles_to_tags.article_id) & ( articles_to_tags.tag == Query.from_( tags_table, ).where( tags_table.tag == Parameter(query_params_count), ).select( tags_table.tag, ) ), ) # fmt: on if author: query_params.append(author) query_params_count += 1 # fmt: off query = query.join( users, ).on( (articles.author_id == users.id) & ( users.id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on if favorited: query_params.append(favorited) query_params_count += 1 # fmt: off query = query.join( favorites, ).on( (articles.id == favorites.article_id) & ( favorites.user_id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on query = query.limit(Parameter(query_params_count + 1)).offset( Parameter(query_params_count + 2), ) query_params.extend([limit, offset]) articles_rows = await self.connection.fetch(query.get_sql(), *query_params) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) for article_row in articles_rows ] async def get_articles_for_user_feed( self, *, user: User, limit: int = 20, offset: int = 0, ) -> List[Article]: articles_rows = await queries.get_articles_for_feed( self.connection, follower_username=user.username, limit=limit, offset=offset, ) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=user, ) for article_row in articles_rows ] async def get_article_by_slug( self, *, slug: str, requested_user: Optional[User] = None, ) -> Article: article_row = await queries.get_article_by_slug(self.connection, slug=slug) if article_row: return await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) raise EntityDoesNotExist("article with slug {0} does not exist".format(slug)) async def get_tags_for_article_by_slug(self, *, slug: str) -> List[str]: tag_rows = await queries.get_tags_for_article_by_slug( self.connection, slug=slug, ) return [row["tag"] for row in tag_rows] async def get_favorites_count_for_article_by_slug(self, *, slug: str) -> int: return ( await queries.get_favorites_count_for_article(self.connection, slug=slug) )["favorites_count"] async def is_article_favorited_by_user(self, *, slug: str, user: User) -> bool: return ( await queries.is_article_in_favorites( self.connection, username=user.username, slug=slug, ) )["favorited"] async def add_article_into_favorites(self, *, article: Article, user: User) -> None: await queries.add_article_to_favorites( self.connection, username=user.username, slug=article.slug, ) async def remove_article_from_favorites( self, *, article: Article, user: User, ) -> None: await queries.remove_article_from_favorites( self.connection, username=user.username, slug=article.slug, ) async def _get_article_from_db_record( self, *, article_row: Record, slug: str, author_username: str, requested_user: Optional[User], ) -> Article: return Article( id_=article_row["id"], slug=slug, title=article_row["title"], description=article_row["description"], body=article_row["body"], author=await self._profiles_repo.get_profile_by_username( username=author_username, requested_user=requested_user, ), tags=await self.get_tags_for_article_by_slug(slug=slug), favorites_count=await self.get_favorites_count_for_article_by_slug( slug=slug, ), favorited=await self.is_article_favorited_by_user( slug=slug, user=requested_user, ) if requested_user else False, created_at=article_row["created_at"], updated_at=article_row["updated_at"], ) async def _link_article_with_tags(self, *, slug: str, tags: Sequence[str]) -> None: await queries.add_tags_to_article( self.connection, [{SLUG_ALIAS: slug, "tag": tag} for tag in tags], ) class Article(IDModelMixin, DateTimeModelMixin, RWModel): slug: str title: str description: str body: str tags: List[str] author: Profile favorited: bool favorites_count: int class ArticleForResponse(RWSchema, Article): tags: List[str] = Field(..., alias="tagList") class ArticleInResponse(RWSchema): article: ArticleForResponse class ArticleInUpdate(RWSchema): title: Optional[str] = None description: Optional[str] = None body: Optional[str] = None def get_slug_for_article(title: str) -> str: return slugify(title) async def update_article_by_slug( article_update: ArticleInUpdate = Body(..., embed=True, alias="article"), current_article: Article = Depends(get_article_by_slug_from_path), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> ArticleInResponse: slug = get_slug_for_article(article_update.title) if article_update.title else None article = await articles_repo.update_article( article=current_article, slug=slug, **article_update.dict(), ) return ArticleInResponse(article=ArticleForResponse.from_orm(article))
null
167,831
from typing import Optional from fastapi import APIRouter, Body, Depends, HTTPException, Response from starlette import status from app.api.dependencies.articles import ( check_article_modification_permissions, get_article_by_slug_from_path, get_articles_filters, ) from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( ArticleForResponse, ArticleInCreate, ArticleInResponse, ArticleInUpdate, ArticlesFilters, ListOfArticlesInResponse, ) from app.resources import strings from app.services.articles import check_article_exists, get_slug_for_article async def get_article_by_slug_from_path( slug: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> Article: try: return await articles_repo.get_article_by_slug(slug=slug, requested_user=user) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.ARTICLE_DOES_NOT_EXIST_ERROR, ) def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class ArticlesRepository(BaseRepository): # noqa: WPS214 def __init__(self, conn: Connection) -> None: super().__init__(conn) self._profiles_repo = ProfilesRepository(conn) self._tags_repo = TagsRepository(conn) async def create_article( # noqa: WPS211 self, *, slug: str, title: str, description: str, body: str, author: User, tags: Optional[Sequence[str]] = None, ) -> Article: async with self.connection.transaction(): article_row = await queries.create_new_article( self.connection, slug=slug, title=title, description=description, body=body, author_username=author.username, ) if tags: await self._tags_repo.create_tags_that_dont_exist(tags=tags) await self._link_article_with_tags(slug=slug, tags=tags) return await self._get_article_from_db_record( article_row=article_row, slug=slug, author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=author, ) async def update_article( # noqa: WPS211 self, *, article: Article, slug: Optional[str] = None, title: Optional[str] = None, body: Optional[str] = None, description: Optional[str] = None, ) -> Article: updated_article = article.copy(deep=True) updated_article.slug = slug or updated_article.slug updated_article.title = title or article.title updated_article.body = body or article.body updated_article.description = description or article.description async with self.connection.transaction(): updated_article.updated_at = await queries.update_article( self.connection, slug=article.slug, author_username=article.author.username, new_slug=updated_article.slug, new_title=updated_article.title, new_body=updated_article.body, new_description=updated_article.description, ) return updated_article async def delete_article(self, *, article: Article) -> None: async with self.connection.transaction(): await queries.delete_article( self.connection, slug=article.slug, author_username=article.author.username, ) async def filter_articles( # noqa: WPS211 self, *, tag: Optional[str] = None, author: Optional[str] = None, favorited: Optional[str] = None, limit: int = 20, offset: int = 0, requested_user: Optional[User] = None, ) -> List[Article]: query_params: List[Union[str, int]] = [] query_params_count = 0 # fmt: off query = Query.from_( articles, ).select( articles.id, articles.slug, articles.title, articles.description, articles.body, articles.created_at, articles.updated_at, Query.from_( users, ).where( users.id == articles.author_id, ).select( users.username, ).as_( AUTHOR_USERNAME_ALIAS, ), ) # fmt: on if tag: query_params.append(tag) query_params_count += 1 # fmt: off query = query.join( articles_to_tags, ).on( (articles.id == articles_to_tags.article_id) & ( articles_to_tags.tag == Query.from_( tags_table, ).where( tags_table.tag == Parameter(query_params_count), ).select( tags_table.tag, ) ), ) # fmt: on if author: query_params.append(author) query_params_count += 1 # fmt: off query = query.join( users, ).on( (articles.author_id == users.id) & ( users.id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on if favorited: query_params.append(favorited) query_params_count += 1 # fmt: off query = query.join( favorites, ).on( (articles.id == favorites.article_id) & ( favorites.user_id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on query = query.limit(Parameter(query_params_count + 1)).offset( Parameter(query_params_count + 2), ) query_params.extend([limit, offset]) articles_rows = await self.connection.fetch(query.get_sql(), *query_params) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) for article_row in articles_rows ] async def get_articles_for_user_feed( self, *, user: User, limit: int = 20, offset: int = 0, ) -> List[Article]: articles_rows = await queries.get_articles_for_feed( self.connection, follower_username=user.username, limit=limit, offset=offset, ) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=user, ) for article_row in articles_rows ] async def get_article_by_slug( self, *, slug: str, requested_user: Optional[User] = None, ) -> Article: article_row = await queries.get_article_by_slug(self.connection, slug=slug) if article_row: return await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) raise EntityDoesNotExist("article with slug {0} does not exist".format(slug)) async def get_tags_for_article_by_slug(self, *, slug: str) -> List[str]: tag_rows = await queries.get_tags_for_article_by_slug( self.connection, slug=slug, ) return [row["tag"] for row in tag_rows] async def get_favorites_count_for_article_by_slug(self, *, slug: str) -> int: return ( await queries.get_favorites_count_for_article(self.connection, slug=slug) )["favorites_count"] async def is_article_favorited_by_user(self, *, slug: str, user: User) -> bool: return ( await queries.is_article_in_favorites( self.connection, username=user.username, slug=slug, ) )["favorited"] async def add_article_into_favorites(self, *, article: Article, user: User) -> None: await queries.add_article_to_favorites( self.connection, username=user.username, slug=article.slug, ) async def remove_article_from_favorites( self, *, article: Article, user: User, ) -> None: await queries.remove_article_from_favorites( self.connection, username=user.username, slug=article.slug, ) async def _get_article_from_db_record( self, *, article_row: Record, slug: str, author_username: str, requested_user: Optional[User], ) -> Article: return Article( id_=article_row["id"], slug=slug, title=article_row["title"], description=article_row["description"], body=article_row["body"], author=await self._profiles_repo.get_profile_by_username( username=author_username, requested_user=requested_user, ), tags=await self.get_tags_for_article_by_slug(slug=slug), favorites_count=await self.get_favorites_count_for_article_by_slug( slug=slug, ), favorited=await self.is_article_favorited_by_user( slug=slug, user=requested_user, ) if requested_user else False, created_at=article_row["created_at"], updated_at=article_row["updated_at"], ) async def _link_article_with_tags(self, *, slug: str, tags: Sequence[str]) -> None: await queries.add_tags_to_article( self.connection, [{SLUG_ALIAS: slug, "tag": tag} for tag in tags], ) class Article(IDModelMixin, DateTimeModelMixin, RWModel): slug: str title: str description: str body: str tags: List[str] author: Profile favorited: bool favorites_count: int async def delete_article_by_slug( article: Article = Depends(get_article_by_slug_from_path), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> None: await articles_repo.delete_article(article=article)
null
167,832
from fastapi import APIRouter, Depends, HTTPException, Query from starlette import status from app.api.dependencies.articles import get_article_by_slug_from_path from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( DEFAULT_ARTICLES_LIMIT, DEFAULT_ARTICLES_OFFSET, ArticleForResponse, ArticleInResponse, ListOfArticlesInResponse, ) from app.resources import strings def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class ArticlesRepository(BaseRepository): # noqa: WPS214 def __init__(self, conn: Connection) -> None: super().__init__(conn) self._profiles_repo = ProfilesRepository(conn) self._tags_repo = TagsRepository(conn) async def create_article( # noqa: WPS211 self, *, slug: str, title: str, description: str, body: str, author: User, tags: Optional[Sequence[str]] = None, ) -> Article: async with self.connection.transaction(): article_row = await queries.create_new_article( self.connection, slug=slug, title=title, description=description, body=body, author_username=author.username, ) if tags: await self._tags_repo.create_tags_that_dont_exist(tags=tags) await self._link_article_with_tags(slug=slug, tags=tags) return await self._get_article_from_db_record( article_row=article_row, slug=slug, author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=author, ) async def update_article( # noqa: WPS211 self, *, article: Article, slug: Optional[str] = None, title: Optional[str] = None, body: Optional[str] = None, description: Optional[str] = None, ) -> Article: updated_article = article.copy(deep=True) updated_article.slug = slug or updated_article.slug updated_article.title = title or article.title updated_article.body = body or article.body updated_article.description = description or article.description async with self.connection.transaction(): updated_article.updated_at = await queries.update_article( self.connection, slug=article.slug, author_username=article.author.username, new_slug=updated_article.slug, new_title=updated_article.title, new_body=updated_article.body, new_description=updated_article.description, ) return updated_article async def delete_article(self, *, article: Article) -> None: async with self.connection.transaction(): await queries.delete_article( self.connection, slug=article.slug, author_username=article.author.username, ) async def filter_articles( # noqa: WPS211 self, *, tag: Optional[str] = None, author: Optional[str] = None, favorited: Optional[str] = None, limit: int = 20, offset: int = 0, requested_user: Optional[User] = None, ) -> List[Article]: query_params: List[Union[str, int]] = [] query_params_count = 0 # fmt: off query = Query.from_( articles, ).select( articles.id, articles.slug, articles.title, articles.description, articles.body, articles.created_at, articles.updated_at, Query.from_( users, ).where( users.id == articles.author_id, ).select( users.username, ).as_( AUTHOR_USERNAME_ALIAS, ), ) # fmt: on if tag: query_params.append(tag) query_params_count += 1 # fmt: off query = query.join( articles_to_tags, ).on( (articles.id == articles_to_tags.article_id) & ( articles_to_tags.tag == Query.from_( tags_table, ).where( tags_table.tag == Parameter(query_params_count), ).select( tags_table.tag, ) ), ) # fmt: on if author: query_params.append(author) query_params_count += 1 # fmt: off query = query.join( users, ).on( (articles.author_id == users.id) & ( users.id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on if favorited: query_params.append(favorited) query_params_count += 1 # fmt: off query = query.join( favorites, ).on( (articles.id == favorites.article_id) & ( favorites.user_id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on query = query.limit(Parameter(query_params_count + 1)).offset( Parameter(query_params_count + 2), ) query_params.extend([limit, offset]) articles_rows = await self.connection.fetch(query.get_sql(), *query_params) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) for article_row in articles_rows ] async def get_articles_for_user_feed( self, *, user: User, limit: int = 20, offset: int = 0, ) -> List[Article]: articles_rows = await queries.get_articles_for_feed( self.connection, follower_username=user.username, limit=limit, offset=offset, ) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=user, ) for article_row in articles_rows ] async def get_article_by_slug( self, *, slug: str, requested_user: Optional[User] = None, ) -> Article: article_row = await queries.get_article_by_slug(self.connection, slug=slug) if article_row: return await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) raise EntityDoesNotExist("article with slug {0} does not exist".format(slug)) async def get_tags_for_article_by_slug(self, *, slug: str) -> List[str]: tag_rows = await queries.get_tags_for_article_by_slug( self.connection, slug=slug, ) return [row["tag"] for row in tag_rows] async def get_favorites_count_for_article_by_slug(self, *, slug: str) -> int: return ( await queries.get_favorites_count_for_article(self.connection, slug=slug) )["favorites_count"] async def is_article_favorited_by_user(self, *, slug: str, user: User) -> bool: return ( await queries.is_article_in_favorites( self.connection, username=user.username, slug=slug, ) )["favorited"] async def add_article_into_favorites(self, *, article: Article, user: User) -> None: await queries.add_article_to_favorites( self.connection, username=user.username, slug=article.slug, ) async def remove_article_from_favorites( self, *, article: Article, user: User, ) -> None: await queries.remove_article_from_favorites( self.connection, username=user.username, slug=article.slug, ) async def _get_article_from_db_record( self, *, article_row: Record, slug: str, author_username: str, requested_user: Optional[User], ) -> Article: return Article( id_=article_row["id"], slug=slug, title=article_row["title"], description=article_row["description"], body=article_row["body"], author=await self._profiles_repo.get_profile_by_username( username=author_username, requested_user=requested_user, ), tags=await self.get_tags_for_article_by_slug(slug=slug), favorites_count=await self.get_favorites_count_for_article_by_slug( slug=slug, ), favorited=await self.is_article_favorited_by_user( slug=slug, user=requested_user, ) if requested_user else False, created_at=article_row["created_at"], updated_at=article_row["updated_at"], ) async def _link_article_with_tags(self, *, slug: str, tags: Sequence[str]) -> None: await queries.add_tags_to_article( self.connection, [{SLUG_ALIAS: slug, "tag": tag} for tag in tags], ) class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None DEFAULT_ARTICLES_LIMIT = 20 DEFAULT_ARTICLES_OFFSET = 0 class ArticleForResponse(RWSchema, Article): tags: List[str] = Field(..., alias="tagList") class ListOfArticlesInResponse(RWSchema): articles: List[ArticleForResponse] articles_count: int async def get_articles_for_user_feed( limit: int = Query(DEFAULT_ARTICLES_LIMIT, ge=1), offset: int = Query(DEFAULT_ARTICLES_OFFSET, ge=0), user: User = Depends(get_current_user_authorizer()), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> ListOfArticlesInResponse: articles = await articles_repo.get_articles_for_user_feed( user=user, limit=limit, offset=offset, ) articles_for_response = [ ArticleForResponse(**article.dict()) for article in articles ] return ListOfArticlesInResponse( articles=articles_for_response, articles_count=len(articles), )
null
167,833
from fastapi import APIRouter, Depends, HTTPException, Query from starlette import status from app.api.dependencies.articles import get_article_by_slug_from_path from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( DEFAULT_ARTICLES_LIMIT, DEFAULT_ARTICLES_OFFSET, ArticleForResponse, ArticleInResponse, ListOfArticlesInResponse, ) from app.resources import strings async def get_article_by_slug_from_path( slug: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> Article: try: return await articles_repo.get_article_by_slug(slug=slug, requested_user=user) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.ARTICLE_DOES_NOT_EXIST_ERROR, ) def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class ArticlesRepository(BaseRepository): # noqa: WPS214 def __init__(self, conn: Connection) -> None: super().__init__(conn) self._profiles_repo = ProfilesRepository(conn) self._tags_repo = TagsRepository(conn) async def create_article( # noqa: WPS211 self, *, slug: str, title: str, description: str, body: str, author: User, tags: Optional[Sequence[str]] = None, ) -> Article: async with self.connection.transaction(): article_row = await queries.create_new_article( self.connection, slug=slug, title=title, description=description, body=body, author_username=author.username, ) if tags: await self._tags_repo.create_tags_that_dont_exist(tags=tags) await self._link_article_with_tags(slug=slug, tags=tags) return await self._get_article_from_db_record( article_row=article_row, slug=slug, author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=author, ) async def update_article( # noqa: WPS211 self, *, article: Article, slug: Optional[str] = None, title: Optional[str] = None, body: Optional[str] = None, description: Optional[str] = None, ) -> Article: updated_article = article.copy(deep=True) updated_article.slug = slug or updated_article.slug updated_article.title = title or article.title updated_article.body = body or article.body updated_article.description = description or article.description async with self.connection.transaction(): updated_article.updated_at = await queries.update_article( self.connection, slug=article.slug, author_username=article.author.username, new_slug=updated_article.slug, new_title=updated_article.title, new_body=updated_article.body, new_description=updated_article.description, ) return updated_article async def delete_article(self, *, article: Article) -> None: async with self.connection.transaction(): await queries.delete_article( self.connection, slug=article.slug, author_username=article.author.username, ) async def filter_articles( # noqa: WPS211 self, *, tag: Optional[str] = None, author: Optional[str] = None, favorited: Optional[str] = None, limit: int = 20, offset: int = 0, requested_user: Optional[User] = None, ) -> List[Article]: query_params: List[Union[str, int]] = [] query_params_count = 0 # fmt: off query = Query.from_( articles, ).select( articles.id, articles.slug, articles.title, articles.description, articles.body, articles.created_at, articles.updated_at, Query.from_( users, ).where( users.id == articles.author_id, ).select( users.username, ).as_( AUTHOR_USERNAME_ALIAS, ), ) # fmt: on if tag: query_params.append(tag) query_params_count += 1 # fmt: off query = query.join( articles_to_tags, ).on( (articles.id == articles_to_tags.article_id) & ( articles_to_tags.tag == Query.from_( tags_table, ).where( tags_table.tag == Parameter(query_params_count), ).select( tags_table.tag, ) ), ) # fmt: on if author: query_params.append(author) query_params_count += 1 # fmt: off query = query.join( users, ).on( (articles.author_id == users.id) & ( users.id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on if favorited: query_params.append(favorited) query_params_count += 1 # fmt: off query = query.join( favorites, ).on( (articles.id == favorites.article_id) & ( favorites.user_id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on query = query.limit(Parameter(query_params_count + 1)).offset( Parameter(query_params_count + 2), ) query_params.extend([limit, offset]) articles_rows = await self.connection.fetch(query.get_sql(), *query_params) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) for article_row in articles_rows ] async def get_articles_for_user_feed( self, *, user: User, limit: int = 20, offset: int = 0, ) -> List[Article]: articles_rows = await queries.get_articles_for_feed( self.connection, follower_username=user.username, limit=limit, offset=offset, ) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=user, ) for article_row in articles_rows ] async def get_article_by_slug( self, *, slug: str, requested_user: Optional[User] = None, ) -> Article: article_row = await queries.get_article_by_slug(self.connection, slug=slug) if article_row: return await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) raise EntityDoesNotExist("article with slug {0} does not exist".format(slug)) async def get_tags_for_article_by_slug(self, *, slug: str) -> List[str]: tag_rows = await queries.get_tags_for_article_by_slug( self.connection, slug=slug, ) return [row["tag"] for row in tag_rows] async def get_favorites_count_for_article_by_slug(self, *, slug: str) -> int: return ( await queries.get_favorites_count_for_article(self.connection, slug=slug) )["favorites_count"] async def is_article_favorited_by_user(self, *, slug: str, user: User) -> bool: return ( await queries.is_article_in_favorites( self.connection, username=user.username, slug=slug, ) )["favorited"] async def add_article_into_favorites(self, *, article: Article, user: User) -> None: await queries.add_article_to_favorites( self.connection, username=user.username, slug=article.slug, ) async def remove_article_from_favorites( self, *, article: Article, user: User, ) -> None: await queries.remove_article_from_favorites( self.connection, username=user.username, slug=article.slug, ) async def _get_article_from_db_record( self, *, article_row: Record, slug: str, author_username: str, requested_user: Optional[User], ) -> Article: return Article( id_=article_row["id"], slug=slug, title=article_row["title"], description=article_row["description"], body=article_row["body"], author=await self._profiles_repo.get_profile_by_username( username=author_username, requested_user=requested_user, ), tags=await self.get_tags_for_article_by_slug(slug=slug), favorites_count=await self.get_favorites_count_for_article_by_slug( slug=slug, ), favorited=await self.is_article_favorited_by_user( slug=slug, user=requested_user, ) if requested_user else False, created_at=article_row["created_at"], updated_at=article_row["updated_at"], ) async def _link_article_with_tags(self, *, slug: str, tags: Sequence[str]) -> None: await queries.add_tags_to_article( self.connection, [{SLUG_ALIAS: slug, "tag": tag} for tag in tags], ) class Article(IDModelMixin, DateTimeModelMixin, RWModel): slug: str title: str description: str body: str tags: List[str] author: Profile favorited: bool favorites_count: int class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None class ArticleForResponse(RWSchema, Article): tags: List[str] = Field(..., alias="tagList") class ArticleInResponse(RWSchema): article: ArticleForResponse async def mark_article_as_favorite( article: Article = Depends(get_article_by_slug_from_path), user: User = Depends(get_current_user_authorizer()), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> ArticleInResponse: if not article.favorited: await articles_repo.add_article_into_favorites(article=article, user=user) return ArticleInResponse( article=ArticleForResponse.from_orm( article.copy( update={ "favorited": True, "favorites_count": article.favorites_count + 1, }, ), ), ) raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=strings.ARTICLE_IS_ALREADY_FAVORITED, )
null
167,834
from fastapi import APIRouter, Depends, HTTPException, Query from starlette import status from app.api.dependencies.articles import get_article_by_slug_from_path from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.database import get_repository from app.db.repositories.articles import ArticlesRepository from app.models.domain.articles import Article from app.models.domain.users import User from app.models.schemas.articles import ( DEFAULT_ARTICLES_LIMIT, DEFAULT_ARTICLES_OFFSET, ArticleForResponse, ArticleInResponse, ListOfArticlesInResponse, ) from app.resources import strings async def get_article_by_slug_from_path( slug: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> Article: try: return await articles_repo.get_article_by_slug(slug=slug, requested_user=user) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.ARTICLE_DOES_NOT_EXIST_ERROR, ) def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class ArticlesRepository(BaseRepository): # noqa: WPS214 def __init__(self, conn: Connection) -> None: super().__init__(conn) self._profiles_repo = ProfilesRepository(conn) self._tags_repo = TagsRepository(conn) async def create_article( # noqa: WPS211 self, *, slug: str, title: str, description: str, body: str, author: User, tags: Optional[Sequence[str]] = None, ) -> Article: async with self.connection.transaction(): article_row = await queries.create_new_article( self.connection, slug=slug, title=title, description=description, body=body, author_username=author.username, ) if tags: await self._tags_repo.create_tags_that_dont_exist(tags=tags) await self._link_article_with_tags(slug=slug, tags=tags) return await self._get_article_from_db_record( article_row=article_row, slug=slug, author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=author, ) async def update_article( # noqa: WPS211 self, *, article: Article, slug: Optional[str] = None, title: Optional[str] = None, body: Optional[str] = None, description: Optional[str] = None, ) -> Article: updated_article = article.copy(deep=True) updated_article.slug = slug or updated_article.slug updated_article.title = title or article.title updated_article.body = body or article.body updated_article.description = description or article.description async with self.connection.transaction(): updated_article.updated_at = await queries.update_article( self.connection, slug=article.slug, author_username=article.author.username, new_slug=updated_article.slug, new_title=updated_article.title, new_body=updated_article.body, new_description=updated_article.description, ) return updated_article async def delete_article(self, *, article: Article) -> None: async with self.connection.transaction(): await queries.delete_article( self.connection, slug=article.slug, author_username=article.author.username, ) async def filter_articles( # noqa: WPS211 self, *, tag: Optional[str] = None, author: Optional[str] = None, favorited: Optional[str] = None, limit: int = 20, offset: int = 0, requested_user: Optional[User] = None, ) -> List[Article]: query_params: List[Union[str, int]] = [] query_params_count = 0 # fmt: off query = Query.from_( articles, ).select( articles.id, articles.slug, articles.title, articles.description, articles.body, articles.created_at, articles.updated_at, Query.from_( users, ).where( users.id == articles.author_id, ).select( users.username, ).as_( AUTHOR_USERNAME_ALIAS, ), ) # fmt: on if tag: query_params.append(tag) query_params_count += 1 # fmt: off query = query.join( articles_to_tags, ).on( (articles.id == articles_to_tags.article_id) & ( articles_to_tags.tag == Query.from_( tags_table, ).where( tags_table.tag == Parameter(query_params_count), ).select( tags_table.tag, ) ), ) # fmt: on if author: query_params.append(author) query_params_count += 1 # fmt: off query = query.join( users, ).on( (articles.author_id == users.id) & ( users.id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on if favorited: query_params.append(favorited) query_params_count += 1 # fmt: off query = query.join( favorites, ).on( (articles.id == favorites.article_id) & ( favorites.user_id == Query.from_( users, ).where( users.username == Parameter(query_params_count), ).select( users.id, ) ), ) # fmt: on query = query.limit(Parameter(query_params_count + 1)).offset( Parameter(query_params_count + 2), ) query_params.extend([limit, offset]) articles_rows = await self.connection.fetch(query.get_sql(), *query_params) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) for article_row in articles_rows ] async def get_articles_for_user_feed( self, *, user: User, limit: int = 20, offset: int = 0, ) -> List[Article]: articles_rows = await queries.get_articles_for_feed( self.connection, follower_username=user.username, limit=limit, offset=offset, ) return [ await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=user, ) for article_row in articles_rows ] async def get_article_by_slug( self, *, slug: str, requested_user: Optional[User] = None, ) -> Article: article_row = await queries.get_article_by_slug(self.connection, slug=slug) if article_row: return await self._get_article_from_db_record( article_row=article_row, slug=article_row[SLUG_ALIAS], author_username=article_row[AUTHOR_USERNAME_ALIAS], requested_user=requested_user, ) raise EntityDoesNotExist("article with slug {0} does not exist".format(slug)) async def get_tags_for_article_by_slug(self, *, slug: str) -> List[str]: tag_rows = await queries.get_tags_for_article_by_slug( self.connection, slug=slug, ) return [row["tag"] for row in tag_rows] async def get_favorites_count_for_article_by_slug(self, *, slug: str) -> int: return ( await queries.get_favorites_count_for_article(self.connection, slug=slug) )["favorites_count"] async def is_article_favorited_by_user(self, *, slug: str, user: User) -> bool: return ( await queries.is_article_in_favorites( self.connection, username=user.username, slug=slug, ) )["favorited"] async def add_article_into_favorites(self, *, article: Article, user: User) -> None: await queries.add_article_to_favorites( self.connection, username=user.username, slug=article.slug, ) async def remove_article_from_favorites( self, *, article: Article, user: User, ) -> None: await queries.remove_article_from_favorites( self.connection, username=user.username, slug=article.slug, ) async def _get_article_from_db_record( self, *, article_row: Record, slug: str, author_username: str, requested_user: Optional[User], ) -> Article: return Article( id_=article_row["id"], slug=slug, title=article_row["title"], description=article_row["description"], body=article_row["body"], author=await self._profiles_repo.get_profile_by_username( username=author_username, requested_user=requested_user, ), tags=await self.get_tags_for_article_by_slug(slug=slug), favorites_count=await self.get_favorites_count_for_article_by_slug( slug=slug, ), favorited=await self.is_article_favorited_by_user( slug=slug, user=requested_user, ) if requested_user else False, created_at=article_row["created_at"], updated_at=article_row["updated_at"], ) async def _link_article_with_tags(self, *, slug: str, tags: Sequence[str]) -> None: await queries.add_tags_to_article( self.connection, [{SLUG_ALIAS: slug, "tag": tag} for tag in tags], ) class Article(IDModelMixin, DateTimeModelMixin, RWModel): slug: str title: str description: str body: str tags: List[str] author: Profile favorited: bool favorites_count: int class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None class ArticleForResponse(RWSchema, Article): tags: List[str] = Field(..., alias="tagList") class ArticleInResponse(RWSchema): article: ArticleForResponse async def remove_article_from_favorites( article: Article = Depends(get_article_by_slug_from_path), user: User = Depends(get_current_user_authorizer()), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> ArticleInResponse: if article.favorited: await articles_repo.remove_article_from_favorites(article=article, user=user) return ArticleInResponse( article=ArticleForResponse.from_orm( article.copy( update={ "favorited": False, "favorites_count": article.favorites_count - 1, }, ), ), ) raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=strings.ARTICLE_IS_NOT_FAVORITED, )
null
167,835
from typing import Optional from fastapi import APIRouter, Body, Depends, Response from starlette import status from app.api.dependencies.articles import get_article_by_slug_from_path from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.comments import ( check_comment_modification_permissions, get_comment_by_id_from_path, ) from app.api.dependencies.database import get_repository from app.db.repositories.comments import CommentsRepository from app.models.domain.articles import Article from app.models.domain.comments import Comment from app.models.domain.users import User from app.models.schemas.comments import ( CommentInCreate, CommentInResponse, ListOfCommentsInResponse, ) async def get_article_by_slug_from_path( slug: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> Article: def get_current_user_authorizer(*, required: bool = True) -> Callable: def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: class CommentsRepository(BaseRepository): def __init__(self, conn: Connection) -> None: async def get_comment_by_id( self, *, comment_id: int, article: Article, user: Optional[User] = None, ) -> Comment: async def get_comments_for_article( self, *, article: Article, user: Optional[User] = None, ) -> List[Comment]: async def create_comment_for_article( self, *, body: str, article: Article, user: User, ) -> Comment: async def delete_comment(self, *, comment: Comment) -> None: async def _get_comment_from_db_record( self, *, comment_row: Record, author_username: str, requested_user: Optional[User], ) -> Comment: class Article(IDModelMixin, DateTimeModelMixin, RWModel): class User(RWModel): class ListOfCommentsInResponse(RWSchema): async def list_comments_for_article( article: Article = Depends(get_article_by_slug_from_path), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), comments_repo: CommentsRepository = Depends(get_repository(CommentsRepository)), ) -> ListOfCommentsInResponse: comments = await comments_repo.get_comments_for_article(article=article, user=user) return ListOfCommentsInResponse(comments=comments)
null
167,836
from typing import Optional from fastapi import APIRouter, Body, Depends, Response from starlette import status from app.api.dependencies.articles import get_article_by_slug_from_path from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.comments import ( check_comment_modification_permissions, get_comment_by_id_from_path, ) from app.api.dependencies.database import get_repository from app.db.repositories.comments import CommentsRepository from app.models.domain.articles import Article from app.models.domain.comments import Comment from app.models.domain.users import User from app.models.schemas.comments import ( CommentInCreate, CommentInResponse, ListOfCommentsInResponse, ) async def get_article_by_slug_from_path( slug: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> Article: try: return await articles_repo.get_article_by_slug(slug=slug, requested_user=user) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.ARTICLE_DOES_NOT_EXIST_ERROR, ) def get_current_user_authorizer(*, required: bool = True) -> Callable: # type: ignore return _get_current_user if required else _get_current_user_optional def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class CommentsRepository(BaseRepository): def __init__(self, conn: Connection) -> None: super().__init__(conn) self._profiles_repo = ProfilesRepository(conn) async def get_comment_by_id( self, *, comment_id: int, article: Article, user: Optional[User] = None, ) -> Comment: comment_row = await queries.get_comment_by_id_and_slug( self.connection, comment_id=comment_id, article_slug=article.slug, ) if comment_row: return await self._get_comment_from_db_record( comment_row=comment_row, author_username=comment_row["author_username"], requested_user=user, ) raise EntityDoesNotExist( "comment with id {0} does not exist".format(comment_id), ) async def get_comments_for_article( self, *, article: Article, user: Optional[User] = None, ) -> List[Comment]: comments_rows = await queries.get_comments_for_article_by_slug( self.connection, slug=article.slug, ) return [ await self._get_comment_from_db_record( comment_row=comment_row, author_username=comment_row["author_username"], requested_user=user, ) for comment_row in comments_rows ] async def create_comment_for_article( self, *, body: str, article: Article, user: User, ) -> Comment: comment_row = await queries.create_new_comment( self.connection, body=body, article_slug=article.slug, author_username=user.username, ) return await self._get_comment_from_db_record( comment_row=comment_row, author_username=comment_row["author_username"], requested_user=user, ) async def delete_comment(self, *, comment: Comment) -> None: await queries.delete_comment_by_id( self.connection, comment_id=comment.id_, author_username=comment.author.username, ) async def _get_comment_from_db_record( self, *, comment_row: Record, author_username: str, requested_user: Optional[User], ) -> Comment: return Comment( id_=comment_row["id"], body=comment_row["body"], author=await self._profiles_repo.get_profile_by_username( username=author_username, requested_user=requested_user, ), created_at=comment_row["created_at"], updated_at=comment_row["updated_at"], ) class Article(IDModelMixin, DateTimeModelMixin, RWModel): slug: str title: str description: str body: str tags: List[str] author: Profile favorited: bool favorites_count: int class User(RWModel): username: str email: str bio: str = "" image: Optional[str] = None class CommentInResponse(RWSchema): comment: Comment class CommentInCreate(RWSchema): body: str async def create_comment_for_article( comment_create: CommentInCreate = Body(..., embed=True, alias="comment"), article: Article = Depends(get_article_by_slug_from_path), user: User = Depends(get_current_user_authorizer()), comments_repo: CommentsRepository = Depends(get_repository(CommentsRepository)), ) -> CommentInResponse: comment = await comments_repo.create_comment_for_article( body=comment_create.body, article=article, user=user, ) return CommentInResponse(comment=comment)
null
167,837
from typing import Optional from fastapi import APIRouter, Body, Depends, Response from starlette import status from app.api.dependencies.articles import get_article_by_slug_from_path from app.api.dependencies.authentication import get_current_user_authorizer from app.api.dependencies.comments import ( check_comment_modification_permissions, get_comment_by_id_from_path, ) from app.api.dependencies.database import get_repository from app.db.repositories.comments import CommentsRepository from app.models.domain.articles import Article from app.models.domain.comments import Comment from app.models.domain.users import User from app.models.schemas.comments import ( CommentInCreate, CommentInResponse, ListOfCommentsInResponse, ) async def get_comment_by_id_from_path( comment_id: int = Path(..., ge=1), article: Article = Depends(articles.get_article_by_slug_from_path), user: Optional[User] = Depends( authentication.get_current_user_authorizer(required=False), ), comments_repo: CommentsRepository = Depends( database.get_repository(CommentsRepository), ), ) -> Comment: try: return await comments_repo.get_comment_by_id( comment_id=comment_id, article=article, user=user, ) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.COMMENT_DOES_NOT_EXIST, ) def get_repository( repo_type: Type[BaseRepository], ) -> Callable[[Connection], BaseRepository]: def _get_repo( conn: Connection = Depends(_get_connection_from_pool), ) -> BaseRepository: return repo_type(conn) return _get_repo class CommentsRepository(BaseRepository): def __init__(self, conn: Connection) -> None: super().__init__(conn) self._profiles_repo = ProfilesRepository(conn) async def get_comment_by_id( self, *, comment_id: int, article: Article, user: Optional[User] = None, ) -> Comment: comment_row = await queries.get_comment_by_id_and_slug( self.connection, comment_id=comment_id, article_slug=article.slug, ) if comment_row: return await self._get_comment_from_db_record( comment_row=comment_row, author_username=comment_row["author_username"], requested_user=user, ) raise EntityDoesNotExist( "comment with id {0} does not exist".format(comment_id), ) async def get_comments_for_article( self, *, article: Article, user: Optional[User] = None, ) -> List[Comment]: comments_rows = await queries.get_comments_for_article_by_slug( self.connection, slug=article.slug, ) return [ await self._get_comment_from_db_record( comment_row=comment_row, author_username=comment_row["author_username"], requested_user=user, ) for comment_row in comments_rows ] async def create_comment_for_article( self, *, body: str, article: Article, user: User, ) -> Comment: comment_row = await queries.create_new_comment( self.connection, body=body, article_slug=article.slug, author_username=user.username, ) return await self._get_comment_from_db_record( comment_row=comment_row, author_username=comment_row["author_username"], requested_user=user, ) async def delete_comment(self, *, comment: Comment) -> None: await queries.delete_comment_by_id( self.connection, comment_id=comment.id_, author_username=comment.author.username, ) async def _get_comment_from_db_record( self, *, comment_row: Record, author_username: str, requested_user: Optional[User], ) -> Comment: return Comment( id_=comment_row["id"], body=comment_row["body"], author=await self._profiles_repo.get_profile_by_username( username=author_username, requested_user=requested_user, ), created_at=comment_row["created_at"], updated_at=comment_row["updated_at"], ) class Comment(IDModelMixin, DateTimeModelMixin, RWModel): body: str author: Profile async def delete_comment_from_article( comment: Comment = Depends(get_comment_by_id_from_path), comments_repo: CommentsRepository = Depends(get_repository(CommentsRepository)), ) -> None: await comments_repo.delete_comment(comment=comment)
null
167,838
from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException from starlette.middleware.cors import CORSMiddleware from app.api.errors.http_error import http_error_handler from app.api.errors.validation_error import http422_error_handler from app.api.routes.api import router as api_router from app.core.config import get_app_settings from app.core.events import create_start_app_handler, create_stop_app_handler async def http_error_handler(_: Request, exc: HTTPException) -> JSONResponse: return JSONResponse({"errors": [exc.detail]}, status_code=exc.status_code) async def http422_error_handler( _: Request, exc: Union[RequestValidationError, ValidationError], ) -> JSONResponse: return JSONResponse( {"errors": exc.errors()}, status_code=HTTP_422_UNPROCESSABLE_ENTITY, ) def get_app_settings() -> AppSettings: app_env = BaseAppSettings().app_env config = environments[app_env] return config() def create_start_app_handler( app: FastAPI, settings: AppSettings, ) -> Callable: # type: ignore async def start_app() -> None: await connect_to_db(app, settings) return start_app def create_stop_app_handler(app: FastAPI) -> Callable: # type: ignore async def stop_app() -> None: await close_db_connection(app) return stop_app def get_application() -> FastAPI: settings = get_app_settings() settings.configure_logging() application = FastAPI(**settings.fastapi_kwargs) application.add_middleware( CORSMiddleware, allow_origins=settings.allowed_hosts, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.add_event_handler( "startup", create_start_app_handler(application, settings), ) application.add_event_handler( "shutdown", create_stop_app_handler(application), ) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) application.include_router(api_router, prefix=settings.api_prefix) return application
null
167,839
import bcrypt from passlib.context import CryptContext def generate_salt() -> str: return bcrypt.gensalt().decode()
null
167,840
import bcrypt from passlib.context import CryptContext pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def verify_password(plain_password: str, hashed_password: str) -> bool: return pwd_context.verify(plain_password, hashed_password)
null
167,841
import bcrypt from passlib.context import CryptContext pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def get_password_hash(password: str) -> str: return pwd_context.hash(password)
null
167,842
from typing import Tuple import sqlalchemy as sa from alembic import op from sqlalchemy import func def create_updated_at_trigger() -> None: op.execute( """ CREATE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = now(); RETURN NEW; END; $$ language 'plpgsql'; """ ) def create_users_table() -> None: op.create_table( "users", sa.Column("id", sa.Integer, primary_key=True), sa.Column("username", sa.Text, unique=True, nullable=False, index=True), sa.Column("email", sa.Text, unique=True, nullable=False, index=True), sa.Column("salt", sa.Text, nullable=False), sa.Column("hashed_password", sa.Text), sa.Column("bio", sa.Text, nullable=False, server_default=""), sa.Column("image", sa.Text), *timestamps(), ) op.execute( """ CREATE TRIGGER update_user_modtime BEFORE UPDATE ON users FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) def create_followers_to_followings_table() -> None: op.create_table( "followers_to_followings", sa.Column( "follower_id", sa.Integer, sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, ), sa.Column( "following_id", sa.Integer, sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, ), ) op.create_primary_key( "pk_followers_to_followings", "followers_to_followings", ["follower_id", "following_id"], ) def create_articles_table() -> None: op.create_table( "articles", sa.Column("id", sa.Integer, primary_key=True), sa.Column("slug", sa.Text, unique=True, nullable=False, index=True), sa.Column("title", sa.Text, nullable=False), sa.Column("description", sa.Text, nullable=False), sa.Column("body", sa.Text, nullable=False), sa.Column( "author_id", sa.Integer, sa.ForeignKey("users.id", ondelete="SET NULL") ), *timestamps(), ) op.execute( """ CREATE TRIGGER update_article_modtime BEFORE UPDATE ON articles FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) def create_tags_table() -> None: op.create_table("tags", sa.Column("tag", sa.Text, primary_key=True)) def create_articles_to_tags_table() -> None: op.create_table( "articles_to_tags", sa.Column( "article_id", sa.Integer, sa.ForeignKey("articles.id", ondelete="CASCADE"), nullable=False, ), sa.Column( "tag", sa.Text, sa.ForeignKey("tags.tag", ondelete="CASCADE"), nullable=False, ), ) op.create_primary_key( "pk_articles_to_tags", "articles_to_tags", ["article_id", "tag"] ) def create_favorites_table() -> None: op.create_table( "favorites", sa.Column( "user_id", sa.Integer, sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, ), sa.Column( "article_id", sa.Integer, sa.ForeignKey("articles.id", ondelete="CASCADE"), nullable=False, ), ) op.create_primary_key("pk_favorites", "favorites", ["user_id", "article_id"]) def create_commentaries_table() -> None: op.create_table( "commentaries", sa.Column("id", sa.Integer, primary_key=True), sa.Column("body", sa.Text, nullable=False), sa.Column( "author_id", sa.Integer, sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, ), sa.Column( "article_id", sa.Integer, sa.ForeignKey("articles.id", ondelete="CASCADE"), nullable=False, ), *timestamps(), ) op.execute( """ CREATE TRIGGER update_comment_modtime BEFORE UPDATE ON commentaries FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) def upgrade() -> None: create_updated_at_trigger() create_users_table() create_followers_to_followings_table() create_articles_table() create_tags_table() create_articles_to_tags_table() create_favorites_table() create_commentaries_table()
null
167,843
from typing import Tuple import sqlalchemy as sa from alembic import op from sqlalchemy import func def downgrade() -> None: op.drop_table("commentaries") op.drop_table("favorites") op.drop_table("articles_to_tags") op.drop_table("tags") op.drop_table("articles") op.drop_table("followers_to_followings") op.drop_table("users") op.execute("DROP FUNCTION update_updated_at_column")
null
167,844
import pathlib import sys from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool from app.core.config import get_app_settings config = context.config target_metadata = None config.set_main_option("sqlalchemy.url", str(DATABASE_URL)) def run_migrations_online() -> None: connectable = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations()
null
167,845
import datetime from pydantic import BaseConfig, BaseModel def convert_datetime_to_realworld(dt: datetime.datetime) -> str: return dt.replace(tzinfo=datetime.timezone.utc).isoformat().replace("+00:00", "Z")
null
167,846
import datetime from pydantic import BaseConfig, BaseModel def convert_field_to_camel_case(string: str) -> str: return "".join( word if index == 0 else word.capitalize() for index, word in enumerate(string.split("_")) )
null
167,847
import os, sys os.environ["TOKENIZERS_PARALLELISM"] = "false" import logging import click import numpy as np from functools import partial from pathlib import Path from typing import Any, Dict, List, Tuple, Union from datetime import datetime from datasets import Dataset, load_dataset, load_from_disk from transformers import ( AutoModelForCausalLM, AutoTokenizer, DataCollatorForLanguageModeling, PreTrainedTokenizer, Trainer, TrainingArguments, set_seed, ) from .consts import ( DEFAULT_INPUT_MODEL, DEFAULT_SEED, END_KEY, INSTRUCTION_KEY, RESPONSE_KEY, INTRO_KEY, INTRO ) logger = logging.getLogger(__name__) class DataCollatorForCompletionOnlyLM_Multi_Rounds(DataCollatorForLanguageModeling): def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]: batch = super().torch_call(examples) # The prompt ends with the response key plus a newline. We encode this and then try to find it in the # sequence of tokens. This should just be a single token. yayi_token_ids = self.tokenizer(RESPONSE_KEY)["input_ids"][0] human_token_ids = self.tokenizer(INSTRUCTION_KEY)["input_ids"][0] labels = batch["labels"].clone() for i in range(len(examples)): response_start, response_end = None, None yayi_position = np.where(batch["labels"][i] == yayi_token_ids)[0].tolist() human_position = np.where(batch["labels"][i] == human_token_ids)[0].tolist() labels[i, :human_position[0]+3] = -100 for response_start,response_end in zip(human_position,yayi_position): if response_start is None or response_end is None: raise RuntimeError( f'Could not find response key {yayi_token_ids}/{human_token_ids} in token IDs' ) labels[i, response_start:response_end+3] = -100 batch["labels"] = labels return batch def get_model_tokenizer( pretrained_model_name_or_path: str = DEFAULT_INPUT_MODEL, *, gradient_checkpointing: bool = False ) -> Tuple[AutoModelForCausalLM, PreTrainedTokenizer]: tokenizer = load_tokenizer(pretrained_model_name_or_path) model = load_model(pretrained_model_name_or_path, gradient_checkpointing=gradient_checkpointing) model.resize_token_embeddings(len(tokenizer)) return model, tokenizer def preprocess_dataset(tokenizer: AutoTokenizer, max_length: int, seed=DEFAULT_SEED, path_or_dataset=None) -> Dataset: """Loads the training dataset and tokenizes it so it is ready for training. Args: tokenizer (AutoTokenizer): Tokenizer tied to the model. max_length (int): Maximum number of tokens to emit from tokenizer. Returns: Dataset: HuggingFace dataset """ dataset = load_training_dataset__multi_rounds(path_or_dataset=path_or_dataset) logger.info("Preprocessing dataset") _preprocessing_function = partial(preprocess_batch, max_length=max_length, tokenizer=tokenizer) dataset = dataset.map( _preprocessing_function, batched=True, remove_columns=["conversations", "system", "text"], ) logger.info(f"datasets after processing: {dataset}") # Make sure we don't have any truncated records, as this would mean the end keyword is missing. logger.info("Processed dataset has %d rows", dataset.num_rows) dataset = dataset.filter(lambda rec: len(rec["input_ids"]) < max_length) logger.info("Processed dataset has %d rows after filtering for truncated records", dataset.num_rows) logger.info("Shuffling dataset") dataset = dataset.shuffle(seed=seed) logger.info("Done preprocessing") return dataset def train( *, data_path: str, input_model: str, local_output_dir: str, dbfs_output_dir: str, epochs: int, per_device_train_batch_size: int, per_device_eval_batch_size: int, lr: float, seed: int, deepspeed: str, gradient_checkpointing: bool, local_rank: str, bf16: bool, logging_steps: int, save_steps: int, eval_steps: int, test_size: Union[float, int], save_total_limit: int, warmup_steps: int, ): set_seed(seed) # Create dir for saving logs and checkpoints timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M") model_name = "YAYI_CHAT" checkpoint_dir_name = f"{model_name}_{timestamp}" local_output_dir = os.path.join(local_output_dir, checkpoint_dir_name) os.makedirs(local_output_dir, exist_ok=True) model, tokenizer = get_model_tokenizer( pretrained_model_name_or_path=input_model, gradient_checkpointing=gradient_checkpointing ) # Use the same max length that the model supports. max_length = None for length_setting in ["n_positions", "max_position_embeddings", "seq_length"]: max_length = getattr(model.config, length_setting, None) if max_length: logger.info(f"Found max lenth: {max_length}") break if not max_length: max_length = 1024 logger.info(f"Using default max length: {max_length}") # Data processing hf_data_dir = data_path.replace(".json","") if os.path.exists(hf_data_dir): logger.info("Load dataset from cache.") split_dataset = load_from_disk(hf_data_dir) else: logger.info("Load dataset from disk.") processed_dataset = preprocess_dataset(tokenizer=tokenizer, max_length=max_length, seed=seed, path_or_dataset=data_path) split_dataset = processed_dataset.train_test_split(test_size=test_size, seed=seed) logger.info("Train data size: %d", split_dataset["train"].num_rows) logger.info("Test data size: %d", split_dataset["test"].num_rows) data_collator = DataCollatorForCompletionOnlyLM_Multi_Rounds( tokenizer=tokenizer, mlm=False, return_tensors="pt", pad_to_multiple_of=8 ) training_args = TrainingArguments( output_dir=local_output_dir, per_device_train_batch_size=per_device_train_batch_size, per_device_eval_batch_size=per_device_eval_batch_size, fp16=False, bf16=bf16, learning_rate=lr, num_train_epochs=epochs, deepspeed=deepspeed, gradient_checkpointing=gradient_checkpointing, logging_dir=f"{local_output_dir}/runs", logging_strategy="steps", logging_steps=logging_steps, evaluation_strategy="steps", eval_steps=eval_steps, save_strategy="steps", save_steps=save_steps, save_total_limit=save_total_limit, load_best_model_at_end=False, report_to="tensorboard", disable_tqdm=False, remove_unused_columns=False, local_rank=local_rank, warmup_steps=warmup_steps, lr_scheduler_type="cosine" ) logger.info("Instantiating Trainer") trainer = Trainer( model=model, tokenizer=tokenizer, args=training_args, train_dataset=split_dataset["train"], eval_dataset=split_dataset["test"], data_collator=data_collator, ) logger.info("Training") trainer.train() logger.info(f"Saving Model to {local_output_dir}") trainer.save_model(output_dir=local_output_dir) if dbfs_output_dir: logger.info(f"Saving Model to {dbfs_output_dir}") trainer.save_model(output_dir=dbfs_output_dir) logger.info("Done.")
null
167,848
import os os.environ["TOKENIZERS_PARALLELISM"] = "false" import logging, torch import click import numpy as np from functools import partial from pathlib import Path from typing import Any, Dict, List, Tuple, Union from datetime import datetime from datasets import Dataset, load_dataset, load_from_disk from transformers import ( AutoModelForCausalLM, AutoTokenizer, DataCollatorForLanguageModeling, PreTrainedTokenizer, Trainer, TrainingArguments, set_seed, ) from .consts import ( DEFAULT_INPUT_MODEL, DEFAULT_SEED, PROMPT_WITH_INPUT_FORMAT, PROMPT_NO_INPUT_FORMAT, END_KEY, INSTRUCTION_KEY, RESPONSE_KEY, INTRO_KEY ) logger = logging.getLogger(__name__) class DataCollatorForCompletionOnlyLM(DataCollatorForLanguageModeling): def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]: batch = super().torch_call(examples) # The prompt ends with the response key plus a newline. We encode this and then try to find it in the # sequence of tokens. This should just be a single token. response_token_ids = self.tokenizer(RESPONSE_KEY)["input_ids"] labels = batch["labels"].clone() for i in range(len(examples)): response_token_ids_start_idx = None for idx in np.where(batch["labels"][i] == response_token_ids[0])[0]: response_token_ids_start_idx = idx break if response_token_ids_start_idx is None: raise RuntimeError( f'Could not find response key {response_token_ids} in token IDs {batch["labels"][i]}' ) response_token_ids_end_idx = response_token_ids_start_idx + 1 # Make pytorch loss function ignore all tokens up through the end of the response key labels[i, :response_token_ids_end_idx] = -100 batch["labels"] = labels return batch def get_model_tokenizer( pretrained_model_name_or_path: str = DEFAULT_INPUT_MODEL, *, gradient_checkpointing: bool = False ) -> Tuple[AutoModelForCausalLM, PreTrainedTokenizer]: tokenizer = load_tokenizer(pretrained_model_name_or_path) model = load_model(pretrained_model_name_or_path, gradient_checkpointing=gradient_checkpointing) model.resize_token_embeddings(len(tokenizer)) return model, tokenizer def preprocess_dataset(tokenizer: AutoTokenizer, max_length: int, seed=DEFAULT_SEED, path_or_dataset=None) -> Dataset: """Loads the training dataset and tokenizes it so it is ready for training. Args: tokenizer (AutoTokenizer): Tokenizer tied to the model. max_length (int): Maximum number of tokens to emit from tokenizer. Returns: Dataset: HuggingFace dataset """ dataset = load_training_dataset(path_or_dataset=path_or_dataset) logger.info("Preprocessing dataset") _preprocessing_function = partial(preprocess_batch, max_length=max_length, tokenizer=tokenizer) dataset = dataset.map( _preprocessing_function, batched=True, remove_columns=["instruction", "input", "output", "text"], ) logger.info(f"datasets after processing: {dataset}") # Make sure we don't have any truncated records, as this would mean the end keyword is missing. logger.info("Processed dataset has %d rows", dataset.num_rows) dataset = dataset.filter(lambda rec: len(rec["input_ids"]) < max_length) logger.info("Processed dataset has %d rows after filtering for truncated records", dataset.num_rows) logger.info("Shuffling dataset") dataset = dataset.shuffle(seed=seed) logger.info("Done preprocessing") return dataset def train( *, data_path: str, input_model: str, local_output_dir: str, dbfs_output_dir: str, epochs: int, per_device_train_batch_size: int, per_device_eval_batch_size: int, lr: float, seed: int, deepspeed: str, gradient_checkpointing: bool, local_rank: str, bf16: bool, logging_steps: int, save_steps: int, eval_steps: int, test_size: Union[float, int], save_total_limit: int, warmup_steps: int, ): set_seed(seed) # Create dir for saving logs and checkpoints timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M") model_name = "YAYI_INST" checkpoint_dir_name = f"{model_name}_{timestamp}" local_output_dir = os.path.join(local_output_dir, checkpoint_dir_name) os.makedirs(local_output_dir, exist_ok=True) model, tokenizer = get_model_tokenizer( pretrained_model_name_or_path=input_model, gradient_checkpointing=gradient_checkpointing ) # Use the same max length that the model supports. max_length = None for length_setting in ["n_positions", "max_position_embeddings", "seq_length"]: max_length = getattr(model.config, length_setting, None) if max_length: logger.info(f"Found max lenth: {max_length}") break if not max_length: max_length = 1024 logger.info(f"Using default max length: {max_length}") # Data processing hf_data_dir = data_path.replace(".json","") if os.path.exists(hf_data_dir): logger.info("Load dataset from cache.") split_dataset = load_from_disk(hf_data_dir) else: logger.info("Load dataset from disk.") processed_dataset = preprocess_dataset(tokenizer=tokenizer, max_length=max_length, seed=seed, path_or_dataset=data_path) split_dataset = processed_dataset.train_test_split(test_size=test_size, seed=seed) logger.info("Train data size: %d", split_dataset["train"].num_rows) logger.info("Test data size: %d", split_dataset["test"].num_rows) data_collator = DataCollatorForCompletionOnlyLM( tokenizer=tokenizer, mlm=False, return_tensors="pt", pad_to_multiple_of=8 ) training_args = TrainingArguments( output_dir=local_output_dir, per_device_train_batch_size=per_device_train_batch_size, per_device_eval_batch_size=per_device_eval_batch_size, fp16=False, bf16=bf16, learning_rate=lr, num_train_epochs=epochs, deepspeed=deepspeed, gradient_checkpointing=gradient_checkpointing, logging_dir=f"{local_output_dir}/runs", logging_strategy="steps", logging_steps=logging_steps, evaluation_strategy="steps", eval_steps=eval_steps, save_strategy="steps", save_steps=save_steps, save_total_limit=save_total_limit, load_best_model_at_end=False, report_to="tensorboard", disable_tqdm=False, remove_unused_columns=False, local_rank=local_rank, warmup_steps=warmup_steps, ) logger.info("Instantiating Trainer") trainer = Trainer( model=model, tokenizer=tokenizer, args=training_args, train_dataset=split_dataset["train"], eval_dataset=split_dataset["test"], data_collator=data_collator, ) logger.info("Training") trainer.train() logger.info(f"Saving Model to {local_output_dir}") trainer.save_model(output_dir=local_output_dir) if dbfs_output_dir: logger.info(f"Saving Model to {dbfs_output_dir}") trainer.save_model(output_dir=dbfs_output_dir) logger.info("Done.")
null
167,849
import os, sys os.environ["TOKENIZERS_PARALLELISM"] = "false" import logging import click import numpy as np from functools import partial from pathlib import Path from typing import Any, Dict, List, Tuple, Union from datetime import datetime from datasets import Dataset, load_dataset, load_from_disk from transformers import ( AutoModelForCausalLM, AutoTokenizer, DataCollatorForLanguageModeling, PreTrainedTokenizer, Trainer, TrainingArguments, set_seed, ) from .consts import ( DEFAULT_INPUT_MODEL, DEFAULT_SEED, PROMPT_WITH_INPUT_FORMAT, PROMPT_NO_INPUT_FORMAT, END_KEY, INSTRUCTION_KEY, RESPONSE_KEY, INTRO_KEY ) logger = logging.getLogger(__name__) class DataCollatorForCompletionOnlyLM(DataCollatorForLanguageModeling): def torch_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]: def get_model_tokenizer( pretrained_model_name_or_path: str = DEFAULT_INPUT_MODEL, *, gradient_checkpointing: bool = False, lora_dim: int = None, lora_module_name: str = None, ) -> Tuple[AutoModelForCausalLM, PreTrainedTokenizer]: def preprocess_dataset(tokenizer: AutoTokenizer, max_length: int, seed=DEFAULT_SEED, path_or_dataset=None) -> Dataset: def train( *, data_path: str, input_model: str, local_output_dir: str, dbfs_output_dir: str, epochs: int, per_device_train_batch_size: int, per_device_eval_batch_size: int, lr: float, seed: int, deepspeed: str, gradient_checkpointing: bool, local_rank: str, bf16: bool, logging_steps: int, save_steps: int, eval_steps: int, test_size: Union[float, int], save_total_limit: int, warmup_steps: int, lora_dim: int, lora_module_name: str, ): set_seed(seed) # Create dir for saving logs and checkpoints timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M") model_name = "YAYI_LORA" checkpoint_dir_name = f"{model_name}_{timestamp}" local_output_dir = os.path.join(local_output_dir, checkpoint_dir_name) os.makedirs(local_output_dir, exist_ok=True) model, tokenizer = get_model_tokenizer( pretrained_model_name_or_path=input_model, gradient_checkpointing=gradient_checkpointing, lora_dim=lora_dim, lora_module_name=lora_module_name, ) # Use the same max length that the model supports. max_length = None for length_setting in ["n_positions", "max_position_embeddings", "seq_length"]: max_length = getattr(model.config, length_setting, None) if max_length: logger.info(f"Found max lenth: {max_length}") break if not max_length: max_length = 1024 logger.info(f"Using default max length: {max_length}") # Data processing hf_data_dir = data_path.replace(".json","") if os.path.exists(hf_data_dir): logger.info("Load dataset from cache.") split_dataset = load_from_disk(hf_data_dir) else: logger.info("Load dataset from disk.") processed_dataset = preprocess_dataset(tokenizer=tokenizer, max_length=max_length, seed=seed, path_or_dataset=data_path) split_dataset = processed_dataset.train_test_split(test_size=test_size, seed=seed) logger.info("Train data size: %d", split_dataset["train"].num_rows) logger.info("Test data size: %d", split_dataset["test"].num_rows) data_collator = DataCollatorForCompletionOnlyLM( tokenizer=tokenizer, mlm=False, return_tensors="pt", pad_to_multiple_of=8 ) training_args = TrainingArguments( output_dir=local_output_dir, per_device_train_batch_size=per_device_train_batch_size, per_device_eval_batch_size=per_device_eval_batch_size, fp16=False, bf16=bf16, learning_rate=lr, num_train_epochs=epochs, deepspeed=deepspeed, logging_dir=f"{local_output_dir}/runs", logging_strategy="steps", logging_steps=logging_steps, evaluation_strategy="steps", eval_steps=eval_steps, save_strategy="steps", save_steps=save_steps, save_total_limit=save_total_limit, load_best_model_at_end=False, report_to="tensorboard", disable_tqdm=False, remove_unused_columns=False, local_rank=local_rank, warmup_steps=warmup_steps, ) logger.info("Instantiating Trainer") trainer = Trainer( model=model, tokenizer=tokenizer, args=training_args, train_dataset=split_dataset["train"], eval_dataset=split_dataset["test"], data_collator=data_collator, ) logger.info("Training") trainer.train() logger.info(f"Saving Model to {local_output_dir}") trainer.save_model(output_dir=local_output_dir) if dbfs_output_dir: logger.info(f"Saving Model to {dbfs_output_dir}") trainer.save_model(output_dir=dbfs_output_dir) logger.info("Done.")
null
167,850
import os, json from argparse import ArgumentParser from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `convert_inst_to_chat` function. Write a Python function `def convert_inst_to_chat(path)` to solve the following problem: Usage: 将 `指令数据格式` 转换为 `对话数据格式`. Here is the function: def convert_inst_to_chat(path): """ Usage: 将 `指令数据格式` 转换为 `对话数据格式`. """ results = [] with open(path, 'r', encoding='utf-8') as f: lines = f.readlines() for line in tqdm(lines): try: inst_data = json.loads(line) results.append({ "system": "", "conversations": [ {"from": "human","value": str(inst_data['instruction'].strip()+"\n"+inst_data['input'].strip()).strip()}, {"from": "yayi","value": inst_data["output"].strip()}]}) except: continue print(f"Data num: {len(results)}") print(f"Example:\n{json.dumps(results[0], ensure_ascii=False, indent=2) if results else 0}") save_path = path.split('.')[0]+'_chat.json' with open(save_path, 'w', encoding='utf-8') as f: f.write(json.dumps(results, ensure_ascii=False, indent=2)) print(f"Save to {save_path}")
Usage: 将 `指令数据格式` 转换为 `对话数据格式`.
167,851
import os, json from argparse import ArgumentParser from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `convert_chat_to_inst` function. Write a Python function `def convert_chat_to_inst(path)` to solve the following problem: Usage: 将 `对话数据格式` 转换为 `指令数据格式` 忽略多轮数据. Here is the function: def convert_chat_to_inst(path): """ Usage: 将 `对话数据格式` 转换为 `指令数据格式` 忽略多轮数据. """ results = [] with open(path, 'r', encoding='utf-8') as f: lines = json.load(f) for line in tqdm(lines): try: if len(line["conversations"])>2: continue results.append({ "system": line.get("system", "").strip(), "instruction": line["conversations"][0]["value"].strip(), "input": "", "output": line["conversations"][1]["value"].strip() }) except: continue print(f"Data num: {len(results)}") print(f"Example:\n{json.dumps(results[0], ensure_ascii=False, indent=2) if results else 0}") save_path = path.split('.')[0]+'_inst.json' with open(save_path, 'a+', encoding='utf-8') as f: for each in results: f.write(json.dumps(each, ensure_ascii=False)+"\n") print(f"Save to {save_path}")
Usage: 将 `对话数据格式` 转换为 `指令数据格式` 忽略多轮数据.
167,852
import os, json from argparse import ArgumentParser from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `merge_multi_chat_files` function. Write a Python function `def merge_multi_chat_files(path)` to solve the following problem: Usage: 合并多个 `对话数据格式` 文件. Here is the function: def merge_multi_chat_files(path): """ Usage: 合并多个 `对话数据格式` 文件. """ results = [] for filepath in path.split(","): print(f"Loading {filepath}") with open(filepath, 'r', encoding='utf-8') as f: results.extend(json.load(f)) save_path = path.split('.')[0]+'_merged.json' with open(save_path, 'w', encoding='utf-8') as f: f.write(json.dumps(results, ensure_ascii=False, indent=2)) print(f"Save to {save_path}")
Usage: 合并多个 `对话数据格式` 文件.
167,854
from setuptools import find_packages, setup import os import subprocess import time version_file = 'pyiqa/version.py' def get_hash(): def write_version_py(): content = """# GENERATED VERSION FILE # TIME: {} __version__ = '{}' __gitsha__ = '{}' version_info = ({}) """ sha = get_hash() with open('VERSION', 'r') as f: SHORT_VERSION = f.read().strip() VERSION_INFO = ', '.join([x if x.isdigit() else f'"{x}"' for x in SHORT_VERSION.split('.')]) version_file_str = content.format(time.asctime(), SHORT_VERSION, sha, VERSION_INFO) with open(version_file, 'w') as f: f.write(version_file_str)
null
167,855
from setuptools import find_packages, setup import os import subprocess import time version_file = 'pyiqa/version.py' def get_version(): with open(version_file, 'r') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__']
null
167,858
import math import torch from torch import autograd as autograd from torch import nn as nn from torch.nn import functional as F from pyiqa.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss def l1_loss(pred, target): return F.l1_loss(pred, target, reduction='none')
null
167,859
import math import torch from torch import autograd as autograd from torch import nn as nn from torch.nn import functional as F from pyiqa.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss def mse_loss(pred, target): return F.mse_loss(pred, target, reduction='none')
null
167,860
import math import torch from torch import autograd as autograd from torch import nn as nn from torch.nn import functional as F from pyiqa.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss def cross_entropy(pred, target): return F.cross_entropy(pred, target, reduction='none')
null
167,861
import math import torch from torch import autograd as autograd from torch import nn as nn from torch.nn import functional as F from pyiqa.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss def nll_loss(pred, target): return F.nll_loss(pred, target, reduction='none')
null
167,862
import math import torch from torch import autograd as autograd from torch import nn as nn from torch.nn import functional as F from pyiqa.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss def charbonnier_loss(pred, target, eps=1e-12): return torch.sqrt((pred - target)**2 + eps)
null
167,863
from cv2 import reduce import torch import numpy as np from torch import nn as nn from torch.nn import functional as F from pyiqa.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss The provided code snippet includes necessary dependencies for implementing the `emd_loss` function. Write a Python function `def emd_loss(pred, target, r=2)` to solve the following problem: Args: pred (Tensor): of shape (N, C). Predicted tensor. target (Tensor): of shape (N, C). Ground truth tensor. r (float): norm level, default l2 norm. Here is the function: def emd_loss(pred, target, r=2): """ Args: pred (Tensor): of shape (N, C). Predicted tensor. target (Tensor): of shape (N, C). Ground truth tensor. r (float): norm level, default l2 norm. """ loss = torch.abs(torch.cumsum(pred, dim=-1) - torch.cumsum(target, dim=-1))**r loss = loss.mean(dim=-1)**(1. / r) return loss
Args: pred (Tensor): of shape (N, C). Predicted tensor. target (Tensor): of shape (N, C). Ground truth tensor. r (float): norm level, default l2 norm.
167,864
from cv2 import reduce import torch import numpy as np from torch import nn as nn from torch.nn import functional as F from pyiqa.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss The provided code snippet includes necessary dependencies for implementing the `plcc_loss` function. Write a Python function `def plcc_loss(pred, target)` to solve the following problem: Args: pred (Tensor): of shape (N, 1). Predicted tensor. target (Tensor): of shape (N, 1). Ground truth tensor. Here is the function: def plcc_loss(pred, target): """ Args: pred (Tensor): of shape (N, 1). Predicted tensor. target (Tensor): of shape (N, 1). Ground truth tensor. """ batch_size = pred.shape[0] if batch_size > 1: vx = pred - pred.mean() vy = target - target.mean() loss = F.normalize(vx, p=2, dim=0) * F.normalize(vy, p=2, dim=0) loss = (1 - loss.sum()) / 2 # normalize to [0, 1] else: loss = F.l1_loss(pred, target) return loss.mean()
Args: pred (Tensor): of shape (N, 1). Predicted tensor. target (Tensor): of shape (N, 1). Ground truth tensor.
167,865
from cv2 import reduce import torch import numpy as np from torch import nn as nn from torch.nn import functional as F from pyiqa.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss The provided code snippet includes necessary dependencies for implementing the `norm_loss_with_normalization` function. Write a Python function `def norm_loss_with_normalization(pred, target, p, q)` to solve the following problem: Args: pred (Tensor): of shape (N, 1). Predicted tensor. target (Tensor): of shape (N, 1). Ground truth tensor. Here is the function: def norm_loss_with_normalization(pred, target, p, q): """ Args: pred (Tensor): of shape (N, 1). Predicted tensor. target (Tensor): of shape (N, 1). Ground truth tensor. """ batch_size = pred.shape[0] if batch_size > 1: vx = pred - pred.mean() vy = target - target.mean() scale = np.power(2, p) * np.power(batch_size, max(0, 1 - p / q)) # p, q>0 norm_pred = F.normalize(vx, p=q, dim=0) norm_target = F.normalize(vy, p=q, dim=0) loss = torch.norm(norm_pred - norm_target, p=p) / scale else: loss = F.l1_loss(pred, target) return loss.mean()
Args: pred (Tensor): of shape (N, 1). Predicted tensor. target (Tensor): of shape (N, 1). Ground truth tensor.
167,866
import math import collections.abc from itertools import repeat import numpy as np from typing import Tuple import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable): return x return tuple(repeat(x, n)) return parse
null
167,867
import math import collections.abc from itertools import repeat import numpy as np from typing import Tuple import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init to_2tuple = _ntuple(2) def symm_pad(im: torch.Tensor, padding: Tuple[int, int, int, int]): """Symmetric padding same as tensorflow. Ref: https://discuss.pytorch.org/t/symmetric-padding/19866/3 """ h, w = im.shape[-2:] left, right, top, bottom = padding x_idx = np.arange(-left, w + right) y_idx = np.arange(-top, h + bottom) def reflect(x, minx, maxx): """ Reflects an array around two points making a triangular waveform that ramps up and down, allowing for pad lengths greater than the input length """ rng = maxx - minx double_rng = 2 * rng mod = np.fmod(x - minx, double_rng) normed_mod = np.where(mod < 0, mod + double_rng, mod) out = np.where(normed_mod >= rng, double_rng - normed_mod, normed_mod) + minx return np.array(out, dtype=x.dtype) x_pad = reflect(x_idx, -0.5, w - 0.5) y_pad = reflect(y_idx, -0.5, h - 0.5) xx, yy = np.meshgrid(x_pad, y_pad) return im[..., yy, xx] def exact_padding_2d(x, kernel, stride=1, dilation=1, mode='same'): assert len(x.shape) == 4, f'Only support 4D tensor input, but got {x.shape}' kernel = to_2tuple(kernel) stride = to_2tuple(stride) dilation = to_2tuple(dilation) b, c, h, w = x.shape h2 = math.ceil(h / stride[0]) w2 = math.ceil(w / stride[1]) pad_row = (h2 - 1) * stride[0] + (kernel[0] - 1) * dilation[0] + 1 - h pad_col = (w2 - 1) * stride[1] + (kernel[1] - 1) * dilation[1] + 1 - w pad_l, pad_r, pad_t, pad_b = (pad_col // 2, pad_col - pad_col // 2, pad_row // 2, pad_row - pad_row // 2) mode = mode if mode != 'same' else 'constant' if mode != 'symmetric': x = F.pad(x, (pad_l, pad_r, pad_t, pad_b), mode=mode) elif mode == 'symmetric': x = symm_pad(x, (pad_l, pad_r, pad_t, pad_b)) return x
null