



"""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 ChineseCLIPImageProcessor






class       UpperCamelCase__			(   unittest.TestCase      ):

			"""simple docstring"""


			def __init__(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__=7						,	SCREAMING_SNAKE_CASE__=3						,	SCREAMING_SNAKE_CASE__=18						,	SCREAMING_SNAKE_CASE__=30						,	SCREAMING_SNAKE_CASE__=400						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=None						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=None						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]						,	SCREAMING_SNAKE_CASE__=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]						,	SCREAMING_SNAKE_CASE__=True						,	)      ->	List[Any]:
				A__											=					size if size is not None else {"height": 224, "width": 224}
				A__											=					crop_size if crop_size is not None else {"height": 18, "width": 18}
				A__											=					parent
				A__											=					batch_size
				A__											=					num_channels
				A__											=					image_size
				A__											=					min_resolution
				A__											=					max_resolution
				A__											=					do_resize
				A__											=					size
				A__											=					do_center_crop
				A__											=					crop_size
				A__											=					do_normalize
				A__											=					image_mean
				A__											=					image_std
				A__											=					do_convert_rgb


			def   snake_case__	(      self		)      ->	int:
				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   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__=False						,	SCREAMING_SNAKE_CASE__=False						,	SCREAMING_SNAKE_CASE__=False		)      ->	Tuple:
				assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

				if equal_resolution:
					A__											=					[]
					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__											=					[]
					for i in range(self.batch_size		):
						A__							,							A__											=					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__											=					[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__						,	0						,	-1		)		) for x in image_inputs]

				if torchify:
					A__											=					[torch.from_numpy(SCREAMING_SNAKE_CASE__		) for x in image_inputs]

				return image_inputs






@require_torch
@require_vision
class       UpperCamelCase__			(   _lowerCAmelCase       ,		unittest.TestCase      ):

			"""simple docstring"""


			A__	:					List[Any]							  =     ChineseCLIPImageProcessor if is_vision_available() else None


			def   snake_case__	(      self		)      ->	str:
				A__											=					ChineseCLIPImageProcessingTester(self						,	do_center_crop=SCREAMING_SNAKE_CASE__		)


			@property
			def   snake_case__	(      self		)      ->	Union[str, Any]:
				return self.image_processor_tester.prepare_image_processor_dict()


			def   snake_case__	(      self		)      ->	Tuple:
				A__											=					self.image_processing_class(**self.image_processor_dict		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"do_resize"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"size"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"do_center_crop"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"center_crop"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"do_normalize"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"image_mean"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"image_std"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"do_convert_rgb"		)		)


			def   snake_case__	(      self		)      ->	List[str]:
				A__											=					self.image_processing_class.from_dict(self.image_processor_dict		)
				self.assertEqual(image_processor.size						,	{"height": 224, "width": 224}		)
				self.assertEqual(image_processor.crop_size						,	{"height": 18, "width": 18}		)

				A__											=					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   snake_case__	(      self		)      ->	str:
				pass


			def   snake_case__	(      self		)      ->	str:
				# Initialize image_processing
				A__											=					self.image_processing_class(**self.image_processor_dict		)
				# create random PIL images
				A__											=					self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE__		)
				for image in image_inputs:
					self.assertIsInstance(SCREAMING_SNAKE_CASE__						,	Image.Image		)

				# Test not batched input
				A__											=					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__											=					image_processing(SCREAMING_SNAKE_CASE__						,	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   snake_case__	(      self		)      ->	List[str]:
				# Initialize image_processing
				A__											=					self.image_processing_class(**self.image_processor_dict		)
				# create random numpy tensors
				A__											=					self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE__						,	numpify=SCREAMING_SNAKE_CASE__		)
				for image in image_inputs:
					self.assertIsInstance(SCREAMING_SNAKE_CASE__						,	np.ndarray		)

				# Test not batched input
				A__											=					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__											=					image_processing(SCREAMING_SNAKE_CASE__						,	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   snake_case__	(      self		)      ->	int:
				# Initialize image_processing
				A__											=					self.image_processing_class(**self.image_processor_dict		)
				# create random PyTorch tensors
				A__											=					self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE__						,	torchify=SCREAMING_SNAKE_CASE__		)
				for image in image_inputs:
					self.assertIsInstance(SCREAMING_SNAKE_CASE__						,	torch.Tensor		)

				# Test not batched input
				A__											=					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__											=					image_processing(SCREAMING_SNAKE_CASE__						,	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       UpperCamelCase__			(   _lowerCAmelCase       ,		unittest.TestCase      ):

			"""simple docstring"""


			A__	:					str							  =     ChineseCLIPImageProcessor if is_vision_available() else None


			def   snake_case__	(      self		)      ->	Dict:
				A__											=					ChineseCLIPImageProcessingTester(self						,	num_channels=4						,	do_center_crop=SCREAMING_SNAKE_CASE__		)
				A__											=					3


			@property
			def   snake_case__	(      self		)      ->	Union[str, Any]:
				return self.image_processor_tester.prepare_image_processor_dict()


			def   snake_case__	(      self		)      ->	Dict:
				A__											=					self.image_processing_class(**self.image_processor_dict		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"do_resize"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"size"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"do_center_crop"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"center_crop"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"do_normalize"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"image_mean"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"image_std"		)		)
				self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__						,	"do_convert_rgb"		)		)


			def   snake_case__	(      self		)      ->	Dict:
				pass







			def   snake_case__	(      self		)      ->	Optional[Any]:
				# Initialize image_processing
				A__											=					self.image_processing_class(**self.image_processor_dict		)
				# create random PIL images
				A__											=					self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE__		)
				for image in image_inputs:
					self.assertIsInstance(SCREAMING_SNAKE_CASE__						,	Image.Image		)

				# Test not batched input
				A__											=					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__											=					image_processing(SCREAMING_SNAKE_CASE__						,	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"],
				    )						,	)











'''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 rescale, resize, to_channel_dimension_format
from ...image_utils import (
    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__)

def     __magic_name__							(				__UpperCAmelCase				,						__UpperCAmelCase   )    ->       str:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							b.T
   __SCREAMING_SNAKE_CASE   				=							np.sum(np.square(__UpperCAmelCase   )				,						axis=1   )
   __SCREAMING_SNAKE_CASE   				=							np.sum(np.square(__UpperCAmelCase   )				,						axis=0   )
   __SCREAMING_SNAKE_CASE   				=							np.matmul(__UpperCAmelCase				,						__UpperCAmelCase   )
   __SCREAMING_SNAKE_CASE   				=							aa[:, None] - 2 * ab + ba[None, :]
   return d

def     __magic_name__							(				__UpperCAmelCase				,						__UpperCAmelCase   )    ->       List[Any]:

   '''simple docstring'''







   __SCREAMING_SNAKE_CASE   				=							x.reshape(-1				,						3   )
   __SCREAMING_SNAKE_CASE   				=							squared_euclidean_distance(__UpperCAmelCase				,						__UpperCAmelCase   )
   return np.argmin(__UpperCAmelCase				,						axis=1   )







class __a			( _snake_case      ):
   __UpperCamelCase :			Any						   =						['pixel_values']





   def __init__(       self					:      Any					,lowerCamelCase					:      Optional[Union[List[List[int]], np.ndarray]] = None					,lowerCamelCase					:      bool = True					,lowerCamelCase					:      Dict[str, int] = None					,lowerCamelCase					:      PILImageResampling = PILImageResampling.BILINEAR					,lowerCamelCase					:      bool = True					,lowerCamelCase					:      bool = True					,**lowerCamelCase					:      Optional[Any]					,):

      '''simple docstring'''

      super().__init__(**lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							size if size is not None else {"""height""": 256, """width""": 256}
      __SCREAMING_SNAKE_CASE   				=							get_size_dict(lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							np.array(lowerCamelCase     ) if clusters is not None else None
      __SCREAMING_SNAKE_CASE   				=							do_resize
      __SCREAMING_SNAKE_CASE   				=							size
      __SCREAMING_SNAKE_CASE   				=							resample
      __SCREAMING_SNAKE_CASE   				=							do_normalize
      __SCREAMING_SNAKE_CASE   				=							do_color_quantize





   def   UpperCAmelCase__  (       self					:      Optional[int]					,lowerCamelCase					:      np.ndarray					,lowerCamelCase					:      Dict[str, int]					,lowerCamelCase					:      PILImageResampling = PILImageResampling.BILINEAR					,lowerCamelCase					:      Optional[Union[str, ChannelDimension]] = None					,**lowerCamelCase					:      int					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							get_size_dict(lowerCamelCase     )
      if "height" not in size or "width" not in size:
         raise ValueError(f"""Size dictionary must contain both height and width keys. Got {size.keys()}"""     )
      return resize(
          lowerCamelCase					,size=(size["""height"""], size["""width"""])					,resample=lowerCamelCase					,data_format=lowerCamelCase					,**lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Optional[Any]					,lowerCamelCase					:      np.ndarray					,lowerCamelCase					:      Optional[Union[str, ChannelDimension]] = None					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							rescale(image=lowerCamelCase					,scale=1 / 127.5					,data_format=lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							image - 1
      return image





   def   UpperCAmelCase__  (       self					:      Dict					,lowerCamelCase					:      ImageInput					,lowerCamelCase					:      bool = None					,lowerCamelCase					:      Dict[str, int] = None					,lowerCamelCase					:      PILImageResampling = None					,lowerCamelCase					:      bool = None					,lowerCamelCase					:      Optional[bool] = None					,lowerCamelCase					:      Optional[Union[List[List[int]], np.ndarray]] = None					,lowerCamelCase					:      Optional[Union[str, TensorType]] = None					,lowerCamelCase					:      Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST					,**lowerCamelCase					:      Any					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							do_resize if do_resize is not None else self.do_resize
      __SCREAMING_SNAKE_CASE   				=							size if size is not None else self.size
      __SCREAMING_SNAKE_CASE   				=							get_size_dict(lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							resample if resample is not None else self.resample
      __SCREAMING_SNAKE_CASE   				=							do_normalize if do_normalize is not None else self.do_normalize
      __SCREAMING_SNAKE_CASE   				=							do_color_quantize if do_color_quantize is not None else self.do_color_quantize
      __SCREAMING_SNAKE_CASE   				=							clusters if clusters is not None else self.clusters
      __SCREAMING_SNAKE_CASE   				=							np.array(lowerCamelCase     )

      __SCREAMING_SNAKE_CASE   				=							make_list_of_images(lowerCamelCase     )

      if not valid_images(lowerCamelCase     ):
         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_color_quantize and clusters is None:
         raise ValueError("""Clusters must be specified if do_color_quantize is True."""     )

      # All transformations expect numpy arrays.
      __SCREAMING_SNAKE_CASE   				=							[to_numpy_array(lowerCamelCase     ) for image in images]

      if do_resize:
         __SCREAMING_SNAKE_CASE   				=							[self.resize(image=lowerCamelCase					,size=lowerCamelCase					,resample=lowerCamelCase     ) for image in images]

      if do_normalize:
         __SCREAMING_SNAKE_CASE   				=							[self.normalize(image=lowerCamelCase     ) for image in images]

      if do_color_quantize:
         __SCREAMING_SNAKE_CASE   				=							[to_channel_dimension_format(lowerCamelCase					,ChannelDimension.LAST     ) for image in images]
         # color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
         __SCREAMING_SNAKE_CASE   				=							np.array(lowerCamelCase     )
         __SCREAMING_SNAKE_CASE   				=							color_quantize(lowerCamelCase					,lowerCamelCase     ).reshape(images.shape[:-1]     )

         # flatten to (batch_size, height*width)
         __SCREAMING_SNAKE_CASE   				=							images.shape[0]
         __SCREAMING_SNAKE_CASE   				=							images.reshape(lowerCamelCase					,-1     )

         # We need to convert back to a list of images to keep consistent behaviour across processors.
         __SCREAMING_SNAKE_CASE   				=							list(lowerCamelCase     )
      else:
         __SCREAMING_SNAKE_CASE   				=							[to_channel_dimension_format(lowerCamelCase					,lowerCamelCase     ) for image in images]

      __SCREAMING_SNAKE_CASE   				=							{"""input_ids""": images}
      return BatchFeature(data=lowerCamelCase					,tensor_type=lowerCamelCase     )





