"""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     UpperCAmelCase						(__UpperCAmelCase  ):



    """simple docstring"""

    def _snake_case			(   self							):
       lowercase__:   int					=      self.config_class(**self.inputs_dict							)
       self.parent.assertTrue(hasattr(UpperCamelCase__    ,			'''embed_dim'''							)							)
       self.parent.assertTrue(hasattr(UpperCamelCase__    ,			'''num_heads'''							)							)



class     UpperCAmelCase						:



    """simple docstring"""

    def __init__(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase=13    ,			_UpperCAmelCase=64    ,			_UpperCAmelCase=3    ,			_UpperCAmelCase=[16, 48, 96]    ,			_UpperCAmelCase=[1, 3, 6]    ,			_UpperCAmelCase=[1, 2, 10]    ,			_UpperCAmelCase=[7, 3, 3]    ,			_UpperCAmelCase=[4, 2, 2]    ,			_UpperCAmelCase=[2, 1, 1]    ,			_UpperCAmelCase=[2, 2, 2]    ,			_UpperCAmelCase=[False, False, True]    ,			_UpperCAmelCase=[0.0, 0.0, 0.0]    ,			_UpperCAmelCase=0.02    ,			_UpperCAmelCase=1e-1_2    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=True    ,			_UpperCAmelCase=2    ,			):
       lowercase__:   int					=      parent
       lowercase__:   Any					=      batch_size
       lowercase__:   List[str]					=      image_size
       lowercase__:   List[Any]					=      patch_sizes
       lowercase__:   Any					=      patch_stride
       lowercase__:   Optional[int]					=      patch_padding
       lowercase__:   Tuple					=      is_training
       lowercase__:   str					=      use_labels
       lowercase__:   int					=      num_labels
       lowercase__:   Optional[int]					=      num_channels
       lowercase__:   Dict					=      embed_dim
       lowercase__:   Optional[Any]					=      num_heads
       lowercase__:   List[str]					=      stride_kv
       lowercase__:   int					=      depth
       lowercase__:   List[str]					=      cls_token
       lowercase__:   Any					=      attention_drop_rate
       lowercase__:   Tuple					=      initializer_range
       lowercase__:   Union[str, Any]					=      layer_norm_eps






    def _snake_case			(   self							):
       lowercase__:   int					=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

       lowercase__:   List[Any]					=      self.get_config()
       return config, pixel_values, labels






    def _snake_case			(   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 _snake_case			(   self    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       lowercase__:   int					=      TFCvtModel(config=UpperCamelCase__							)
       lowercase__:   Any					=      model(UpperCamelCase__    ,			training=UpperCamelCase__							)
       lowercase__:   Optional[Any]					=      (self.image_size, self.image_size)
       lowercase__, lowercase__:   Tuple					=      image_size[0], image_size[1]
       for i in range(len(self.depth							)							):
          lowercase__:   str					=      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    ,			_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
       lowercase__:   Dict					=      self.num_labels
       lowercase__:   Any					=      TFCvtForImageClassification(UpperCamelCase__							)
       lowercase__:   List[Any]					=      model(UpperCamelCase__    ,			labels=UpperCamelCase__    ,			training=UpperCamelCase__							)
       self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels)							)






    def _snake_case			(   self							):
       lowercase__:   Dict					=      self.prepare_config_and_inputs()
       lowercase__, lowercase__, lowercase__:   Tuple					=      config_and_inputs
       lowercase__:   Dict					=      {'''pixel_values''': pixel_values}
       return config, inputs_dict



@require_tf
class     UpperCAmelCase						(__UpperCAmelCase    ,__UpperCAmelCase    ,unittest.TestCase  ):



    """simple docstring"""

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






    def _snake_case			(   self							):
       lowercase__:   Optional[int]					=      TFCvtModelTester(self							)
       lowercase__:   str					=      TFCvtConfigTester(self    ,			config_class=UpperCamelCase__    ,			has_text_modality=UpperCamelCase__    ,			hidden_size=37							)






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






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






    @unittest.skip(reason='''Cvt does not support input and output embeddings'''							)
    def _snake_case			(   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 _snake_case			(   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 _snake_case			(   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 _snake_case			(   self							):
       lowercase__:   Optional[int]					=      tf.keras.mixed_precision.Policy('''mixed_float16'''							)
       tf.keras.mixed_precision.set_global_policy(UpperCamelCase__							)
       super().test_keras_fit()
       tf.keras.mixed_precision.set_global_policy('''float32'''							)






    def _snake_case			(   self							):
       lowercase__, lowercase__:   Any					=      self.model_tester.prepare_config_and_inputs_for_common()

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

          lowercase__:   Optional[Any]					=      ['''pixel_values''']
          self.assertListEqual(arg_names[:1]    ,			UpperCamelCase__							)






    def _snake_case			(   self							):



       def check_hidden_states_output(_UpperCAmelCase    ,			_UpperCAmelCase    ,			_UpperCAmelCase							):
          lowercase__:   str					=      model_class(UpperCamelCase__							)

          lowercase__:   Optional[int]					=      model(**self._prepare_for_class(UpperCamelCase__    ,			UpperCamelCase__							)							)
          lowercase__:   Any					=      outputs.hidden_states

          lowercase__:   Dict					=      len(self.model_tester.depth							)
          self.assertEqual(len(UpperCamelCase__							)    ,			UpperCamelCase__							)

          # 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[Any]					=      self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          lowercase__:   List[str]					=      True
          check_hidden_states_output(UpperCamelCase__    ,			UpperCamelCase__    ,			UpperCamelCase__							)

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          lowercase__:   List[Any]					=      True

          check_hidden_states_output(UpperCamelCase__    ,			UpperCamelCase__    ,			UpperCamelCase__							)






    def _snake_case			(   self							):
       lowercase__:   str					=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__							)






    def _snake_case			(   self							):
       lowercase__:   Union[str, Any]					=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__							)






    @slow
    def _snake_case			(   self							):



       for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowercase__:   Optional[Any]					=      TFCvtModel.from_pretrained(UpperCamelCase__							)
          self.assertIsNotNone(UpperCamelCase__							)



def SCREAMING_SNAKE_CASE__			(   )  ->  Union[str, Any]:
   lowercase__:   Dict					=      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							):
       return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)






    @slow
    def _snake_case			(   self							):
       lowercase__:   Optional[int]					=      TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

       lowercase__:   List[str]					=      self.default_image_processor
       lowercase__:   List[Any]					=      prepare_img()
       lowercase__:   List[str]					=      image_processor(images=UpperCamelCase__    ,			return_tensors='''tf'''							)

       # forward pass
       lowercase__:   Optional[Any]					=      model(**UpperCamelCase__							)

       # verify the logits
       lowercase__:   Tuple					=      tf.TensorShape((1, 1000)							)
       self.assertEqual(outputs.logits.shape    ,			UpperCamelCase__							)

       lowercase__:   Union[str, Any]					=      tf.constant([0.9_285, 0.9_015, -0.3_150]							)
       self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()    ,			UpperCamelCase__    ,			atol=1e-4							)							)






import argparse
from collections import defaultdict

import yaml


_A     =			'''docs/source/en/_toctree.yml'''





def __UpperCamelCase			(       _A  ):
						lowerCAmelCase_      			=  defaultdict(_A  )
						for doc in model_doc:
												counts[doc["local"]] += 1
						lowerCAmelCase_      			=  [key for key, value in counts.items() if value > 1]

						lowerCAmelCase_      			=  []
						for duplicate_key in duplicates:
												lowerCAmelCase_      			=  list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key}  )
												if len(_A  ) > 1:
																		raise ValueError(
																		    f"{duplicate_key} is present several times in the documentation table of content at "
																		    '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '''
																		    '''others.'''  )
												# Only add this once
												new_doc.append({'''local''': duplicate_key, '''title''': titles[0]}  )

						# Add none duplicate-keys
						new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1]  )

						# Sort
						return sorted(_A ,  key=lambda _A  : s["title"].lower()  )





def __UpperCamelCase			(       _A=False  ):
						with open(_A ,  encoding='''utf-8'''  ) as f:
												lowerCAmelCase_      			=  yaml.safe_load(f.read()  )

						# Get to the API doc
						lowerCAmelCase_      			=  0
						while content[api_idx]["title"] != "API":
												api_idx += 1
						lowerCAmelCase_      			=  content[api_idx]['''sections''']

						# Then to the model doc
						lowerCAmelCase_      			=  0
						while api_doc[model_idx]["title"] != "Models":
												model_idx += 1

						lowerCAmelCase_      			=  api_doc[model_idx]['''sections''']

						lowerCAmelCase_      			=  [(idx, section) for idx, section in enumerate(_A  ) if '''sections''' in section]
						lowerCAmelCase_      			=  False
						for idx, modality_doc in modalities_docs:
												lowerCAmelCase_      			=  modality_doc['''sections''']
												lowerCAmelCase_      			=  clean_model_doc_toc(_A  )

												if old_modality_doc != new_modality_doc:
																		lowerCAmelCase_      			=  True
																		if overwrite:
																								lowerCAmelCase_      			=  new_modality_doc

						if diff:
												if overwrite:
																		lowerCAmelCase_      			=  model_doc
																		lowerCAmelCase_      			=  api_doc
																		with open(_A ,  '''w''' ,  encoding='''utf-8'''  ) as f:
																								f.write(yaml.dump(_A ,  allow_unicode=_A  )  )
												else:
																		raise ValueError(
																		    '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.'''  )


if __name__ == "__main__":
						_A     =			argparse.ArgumentParser()
						parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
						_A     =			parser.parse_args()

						check_model_doc(args.fix_and_overwrite)




