

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    _lowercase				(					__lowerCamelCase			):

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			List[str]:
         """simple docstring"""





         A_							       =		self.config_class(**self.inputs_dict       )
         self.parent.assertTrue(hasattr(lowerCamelCase__			,						'''embed_dim'''       )       )
         self.parent.assertTrue(hasattr(lowerCamelCase__			,						'''num_heads'''       )       )



class    _lowercase				:

   def __init__(				self	:    str			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    Dict=1_3			,						lowerCamelCase__	:    Tuple=6_4			,						lowerCamelCase__	:    Union[str, Any]=3			,						lowerCamelCase__	:    Dict=[1_6, 4_8, 9_6]			,						lowerCamelCase__	:    List[str]=[1, 3, 6]			,						lowerCamelCase__	:    Optional[Any]=[1, 2, 1_0]			,						lowerCamelCase__	:    Union[str, Any]=[7, 3, 3]			,						lowerCamelCase__	:    List[Any]=[4, 2, 2]			,						lowerCamelCase__	:    int=[2, 1, 1]			,						lowerCamelCase__	:    Dict=[2, 2, 2]			,						lowerCamelCase__	:    List[str]=[False, False, True]			,						lowerCamelCase__	:    Optional[Any]=[0.0, 0.0, 0.0]			,						lowerCamelCase__	:    Union[str, Any]=0.02			,						lowerCamelCase__	:    str=1e-12			,						lowerCamelCase__	:    str=True			,						lowerCamelCase__	:    str=True			,						lowerCamelCase__	:    Optional[int]=2			,						) ->			Optional[int]:
         """simple docstring"""





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

   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			Dict:
         """simple docstring"""





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

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

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

   def     UpperCamelCase					(				self	:    Any       ) ->			int:
         """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     UpperCamelCase					(				self	:    str			,						lowerCamelCase__	:    Tuple			,						lowerCamelCase__	:    Union[str, Any]			,						lowerCamelCase__	:    List[str]       ) ->			Optional[int]:
         """simple docstring"""





         A_							       =		CvtModel(config=lowerCamelCase__       )
         model.to(lowerCamelCase__       )
         model.eval()
         A_							       =		model(lowerCamelCase__       )
         A_							       =		(self.image_size, self.image_size)
         A_       ,A_							       =		image_size[0], image_size[1]
         for i in range(len(self.depth       )       ):
               A_							       =		floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1       )
               A_							       =		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     UpperCamelCase					(				self	:    List[Any]			,						lowerCamelCase__	:    Union[str, Any]			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    Union[str, Any]       ) ->			Union[str, Any]:
         """simple docstring"""





         A_							       =		self.num_labels
         A_							       =		CvtForImageClassification(lowerCamelCase__       )
         model.to(lowerCamelCase__       )
         model.eval()
         A_							       =		model(lowerCamelCase__			,						labels=lowerCamelCase__       )
         self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels)       )





   def     UpperCamelCase					(				self	:    str       ) ->			Optional[Any]:
         """simple docstring"""





         A_							       =		self.prepare_config_and_inputs()
         A_       ,A_       ,A_							       =		config_and_inputs
         A_							       =		{'''pixel_values''': pixel_values}
         return config, inputs_dict



@require_torch
class    _lowercase				(					__lowerCamelCase,__lowerCamelCase,unittest.TestCase			):
   _lowercase     :       List[Any]  					=    (CvtModel, CvtForImageClassification) if is_torch_available() else ()
   _lowercase     :       Union[str, Any]  					=    (
       {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
       if is_torch_available()
       else {}
   )

   _lowercase     :       Any  					=    False
   _lowercase     :       Optional[Any]  					=    False
   _lowercase     :       Union[str, Any]  					=    False
   _lowercase     :       List[Any]  					=    False
   _lowercase     :       Optional[int]  					=    False

   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			Any:
         """simple docstring"""





         A_							       =		CvtModelTester(self       )
         A_							       =		ConfigTester(self			,						config_class=lowerCamelCase__			,						has_text_modality=lowerCamelCase__			,						hidden_size=3_7       )

   def     UpperCamelCase					(				self	:    int       ) ->			int:
         """simple docstring"""





         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     UpperCamelCase					(				self	:    Tuple       ) ->			Dict:
         """simple docstring"""





         return

   @unittest.skip(reason='''Cvt does not output attentions'''       )
   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			str:
         """simple docstring"""





         pass

   @unittest.skip(reason='''Cvt does not use inputs_embeds'''       )
   def     UpperCamelCase					(				self	:    List[str]       ) ->			Optional[Any]:
         """simple docstring"""





         pass

   @unittest.skip(reason='''Cvt does not support input and output embeddings'''       )
   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Dict:
         """simple docstring"""





         pass

   def     UpperCamelCase					(				self	:    List[str]       ) ->			Optional[int]:
         """simple docstring"""





         A_       ,A_							       =		self.model_tester.prepare_config_and_inputs_for_common()

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

               A_							       =		['''pixel_values''']
               self.assertListEqual(arg_names[:1]			,						lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			int:
         """simple docstring"""





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

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			Any:
         """simple docstring"""





         def check_hidden_states_output(lowerCamelCase__	:    Optional[int]			,						lowerCamelCase__	:    Optional[Any]			,						lowerCamelCase__	:    Tuple       ):
               A_							       =		model_class(lowerCamelCase__       )
               model.to(lowerCamelCase__       )
               model.eval()

               with torch.no_grad():
                     A_							       =		model(**self._prepare_for_class(lowerCamelCase__			,						lowerCamelCase__       )       )

               A_							       =		outputs.hidden_states

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

         A_       ,A_							       =		self.model_tester.prepare_config_and_inputs_for_common()

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

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

               check_hidden_states_output(lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__       )

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			List[Any]:
         """simple docstring"""





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

   @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''       )
   def     UpperCamelCase					(				self	:    Tuple       ) ->			Dict:
         """simple docstring"""





         pass





   @slow
   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			Dict:
         """simple docstring"""





         for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               A_							       =		CvtModel.from_pretrained(lowerCamelCase__       )
               self.assertIsNotNone(lowerCamelCase__       )







def 							_lowerCamelCase   (			):
      '''simple docstring'''







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





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

   @cached_property
   def     UpperCamelCase					(				self	:    Any       ) ->			int:
         """simple docstring"""





         return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )





   @slow
   def     UpperCamelCase					(				self	:    List[str]       ) ->			Optional[int]:
         """simple docstring"""





         A_							       =		CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(lowerCamelCase__       )

         A_							       =		self.default_image_processor
         A_							       =		prepare_img()
         A_							       =		image_processor(images=lowerCamelCase__			,						return_tensors='''pt'''       ).to(lowerCamelCase__       )

         # forward pass
         with torch.no_grad():
               A_							       =		model(**lowerCamelCase__       )

         # verify the logits
         A_							       =		torch.Size((1, 1_0_0_0)       )
         self.assertEqual(outputs.logits.shape			,						lowerCamelCase__       )

         A_							       =		torch.tensor([0.9285, 0.9015, -0.3150]       ).to(lowerCamelCase__       )

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








__lowercase				      =						[4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
__lowercase				      =						[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
__lowercase				      =						{
    0: """Sunday""",
    1: """Monday""",
    2: """Tuesday""",
    3: """Wednesday""",
    4: """Thursday""",
    5: """Friday""",
    6: """Saturday""",
}







def 							_lowerCamelCase   (			SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE   ):
      '''simple docstring'''







      assert len(str(SCREAMING_SNAKE_CASE   )   ) > 2, "year should be in YYYY format"
      assert 1 <= month <= 12, "month should be between 1 to 12"
      assert 1 <= day <= 31, "day should be between 1 to 31"

      # Doomsday algorithm:
      A_							       =		year // 100
      A_							       =		(5 * (century % 4) + 2) % 7
      A_							       =		year % 100
      A_							       =		centurian % 12
      A_							       =		(
          (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor
      ) % 7
      A_							       =		(
          DOOMSDAY_NOT_LEAP[month - 1]
          if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0)
          else DOOMSDAY_LEAP[month - 1]
      )
      A_							       =		(dooms_day + day - day_anchor) % 7
      return WEEK_DAY_NAMES[week_day]


if __name__ == "__main__":
      import doctest

      doctest.testmod()





