

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


_lowerCamelCase    :       List[Any]        =							logging.get_logger(__name__)





class  __UpperCAmelCase					(	A__						):
   UpperCamelCase       					=					['pixel_values']



   def __init__(							self							:					int,		__A							:					Union[str, Any] = True,		__A							:					str = None,		__A							:					Any = PIL.Image.BICUBIC,		__A							:					str = True,		__A							:					Dict = None,		__A							:					Any = 1 / 2_5_5,		__A							:					Union[str, Any] = True,		__A							:					Optional[Any] = True,		__A							:					Optional[int] = None,		__A							:					Optional[Any] = None,		**__A							:					int,		):
     super().__init__(**lowerCamelCase__						)
     UpperCAmelCase	:							Tuple						=			size if size is not None else {'''height''': 2_5_6, '''width''': 2_5_6}
     UpperCAmelCase	:							Optional[int]						=			get_size_dict(lowerCamelCase__						)
     UpperCAmelCase	:							int						=			crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
     UpperCAmelCase	:							Optional[Any]						=			get_size_dict(lowerCamelCase__,		param_name='''crop_size'''						)

     UpperCAmelCase	:							Optional[Any]						=			do_resize
     UpperCAmelCase	:							List[Any]						=			size
     UpperCAmelCase	:							Dict						=			resample
     UpperCAmelCase	:							Optional[Any]						=			do_center_crop
     UpperCAmelCase	:							Optional[int]						=			crop_size
     UpperCAmelCase	:							List[Any]						=			do_rescale
     UpperCAmelCase	:							List[str]						=			rescale_factor
     UpperCAmelCase	:							Any						=			do_normalize
     UpperCAmelCase	:							Tuple						=			image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     UpperCAmelCase	:							Any						=			image_std if image_std is not None else IMAGENET_STANDARD_STD



   def 	__magic_name__   (							self							:					Dict,		__A							:					Optional[int],		__A							:					Dict,		__A							:					Any = PIL.Image.BICUBIC,		__A							:					str = None,		**__A							:					Dict,		):
     UpperCAmelCase	:							Tuple						=			get_size_dict(lowerCamelCase__						)
     if "height" not in size or "width" not in size:
       raise ValueError(F'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''						)
     return resize(
         lowerCamelCase__,		size=(size['''height'''], size['''width''']),		resample=lowerCamelCase__,		data_format=lowerCamelCase__,		**lowerCamelCase__						)



   def 	__magic_name__   (							self							:					Any,		__A							:					Dict,		__A							:					int,		__A							:					Tuple = None,		**__A							:					int,		):
     UpperCAmelCase	:							List[str]						=			get_size_dict(lowerCamelCase__						)
     if "height" not in size or "width" not in size:
       raise ValueError(F'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'''						)
     return center_crop(lowerCamelCase__,		size=(size['''height'''], size['''width''']),		data_format=lowerCamelCase__,		**lowerCamelCase__						)



   def 	__magic_name__   (							self							:					Optional[Any],		__A							:					int,		__A							:					Tuple,		__A							:					Dict = None,		**__A							:					str,		):
     return rescale(lowerCamelCase__,		scale=lowerCamelCase__,		data_format=lowerCamelCase__,		**lowerCamelCase__						)



   def 	__magic_name__   (							self							:					int,		__A							:					Dict,		__A							:					int,		__A							:					Optional[Any],		__A							:					Dict = None,		**__A							:					int,		):
     return normalize(lowerCamelCase__,		mean=lowerCamelCase__,		std=lowerCamelCase__,		data_format=lowerCamelCase__,		**lowerCamelCase__						)





   def 	__magic_name__   (							self							:					List[str],		__A							:					int,		__A							:					Optional[int] = None,		__A							:					Tuple = None,		__A							:					Any=None,		__A							:					Optional[Any] = None,		__A							:					Dict = None,		__A							:					int = None,		__A							:					Optional[Any] = None,		__A							:					List[Any] = None,		__A							:					Optional[int] = None,		__A							:					Optional[Any] = None,		__A							:					int = None,		__A							:					List[str] = ChannelDimension.FIRST,		**__A							:					Optional[int],		):
     UpperCAmelCase	:							List[Any]						=			do_resize if do_resize is not None else self.do_resize
     UpperCAmelCase	:							str						=			resample if resample is not None else self.resample
     UpperCAmelCase	:							List[Any]						=			do_center_crop if do_center_crop is not None else self.do_center_crop
     UpperCAmelCase	:							Optional[int]						=			do_rescale if do_rescale is not None else self.do_rescale
     UpperCAmelCase	:							int						=			rescale_factor if rescale_factor is not None else self.rescale_factor
     UpperCAmelCase	:							int						=			do_normalize if do_normalize is not None else self.do_normalize
     UpperCAmelCase	:							Optional[int]						=			image_mean if image_mean is not None else self.image_mean
     UpperCAmelCase	:							Tuple						=			image_std if image_std is not None else self.image_std

     UpperCAmelCase	:							Optional[int]						=			size if size is not None else self.size
     UpperCAmelCase	:							Tuple						=			get_size_dict(lowerCamelCase__						)
     UpperCAmelCase	:							Dict						=			crop_size if crop_size is not None else self.crop_size
     UpperCAmelCase	:							List[str]						=			get_size_dict(lowerCamelCase__,		param_name='''crop_size'''						)

     UpperCAmelCase	:							List[str]						=			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_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.'''						)

     # All transformations expect numpy arrays.
     UpperCAmelCase	:							List[Any]						=			[to_numpy_array(lowerCamelCase__						) for image in images]

     if do_resize:
       UpperCAmelCase	:							List[str]						=			[self.resize(image=lowerCamelCase__,		size=lowerCamelCase__,		resample=lowerCamelCase__						) for image in images]

     if do_center_crop:
       UpperCAmelCase	:							Optional[int]						=			[self.center_crop(image=lowerCamelCase__,		size=lowerCamelCase__						) for image in images]

     if do_rescale:
       UpperCAmelCase	:							List[str]						=			[self.rescale(image=lowerCamelCase__,		scale=lowerCamelCase__						) for image in images]

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

     UpperCAmelCase	:							str						=			[to_channel_dimension_format(lowerCamelCase__,		lowerCamelCase__						) for image in images]

     UpperCAmelCase	:							Any						=			{'''pixel_values''': images}
     return BatchFeature(data=lowerCamelCase__,		tensor_type=lowerCamelCase__						)








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



   def __init__(							self							:					List[Any],		__A							:					str,		__A							:					List[str]=7,		__A							:					List[str]=3,		__A							:					Optional[int]=1_8,		__A							:					List[Any]=3_0,		__A							:					Tuple=4_0_0,		__A							:					Tuple=True,		__A							:					List[Any]=None,		__A							:					str=True,		__A							:					int=None,		__A							:					Optional[Any]=True,		__A							:					List[Any]=[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],		__A							:					List[str]=[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],		__A							:					Tuple=True,		):
     UpperCAmelCase	:							int						=			size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
     UpperCAmelCase	:							Optional[Any]						=			crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8}
     UpperCAmelCase	:							int						=			parent
     UpperCAmelCase	:							Union[str, Any]						=			batch_size
     UpperCAmelCase	:							List[Any]						=			num_channels
     UpperCAmelCase	:							Dict						=			image_size
     UpperCAmelCase	:							List[str]						=			min_resolution
     UpperCAmelCase	:							Optional[Any]						=			max_resolution
     UpperCAmelCase	:							Union[str, Any]						=			do_resize
     UpperCAmelCase	:							Dict						=			size
     UpperCAmelCase	:							Any						=			do_center_crop
     UpperCAmelCase	:							Union[str, Any]						=			crop_size
     UpperCAmelCase	:							List[str]						=			do_normalize
     UpperCAmelCase	:							Optional[Any]						=			image_mean
     UpperCAmelCase	:							Optional[Any]						=			image_std
     UpperCAmelCase	:							List[Any]						=			do_convert_rgb



   def 	__magic_name__   (							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 	__magic_name__   (							self							:					Optional[Any],		__A							:					Any=False,		__A							:					str=False,		__A							:					List[Any]=False						):
     assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

     if equal_resolution:
       UpperCAmelCase	:							Dict						=			[]
       for i in range(self.batch_size						):
         image_inputs.append(
             np.random.randint(
                 2_5_5,		size=(self.num_channels, self.max_resolution, self.max_resolution),		dtype=np.uinta						)						)
     else:
       UpperCAmelCase	:							Tuple						=			[]
       for i in range(self.batch_size						):
         UpperCAmelCase			,						UpperCAmelCase	:							Tuple						=			np.random.choice(np.arange(self.min_resolution,		self.max_resolution						),		2						)
         image_inputs.append(np.random.randint(2_5_5,		size=(self.num_channels, width, height),		dtype=np.uinta						)						)

     if not numpify and not torchify:
       # PIL expects the channel dimension as last dimension
       UpperCAmelCase	:							Optional[int]						=			[Image.fromarray(np.moveaxis(__A,		0,		-1						)						) for x in image_inputs]

     if torchify:
       UpperCAmelCase	:							str						=			[torch.from_numpy(__A						) for x in image_inputs]

     return image_inputs






@require_torch
@require_vision
class  __UpperCAmelCase					(	lowerCamelCase__      ,  unittest.TestCase						):
   UpperCamelCase       					=					ChineseCLIPImageProcessor if is_vision_available() else None



   def 	__magic_name__   (							self							:					Dict						):
     UpperCAmelCase	:							Optional[Any]						=			ChineseCLIPImageProcessingTester(self,		do_center_crop=__A						)



   @property
   def 	__magic_name__   (							self							:					Tuple						):
     return self.image_processor_tester.prepare_image_processor_dict()



   def 	__magic_name__   (							self							:					Any						):
     UpperCAmelCase	:							List[Any]						=			self.image_processing_class(**self.image_processor_dict						)
     self.assertTrue(hasattr(__A,		'''do_resize'''						)						)
     self.assertTrue(hasattr(__A,		'''size'''						)						)
     self.assertTrue(hasattr(__A,		'''do_center_crop'''						)						)
     self.assertTrue(hasattr(__A,		'''center_crop'''						)						)
     self.assertTrue(hasattr(__A,		'''do_normalize'''						)						)
     self.assertTrue(hasattr(__A,		'''image_mean'''						)						)
     self.assertTrue(hasattr(__A,		'''image_std'''						)						)
     self.assertTrue(hasattr(__A,		'''do_convert_rgb'''						)						)



   def 	__magic_name__   (							self							:					Optional[Any]						):
     UpperCAmelCase	:							Union[str, Any]						=			self.image_processing_class.from_dict(self.image_processor_dict						)
     self.assertEqual(image_processor.size,		{'''height''': 2_2_4, '''width''': 2_2_4}						)
     self.assertEqual(image_processor.crop_size,		{'''height''': 1_8, '''width''': 1_8}						)

     UpperCAmelCase	:							int						=			self.image_processing_class.from_dict(self.image_processor_dict,		size=4_2,		crop_size=8_4						)
     self.assertEqual(image_processor.size,		{'''shortest_edge''': 4_2}						)
     self.assertEqual(image_processor.crop_size,		{'''height''': 8_4, '''width''': 8_4}						)



   def 	__magic_name__   (							self							:					Union[str, Any]						):
     pass



   def 	__magic_name__   (							self							:					Tuple						):
     # Initialize image_processing
     UpperCAmelCase	:							Dict						=			self.image_processing_class(**self.image_processor_dict						)
     # create random PIL images
     UpperCAmelCase	:							Optional[int]						=			self.image_processor_tester.prepare_inputs(equal_resolution=__A						)
     for image in image_inputs:
       self.assertIsInstance(__A,		Image.Image						)

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

     # Test not batched input
     UpperCAmelCase	:							List[str]						=			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
     UpperCAmelCase	:							Dict						=			image_processing(__A,		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 	__magic_name__   (							self							:					Any						):
     # Initialize image_processing
     UpperCAmelCase	:							str						=			self.image_processing_class(**self.image_processor_dict						)
     # create random PyTorch tensors
     UpperCAmelCase	:							Optional[Any]						=			self.image_processor_tester.prepare_inputs(equal_resolution=__A,		torchify=__A						)
     for image in image_inputs:
       self.assertIsInstance(__A,		torch.Tensor						)

     # Test not batched input
     UpperCAmelCase	:							str						=			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
     UpperCAmelCase	:							List[str]						=			image_processing(__A,		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						):
   UpperCamelCase       					=					ChineseCLIPImageProcessor if is_vision_available() else None



   def 	__magic_name__   (							self							:					Optional[Any]						):
     UpperCAmelCase	:							str						=			ChineseCLIPImageProcessingTester(self,		num_channels=4,		do_center_crop=__A						)
     UpperCAmelCase	:							Dict						=			3



   @property
   def 	__magic_name__   (							self							:					List[Any]						):
     return self.image_processor_tester.prepare_image_processor_dict()



   def 	__magic_name__   (							self							:					Dict						):
     UpperCAmelCase	:							List[Any]						=			self.image_processing_class(**self.image_processor_dict						)
     self.assertTrue(hasattr(__A,		'''do_resize'''						)						)
     self.assertTrue(hasattr(__A,		'''size'''						)						)
     self.assertTrue(hasattr(__A,		'''do_center_crop'''						)						)
     self.assertTrue(hasattr(__A,		'''center_crop'''						)						)
     self.assertTrue(hasattr(__A,		'''do_normalize'''						)						)
     self.assertTrue(hasattr(__A,		'''image_mean'''						)						)
     self.assertTrue(hasattr(__A,		'''image_std'''						)						)
     self.assertTrue(hasattr(__A,		'''do_convert_rgb'''						)						)



   def 	__magic_name__   (							self							:					List[Any]						):
     pass





   def 	__magic_name__   (							self							:					Tuple						):
     # Initialize image_processing
     UpperCAmelCase	:							Optional[Any]						=			self.image_processing_class(**self.image_processor_dict						)
     # create random PIL images
     UpperCAmelCase	:							Dict						=			self.image_processor_tester.prepare_inputs(equal_resolution=__A						)
     for image in image_inputs:
       self.assertIsInstance(__A,		Image.Image						)

     # Test not batched input
     UpperCAmelCase	:							Tuple						=			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
     UpperCAmelCase	:							Tuple						=			image_processing(__A,		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'''],
         ),		)





