






'''simple docstring'''






import unittest
from typing import Dict, List, Optional, Union

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 BridgeTowerImageProcessor




class a_    (    unittest.TestCase							):







   def __init__(self					,   __a					,   __a = True					,   __a = None					,   __a = 3_2					,   __a = True					,   __a = 1 / 2_5_5					,   __a = True					,   __a = True					,   __a = [0.48_145_466, 0.4_578_275, 0.40_821_073]					,   __a = [0.26_862_954, 0.26_130_258, 0.27_577_711]					,   __a = True					,   __a=7					,   __a=3_0					,   __a=4_0_0					,   __a=3					,   )			->      Dict:
      """simple docstring"""






      __snake_case				:      List[str]     							= parent
      __snake_case				:      List[Any]     							= do_resize
      __snake_case				:      List[Any]     							= size if size is not None else {'shortest_edge': 2_8_8}
      __snake_case				:      Any     							= size_divisor
      __snake_case				:      List[str]     							= do_rescale
      __snake_case				:      List[str]     							= rescale_factor
      __snake_case				:      List[Any]     							= do_normalize
      __snake_case				:      List[str]     							= do_center_crop
      __snake_case				:      str     							= image_mean
      __snake_case				:      Optional[Any]     							= image_std
      __snake_case				:      int     							= do_pad
      __snake_case				:      List[str]     							= batch_size
      __snake_case				:      Dict     							= num_channels
      __snake_case				:      Dict     							= min_resolution
      __snake_case				:      List[str]     							= max_resolution







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
          "size_divisor": self.size_divisor,
      }







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a=False)			->      Tuple:
      """simple docstring"""






      if not batched:
         __snake_case				:      int     							= self.size['shortest_edge']
         __snake_case				:      Dict     							= image_inputs[0]
         if isinstance(__a					,   Image.Image):
            __snake_case							,__snake_case				:      List[Any]     							= image.size
         else:
            __snake_case							,__snake_case				:      Optional[Any]     							= image.shape[1], image.shape[2]
         __snake_case				:      List[Any]     							= size / min(__a					,   __a)
         if h < w:
            __snake_case							,__snake_case				:      Tuple     							= size, scale * w
         else:
            __snake_case							,__snake_case				:      List[Any]     							= scale * h, size

         __snake_case				:      Dict     							= int((1_3_3_3 / 8_0_0) * size)
         if max(__a					,   __a) > max_size:
            __snake_case				:      Union[str, Any]     							= max_size / max(__a					,   __a)
            __snake_case				:      List[str]     							= newh * scale
            __snake_case				:      List[Any]     							= neww * scale

         __snake_case							,__snake_case				:      List[str]     							= int(newh + 0.5), int(neww + 0.5)
         __snake_case							,__snake_case				:      List[str]     							= (
             newh // self.size_divisor * self.size_divisor,
             neww // self.size_divisor * self.size_divisor,
         )

      else:
         __snake_case				:      List[Any]     							= []
         for image in image_inputs:
            __snake_case							,__snake_case				:      List[Any]     							= self.get_expected_values([image])
            expected_values.append((expected_height, expected_width))
         __snake_case				:      Tuple     							= max(__a					,   key=lambda __a: item[0])[0]
         __snake_case				:      List[str]     							= max(__a					,   key=lambda __a: item[1])[1]

      return expected_height, expected_width




@require_torch
@require_vision
class a_    (    UpperCamelCase_		,      unittest.TestCase							):
   _snake_case        =							BridgeTowerImageProcessor if is_vision_available() else None







   def     SCREAMING_SNAKE_CASE__					(self)			->      Any:
      """simple docstring"""






      __snake_case				:      Any     							= BridgeTowerImageProcessingTester(self)







   @property
   def     SCREAMING_SNAKE_CASE__					(self)			->      Dict:
      """simple docstring"""






      return self.image_processor_tester.prepare_image_processor_dict()







   def     SCREAMING_SNAKE_CASE__					(self)			->      Any:
      """simple docstring"""






      __snake_case				:      Tuple     							= self.image_processing_class(**self.image_processor_dict)
      self.assertTrue(hasattr(__a					,   'image_mean'))
      self.assertTrue(hasattr(__a					,   'image_std'))
      self.assertTrue(hasattr(__a					,   'do_normalize'))
      self.assertTrue(hasattr(__a					,   'do_resize'))
      self.assertTrue(hasattr(__a					,   'size'))
      self.assertTrue(hasattr(__a					,   'size_divisor'))







   def     SCREAMING_SNAKE_CASE__					(self)			->      Optional[int]:
      """simple docstring"""






      pass







   def     SCREAMING_SNAKE_CASE__					(self)			->      str:
      """simple docstring"""






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

      # Test not batched input
      __snake_case				:      Optional[int]     							= image_processing(image_inputs[0]					,   return_tensors='pt').pixel_values

      __snake_case							,__snake_case				:      Optional[int]     							= self.image_processor_tester.get_expected_values(__a)
      self.assertEqual(
          encoded_images.shape					,   (1, self.image_processor_tester.num_channels, expected_height, expected_width)					,   )

      # Test batched
      __snake_case				:      str     							= image_processing(__a					,   return_tensors='pt').pixel_values

      __snake_case							,__snake_case				:      List[Any]     							= self.image_processor_tester.get_expected_values(__a					,   batched=__a)
      self.assertEqual(
          encoded_images.shape					,   (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )					,   )







   def     SCREAMING_SNAKE_CASE__					(self)			->      Union[str, Any]:
      """simple docstring"""






      __snake_case				:      Tuple     							= self.image_processing_class(**self.image_processor_dict)
      # create random numpy tensors
      __snake_case				:      Optional[int]     							= prepare_image_inputs(self.image_processor_tester					,   equal_resolution=__a					,   numpify=__a)
      for image in image_inputs:
         self.assertIsInstance(__a					,   np.ndarray)

      # Test not batched input
      __snake_case				:      List[Any]     							= image_processing(image_inputs[0]					,   return_tensors='pt').pixel_values

      __snake_case							,__snake_case				:      List[str]     							= self.image_processor_tester.get_expected_values(__a)
      self.assertEqual(
          encoded_images.shape					,   (1, self.image_processor_tester.num_channels, expected_height, expected_width)					,   )

      # Test batched
      __snake_case				:      Union[str, Any]     							= image_processing(__a					,   return_tensors='pt').pixel_values

      __snake_case							,__snake_case				:      Union[str, Any]     							= self.image_processor_tester.get_expected_values(__a					,   batched=__a)
      self.assertEqual(
          encoded_images.shape					,   (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )					,   )







   def     SCREAMING_SNAKE_CASE__					(self)			->      List[Any]:
      """simple docstring"""






      __snake_case				:      Tuple     							= self.image_processing_class(**self.image_processor_dict)
      # create random PyTorch tensors
      __snake_case				:      Tuple     							= prepare_image_inputs(self.image_processor_tester					,   equal_resolution=__a					,   torchify=__a)
      for image in image_inputs:
         self.assertIsInstance(__a					,   torch.Tensor)

      # Test not batched input
      __snake_case				:      Dict     							= image_processing(image_inputs[0]					,   return_tensors='pt').pixel_values

      __snake_case							,__snake_case				:      Dict     							= self.image_processor_tester.get_expected_values(__a)
      self.assertEqual(
          encoded_images.shape					,   (1, self.image_processor_tester.num_channels, expected_height, expected_width)					,   )

      # Test batched
      __snake_case				:      Optional[int]     							= image_processing(__a					,   return_tensors='pt').pixel_values

      __snake_case							,__snake_case				:      Union[str, Any]     							= self.image_processor_tester.get_expected_values(__a					,   batched=__a)
      self.assertEqual(
          encoded_images.shape					,   (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )					,   )







'''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 (
    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,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
      import PIL


__A    	=   logging.get_logger(__name__)




class a_    (    UpperCamelCase_							):
   _snake_case        =							["""pixel_values"""]







   def __init__(self					,   __a = True					,   __a = None					,   __a = None					,   __a = PILImageResampling.BILINEAR					,   __a = True					,   __a = 1 / 2_5_5					,   __a = True					,   __a = None					,   __a = None					,   **__a					,   )			->      None:
      """simple docstring"""






      super().__init__(**__a)
      __snake_case				:      Tuple     							= size if size is not None else {'shortest_edge': 3_8_4}
      __snake_case				:      List[Any]     							= get_size_dict(__a					,   default_to_square=__a)

      __snake_case				:      int     							= do_resize
      __snake_case				:      List[str]     							= size
      # Default value set here for backwards compatibility where the value in config is None
      __snake_case				:      Any     							= crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
      __snake_case				:      Tuple     							= resample
      __snake_case				:      Dict     							= do_rescale
      __snake_case				:      Any     							= rescale_factor
      __snake_case				:      str     							= do_normalize
      __snake_case				:      Union[str, Any]     							= image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
      __snake_case				:      Dict     							= image_std if image_std is not None else IMAGENET_STANDARD_STD







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a					,   __a					,   __a = PILImageResampling.BICUBIC					,   __a = None					,   **__a					,   )			->      np.ndarray:
      """simple docstring"""






      __snake_case				:      Dict     							= get_size_dict(__a					,   default_to_square=__a)
      if "shortest_edge" not in size:
         raise ValueError(F"""Size dictionary must contain 'shortest_edge' key. Got {size.keys()}""")
      __snake_case				:      List[str]     							= size['shortest_edge']

      if shortest_edge < 3_8_4:
         # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
         __snake_case				:      Any     							= int(shortest_edge / crop_pct)
         __snake_case				:      Any     							= get_resize_output_image_size(__a					,   size=__a					,   default_to_square=__a)
         __snake_case				:      int     							= resize(image=__a					,   size=__a					,   resample=__a					,   data_format=__a					,   **__a)
         # then crop to (shortest_edge, shortest_edge)
         return center_crop(image=__a					,   size=(shortest_edge, shortest_edge)					,   data_format=__a					,   **__a)
      else:
         # warping (no cropping) when evaluated at 384 or larger
         return resize(
             __a					,   size=(shortest_edge, shortest_edge)					,   resample=__a					,   data_format=__a					,   **__a)







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a					,   __a = None					,   **__a					,   )			->      Any:
      """simple docstring"""






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







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a					,   __a					,   __a = None					,   **__a					,   )			->      np.ndarray:
      """simple docstring"""






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







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a = None					,   __a = None					,   __a = None					,   __a = None					,   __a = None					,   __a = None					,   __a = None					,   __a = None					,   __a = None					,   __a = None					,   __a = ChannelDimension.FIRST					,   **__a					,   )			->      PIL.Image.Image:
      """simple docstring"""






      __snake_case				:      Optional[int]     							= do_resize if do_resize is not None else self.do_resize
      __snake_case				:      Dict     							= crop_pct if crop_pct is not None else self.crop_pct
      __snake_case				:      Tuple     							= resample if resample is not None else self.resample
      __snake_case				:      Any     							= do_rescale if do_rescale is not None else self.do_rescale
      __snake_case				:      Any     							= rescale_factor if rescale_factor is not None else self.rescale_factor
      __snake_case				:      Union[str, Any]     							= do_normalize if do_normalize is not None else self.do_normalize
      __snake_case				:      Optional[int]     							= image_mean if image_mean is not None else self.image_mean
      __snake_case				:      Optional[Any]     							= image_std if image_std is not None else self.image_std

      __snake_case				:      List[str]     							= size if size is not None else self.size
      __snake_case				:      Any     							= get_size_dict(__a					,   default_to_square=__a)

      __snake_case				:      Dict     							= make_list_of_images(__a)

      if not valid_images(__a):
         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 or resample is None:
         raise ValueError('Size and resample must be specified if do_resize is True.')

      if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
         raise ValueError('crop_pct must be specified if size < 384.')

      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.')

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

      if do_resize:
         __snake_case				:      Optional[int]     							= [self.resize(image=__a					,   size=__a					,   crop_pct=__a					,   resample=__a) for image in images]

      if do_rescale:
         __snake_case				:      Optional[int]     							= [self.rescale(image=__a					,   scale=__a) for image in images]

      if do_normalize:
         __snake_case				:      Any     							= [self.normalize(image=__a					,   mean=__a					,   std=__a) for image in images]

      __snake_case				:      Dict     							= [to_channel_dimension_format(__a					,   __a) for image in images]

      __snake_case				:      Union[str, Any]     							= {'pixel_values': images}
      return BatchFeature(data=__a					,   tensor_type=__a)