code: def _calculate_downsample(
      image_size: tuple[int, int],
      bytes_per_pixel: int,
      *,
      max_size: tuple[int, int] | None = None,
      max_pixels: int | None = None,
      max_bytes: int | None = None,
  ) -> tuple[int, int]:
      """Calculate image size required to downsample an image to fit limits.
  
      If no limit is exceeded, the input image's size is returned.
  
      Args:
          image_size: Dimensions of image.
          bytes_per_pixel: Number of bytes per pixel.
          max_size: The maximum width and height of the image.
          max_pixels: The maximum number of pixels in the image. Some image consumers
              limit the total number of pixels as some value other than width*height.
          max_bytes: The maximum number of bytes in the image. RGB is counted as 4
              bytes; all other modes are counted as 1 byte.
      """
      size = image_size
  
      if max_size is not None:
          overage = max_size[0] / size[0], max_size[1] / size[1]
          size_factor = min(overage)
          if size_factor < 1.0:
              log.debug("Resizing image to fit image dimensions limit")
              size = floor(size[0] * size_factor), floor(
                  size[1] * size_factor
              )
              if size[0] == 0:
                  size = 1, min(size[1], max_size[1])
              elif size[1] == 0:
                  size = min(size[0], max_size[0]), 1
  
      if max_pixels is not None:
          if size[0] * size[1] > max_pixels:
              log.debug("Resizing image to fit image pixel limit")
              pixels_factor = sqrt(max_pixels / (size[0] * size[1]))
              size = floor(size[0] * pixels_factor), floor(
                  size[1] * pixels_factor
              )
  
      if max_bytes is not None:
          bpp = bytes_per_pixel
          # stride = bytes per line
          stride = size[0] * bpp
          height = size[1]
          if stride * height > max_bytes:
              log.debug("Resizing image to fit image byte size limit")
              bytes_factor = sqrt(max_bytes / (stride * height))
              scaled_stride = floor(stride * bytes_factor)
              scaled_height = floor(height * bytes_factor)
              if scaled_stride == 0:
                  scaled_stride = bpp
                  scaled_height = min(max_bytes // bpp, scaled_height)
              if scaled_height == 0:
                  scaled_height = 1
                  scaled_stride = min(
                      max_bytes // scaled_height, scaled_stride
                  )
              size = floor(scaled_stride / bpp), scaled_height
  
      return size
  
imports: from __future__ import annotations
  import logging
  from math import floor, sqrt
  from PIL import Image
label_desc: Use image node_id 2 for calling a global function with example usage: _calculate_downsample(image_size, bytes_per_pixel) and returns: size