
from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import TFCvtForImageClassification, TFCvtModel
		from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class  lowerCamelCase__							(				__lowercase):




	'''simple docstring'''




	def    _lowerCamelCase				(					self		:str						)		-> str:
								__UpperCamelCase	:   Any			   =					self.config_class(**self.inputs_dict						)
								self.parent.assertTrue(hasattr(a     ,   "embed_dim"						)						)
								self.parent.assertTrue(hasattr(a     ,   "num_heads"						)						)




class  lowerCamelCase__							:




	'''simple docstring'''




	def __init__(					self		:str     ,   a		:Optional[Any]     ,   a		:List[Any]=1_3     ,   a		:List[Any]=6_4     ,   a		:List[Any]=3     ,   a		:List[Any]=[1_6, 4_8, 9_6]     ,   a		:Union[str, Any]=[1, 3, 6]     ,   a		:str=[1, 2, 1_0]     ,   a		:List[str]=[7, 3, 3]     ,   a		:Optional[Any]=[4, 2, 2]     ,   a		:List[Any]=[2, 1, 1]     ,   a		:Tuple=[2, 2, 2]     ,   a		:List[str]=[False, False, True]     ,   a		:int=[0.0, 0.0, 0.0]     ,   a		:Union[str, Any]=0.02     ,   a		:Any=1E-1_2     ,   a		:List[str]=True     ,   a		:Union[str, Any]=True     ,   a		:Dict=2     ,   )		-> Any:
								__UpperCamelCase	:   Optional[int]			   =					parent
								__UpperCamelCase	:   List[Any]			   =					batch_size
								__UpperCamelCase	:   List[str]			   =					image_size
								__UpperCamelCase	:   str			   =					patch_sizes
								__UpperCamelCase	:   List[str]			   =					patch_stride
								__UpperCamelCase	:   Dict			   =					patch_padding
								__UpperCamelCase	:   int			   =					is_training
								__UpperCamelCase	:   Union[str, Any]			   =					use_labels
								__UpperCamelCase	:   str			   =					num_labels
								__UpperCamelCase	:   Optional[int]			   =					num_channels
								__UpperCamelCase	:   List[Any]			   =					embed_dim
								__UpperCamelCase	:   int			   =					num_heads
								__UpperCamelCase	:   Union[str, Any]			   =					stride_kv
								__UpperCamelCase	:   str			   =					depth
								__UpperCamelCase	:   Optional[Any]			   =					cls_token
								__UpperCamelCase	:   Optional[int]			   =					attention_drop_rate
								__UpperCamelCase	:   int			   =					initializer_range
								__UpperCamelCase	:   str			   =					layer_norm_eps







	def    _lowerCamelCase				(					self		:str						)		-> Union[str, Any]:
								__UpperCamelCase	:   Dict			   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

								__UpperCamelCase	:   Any			   =					None
								if self.use_labels:
															# create a random int32 tensor of given shape
															__UpperCamelCase	:   int			   =					ids_tensor([self.batch_size]     ,   self.num_labels						)

								__UpperCamelCase	:   Dict			   =					self.get_config()
								return config, pixel_values, labels







	def    _lowerCamelCase				(					self		:List[Any]						)		-> Dict:
								return CvtConfig(
								    image_size=self.image_size     ,   num_labels=self.num_labels     ,   num_channels=self.num_channels     ,   embed_dim=self.embed_dim     ,   num_heads=self.num_heads     ,   patch_sizes=self.patch_sizes     ,   patch_padding=self.patch_padding     ,   patch_stride=self.patch_stride     ,   stride_kv=self.stride_kv     ,   depth=self.depth     ,   cls_token=self.cls_token     ,   attention_drop_rate=self.attention_drop_rate     ,   initializer_range=self.initializer_range     ,   )







	def    _lowerCamelCase				(					self		:Tuple     ,   a		:str     ,   a		:Optional[int]     ,   a		:int						)		-> List[Any]:
								__UpperCamelCase	:   List[Any]			   =					TFCvtModel(config=a						)
								__UpperCamelCase	:   Optional[Any]			   =					model(a     ,   training=a						)
								__UpperCamelCase	:   Any			   =					(self.image_size, self.image_size)
								__UpperCamelCase   ,						__UpperCamelCase	:   str			   =					image_size[0], image_size[1]
								for i in range(len(self.depth						)						):
															__UpperCamelCase	:   Union[str, Any]			   =					floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1						)
															__UpperCamelCase	:   int			   =					floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1						)
								self.parent.assertEqual(result.last_hidden_state.shape     ,   (self.batch_size, self.embed_dim[-1], height, width)						)







	def    _lowerCamelCase				(					self		:List[Any]     ,   a		:List[str]     ,   a		:Dict     ,   a		:Optional[Any]						)		-> int:
								__UpperCamelCase	:   Union[str, Any]			   =					self.num_labels
								__UpperCamelCase	:   Dict			   =					TFCvtForImageClassification(a						)
								__UpperCamelCase	:   Union[str, Any]			   =					model(a     ,   labels=a     ,   training=a						)
								self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.num_labels)						)







	def    _lowerCamelCase				(					self		:str						)		-> Tuple:
								__UpperCamelCase	:   int			   =					self.prepare_config_and_inputs()
								__UpperCamelCase   ,						__UpperCamelCase   ,						__UpperCamelCase	:   Union[str, Any]			   =					config_and_inputs
								__UpperCamelCase	:   Union[str, Any]			   =					{"pixel_values": pixel_values}
								return config, inputs_dict




@require_tf
class  lowerCamelCase__							(				__lowercase     ,						__lowercase     ,						unittest.TestCase):




	'''simple docstring'''




	_A								=     (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
	_A								=     (
	    {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification}
	    if is_tf_available()
	    else {}
	)
	_A								=     False
	_A								=     False
	_A								=     False
	_A								=     False
	_A								=     False







	def    _lowerCamelCase				(					self		:Union[str, Any]						)		-> Any:
								__UpperCamelCase	:   Union[str, Any]			   =					TFCvtModelTester(self						)
								__UpperCamelCase	:   int			   =					TFCvtConfigTester(self     ,   config_class=a     ,   has_text_modality=a     ,   hidden_size=3_7						)







	def    _lowerCamelCase				(					self		:Optional[int]						)		-> Tuple:
								self.config_tester.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()







	@unittest.skip(reason="Cvt does not output attentions"						)
	def    _lowerCamelCase				(					self		:List[str]						)		-> int:
								pass







	@unittest.skip(reason="Cvt does not use inputs_embeds"						)
	def    _lowerCamelCase				(					self		:int						)		-> Optional[int]:
								pass







	@unittest.skip(reason="Cvt does not support input and output embeddings"						)
	def    _lowerCamelCase				(					self		:List[Any]						)		-> str:
								pass







	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices("GPU"						)						) == 0     ,   reason="TF does not support backprop for grouped convolutions on CPU."     ,   )
	def    _lowerCamelCase				(					self		:List[Any]						)		-> Optional[Any]:
								super().test_dataset_conversion()







	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices("GPU"						)						) == 0     ,   reason="TF does not support backprop for grouped convolutions on CPU."     ,   )
	@slow
	def    _lowerCamelCase				(					self		:Dict						)		-> Optional[int]:
								super().test_keras_fit()







	@unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"						)
	def    _lowerCamelCase				(					self		:Optional[Any]						)		-> List[str]:
								__UpperCamelCase	:   Optional[int]			   =					tf.keras.mixed_precision.Policy("mixed_float16"						)
								tf.keras.mixed_precision.set_global_policy(a						)
								super().test_keras_fit()
								tf.keras.mixed_precision.set_global_policy("float32"						)







	def    _lowerCamelCase				(					self		:List[Any]						)		-> Dict:
								__UpperCamelCase   ,						__UpperCamelCase	:   Optional[int]			   =					self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															__UpperCamelCase	:   List[str]			   =					model_class(a						)
															__UpperCamelCase	:   Tuple			   =					inspect.signature(model.call						)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															__UpperCamelCase	:   int			   =					[*signature.parameters.keys()]

															__UpperCamelCase	:   str			   =					["pixel_values"]
															self.assertListEqual(arg_names[:1]     ,   a						)







	def    _lowerCamelCase				(					self		:Tuple						)		-> Union[str, Any]:
								def check_hidden_states_output(a		:Optional[int]     ,   a		:Union[str, Any]     ,   a		:Any						):
															__UpperCamelCase	:   List[Any]			   =					model_class(a						)

															__UpperCamelCase	:   Dict			   =					model(**self._prepare_for_class(a     ,   a						)						)
															__UpperCamelCase	:   Optional[Any]			   =					outputs.hidden_states

															__UpperCamelCase	:   str			   =					len(self.model_tester.depth						)
															self.assertEqual(len(a						)     ,   a						)

															# verify the first hidden states (first block)
															self.assertListEqual(
															    list(hidden_states[0].shape[-3:]						)     ,   [
															        self.model_tester.embed_dim[0],
															        self.model_tester.image_size // 4,
															        self.model_tester.image_size // 4,
															    ]     ,   )

								__UpperCamelCase   ,						__UpperCamelCase	:   Optional[Any]			   =					self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															__UpperCamelCase	:   Union[str, Any]			   =					True
															check_hidden_states_output(a     ,   a     ,   a						)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															__UpperCamelCase	:   Tuple			   =					True

															check_hidden_states_output(a     ,   a     ,   a						)







	def    _lowerCamelCase				(					self		:List[str]						)		-> Optional[Any]:
								__UpperCamelCase	:   Optional[Any]			   =					self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a						)







	def    _lowerCamelCase				(					self		:Tuple						)		-> Any:
								__UpperCamelCase	:   int			   =					self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*a						)







	@slow
	def    _lowerCamelCase				(					self		:Dict						)		-> Optional[Any]:
								for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															__UpperCamelCase	:   Union[str, Any]			   =					TFCvtModel.from_pretrained(a						)
															self.assertIsNotNone(a						)




def 	_SCREAMING_SNAKE_CASE					(		)					->    Optional[int]:






							'''simple docstring'''





							__UpperCamelCase	:   Any			   =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
							return image




@require_tf
@require_vision
class  lowerCamelCase__							(				unittest.TestCase):




	'''simple docstring'''




	@cached_property
	def    _lowerCamelCase				(					self		:int						)		-> str:
								return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)







	@slow
	def    _lowerCamelCase				(					self		:List[Any]						)		-> int:
								__UpperCamelCase	:   Any			   =					TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

								__UpperCamelCase	:   List[str]			   =					self.default_image_processor
								__UpperCamelCase	:   Tuple			   =					prepare_img()
								__UpperCamelCase	:   Union[str, Any]			   =					image_processor(images=a     ,   return_tensors="tf"						)

								# forward pass
								__UpperCamelCase	:   Tuple			   =					model(**a						)

								# verify the logits
								__UpperCamelCase	:   Union[str, Any]			   =					tf.TensorShape((1, 1_0_0_0)						)
								self.assertEqual(outputs.logits.shape     ,   a						)

								__UpperCamelCase	:   Any			   =					tf.constant([0.9285, 0.9015, -0.3150]						)
								self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,   a     ,   atol=1E-4						)						)

import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image


if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'):
		lowercase  :					int													=       {
		    'linear': PIL.Image.Resampling.BILINEAR,
		    'bilinear': PIL.Image.Resampling.BILINEAR,
		    'bicubic': PIL.Image.Resampling.BICUBIC,
		    'lanczos': PIL.Image.Resampling.LANCZOS,
		    'nearest': PIL.Image.Resampling.NEAREST,
		}
else:
		lowercase  :					Any													=       {
		    'linear': PIL.Image.LINEAR,
		    'bilinear': PIL.Image.BILINEAR,
		    'bicubic': PIL.Image.BICUBIC,
		    'lanczos': PIL.Image.LANCZOS,
		    'nearest': PIL.Image.NEAREST,
		}




def 	_SCREAMING_SNAKE_CASE					(		_lowerCamelCase :			int)					->    Any:






							'''simple docstring'''





							__UpperCamelCase	:   Union[str, Any]			   =					(images / 2 + 0.5).clamp(0						,  1)
							__UpperCamelCase	:   int			   =					images.cpu().permute(0						,  2						,  3						,  1).float().numpy()
							__UpperCamelCase	:   Dict			   =					numpy_to_pil(_lowerCamelCase)
							return images




def 	_SCREAMING_SNAKE_CASE					(		_lowerCamelCase :			Optional[Any])					->    Optional[Any]:






							'''simple docstring'''





							if images.ndim == 3:
														__UpperCamelCase	:   Optional[int]			   =					images[None, ...]
							__UpperCamelCase	:   Dict			   =					(images * 255).round().astype("uint8")
							if images.shape[-1] == 1:
														# special case for grayscale (single channel) images
														__UpperCamelCase	:   int			   =					[Image.fromarray(image.squeeze()						,  mode="L") for image in images]
							else:
														__UpperCamelCase	:   Union[str, Any]			   =					[Image.fromarray(_lowerCamelCase) for image in images]

							return pil_images