




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__(					__lowerCamelCase):
      def 			lowerCAmelCase__						(				self: int   ):
             __lowerCamelCase   =						self.config_class(**self.inputs_dict   )
             self.parent.assertTrue(hasattr(__A    ,       """embed_dim"""   )   )
             self.parent.assertTrue(hasattr(__A    ,       """num_heads"""   )   )





class     lowerCamelCase__:
      def __init__(				self: str    ,       UpperCamelCase_: Optional[int]    ,       UpperCamelCase_: Dict=13    ,       UpperCamelCase_: Optional[Any]=64    ,       UpperCamelCase_: Tuple=3    ,       UpperCamelCase_: str=[16, 48, 96]    ,       UpperCamelCase_: List[Any]=[1, 3, 6]    ,       UpperCamelCase_: Tuple=[1, 2, 10]    ,       UpperCamelCase_: str=[7, 3, 3]    ,       UpperCamelCase_: Optional[int]=[4, 2, 2]    ,       UpperCamelCase_: Any=[2, 1, 1]    ,       UpperCamelCase_: List[str]=[2, 2, 2]    ,       UpperCamelCase_: List[Any]=[False, False, True]    ,       UpperCamelCase_: Dict=[0.0, 0.0, 0.0]    ,       UpperCamelCase_: Dict=0.02    ,       UpperCamelCase_: int=1E-12    ,       UpperCamelCase_: int=True    ,       UpperCamelCase_: List[Any]=True    ,       UpperCamelCase_: List[Any]=2    ,       ):
             __lowerCamelCase   =						parent
             __lowerCamelCase   =						batch_size
             __lowerCamelCase   =						image_size
             __lowerCamelCase   =						patch_sizes
             __lowerCamelCase   =						patch_stride
             __lowerCamelCase   =						patch_padding
             __lowerCamelCase   =						is_training
             __lowerCamelCase   =						use_labels
             __lowerCamelCase   =						num_labels
             __lowerCamelCase   =						num_channels
             __lowerCamelCase   =						embed_dim
             __lowerCamelCase   =						num_heads
             __lowerCamelCase   =						stride_kv
             __lowerCamelCase   =						depth
             __lowerCamelCase   =						cls_token
             __lowerCamelCase   =						attention_drop_rate
             __lowerCamelCase   =						initializer_range
             __lowerCamelCase   =						layer_norm_eps
      def 			lowerCAmelCase__						(				self: Any   ):
             __lowerCamelCase   =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

             __lowerCamelCase   =						self.get_config()
             return config, pixel_values, labels
      def 			lowerCAmelCase__						(				self: str   ):
             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: Any    ,       UpperCamelCase_: List[str]    ,       UpperCamelCase_: List[str]    ,       UpperCamelCase_: Optional[Any]   ):
             __lowerCamelCase   =						TFCvtModel(config=__A   )
             __lowerCamelCase   =						model(__A    ,       training=__A   )
             __lowerCamelCase   =						(self.image_size, self.image_size)
             __lowerCamelCase,   __lowerCamelCase   =						image_size[0], image_size[1]
             for i in range(len(self.depth   )   ):
                    __lowerCamelCase   =						floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
                    __lowerCamelCase   =						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: Optional[Any]    ,       UpperCamelCase_: Any    ,       UpperCamelCase_: Optional[int]    ,       UpperCamelCase_: Optional[Any]   ):
             __lowerCamelCase   =						self.num_labels
             __lowerCamelCase   =						TFCvtForImageClassification(__A   )
             __lowerCamelCase   =						model(__A    ,       labels=__A    ,       training=__A   )
             self.parent.assertEqual(result.logits.shape    ,       (self.batch_size, self.num_labels)   )




      def 			lowerCAmelCase__						(				self: Optional[Any]   ):
             __lowerCamelCase   =						self.prepare_config_and_inputs()
             __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase   =						config_and_inputs
             __lowerCamelCase   =						{"""pixel_values""": pixel_values}
             return config, inputs_dict





@require_tf
class     lowerCamelCase__(					__lowerCamelCase ,     __lowerCamelCase ,     unittest.TestCase):
      UpperCAmelCase__      :	Optional[int]    		=   (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
      UpperCAmelCase__      :	int    		=   (
          {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification}
          if is_tf_available()
          else {}
      )
      UpperCAmelCase__      :	Optional[Any]    		=   False
      UpperCAmelCase__      :	Union[str, Any]    		=   False
      UpperCAmelCase__      :	Optional[int]    		=   False
      UpperCAmelCase__      :	Any    		=   False
      UpperCAmelCase__      :	int    		=   False
      def 			lowerCAmelCase__						(				self: List[Any]   ):
             __lowerCamelCase   =						TFCvtModelTester(self   )
             __lowerCamelCase   =						TFCvtConfigTester(self    ,       config_class=__A    ,       has_text_modality=__A    ,       hidden_size=37   )
      def 			lowerCAmelCase__						(				self: Any   ):
             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: Tuple   ):
             pass
      @unittest.skip(reason="""Cvt does not use inputs_embeds"""   )
      def 			lowerCAmelCase__						(				self: List[str]   ):
             pass
      @unittest.skip(reason="""Cvt does not support input and output embeddings"""   )
      def 			lowerCAmelCase__						(				self: int   ):
             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: Dict   ):
             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: List[Any]   ):
             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: Union[str, Any]   ):
             __lowerCamelCase   =						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: Optional[int]   ):
             __lowerCamelCase,   __lowerCamelCase   =						self.model_tester.prepare_config_and_inputs_for_common()

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

                    __lowerCamelCase   =						["""pixel_values"""]
                    self.assertListEqual(arg_names[:1]    ,       __A   )
      def 			lowerCAmelCase__						(				self: Union[str, Any]   ):
             def check_hidden_states_output(UpperCamelCase_: List[Any]    ,       UpperCamelCase_: List[Any]    ,       UpperCamelCase_: Dict   ):
                    __lowerCamelCase   =						model_class(__A   )

                    __lowerCamelCase   =						model(**self._prepare_for_class(__A    ,       __A   )   )
                    __lowerCamelCase   =						outputs.hidden_states

                    __lowerCamelCase   =						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,
                        ]    ,       )

             __lowerCamelCase,   __lowerCamelCase   =						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    __lowerCamelCase   =						True
                    check_hidden_states_output(__A    ,       __A    ,       __A   )

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

                    check_hidden_states_output(__A    ,       __A    ,       __A   )
      def 			lowerCAmelCase__						(				self: Any   ):
             __lowerCamelCase   =						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__A   )
      def 			lowerCAmelCase__						(				self: str   ):
             __lowerCamelCase   =						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*__A   )




      @slow
      def 			lowerCAmelCase__						(				self: Dict   ):
             for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    __lowerCamelCase   =						TFCvtModel.from_pretrained(__A   )
                    self.assertIsNotNone(__A   )




def 					lowerCamelCase__       (						):





       '''simple docstring'''



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





@require_tf
@require_vision
class     lowerCamelCase__(					unittest.TestCase):
      @cached_property
      def 			lowerCAmelCase__						(				self: Dict   ):
             return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )




      @slow
      def 			lowerCAmelCase__						(				self: Dict   ):
             __lowerCamelCase   =						TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

             __lowerCamelCase   =						self.default_image_processor
             __lowerCamelCase   =						prepare_img()
             __lowerCamelCase   =						image_processor(images=__A    ,       return_tensors="""tf"""   )

             # forward pass
             __lowerCamelCase   =						model(**__A   )

             # verify the logits
             __lowerCamelCase   =						tf.TensorShape((1, 10_00)   )
             self.assertEqual(outputs.logits.shape    ,       __A   )

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








'''simple docstring'''
from __future__ import annotations

from typing import Any

class      snake_case     (    __lowerCamelCase       ):




 """simple docstring"""



 pass






class      snake_case     :




 """simple docstring"""



 def __init__(       self       :							List[Any]							,	__A       :							Any	):
        __UpperCamelCase       =  data
        __UpperCamelCase       =  None






 def __iter__(       self       :							Optional[Any]	):
        __UpperCamelCase       =  self
        __UpperCamelCase       =  []
        while node:
               if node in visited:
                      raise ContainsLoopError
               visited.append(__A	)
               yield node.data
               __UpperCamelCase       =  node.next_node






 @property
 def        _lowerCamelCase					(       self       :							List[str]	):
        try:
               list(self	)
               return False
        except ContainsLoopError:
               return True


if __name__ == "__main__":
    a__							:							Dict =Node(1)
    a__							:							Optional[int] =Node(2)
    a__							:							List[str] =Node(3)
    a__							:							Optional[int] =Node(4)
    print(root_node.has_loop)  # False
    a__							:							str =root_node.next_node
    print(root_node.has_loop)  # True

    a__							:							Optional[int] =Node(5)
    a__							:							List[Any] =Node(6)
    a__							:							int =Node(5)
    a__							:							Tuple =Node(6)
    print(root_node.has_loop)  # False

    a__							:							str =Node(1)
    print(root_node.has_loop)  # False
