





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 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.config_class(**self.inputs_dict       )
           self.parent.assertTrue(hasattr(lowerCamelCase__						,"""embed_dim"""       )       )
           self.parent.assertTrue(hasattr(lowerCamelCase__						,"""num_heads"""       )       )

class 		UpperCamelCase__ :



     '''simple docstring'''

     def __init__(							self						:    Any						,lowerCamelCase__						:    Dict						,lowerCamelCase__						:    Tuple=13						,lowerCamelCase__						:    Dict=64						,lowerCamelCase__						:    Union[str, Any]=3						,lowerCamelCase__						:    str=[16, 48, 96]						,lowerCamelCase__						:    int=[1, 3, 6]						,lowerCamelCase__						:    int=[1, 2, 10]						,lowerCamelCase__						:    Tuple=[7, 3, 3]						,lowerCamelCase__						:    Dict=[4, 2, 2]						,lowerCamelCase__						:    str=[2, 1, 1]						,lowerCamelCase__						:    Any=[2, 2, 2]						,lowerCamelCase__						:    Optional[Any]=[False, False, True]						,lowerCamelCase__						:    int=[0.0, 0.0, 0.0]						,lowerCamelCase__						:    int=0.02						,lowerCamelCase__						:    Union[str, Any]=1e-1_2						,lowerCamelCase__						:    int=True						,lowerCamelCase__						:    Union[str, Any]=True						,lowerCamelCase__						:    Any=2						,)     ->		str:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						parent
           SCREAMING_SNAKE_CASE		=						batch_size
           SCREAMING_SNAKE_CASE		=						image_size
           SCREAMING_SNAKE_CASE		=						patch_sizes
           SCREAMING_SNAKE_CASE		=						patch_stride
           SCREAMING_SNAKE_CASE		=						patch_padding
           SCREAMING_SNAKE_CASE		=						is_training
           SCREAMING_SNAKE_CASE		=						use_labels
           SCREAMING_SNAKE_CASE		=						num_labels
           SCREAMING_SNAKE_CASE		=						num_channels
           SCREAMING_SNAKE_CASE		=						embed_dim
           SCREAMING_SNAKE_CASE		=						num_heads
           SCREAMING_SNAKE_CASE		=						stride_kv
           SCREAMING_SNAKE_CASE		=						depth
           SCREAMING_SNAKE_CASE		=						cls_token
           SCREAMING_SNAKE_CASE		=						attention_drop_rate
           SCREAMING_SNAKE_CASE		=						initializer_range
           SCREAMING_SNAKE_CASE		=						layer_norm_eps






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

           SCREAMING_SNAKE_CASE		=						self.get_config()
           return config, pixel_values, labels






     def 				SCREAMING_SNAKE_CASE__  (							self						:    int       )     ->		Union[str, 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 				SCREAMING_SNAKE_CASE__  (							self						:    int						,lowerCamelCase__						:    Dict						,lowerCamelCase__						:    int						,lowerCamelCase__						:    List[str]       )     ->		str:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						TFCvtModel(config=lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,training=lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						(self.image_size, self.image_size)
           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						image_size[0], image_size[1]
           for i in range(len(self.depth       )       ):
                 SCREAMING_SNAKE_CASE		=						floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
                 SCREAMING_SNAKE_CASE		=						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 				SCREAMING_SNAKE_CASE__  (							self						:    Union[str, Any]						,lowerCamelCase__						:    Dict						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    List[str]       )     ->		List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.num_labels
           SCREAMING_SNAKE_CASE		=						TFCvtForImageClassification(lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						model(lowerCamelCase__						,labels=lowerCamelCase__						,training=lowerCamelCase__       )
           self.parent.assertEqual(result.logits.shape						,(self.batch_size, self.num_labels)       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.prepare_config_and_inputs()
           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						config_and_inputs
           SCREAMING_SNAKE_CASE		=						{"""pixel_values""": pixel_values}
           return config, inputs_dict

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



     '''simple docstring'''

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






     def 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						TFCvtModelTester(self       )
           SCREAMING_SNAKE_CASE		=						TFCvtConfigTester(self						,config_class=lowerCamelCase__						,has_text_modality=lowerCamelCase__						,hidden_size=37       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict       )     ->		Optional[Any]:




           '''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 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		Optional[Any]:




           '''simple docstring'''


           pass






     @unittest.skip(reason="""Cvt does not use inputs_embeds"""       )
     def 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		List[str]:




           '''simple docstring'''


           pass






     @unittest.skip(reason="""Cvt does not support input and output embeddings"""       )
     def 				SCREAMING_SNAKE_CASE__  (							self						:    int       )     ->		Optional[int]:




           '''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 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[int]       )     ->		Optional[Any]:




           '''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 				SCREAMING_SNAKE_CASE__  (							self						:    List[str]       )     ->		List[str]:




           '''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 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						tf.keras.mixed_precision.Policy("""mixed_float16"""       )
           tf.keras.mixed_precision.set_global_policy(lowerCamelCase__       )
           super().test_keras_fit()
           tf.keras.mixed_precision.set_global_policy("""float32"""       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[int]       )     ->		str:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()

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

                 SCREAMING_SNAKE_CASE		=						["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]						,lowerCamelCase__       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		int:




           '''simple docstring'''


           def check_hidden_states_output(lowerCamelCase__						:    str						,lowerCamelCase__						:    str						,lowerCamelCase__						:    List[str]       ):
                 SCREAMING_SNAKE_CASE		=						model_class(lowerCamelCase__       )

                 SCREAMING_SNAKE_CASE		=						model(**self._prepare_for_class(lowerCamelCase__						,lowerCamelCase__       )       )
                 SCREAMING_SNAKE_CASE		=						outputs.hidden_states

                 SCREAMING_SNAKE_CASE		=						len(self.model_tester.depth       )
                 self.assertEqual(len(lowerCamelCase__       )						,lowerCamelCase__       )

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

           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 SCREAMING_SNAKE_CASE		=						True
                 check_hidden_states_output(lowerCamelCase__						,lowerCamelCase__						,lowerCamelCase__       )

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 SCREAMING_SNAKE_CASE		=						True

                 check_hidden_states_output(lowerCamelCase__						,lowerCamelCase__						,lowerCamelCase__       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[int]       )     ->		Dict:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase__       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Any       )     ->		Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__       )






     @slow
     def 				SCREAMING_SNAKE_CASE__  (							self						:    int       )     ->		Optional[int]:




           '''simple docstring'''


           for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 SCREAMING_SNAKE_CASE		=						TFCvtModel.from_pretrained(lowerCamelCase__       )
                 self.assertIsNotNone(lowerCamelCase__       )



def    __lowercase   (      ) ->   Any:


      '''simple docstring'''


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



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



     '''simple docstring'''

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




           '''simple docstring'''


           return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )






     @slow
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		Optional[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

           SCREAMING_SNAKE_CASE		=						self.default_image_processor
           SCREAMING_SNAKE_CASE		=						prepare_img()
           SCREAMING_SNAKE_CASE		=						image_processor(images=lowerCamelCase__						,return_tensors="""tf"""       )

           # forward pass
           SCREAMING_SNAKE_CASE		=						model(**lowerCamelCase__       )

           # verify the logits
           SCREAMING_SNAKE_CASE		=						tf.TensorShape((1, 1000)       )
           self.assertEqual(outputs.logits.shape						,lowerCamelCase__       )

           SCREAMING_SNAKE_CASE		=						tf.constant([0.9285, 0.9015, -0.3150]       )
           self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()						,lowerCamelCase__						,atol=1e-4       )       )









import os
from distutils.util import strtobool



def    __lowercase   (      _SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE	) ->   Tuple:


      '''simple docstring'''


      for e in env_keys:
            SCREAMING_SNAKE_CASE		=						int(os.environ.get(_SCREAMING_SNAKE_CASE ,						-1	)	)
            if val >= 0:
                  return val
      return default



def    __lowercase   (      _SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE=False	) ->   Optional[int]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE		=						os.environ.get(_SCREAMING_SNAKE_CASE ,						str(_SCREAMING_SNAKE_CASE	)	)
      return strtobool(_SCREAMING_SNAKE_CASE	) == 1  # As its name indicates `strtobool` actually returns an int...



def    __lowercase   (      _SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE="no"	) ->   Any:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE		=						os.environ.get(_SCREAMING_SNAKE_CASE ,						str(_SCREAMING_SNAKE_CASE	)	)
      return value


