




'''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,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


lowerCAmelCase_			:     Any							    =     logging.get_logger(__name__)


if is_vision_available():
 import PIL







class     SCREAMING_SNAKE_CASE						(	snake_case_							):
      __magic_name__     :					List[Any]             =				['''pixel_values''']






      def __init__(   self      :     Optional[Any]	,	lowercase__      :     bool = True	,	lowercase__      :     Dict[str, int] = None	,	lowercase__      :     PILImageResampling = PILImageResampling.BICUBIC	,	lowercase__      :     bool = True	,	lowercase__      :     Dict[str, int] = None	,	lowercase__      :     bool = True	,	lowercase__      :     Union[int, float] = 1 / 255	,	lowercase__      :     bool = True	,	lowercase__      :     Optional[Union[float, List[float]]] = None	,	lowercase__      :     Optional[Union[float, List[float]]] = None	,	lowercase__      :     bool = True	,	**lowercase__      :     Tuple	,	):


           '''simple docstring'''

           super().__init__(**lowercase__					)
           a_    :       Optional[int]    	=     size if size is not None else {"""shortest_edge""": 224}
           a_    :       List[Any]    	=     get_size_dict(lowercase__	,	default_to_square=lowercase__					)
           a_    :       Optional[Any]    	=     crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
           a_    :       Tuple    	=     get_size_dict(lowercase__					)

           a_    :       List[Any]    	=     do_resize
           a_    :       List[str]    	=     size
           a_    :       Union[str, Any]    	=     resample
           a_    :       Union[str, Any]    	=     do_center_crop
           a_    :       str    	=     crop_size
           a_    :       Tuple    	=     do_rescale
           a_    :       int    	=     rescale_factor
           a_    :       Union[str, Any]    	=     do_normalize
           a_    :       str    	=     image_mean if image_mean is not None else OPENAI_CLIP_MEAN
           a_    :       Optional[Any]    	=     image_std if image_std is not None else OPENAI_CLIP_STD
           a_    :       Tuple    	=     do_convert_rgb






      def        lowercase_	(   self      :     Dict	,	lowercase__      :     np.ndarray	,	lowercase__      :     Dict[str, int]	,	lowercase__      :     PILImageResampling = PILImageResampling.BICUBIC	,	lowercase__      :     Optional[Union[str, ChannelDimension]] = None	,	**lowercase__      :     Optional[int]	,	):


           '''simple docstring'''

           a_    :       Optional[int]    	=     get_size_dict(lowercase__	,	default_to_square=lowercase__					)
           a_    :       str    	=     get_resize_output_image_size(
               lowercase__	,	size=(size["""height"""], size["""width"""])	,	default_to_square=lowercase__					)
           return resize(lowercase__	,	size=lowercase__	,	resample=lowercase__	,	data_format=lowercase__	,	**lowercase__					)






      def        lowercase_	(   self      :     List[Any]	,	lowercase__      :     np.ndarray	,	lowercase__      :     Dict[str, int]	,	lowercase__      :     Optional[Union[str, ChannelDimension]] = None	,	**lowercase__      :     Dict	,	):


           '''simple docstring'''

           a_    :       Any    	=     get_size_dict(lowercase__					)
           return center_crop(lowercase__	,	size=(size["""height"""], size["""width"""])	,	data_format=lowercase__	,	**lowercase__					)






      def        lowercase_	(   self      :     List[Any]	,	lowercase__      :     np.ndarray	,	lowercase__      :     Union[int, float]	,	lowercase__      :     Optional[Union[str, ChannelDimension]] = None	,	**lowercase__      :     List[Any]	,	):


           '''simple docstring'''

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






      def        lowercase_	(   self      :     Dict	,	lowercase__      :     np.ndarray	,	lowercase__      :     Union[float, List[float]]	,	lowercase__      :     Union[float, List[float]]	,	lowercase__      :     Optional[Union[str, ChannelDimension]] = None	,	**lowercase__      :     int	,	):


           '''simple docstring'''

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






      def        lowercase_	(   self      :     Union[str, Any]	,	lowercase__      :     ImageInput	,	lowercase__      :     bool = None	,	lowercase__      :     Dict[str, int] = None	,	lowercase__      :     PILImageResampling = None	,	lowercase__      :     bool = None	,	lowercase__      :     int = None	,	lowercase__      :     bool = None	,	lowercase__      :     float = None	,	lowercase__      :     bool = None	,	lowercase__      :     Optional[Union[float, List[float]]] = None	,	lowercase__      :     Optional[Union[float, List[float]]] = None	,	lowercase__      :     bool = None	,	lowercase__      :     Optional[Union[str, TensorType]] = None	,	lowercase__      :     Optional[ChannelDimension] = ChannelDimension.FIRST	,	**lowercase__      :     List[Any]	,	):


           '''simple docstring'''

           a_    :       List[Any]    	=     do_resize if do_resize is not None else self.do_resize
           a_    :       Dict    	=     size if size is not None else self.size
           a_    :       str    	=     get_size_dict(lowercase__	,	default_to_square=lowercase__					)
           a_    :       Tuple    	=     resample if resample is not None else self.resample
           a_    :       Optional[Any]    	=     do_center_crop if do_center_crop is not None else self.do_center_crop
           a_    :       Tuple    	=     crop_size if crop_size is not None else self.crop_size
           a_    :       Union[str, Any]    	=     get_size_dict(lowercase__					)
           a_    :       str    	=     do_rescale if do_rescale is not None else self.do_rescale
           a_    :       Union[str, Any]    	=     rescale_factor if rescale_factor is not None else self.rescale_factor
           a_    :       Any    	=     do_normalize if do_normalize is not None else self.do_normalize
           a_    :       Optional[int]    	=     image_mean if image_mean is not None else self.image_mean
           a_    :       List[Any]    	=     image_std if image_std is not None else self.image_std
           a_    :       List[str]    	=     do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

           a_    :       List[Any]    	=     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_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."""					)

           # PIL RGBA images are converted to RGB
           if do_convert_rgb:
                a_    :       Union[str, Any]    	=     [convert_to_rgb(lowercase__					) for image in images]

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

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

           if do_center_crop:
                a_    :       int    	=     [self.center_crop(image=lowercase__	,	size=lowercase__					) for image in images]

           if do_rescale:
                a_    :       Optional[Any]    	=     [self.rescale(image=lowercase__	,	scale=lowercase__					) for image in images]

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

           a_    :       int    	=     [to_channel_dimension_format(lowercase__	,	lowercase__					) for image in images]

           a_    :       Union[str, Any]    	=     {"""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


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import CLIPImageProcessor







class     SCREAMING_SNAKE_CASE						(	unittest.TestCase							):






      def __init__(   self      :     Tuple	,	lowercase__      :     Union[str, Any]	,	lowercase__      :     Optional[Any]=7	,	lowercase__      :     str=3	,	lowercase__      :     Tuple=18	,	lowercase__      :     Dict=30	,	lowercase__      :     List[Any]=400	,	lowercase__      :     Optional[Any]=True	,	lowercase__      :     Union[str, Any]=None	,	lowercase__      :     Union[str, Any]=True	,	lowercase__      :     Tuple=None	,	lowercase__      :     str=True	,	lowercase__      :     List[Any]=[0.48145466, 0.4578275, 0.40821073]	,	lowercase__      :     Optional[Any]=[0.26862954, 0.26130258, 0.27577711]	,	lowercase__      :     str=True	,	):


           '''simple docstring'''

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






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           return {
               "do_resize": self.do_resize,
               "size": self.size,
               "do_center_crop": self.do_center_crop,
               "crop_size": self.crop_size,
               "do_normalize": self.do_normalize,
               "image_mean": self.image_mean,
               "image_std": self.image_std,
               "do_convert_rgb": self.do_convert_rgb,
           }






      def        lowercase_	(   self      :     str	,	lowercase__      :     Union[str, Any]=False	,	lowercase__      :     Union[str, Any]=False	,	lowercase__      :     Union[str, Any]=False					):


           '''simple docstring'''

           assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

           if equal_resolution:
                a_    :       Union[str, Any]    	=     []
                for i in range(self.batch_size					):
                     image_inputs.append(
                         np.random.randint(
                             255	,	size=(self.num_channels, self.max_resolution, self.max_resolution)	,	dtype=np.uinta					)					)
           else:
                a_    :       int    	=     []
                for i in range(self.batch_size					):
                     a_	,    a_    :       Any    	=     np.random.choice(np.arange(self.min_resolution	,	self.max_resolution					)	,	2					)
                     image_inputs.append(np.random.randint(255	,	size=(self.num_channels, width, height)	,	dtype=np.uinta					)					)

           if not numpify and not torchify:
                # PIL expects the channel dimension as last dimension
                a_    :       Union[str, Any]    	=     [Image.fromarray(np.moveaxis(lowercase__	,	0	,	-1					)					) for x in image_inputs]

           if torchify:
                a_    :       List[Any]    	=     [torch.from_numpy(lowercase__					) for x in image_inputs]

           return image_inputs







@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					int             =				CLIPImageProcessor if is_vision_available() else None






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           a_    :       Dict    	=     CLIPImageProcessingTester(self					)






      @property
      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()






      def        lowercase_	(   self      :     Optional[Any]					):


           '''simple docstring'''

           a_    :       List[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"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_normalize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_mean"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_std"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_convert_rgb"""					)					)






      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           a_    :       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}					)

           a_    :       Optional[int]    	=     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        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           a_    :       str    	=     self.image_processing_class(**self.image_processor_dict					)
           # create random PIL images
           a_    :       str    	=     self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__					)
           for image in image_inputs:
                self.assertIsInstance(lowercase__	,	Image.Image					)

           # Test not batched input
           a_    :       Optional[Any]    	=     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
           a_    :       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"""],
               )	,	)






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

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

           # Test not batched input
           a_    :       Tuple    	=     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
           a_    :       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"""],
               )	,	)






      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           a_    :       Dict    	=     self.image_processing_class(**self.image_processor_dict					)
           # create random PyTorch tensors
           a_    :       Optional[int]    	=     self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__	,	torchify=lowercase__					)
           for image in image_inputs:
                self.assertIsInstance(lowercase__	,	torch.Tensor					)

           # Test not batched input
           a_    :       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
           a_    :       int    	=     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"""],
               )	,	)







@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					List[str]             =				CLIPImageProcessor if is_vision_available() else None






      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           a_    :       str    	=     CLIPImageProcessingTester(self	,	num_channels=4					)
           a_    :       Dict    	=     3






      @property
      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       int    	=     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"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_normalize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_mean"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_std"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_convert_rgb"""					)					)






      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

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

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

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