

'''simple docstring'''






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    get_resize_output_image_size,
    normalize,
    pad,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging
from ...utils.import_utils import is_vision_available


snake_case_       =       logging.get_logger(__name__)


if is_vision_available():
      import PIL
class 	SCREAMING_SNAKE_CASE__			(				_UpperCAmelCase      ):
    _A			    =							["pixel_values"]




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






          """simple docstring"""






          super().__init__(**lowercase__			)

          SCREAMING_SNAKE_CASE_      :			List[Any]     =       size if size is not None else {"height": 2560, "width": 1920}
          if isinstance(lowercase__				,     (tuple, list)			):
                # The previous feature extractor size parameter was in (width, height) format
                SCREAMING_SNAKE_CASE_      :			Optional[int]     =       size[::-1]
          SCREAMING_SNAKE_CASE_      :			int     =       get_size_dict(lowercase__			)

          SCREAMING_SNAKE_CASE_      :			List[Any]     =       do_resize
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       size
          SCREAMING_SNAKE_CASE_      :			Tuple     =       resample
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       do_thumbnail
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       do_align_long_axis
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       do_pad
          SCREAMING_SNAKE_CASE_      :			List[str]     =       do_rescale
          SCREAMING_SNAKE_CASE_      :			Tuple     =       rescale_factor
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       do_normalize
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
          SCREAMING_SNAKE_CASE_      :			int     =       image_std if image_std is not None else IMAGENET_STANDARD_STD




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__				,     lowercase__ = None			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_      :			int     =       get_image_size(lowercase__			)
          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_      :			Optional[int]     =       size["height"], size["width"]

          if (output_width < output_height and input_width > input_height) or (
              output_width > output_height and input_width < input_height
          ):
                SCREAMING_SNAKE_CASE_      :			int     =       np.rotaa(lowercase__				,     3			)

          if data_format is not None:
                SCREAMING_SNAKE_CASE_      :			Dict     =       to_channel_dimension_format(lowercase__				,     lowercase__			)

          return image




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__				,     lowercase__ = False				,     lowercase__ = None				,     ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       size["height"], size["width"]
          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_      :			int     =       get_image_size(lowercase__			)

          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       output_width - input_width
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       output_height - input_height

          if random_padding:
                SCREAMING_SNAKE_CASE_      :			Optional[int]     =       np.random.randint(low=0				,     high=delta_height + 1			)
                SCREAMING_SNAKE_CASE_      :			List[Any]     =       np.random.randint(low=0				,     high=delta_width + 1			)
          else:
                SCREAMING_SNAKE_CASE_      :			Dict     =       delta_height // 2
                SCREAMING_SNAKE_CASE_      :			List[Any]     =       delta_width // 2

          SCREAMING_SNAKE_CASE_      :			List[Any]     =       delta_height - pad_top
          SCREAMING_SNAKE_CASE_      :			Dict     =       delta_width - pad_left

          SCREAMING_SNAKE_CASE_      :			List[Any]     =       ((pad_top, pad_bottom), (pad_left, pad_right))
          return pad(lowercase__				,     lowercase__				,     data_format=lowercase__			)




    def   __lowerCamelCase      (					self				,     *lowercase__				,     **lowercase__			):






          """simple docstring"""






          logger.info("pad is deprecated and will be removed in version 4.27. Please use pad_image instead."			)
          return self.pad_image(*lowercase__				,     **lowercase__			)




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__				,     lowercase__ = PILImageResampling.BICUBIC				,     lowercase__ = None				,     **lowercase__				,     ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_      :			Tuple     =       get_image_size(lowercase__			)
          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       size["height"], size["width"]

          # We always resize to the smallest of either the input or output size.
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       min(lowercase__				,     lowercase__			)
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       min(lowercase__				,     lowercase__			)

          if height == input_height and width == input_width:
                return image

          if input_height > input_width:
                SCREAMING_SNAKE_CASE_      :			List[str]     =       int(input_width * height / input_height			)
          elif input_width > input_height:
                SCREAMING_SNAKE_CASE_      :			Dict     =       int(input_height * width / input_width			)

          return resize(
              lowercase__				,     size=(height, width)				,     resample=lowercase__				,     reducing_gap=2.0				,     data_format=lowercase__				,     **lowercase__			)




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__				,     lowercase__ = PILImageResampling.BICUBIC				,     lowercase__ = None				,     **lowercase__				,     ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Tuple     =       get_size_dict(lowercase__			)
          SCREAMING_SNAKE_CASE_      :			Any     =       min(size["height"]				,     size["width"]			)
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       get_resize_output_image_size(lowercase__				,     size=lowercase__				,     default_to_square=lowercase__			)
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       resize(lowercase__				,     size=lowercase__				,     resample=lowercase__				,     data_format=lowercase__				,     **lowercase__			)
          return resized_image




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






          """simple docstring"""






          return rescale(lowercase__				,     scale=lowercase__				,     data_format=lowercase__				,     **lowercase__			)




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






          """simple docstring"""






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







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






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[str]     =       do_resize if do_resize is not None else self.do_resize
          SCREAMING_SNAKE_CASE_      :			int     =       size if size is not None else self.size
          if isinstance(lowercase__				,     (tuple, list)			):
                # Previous feature extractor had size in (width, height) format
                SCREAMING_SNAKE_CASE_      :			Optional[int]     =       size[::-1]
          SCREAMING_SNAKE_CASE_      :			str     =       get_size_dict(lowercase__			)
          SCREAMING_SNAKE_CASE_      :			List[str]     =       resample if resample is not None else self.resample
          SCREAMING_SNAKE_CASE_      :			Tuple     =       do_thumbnail if do_thumbnail is not None else self.do_thumbnail
          SCREAMING_SNAKE_CASE_      :			Dict     =       do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
          SCREAMING_SNAKE_CASE_      :			Tuple     =       do_pad if do_pad is not None else self.do_pad
          SCREAMING_SNAKE_CASE_      :			Dict     =       do_rescale if do_rescale is not None else self.do_rescale
          SCREAMING_SNAKE_CASE_      :			int     =       rescale_factor if rescale_factor is not None else self.rescale_factor
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       do_normalize if do_normalize is not None else self.do_normalize
          SCREAMING_SNAKE_CASE_      :			int     =       image_mean if image_mean is not None else self.image_mean
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       image_std if image_std is not None else self.image_std

          SCREAMING_SNAKE_CASE_      :			str     =       make_list_of_images(lowercase__			)

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

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

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

          if do_pad and size is None:
                raise ValueError("Size must be specified if do_pad 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."			)

          # All transformations expect numpy arrays.
          SCREAMING_SNAKE_CASE_      :			Tuple     =       [to_numpy_array(lowercase__			) for image in images]

          if do_align_long_axis:
                SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       [self.align_long_axis(lowercase__				,     size=lowercase__			) for image in images]

          if do_resize:
                SCREAMING_SNAKE_CASE_      :			Any     =       [self.resize(image=lowercase__				,     size=lowercase__				,     resample=lowercase__			) for image in images]

          if do_thumbnail:
                SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       [self.thumbnail(image=lowercase__				,     size=lowercase__			) for image in images]

          if do_pad:
                SCREAMING_SNAKE_CASE_      :			List[str]     =       [self.pad_image(image=lowercase__				,     size=lowercase__				,     random_padding=lowercase__			) for image in images]

          if do_rescale:
                SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       [self.rescale(image=lowercase__				,     scale=lowercase__			) for image in images]

          if do_normalize:
                SCREAMING_SNAKE_CASE_      :			Optional[int]     =       [self.normalize(image=lowercase__				,     mean=lowercase__				,     std=lowercase__			) for image in images]

          SCREAMING_SNAKE_CASE_      :			Tuple     =       [to_channel_dimension_format(lowercase__				,     lowercase__			) for image in images]

          SCREAMING_SNAKE_CASE_      :			Dict     =       {"pixel_values": images}
          return BatchFeature(data=lowercase__				,     tensor_type=lowercase__			)




'''simple docstring'''






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import MobileNetVaImageProcessor
class 	SCREAMING_SNAKE_CASE__			(				unittest.TestCase      ):




    def __init__(					self				,     lowercase__				,     lowercase__=7				,     lowercase__=3				,     lowercase__=18				,     lowercase__=30				,     lowercase__=400				,     lowercase__=True				,     lowercase__=None				,     lowercase__=True				,     lowercase__=None				,     ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[str]     =       size if size is not None else {"shortest_edge": 20}
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       crop_size if crop_size is not None else {"height": 18, "width": 18}
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       parent
          SCREAMING_SNAKE_CASE_      :			Tuple     =       batch_size
          SCREAMING_SNAKE_CASE_      :			int     =       num_channels
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       image_size
          SCREAMING_SNAKE_CASE_      :			Dict     =       min_resolution
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       max_resolution
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       do_resize
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       size
          SCREAMING_SNAKE_CASE_      :			Tuple     =       do_center_crop
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       crop_size







    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          return {
              "do_resize": self.do_resize,
              "size": self.size,
              "do_center_crop": self.do_center_crop,
              "crop_size": self.crop_size,
          }






@require_torch
@require_vision
class 	SCREAMING_SNAKE_CASE__			(				_UpperCAmelCase,unittest.TestCase      ):
    _A			    =							MobileNetVaImageProcessor if is_vision_available() else None




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Any     =       MobileNetVaImageProcessingTester(self			)




    @property
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          return self.image_processor_tester.prepare_image_processor_dict()




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       self.image_processing_class(**self.image_processor_dict			)
          self.assertTrue(hasattr(lowercase__				,     "do_resize"			)			)
          self.assertTrue(hasattr(lowercase__				,     "size"			)			)
          self.assertTrue(hasattr(lowercase__				,     "do_center_crop"			)			)
          self.assertTrue(hasattr(lowercase__				,     "center_crop"			)			)




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       self.image_processing_class.from_dict(self.image_processor_dict			)
          self.assertEqual(image_processor.size				,     {"shortest_edge": 20}			)
          self.assertEqual(image_processor.crop_size				,     {"height": 18, "width": 18}			)

          SCREAMING_SNAKE_CASE_      :			List[str]     =       self.image_processing_class.from_dict(self.image_processor_dict				,     size=42				,     crop_size=84			)
          self.assertEqual(image_processor.size				,     {"shortest_edge": 42}			)
          self.assertEqual(image_processor.crop_size				,     {"height": 84, "width": 84}			)




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          pass




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       self.image_processing_class(**self.image_processor_dict			)
          # create random PIL images
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       prepare_image_inputs(self.image_processor_tester				,     equal_resolution=lowercase__			)
          for image in image_inputs:
                self.assertIsInstance(lowercase__				,     Image.Image			)

          # Test not batched input
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       image_processing(image_inputs[0]				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )

          # Test batched
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       image_processing(lowercase__				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       self.image_processing_class(**self.image_processor_dict			)
          # create random numpy tensors
          SCREAMING_SNAKE_CASE_      :			Dict     =       prepare_image_inputs(self.image_processor_tester				,     equal_resolution=lowercase__				,     numpify=lowercase__			)
          for image in image_inputs:
                self.assertIsInstance(lowercase__				,     np.ndarray			)

          # Test not batched input
          SCREAMING_SNAKE_CASE_      :			Dict     =       image_processing(image_inputs[0]				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )

          # Test batched
          SCREAMING_SNAKE_CASE_      :			Dict     =       image_processing(lowercase__				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )







    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[str]     =       self.image_processing_class(**self.image_processor_dict			)
          # create random PyTorch tensors
          SCREAMING_SNAKE_CASE_      :			Any     =       prepare_image_inputs(self.image_processor_tester				,     equal_resolution=lowercase__				,     torchify=lowercase__			)
          for image in image_inputs:
                self.assertIsInstance(lowercase__				,     torch.Tensor			)

          # Test not batched input
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       image_processing(image_inputs[0]				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )

          # Test batched
          SCREAMING_SNAKE_CASE_      :			List[str]     =       image_processing(lowercase__				,     return_tensors="pt"			).pixel_values
          self.assertEqual(
              encoded_images.shape				,     (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size["height"],
                  self.image_processor_tester.crop_size["width"],
              )				,     )

