


'''simple docstring'''







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 					lowercase_     (    a__   ):


    def    __a							(     self    ):
          UpperCamelCase__										=				self.config_class(**self.inputs_dict    )
          self.parent.assertTrue(hasattr(a  ,					"embed_dim"    )    )
          self.parent.assertTrue(hasattr(a  ,					"num_heads"    )    )

class 					lowercase_     :


    def __init__(     self  ,					a  ,					a=13  ,					a=64  ,					a=3  ,					a=[16, 48, 96]  ,					a=[1, 3, 6]  ,					a=[1, 2, 10]  ,					a=[7, 3, 3]  ,					a=[4, 2, 2]  ,					a=[2, 1, 1]  ,					a=[2, 2, 2]  ,					a=[False, False, True]  ,					a=[0.0, 0.0, 0.0]  ,					a=0.02  ,					a=1e-12  ,					a=True  ,					a=True  ,					a=2  ,					):
          UpperCamelCase__										=				parent
          UpperCamelCase__										=				batch_size
          UpperCamelCase__										=				image_size
          UpperCamelCase__										=				patch_sizes
          UpperCamelCase__										=				patch_stride
          UpperCamelCase__										=				patch_padding
          UpperCamelCase__										=				is_training
          UpperCamelCase__										=				use_labels
          UpperCamelCase__										=				num_labels
          UpperCamelCase__										=				num_channels
          UpperCamelCase__										=				embed_dim
          UpperCamelCase__										=				num_heads
          UpperCamelCase__										=				stride_kv
          UpperCamelCase__										=				depth
          UpperCamelCase__										=				cls_token
          UpperCamelCase__										=				attention_drop_rate
          UpperCamelCase__										=				initializer_range
          UpperCamelCase__										=				layer_norm_eps


    def    __a							(     self    ):
          UpperCamelCase__										=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

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


    def    __a							(     self    ):
          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    __a							(     self  ,					a  ,					a  ,					a    ):
          UpperCamelCase__										=				TFCvtModel(config=a    )
          UpperCamelCase__										=				model(a  ,					training=a    )
          UpperCamelCase__										=				(self.image_size, self.image_size)
          UpperCamelCase__					,	UpperCamelCase__										=				image_size[0], image_size[1]
          for i in range(len(self.depth    )    ):
                UpperCamelCase__										=				floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1    )
                UpperCamelCase__										=				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    __a							(     self  ,					a  ,					a  ,					a    ):
          UpperCamelCase__										=				self.num_labels
          UpperCamelCase__										=				TFCvtForImageClassification(a    )
          UpperCamelCase__										=				model(a  ,					labels=a  ,					training=a    )
          self.parent.assertEqual(result.logits.shape  ,					(self.batch_size, self.num_labels)    )


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

@require_tf
class 					lowercase_     (    a__  ,						a__  ,						unittest.TestCase   ):
    __UpperCAmelCase   			=	(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
    __UpperCAmelCase   			=	(
        {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification}
        if is_tf_available()
        else {}
    )
    __UpperCAmelCase   			=	False
    __UpperCAmelCase   			=	False
    __UpperCAmelCase   			=	False
    __UpperCAmelCase   			=	False
    __UpperCAmelCase   			=	False


    def    __a							(     self    ):
          UpperCamelCase__										=				TFCvtModelTester(self    )
          UpperCamelCase__										=				TFCvtConfigTester(self  ,					config_class=a  ,					has_text_modality=a  ,					hidden_size=37    )


    def    __a							(     self    ):
          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    __a							(     self    ):
          pass


    @unittest.skip(reason="Cvt does not use inputs_embeds"    )
    def    __a							(     self    ):
          pass


    @unittest.skip(reason="Cvt does not support input and output embeddings"    )
    def    __a							(     self    ):
          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    __a							(     self    ):
          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    __a							(     self    ):
          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    __a							(     self    ):
          UpperCamelCase__										=				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    __a							(     self    ):
          UpperCamelCase__					,	UpperCamelCase__										=				self.model_tester.prepare_config_and_inputs_for_common()

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

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


    def    __a							(     self    ):
          def check_hidden_states_output(a  ,					a  ,					a    ):
                UpperCamelCase__										=				model_class(a    )

                UpperCamelCase__										=				model(**self._prepare_for_class(a  ,					a    )    )
                UpperCamelCase__										=				outputs.hidden_states

                UpperCamelCase__										=				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__										=				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                UpperCamelCase__										=				True
                check_hidden_states_output(a  ,					a  ,					a    )

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

                check_hidden_states_output(a  ,					a  ,					a    )


    def    __a							(     self    ):
          UpperCamelCase__										=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*a    )


    def    __a							(     self    ):
          UpperCamelCase__										=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*a    )


    @slow
    def    __a							(     self    ):
          for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                UpperCamelCase__										=				TFCvtModel.from_pretrained(a    )
                self.assertIsNotNone(a    )







def _UpperCamelCase       (     )							->		Optional[int]:


      '''simple docstring'''



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



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


    @cached_property
    def    __a							(     self    ):
          return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )


    @slow
    def    __a							(     self    ):
          UpperCamelCase__										=				TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

          UpperCamelCase__										=				self.default_image_processor
          UpperCamelCase__										=				prepare_img()
          UpperCamelCase__										=				image_processor(images=a  ,					return_tensors="tf"    )

          # forward pass
          UpperCamelCase__										=				model(**a    )

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

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










'''simple docstring'''

import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


__lowerCAmelCase									=   logging.getLogger()

@unittest.skip('Temporarily disable the doc tests.'   )
@require_torch
@require_tf
@slow
class 	__magic_name__						(    unittest.TestCase   ):







							def 							__lowercase			(							self					:       str	,_UpperCAmelCase					:       Path	,_UpperCAmelCase					:       Union[str, None] = None	,_UpperCAmelCase					:       Union[List[str], None] = None	,_UpperCAmelCase					:       Union[str, List[str], None] = None	,_UpperCAmelCase					:       bool = True	,):
									_a     :      Dict        =							[file for file in os.listdir(_UpperCAmelCase		) if os.path.isfile(os.path.join(_UpperCAmelCase	,_UpperCAmelCase		)		)]

									if identifier is not None:
											_a     :      str        =							[file for file in files if identifier in file]

									if n_identifier is not None:
											if isinstance(_UpperCAmelCase	,_UpperCAmelCase		):
													for n_ in n_identifier:
															_a     :      int        =							[file for file in files if n_ not in file]
											else:
													_a     :      Optional[Any]        =							[file for file in files if n_identifier not in file]

									_a     :      Dict        =							ignore_files or []
									ignore_files.append('__init__.py'		)
									_a     :      List[str]        =							[file for file in files if file not in ignore_files]

									for file in files:
											# Open all files
											print('Testing'	,_UpperCAmelCase		)

											if only_modules:
													_a     :      Any        =							file.split('.'		)[0]
													try:
															_a     :      Optional[int]        =							getattr(_UpperCAmelCase	,_UpperCAmelCase		)
															_a     :      Dict        =							doctest.DocTestSuite(_UpperCAmelCase		)
															_a     :      Optional[int]        =							unittest.TextTestRunner().run(_UpperCAmelCase		)
															self.assertIs(len(result.failures		)	,0		)
													except AttributeError:
															logger.info(F"""{module_identifier} is not a module."""		)
											else:
													_a     :      str        =							doctest.testfile(str('..' / directory / file		)	,optionflags=doctest.ELLIPSIS		)
													self.assertIs(result.failed	,0		)







							def 							__lowercase			(							self					:       Union[str, Any]		):
									_a     :      Optional[Any]        =							Path('src/transformers'		)
									_a     :      Optional[Any]        =							'modeling'
									_a     :      Union[str, Any]        =							[
									    'modeling_ctrl.py',
									    'modeling_tf_ctrl.py',
									]
									self.analyze_directory(_UpperCAmelCase	,identifier=_UpperCAmelCase	,ignore_files=_UpperCAmelCase		)







							def 							__lowercase			(							self					:       int		):
									_a     :      str        =							Path('src/transformers'		)
									_a     :      List[str]        =							'tokenization'
									self.analyze_directory(_UpperCAmelCase	,identifier=_UpperCAmelCase		)







							def 							__lowercase			(							self					:       int		):
									_a     :      Any        =							Path('src/transformers'		)
									_a     :      str        =							'configuration'
									self.analyze_directory(_UpperCAmelCase	,identifier=_UpperCAmelCase		)







							def 							__lowercase			(							self					:       Dict		):
									_a     :      Tuple        =							Path('src/transformers'		)
									_a     :      Optional[int]        =							['configuration', 'modeling', 'tokenization']
									self.analyze_directory(_UpperCAmelCase	,n_identifier=_UpperCAmelCase		)







							def 							__lowercase			(							self					:       Optional[Any]		):
									_a     :      Union[str, Any]        =							Path('docs/source'		)
									_a     :      List[str]        =							['favicon.ico']
									self.analyze_directory(_UpperCAmelCase	,ignore_files=_UpperCAmelCase	,only_modules=_UpperCAmelCase		)




