





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     UpperCamelCase__					(     lowerCamelCase__				):






		'''simple docstring'''






		def 						snake_case__				(							self  )       -> Dict:






									"""simple docstring"""
									lowercase_	:   Tuple  				=     self.config_class(**self.inputs_dict  )
									self.parent.assertTrue(hasattr(snake_case__,   """embed_dim"""  )  )
									self.parent.assertTrue(hasattr(snake_case__,   """num_heads"""  )  )




class     UpperCamelCase__					:






		'''simple docstring'''






		def __init__(							self,   snake_case__,   snake_case__=13,   snake_case__=64,   snake_case__=3,   snake_case__=[16, 48, 96],   snake_case__=[1, 3, 6],   snake_case__=[1, 2, 10],   snake_case__=[7, 3, 3],   snake_case__=[4, 2, 2],   snake_case__=[2, 1, 1],   snake_case__=[2, 2, 2],   snake_case__=[False, False, True],   snake_case__=[0.0, 0.0, 0.0],   snake_case__=0.02,   snake_case__=1E-12,   snake_case__=True,   snake_case__=True,   snake_case__=2,   )       -> Dict:






									"""simple docstring"""
									lowercase_	:   Tuple  				=     parent
									lowercase_	:   Union[str, Any]  				=     batch_size
									lowercase_	:   Union[str, Any]  				=     image_size
									lowercase_	:   Union[str, Any]  				=     patch_sizes
									lowercase_	:   Optional[int]  				=     patch_stride
									lowercase_	:   Optional[int]  				=     patch_padding
									lowercase_	:   Optional[Any]  				=     is_training
									lowercase_	:   Optional[Any]  				=     use_labels
									lowercase_	:   Dict  				=     num_labels
									lowercase_	:   Tuple  				=     num_channels
									lowercase_	:   Union[str, Any]  				=     embed_dim
									lowercase_	:   int  				=     num_heads
									lowercase_	:   Optional[Any]  				=     stride_kv
									lowercase_	:   str  				=     depth
									lowercase_	:   Tuple  				=     cls_token
									lowercase_	:   Dict  				=     attention_drop_rate
									lowercase_	:   Tuple  				=     initializer_range
									lowercase_	:   Any  				=     layer_norm_eps






		def 						snake_case__				(							self  )       -> Any:






									"""simple docstring"""
									lowercase_	:   List[Any]  				=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

									lowercase_	:   List[str]  				=     self.get_config()
									return config, pixel_values, labels






		def 						snake_case__				(							self  )       -> Any:






									"""simple docstring"""
									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 						snake_case__				(							self,   snake_case__,   snake_case__,   snake_case__  )       -> str:






									"""simple docstring"""
									lowercase_	:   Tuple  				=     TFCvtModel(config=snake_case__  )
									lowercase_	:   List[Any]  				=     model(snake_case__,   training=snake_case__  )
									lowercase_	:   str  				=     (self.image_size, self.image_size)
									lowercase_				,		lowercase_	:   Any  				=     image_size[0], image_size[1]
									for i in range(len(self.depth  )  ):
																lowercase_	:   List[Any]  				=     floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1  )
																lowercase_	:   List[str]  				=     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 						snake_case__				(							self,   snake_case__,   snake_case__,   snake_case__  )       -> int:






									"""simple docstring"""
									lowercase_	:   Tuple  				=     self.num_labels
									lowercase_	:   str  				=     TFCvtForImageClassification(snake_case__  )
									lowercase_	:   Optional[Any]  				=     model(snake_case__,   labels=snake_case__,   training=snake_case__  )
									self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels)  )






		def 						snake_case__				(							self  )       -> Any:






									"""simple docstring"""
									lowercase_	:   List[Any]  				=     self.prepare_config_and_inputs()
									lowercase_				,		lowercase_				,		lowercase_	:   int  				=     config_and_inputs
									lowercase_	:   Any  				=     {"""pixel_values""": pixel_values}
									return config, inputs_dict




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






		'''simple docstring'''






		__a       :       List[str]       =	(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
		__a       :       Union[str, Any]       =	(
		    {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
		    if is_tf_available()
		    else {}
		)
		__a       :       str       =	False
		__a       :       Dict       =	False
		__a       :       List[Any]       =	False
		__a       :       Union[str, Any]       =	False
		__a       :       Dict       =	False






		def 						snake_case__				(							self  )       -> int:






									"""simple docstring"""
									lowercase_	:   int  				=     TFCvtModelTester(self  )
									lowercase_	:   Union[str, Any]  				=     TFCvtConfigTester(self,   config_class=snake_case__,   has_text_modality=snake_case__,   hidden_size=37  )






		def 						snake_case__				(							self  )       -> Optional[int]:






									"""simple docstring"""
									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 						snake_case__				(							self  )       -> Optional[Any]:






									"""simple docstring"""
									pass






		@unittest.skip(reason="""Cvt does not use inputs_embeds"""  )
		def 						snake_case__				(							self  )       -> Tuple:






									"""simple docstring"""
									pass






		@unittest.skip(reason="""Cvt does not support input and output embeddings"""  )
		def 						snake_case__				(							self  )       -> Dict:






									"""simple docstring"""
									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 						snake_case__				(							self  )       -> List[str]:






									"""simple docstring"""
									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 						snake_case__				(							self  )       -> List[Any]:






									"""simple docstring"""
									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 						snake_case__				(							self  )       -> List[str]:






									"""simple docstring"""
									lowercase_	:   List[str]  				=     tf.keras.mixed_precision.Policy("""mixed_float16"""  )
									tf.keras.mixed_precision.set_global_policy(snake_case__  )
									super().test_keras_fit()
									tf.keras.mixed_precision.set_global_policy("""float32"""  )






		def 						snake_case__				(							self  )       -> List[Any]:






									"""simple docstring"""
									lowercase_				,		lowercase_	:   Tuple  				=     self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
																lowercase_	:   Dict  				=     model_class(snake_case__  )
																lowercase_	:   List[Any]  				=     inspect.signature(model.call  )
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																lowercase_	:   Dict  				=     [*signature.parameters.keys()]

																lowercase_	:   Union[str, Any]  				=     ["""pixel_values"""]
																self.assertListEqual(arg_names[:1],   snake_case__  )






		def 						snake_case__				(							self  )       -> Union[str, Any]:






									"""simple docstring"""
									def check_hidden_states_output(snake_case__,   snake_case__,   snake_case__  ):
																lowercase_	:   List[str]  				=     model_class(snake_case__  )

																lowercase_	:   List[str]  				=     model(**self._prepare_for_class(snake_case__,   snake_case__  )  )
																lowercase_	:   Dict  				=     outputs.hidden_states

																lowercase_	:   int  				=     len(self.model_tester.depth  )
																self.assertEqual(len(snake_case__  ),   snake_case__  )

																# 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,
																    ],   )

									lowercase_				,		lowercase_	:   Optional[int]  				=     self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
																lowercase_	:   Optional[int]  				=     True
																check_hidden_states_output(snake_case__,   snake_case__,   snake_case__  )

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																lowercase_	:   Optional[int]  				=     True

																check_hidden_states_output(snake_case__,   snake_case__,   snake_case__  )






		def 						snake_case__				(							self  )       -> List[str]:






									"""simple docstring"""
									lowercase_	:   Optional[Any]  				=     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*snake_case__  )






		def 						snake_case__				(							self  )       -> Union[str, Any]:






									"""simple docstring"""
									lowercase_	:   Dict  				=     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*snake_case__  )






		@slow
		def 						snake_case__				(							self  )       -> List[Any]:






									"""simple docstring"""
									for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																lowercase_	:   Dict  				=     TFCvtModel.from_pretrained(snake_case__  )
																self.assertIsNotNone(snake_case__  )





def  __magic_name__  (				)				-> Optional[Any]:

							"""simple docstring"""



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




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






		'''simple docstring'''






		@cached_property
		def 						snake_case__				(							self  )       -> Optional[Any]:






									"""simple docstring"""
									return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )






		@slow
		def 						snake_case__				(							self  )       -> int:






									"""simple docstring"""
									lowercase_	:   Optional[int]  				=     TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

									lowercase_	:   Union[str, Any]  				=     self.default_image_processor
									lowercase_	:   Any  				=     prepare_img()
									lowercase_	:   Any  				=     image_processor(images=snake_case__,   return_tensors="""tf"""  )

									# forward pass
									lowercase_	:   List[Any]  				=     model(**snake_case__  )

									# verify the logits
									lowercase_	:   Optional[Any]  				=     tf.TensorShape((1, 10_00)  )
									self.assertEqual(outputs.logits.shape,   snake_case__  )

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






UpperCAmelCase_							=				8.31_44_62  # Unit - J mol-1 K-1





def  __magic_name__  (				lowercase				,       lowercase				,       lowercase				)				-> float:

							"""simple docstring"""



							if moles < 0 or kelvin < 0 or volume < 0:
														raise ValueError("""Invalid inputs. Enter positive value."""				)
							return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume





def  __magic_name__  (				lowercase				,       lowercase				,       lowercase				)				-> float:

							"""simple docstring"""



							if moles < 0 or kelvin < 0 or pressure < 0:
														raise ValueError("""Invalid inputs. Enter positive value."""				)
							return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure


if __name__ == "__main__":
							from doctest import testmod

							testmod()