




'''simple docstring'''




from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
     import PIL

a_      :		Optional[int]							      =       logging.get_logger(__name__)





def      a_							(      __snake_case							:			str   )							->						List[List[ImageInput]]:



       """simple docstring"""






       if isinstance(__snake_case   ,       (list, tuple)   ) and isinstance(videos[0]   ,       (list, tuple)   ) and is_valid_image(videos[0][0]   ):
              return videos

       elif isinstance(__snake_case   ,       (list, tuple)   ) and is_valid_image(videos[0]   ):
              return [videos]

       elif is_valid_image(__snake_case   ):
              return [[videos]]

       raise ValueError(F'''Could not make batched video from {videos}'''   )


class   __UpperCamelCase       ( _lowerCamelCase				):
       lowercase	:    List[str]      						=['pixel_values']






       def __init__(							self,		lowerCAmelCase = True,		lowerCAmelCase = None,		lowerCAmelCase = PILImageResampling.BILINEAR,		lowerCAmelCase = True,		lowerCAmelCase = None,		lowerCAmelCase = True,		lowerCAmelCase = 1 / 255,		lowerCAmelCase = True,		lowerCAmelCase = True,		lowerCAmelCase = None,		lowerCAmelCase = None,		**lowerCAmelCase,		):



              """simple docstring"""







              super().__init__(**_UpperCamelCase  )
              lowerCamelCase_							=size if size is not None else {'''shortest_edge''': 256}
              lowerCamelCase_							=get_size_dict(_UpperCamelCase,		default_to_square=_UpperCamelCase  )
              lowerCamelCase_							=crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
              lowerCamelCase_							=get_size_dict(_UpperCamelCase,		param_name='''crop_size'''  )

              lowerCamelCase_							=do_resize
              lowerCamelCase_							=size
              lowerCamelCase_							=do_center_crop
              lowerCamelCase_							=crop_size
              lowerCamelCase_							=resample
              lowerCamelCase_							=do_rescale
              lowerCamelCase_							=rescale_factor
              lowerCamelCase_							=offset
              lowerCamelCase_							=do_normalize
              lowerCamelCase_							=image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
              lowerCamelCase_							=image_std if image_std is not None else IMAGENET_STANDARD_STD






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase = PILImageResampling.BILINEAR,		lowerCAmelCase = None,		**lowerCAmelCase,		):



              """simple docstring"""







              lowerCamelCase_							=get_size_dict(_UpperCamelCase,		default_to_square=_UpperCamelCase  )
              if "shortest_edge" in size:
                     lowerCamelCase_							=get_resize_output_image_size(_UpperCamelCase,		size['''shortest_edge'''],		default_to_square=_UpperCamelCase  )
              elif "height" in size and "width" in size:
                     lowerCamelCase_							=(size['''height'''], size['''width'''])
              else:
                     raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''  )
              return resize(_UpperCamelCase,		size=_UpperCamelCase,		resample=_UpperCamelCase,		data_format=_UpperCamelCase,		**_UpperCamelCase  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase = None,		**lowerCAmelCase,		):



              """simple docstring"""







              lowerCamelCase_							=get_size_dict(_UpperCamelCase  )
              if "height" not in size or "width" not in size:
                     raise ValueError(f'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}'''  )
              return center_crop(_UpperCamelCase,		size=(size['''height'''], size['''width''']),		data_format=_UpperCamelCase,		**_UpperCamelCase  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase = True,		lowerCAmelCase = None,		**lowerCAmelCase,		):



              """simple docstring"""







              lowerCamelCase_							=image.astype(np.floataa  )
              if offset:
                     lowerCamelCase_							=image - (scale / 2)
              return rescale(_UpperCamelCase,		scale=_UpperCamelCase,		data_format=_UpperCamelCase,		**_UpperCamelCase  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase,		lowerCAmelCase = None,		**lowerCAmelCase,		):



              """simple docstring"""







              return normalize(_UpperCamelCase,		mean=_UpperCamelCase,		std=_UpperCamelCase,		data_format=_UpperCamelCase,		**_UpperCamelCase  )






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = ChannelDimension.FIRST,		):



              """simple docstring"""







              if do_resize and size is None or resample is None:
                     raise ValueError('''Size and resample must be specified if do_resize is True.'''  )

              if do_center_crop and crop_size is None:
                     raise ValueError('''Crop size must be specified if do_center_crop is True.'''  )

              if do_rescale and rescale_factor is None:
                     raise ValueError('''Rescale factor must be specified if do_rescale is True.'''  )

              if do_normalize and (image_mean is None or image_std is None):
                     raise ValueError('''Image mean and std must be specified if do_normalize is True.'''  )

              if offset and not do_rescale:
                     raise ValueError('''For offset, do_rescale must also be set to True.'''  )

              # All transformations expect numpy arrays.
              lowerCamelCase_							=to_numpy_array(_UpperCamelCase  )

              if do_resize:
                     lowerCamelCase_							=self.resize(image=_UpperCamelCase,		size=_UpperCamelCase,		resample=_UpperCamelCase  )

              if do_center_crop:
                     lowerCamelCase_							=self.center_crop(_UpperCamelCase,		size=_UpperCamelCase  )

              if do_rescale:
                     lowerCamelCase_							=self.rescale(image=_UpperCamelCase,		scale=_UpperCamelCase,		offset=_UpperCamelCase  )

              if do_normalize:
                     lowerCamelCase_							=self.normalize(image=_UpperCamelCase,		mean=_UpperCamelCase,		std=_UpperCamelCase  )

              lowerCamelCase_							=to_channel_dimension_format(_UpperCamelCase,		_UpperCamelCase  )
              return image






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = None,		lowerCAmelCase = ChannelDimension.FIRST,		**lowerCAmelCase,		):



              """simple docstring"""







              lowerCamelCase_							=do_resize if do_resize is not None else self.do_resize
              lowerCamelCase_							=resample if resample is not None else self.resample
              lowerCamelCase_							=do_center_crop if do_center_crop is not None else self.do_center_crop
              lowerCamelCase_							=do_rescale if do_rescale is not None else self.do_rescale
              lowerCamelCase_							=rescale_factor if rescale_factor is not None else self.rescale_factor
              lowerCamelCase_							=offset if offset is not None else self.offset
              lowerCamelCase_							=do_normalize if do_normalize is not None else self.do_normalize
              lowerCamelCase_							=image_mean if image_mean is not None else self.image_mean
              lowerCamelCase_							=image_std if image_std is not None else self.image_std

              lowerCamelCase_							=size if size is not None else self.size
              lowerCamelCase_							=get_size_dict(_UpperCamelCase,		default_to_square=_UpperCamelCase  )
              lowerCamelCase_							=crop_size if crop_size is not None else self.crop_size
              lowerCamelCase_							=get_size_dict(_UpperCamelCase,		param_name='''crop_size'''  )

              if not valid_images(_UpperCamelCase  ):
                     raise ValueError(
                         '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                         '''torch.Tensor, tf.Tensor or jax.ndarray.'''  )

              lowerCamelCase_							=make_batched(_UpperCamelCase  )

              lowerCamelCase_							=[
                  [
                      self._preprocess_image(
                          image=_UpperCamelCase,		do_resize=_UpperCamelCase,		size=_UpperCamelCase,		resample=_UpperCamelCase,		do_center_crop=_UpperCamelCase,		crop_size=_UpperCamelCase,		do_rescale=_UpperCamelCase,		rescale_factor=_UpperCamelCase,		offset=_UpperCamelCase,		do_normalize=_UpperCamelCase,		image_mean=_UpperCamelCase,		image_std=_UpperCamelCase,		data_format=_UpperCamelCase,		)
                      for img in video
                  ]
                  for video in videos
              ]

              lowerCamelCase_							={'''pixel_values''': videos}
              return BatchFeature(data=_UpperCamelCase,		tensor_type=_UpperCamelCase  )











import numpy as np
from PIL import Image



def _a				(	lowerCamelCase:   np.ndarray					,				lowerCamelCase:   int					,				lowerCamelCase:   int )	->						np.ndarray:







      '''simple docstring'''






      __A          =				np.array(lowerCamelCase )
      if arr.shape[0] != arr.shape[1]:
            raise ValueError('''The input array is not a square matrix''' )
      __A          =				0
      __A          =				0
      __A          =				0
      __A          =				0

      # compute the shape of the output matrix
      __A          =				(arr.shape[0] - size) // stride + 1
      # initialize the output matrix with zeros of shape maxpool_shape
      __A          =				np.zeros((maxpool_shape, maxpool_shape) )

      while i < arr.shape[0]:
            if i + size > arr.shape[0]:
                  # if the end of the matrix is reached, break
                  break
            while j < arr.shape[1]:
                  # if the end of the matrix is reached, break
                  if j + size > arr.shape[1]:
                        break
                  # compute the maximum of the pooling matrix
                  __A          =				np.max(arr[i : i + size, j : j + size] )
                  # shift the pooling matrix by stride of column pixels
                  j += stride
                  mat_j += 1

            # shift the pooling matrix by stride of row pixels
            i += stride
            mat_i += 1

            # reset the column index to 0
            __A          =				0
            __A          =				0

      return updated_arr



def _a				(	lowerCamelCase:   np.ndarray					,				lowerCamelCase:   int					,				lowerCamelCase:   int )	->						np.ndarray:







      '''simple docstring'''






      __A          =				np.array(lowerCamelCase )
      if arr.shape[0] != arr.shape[1]:
            raise ValueError('''The input array is not a square matrix''' )
      __A          =				0
      __A          =				0
      __A          =				0
      __A          =				0

      # compute the shape of the output matrix
      __A          =				(arr.shape[0] - size) // stride + 1
      # initialize the output matrix with zeros of shape avgpool_shape
      __A          =				np.zeros((avgpool_shape, avgpool_shape) )

      while i < arr.shape[0]:
            # if the end of the matrix is reached, break
            if i + size > arr.shape[0]:
                  break
            while j < arr.shape[1]:
                  # if the end of the matrix is reached, break
                  if j + size > arr.shape[1]:
                        break
                  # compute the average of the pooling matrix
                  __A          =				int(np.average(arr[i : i + size, j : j + size] ) )
                  # shift the pooling matrix by stride of column pixels
                  j += stride
                  mat_j += 1

            # shift the pooling matrix by stride of row pixels
            i += stride
            mat_i += 1
            # reset the column index to 0
            __A          =				0
            __A          =				0

      return updated_arr


# Main Function
if __name__ == "__main__":
       from doctest import testmod

       testmod(name='avgpooling', verbose=True)

       # Loading the image
       snake_case__					:							Optional[Any]													=     Image.open('path_to_image')

       # Converting the image to numpy array and maxpooling, displaying the result
       # Ensure that the image is a square matrix

       Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

       # Converting the image to numpy array and averagepooling, displaying the result
       # Ensure that the image is a square matrix

       Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()





