




import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import CvtForImageClassification, CvtModel
 from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor

class  _lowerCamelCase						(			UpperCAmelCase_   ):

      """simple docstring"""

      def       snake_case	(     self					: Union[str, Any]				):
          __UpperCamelCase  		=						self.config_class(**self.inputs_dict				)
          self.parent.assertTrue(hasattr(_lowercase ,       '''embed_dim'''				)				)
          self.parent.assertTrue(hasattr(_lowercase ,       '''num_heads'''				)				)







class  _lowerCamelCase						:

      """simple docstring"""

      def __init__(     self					: int ,       snake_case					: Tuple ,       snake_case					: Optional[int]=13 ,       snake_case					: Optional[Any]=64 ,       snake_case					: Tuple=3 ,       snake_case					: Any=[16, 48, 96] ,       snake_case					: List[str]=[1, 3, 6] ,       snake_case					: str=[1, 2, 10] ,       snake_case					: Optional[int]=[7, 3, 3] ,       snake_case					: List[Any]=[4, 2, 2] ,       snake_case					: Optional[int]=[2, 1, 1] ,       snake_case					: List[str]=[2, 2, 2] ,       snake_case					: str=[False, False, True] ,       snake_case					: Optional[Any]=[0.0, 0.0, 0.0] ,       snake_case					: Union[str, Any]=0.02 ,       snake_case					: Tuple=1E-12 ,       snake_case					: List[str]=True ,       snake_case					: int=True ,       snake_case					: Dict=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       snake_case	(     self					: str				):
          __UpperCamelCase  		=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

          __UpperCamelCase  		=						None
          if self.use_labels:
              __UpperCamelCase  		=						ids_tensor([self.batch_size] ,       self.num_labels				)

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







      def       snake_case	(     self					: Optional[Any]				):
          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					: str ,       snake_case					: int ,       snake_case					: Any ,       snake_case					: int				):
          __UpperCamelCase  		=						CvtModel(config=_lowercase				)
          model.to(_lowercase				)
          model.eval()
          __UpperCamelCase  		=						model(_lowercase				)
          __UpperCamelCase  		=						(self.image_size, self.image_size)
          __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       snake_case	(     self					: Optional[Any] ,       snake_case					: Union[str, Any] ,       snake_case					: int ,       snake_case					: Optional[Any]				):
          __UpperCamelCase  		=						self.num_labels
          __UpperCamelCase  		=						CvtForImageClassification(_lowercase				)
          model.to(_lowercase				)
          model.eval()
          __UpperCamelCase  		=						model(_lowercase ,       labels=_lowercase				)
          self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_labels)				)







      def       snake_case	(     self					: Dict				):
          __UpperCamelCase  		=						self.prepare_config_and_inputs()
          __UpperCamelCase  		=						config_and_inputs
          __UpperCamelCase  		=						{'pixel_values': pixel_values}
          return config, inputs_dict







@require_torch
class  _lowerCamelCase						(			UpperCAmelCase_							,			UpperCAmelCase_							,			unittest.TestCase   ):

      """simple docstring"""

      lowerCAmelCase__			: Optional[int]    =					(CvtModel, CvtForImageClassification) if is_torch_available() else ()
      lowerCAmelCase__			: List[str]    =					(
          {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
          if is_torch_available()
          else {}
      )

      lowerCAmelCase__			: Union[str, Any]    =					False
      lowerCAmelCase__			: Any    =					False
      lowerCAmelCase__			: Any    =					False
      lowerCAmelCase__			: Union[str, Any]    =					False
      lowerCAmelCase__			: Dict    =					False







      def       snake_case	(     self					: Any				):
          __UpperCamelCase  		=						CvtModelTester(self				)
          __UpperCamelCase  		=						ConfigTester(self ,       config_class=_lowercase ,       has_text_modality=_lowercase ,       hidden_size=37				)







      def       snake_case	(     self					: Union[str, Any]				):
          self.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()







      def       snake_case	(     self					: str				):
          return







      @unittest.skip(reason='''Cvt does not output attentions'''				)
      def       snake_case	(     self					: Optional[Any]				):
          pass







      @unittest.skip(reason='''Cvt does not use inputs_embeds'''				)
      def       snake_case	(     self					: Optional[Any]				):
          pass







      @unittest.skip(reason='''Cvt does not support input and output embeddings'''				)
      def       snake_case	(     self					: List[str]				):
          pass







      def       snake_case	(     self					: List[Any]				):
          __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs_for_common()

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

              __UpperCamelCase  		=						['pixel_values']
              self.assertListEqual(arg_names[:1] ,       _lowercase				)







      def       snake_case	(     self					: int				):
          __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_lowercase				)







      def       snake_case	(     self					: Optional[Any]				):
          def check_hidden_states_output(snake_case					: str ,       snake_case					: List[Any] ,       snake_case					: Dict				):
              __UpperCamelCase  		=						model_class(_lowercase				)
              model.to(_lowercase				)
              model.eval()

              with torch.no_grad():
                  __UpperCamelCase  		=						model(**self._prepare_for_class(_lowercase ,       _lowercase				)				)

              __UpperCamelCase  		=						outputs.hidden_states

              __UpperCamelCase  		=						len(self.model_tester.depth				)
              self.assertEqual(len(_lowercase				) ,       _lowercase				)

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

          for model_class in self.all_model_classes:
              __UpperCamelCase  		=						True
              check_hidden_states_output(_lowercase ,       _lowercase ,       _lowercase				)

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

              check_hidden_states_output(_lowercase ,       _lowercase ,       _lowercase				)







      def       snake_case	(     self					: Tuple				):
          __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_lowercase				)







      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''				)
      def       snake_case	(     self					: int				):
          pass







      @slow
      def       snake_case	(     self					: Optional[Any]				):
          for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __UpperCamelCase  		=						CvtModel.from_pretrained(_lowercase				)
              self.assertIsNotNone(_lowercase				)







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

    """simple docstring"""


    __UpperCamelCase  		=						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
    return image


@require_torch
@require_vision
class  _lowerCamelCase						(			unittest.TestCase   ):

      """simple docstring"""

      @cached_property
      def       snake_case	(     self					: Optional[int]				):
          return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)







      @slow
      def       snake_case	(     self					: Union[str, Any]				):
          __UpperCamelCase  		=						CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(_lowercase				)

          __UpperCamelCase  		=						self.default_image_processor
          __UpperCamelCase  		=						prepare_img()
          __UpperCamelCase  		=						image_processor(images=_lowercase ,       return_tensors='''pt'''				).to(_lowercase				)

          # forward pass
          with torch.no_grad():
              __UpperCamelCase  		=						model(**_lowercase				)

          # verify the logits
          __UpperCamelCase  		=						torch.Size((1, 1000)				)
          self.assertEqual(outputs.logits.shape ,       _lowercase				)

          __UpperCamelCase  		=						torch.tensor([0.92_85, 0.90_15, -0.31_50]				).to(_lowercase				)

          self.assertTrue(torch.allclose(outputs.logits[0, :3] ,       _lowercase ,       atol=1E-4				)				)











def 					__SCREAMING_SNAKE_CASE   (  lowercase_					,     lowercase_ = False      )       ->	str:

    """simple docstring"""


    if not isinstance(lowercase_					,     lowercase_      ):
        __UpperCamelCase  		=						F"Expected string as input, found {type(lowercase_      )}"
        raise ValueError(lowercase_      )
    if not isinstance(lowercase_					,     lowercase_      ):
        __UpperCamelCase  		=						F"Expected boolean as use_pascal parameter, found {type(lowercase_      )}"
        raise ValueError(lowercase_      )

    __UpperCamelCase  		=						input_str.split('''_'''      )

    __UpperCamelCase  		=						0 if use_pascal else 1

    __UpperCamelCase  		=						words[start_index:]

    __UpperCamelCase  		=						[word[0].upper() + word[1:] for word in words_to_capitalize]

    __UpperCamelCase  		=						'''''' if use_pascal else words[0]

    return "".join([initial_word, *capitalized_words]      )


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

 testmod()






