
import collections
import inspect
import unittest

from transformers import SwinvaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
  import torch
  from torch import nn

  from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
  from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor

class __snake_case		:
    def __init__(  self		,snake_case		,snake_case=13		,snake_case=32		,snake_case=2		,snake_case=3		,snake_case=16		,snake_case=[1, 2, 1]		,snake_case=[2, 2, 4]		,snake_case=2		,snake_case=2.0		,snake_case=True		,snake_case=0.0		,snake_case=0.0		,snake_case=0.1		,snake_case="gelu"		,snake_case=False		,snake_case=True		,snake_case=0.02		,snake_case=1e-5		,snake_case=True		,snake_case=None		,snake_case=True		,snake_case=10		,snake_case=8		,):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      parent
           lowercase							:     List[str]       	=      batch_size
           lowercase							:     Dict       	=      image_size
           lowercase							:     Optional[Any]       	=      patch_size
           lowercase							:     Tuple       	=      num_channels
           lowercase							:     Optional[int]       	=      embed_dim
           lowercase							:     Dict       	=      depths
           lowercase							:     int       	=      num_heads
           lowercase							:     List[str]       	=      window_size
           lowercase							:     List[Any]       	=      mlp_ratio
           lowercase							:     List[Any]       	=      qkv_bias
           lowercase							:     List[str]       	=      hidden_dropout_prob
           lowercase							:     Tuple       	=      attention_probs_dropout_prob
           lowercase							:     Union[str, Any]       	=      drop_path_rate
           lowercase							:     Union[str, Any]       	=      hidden_act
           lowercase							:     Dict       	=      use_absolute_embeddings
           lowercase							:     int       	=      patch_norm
           lowercase							:     Optional[int]       	=      layer_norm_eps
           lowercase							:     Dict       	=      initializer_range
           lowercase							:     Optional[Any]       	=      is_training
           lowercase							:     Dict       	=      scope
           lowercase							:     Optional[Any]       	=      use_labels
           lowercase							:     Optional[int]       	=      type_sequence_label_size
           lowercase							:     int       	=      encoder_stride
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     int       	=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

           lowercase							:     str       	=      None
           if self.use_labels:
                  lowercase							:     int       	=      ids_tensor([self.batch_size]		,self.type_sequence_label_size      )

           lowercase							:     int       	=      self.get_config()

           return config, pixel_values, labels
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           return SwinvaConfig(
               image_size=self.image_size		,patch_size=self.patch_size		,num_channels=self.num_channels		,embed_dim=self.embed_dim		,depths=self.depths		,num_heads=self.num_heads		,window_size=self.window_size		,mlp_ratio=self.mlp_ratio		,qkv_bias=self.qkv_bias		,hidden_dropout_prob=self.hidden_dropout_prob		,attention_probs_dropout_prob=self.attention_probs_dropout_prob		,drop_path_rate=self.drop_path_rate		,hidden_act=self.hidden_act		,use_absolute_embeddings=self.use_absolute_embeddings		,path_norm=self.patch_norm		,layer_norm_eps=self.layer_norm_eps		,initializer_range=self.initializer_range		,encoder_stride=self.encoder_stride		,)
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Dict       	=      SwinvaModel(config=snake_case      )
           model.to(snake_case      )
           model.eval()
           lowercase							:     Tuple       	=      model(snake_case      )

           lowercase							:     List[Any]       	=      ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths      ) - 1))
           lowercase							:     int       	=      int(config.embed_dim * 2 ** (len(config.depths      ) - 1)      )

           self.parent.assertEqual(result.last_hidden_state.shape		,(self.batch_size, expected_seq_len, expected_dim)      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case      ):



           '''simple docstring'''







           lowercase							:     str       	=      SwinvaForMaskedImageModeling(config=snake_case      )
           model.to(snake_case      )
           model.eval()
           lowercase							:     Optional[int]       	=      model(snake_case      )
           self.parent.assertEqual(
               result.logits.shape		,(self.batch_size, self.num_channels, self.image_size, self.image_size)      )

           # test greyscale images
           lowercase							:     Tuple       	=      1
           lowercase							:     Union[str, Any]       	=      SwinvaForMaskedImageModeling(snake_case      )
           model.to(snake_case      )
           model.eval()

           lowercase							:     Tuple       	=      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
           lowercase							:     List[Any]       	=      model(snake_case      )
           self.parent.assertEqual(result.logits.shape		,(self.batch_size, 1, self.image_size, self.image_size)      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      self.type_sequence_label_size
           lowercase							:     Optional[int]       	=      SwinvaForImageClassification(snake_case      )
           model.to(snake_case      )
           model.eval()
           lowercase							:     Tuple       	=      model(snake_case		,labels=snake_case      )
           self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.type_sequence_label_size)      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Dict       	=      self.prepare_config_and_inputs()
           lowercase							:     Union[str, Any]       	=      config_and_inputs
           lowercase							:     Optional[Any]       	=      {"pixel_values": pixel_values}
           return config, inputs_dict






@require_torch
class __snake_case		(      __lowercase					,	__lowercase					,	unittest.TestCase     ):
    _a		:						int=				(
        (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
    )
    _a		:						int=				(
        {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification}
        if is_torch_available()
        else {}
    )

    _a		:						Optional[int]=				False
    _a		:						int=				False
    _a		:						List[str]=				False
    _a		:						Union[str, Any]=				False
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Optional[Any]       	=      SwinvaModelTester(self      )
           lowercase							:     List[Any]       	=      ConfigTester(self		,config_class=snake_case		,embed_dim=37      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           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       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Any       	=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*snake_case      )
    @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0."""      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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



           '''simple docstring'''







           pass
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     str       	=      self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  lowercase							:     List[Any]       	=      model_class(snake_case      )
                  self.assertIsInstance(model.get_input_embeddings()		,(nn.Module)      )
                  lowercase							:     Optional[Any]       	=      model.get_output_embeddings()
                  self.assertTrue(x is None or isinstance(snake_case		,nn.Linear      )      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     List[str]       	=      self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  lowercase							:     Optional[int]       	=      model_class(snake_case      )
                  lowercase							:     List[Any]       	=      inspect.signature(model.forward      )
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  lowercase							:     Dict       	=      [*signature.parameters.keys()]

                  lowercase							:     Union[str, Any]       	=      ["pixel_values"]
                  self.assertListEqual(arg_names[:1]		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     str       	=      self.model_tester.prepare_config_and_inputs_for_common()
           lowercase							:     Any       	=      True

           for model_class in self.all_model_classes:
                  lowercase							:     str       	=      True
                  lowercase							:     Dict       	=      False
                  lowercase							:     Union[str, Any]       	=      True
                  lowercase							:     Dict       	=      model_class(snake_case      )
                  model.to(snake_case      )
                  model.eval()
                  with torch.no_grad():
                         lowercase							:     Union[str, Any]       	=      model(**self._prepare_for_class(snake_case		,snake_case      )      )
                  lowercase							:     Union[str, Any]       	=      outputs.attentions
                  lowercase							:     int       	=      len(self.model_tester.depths      )
                  self.assertEqual(len(snake_case      )		,snake_case      )

                  # check that output_attentions also work using config
                  del inputs_dict["output_attentions"]
                  lowercase							:     Optional[Any]       	=      True
                  lowercase							:     Any       	=      config.window_size**2
                  lowercase							:     str       	=      model_class(snake_case      )
                  model.to(snake_case      )
                  model.eval()
                  with torch.no_grad():
                         lowercase							:     Union[str, Any]       	=      model(**self._prepare_for_class(snake_case		,snake_case      )      )
                  lowercase							:     int       	=      outputs.attentions
                  self.assertEqual(len(snake_case      )		,snake_case      )

                  self.assertListEqual(
                      list(attentions[0].shape[-3:]      )		,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]		,)
                  lowercase							:     Optional[Any]       	=      len(snake_case      )

                  # Check attention is always last and order is fine
                  lowercase							:     Any       	=      True
                  lowercase							:     Tuple       	=      True
                  lowercase							:     Any       	=      model_class(snake_case      )
                  model.to(snake_case      )
                  model.eval()
                  with torch.no_grad():
                         lowercase							:     Optional[Any]       	=      model(**self._prepare_for_class(snake_case		,snake_case      )      )

                  if hasattr(self.model_tester		,"""num_hidden_states_types"""      ):
                         lowercase							:     Optional[int]       	=      self.model_tester.num_hidden_states_types
                  else:
                         # also another +1 for reshaped_hidden_states
                         lowercase							:     Optional[Any]       	=      2
                  self.assertEqual(out_len + added_hidden_states		,len(snake_case      )      )

                  lowercase							:     List[str]       	=      outputs.attentions

                  self.assertEqual(len(snake_case      )		,snake_case      )

                  self.assertListEqual(
                      list(self_attentions[0].shape[-3:]      )		,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]		,)
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case		,snake_case		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      model_class(snake_case      )
           model.to(snake_case      )
           model.eval()

           with torch.no_grad():
                  lowercase							:     int       	=      model(**self._prepare_for_class(snake_case		,snake_case      )      )

           lowercase							:     Union[str, Any]       	=      outputs.hidden_states

           lowercase							:     Tuple       	=      getattr(
               self.model_tester		,"""expected_num_hidden_layers"""		,len(self.model_tester.depths      ) + 1      )
           self.assertEqual(len(snake_case      )		,snake_case      )

           # Swinv2 has a different seq_length
           lowercase							:     str       	=      (
               config.patch_size
               if isinstance(config.patch_size		,collections.abc.Iterable      )
               else (config.patch_size, config.patch_size)
           )

           lowercase							:     str       	=      (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

           self.assertListEqual(
               list(hidden_states[0].shape[-2:]      )		,[num_patches, self.model_tester.embed_dim]		,)

           lowercase							:     str       	=      outputs.reshaped_hidden_states
           self.assertEqual(len(snake_case      )		,snake_case      )

           lowercase							:     List[Any]       	=      reshaped_hidden_states[0].shape
           lowercase							:     int       	=      (
               reshaped_hidden_states[0].view(snake_case		,snake_case		,height * width      ).permute(0		,2		,1      )
           )
           self.assertListEqual(
               list(reshaped_hidden_states.shape[-2:]      )		,[num_patches, self.model_tester.embed_dim]		,)
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      self.model_tester.prepare_config_and_inputs_for_common()

           lowercase							:     Union[str, Any]       	=      (
               self.model_tester.image_size
               if isinstance(self.model_tester.image_size		,collections.abc.Iterable      )
               else (self.model_tester.image_size, self.model_tester.image_size)
           )

           for model_class in self.all_model_classes:
                  lowercase							:     Optional[int]       	=      True
                  self.check_hidden_states_output(snake_case		,snake_case		,snake_case		,snake_case      )

                  # check that output_hidden_states also work using config
                  del inputs_dict["output_hidden_states"]
                  lowercase							:     str       	=      True

                  self.check_hidden_states_output(snake_case		,snake_case		,snake_case		,snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     str       	=      self.model_tester.prepare_config_and_inputs_for_common()
           lowercase							:     List[Any]       	=      3

           lowercase							:     Tuple       	=      (
               self.model_tester.image_size
               if isinstance(self.model_tester.image_size		,collections.abc.Iterable      )
               else (self.model_tester.image_size, self.model_tester.image_size)
           )
           lowercase							:     List[str]       	=      (
               config.patch_size
               if isinstance(config.patch_size		,collections.abc.Iterable      )
               else (config.patch_size, config.patch_size)
           )

           lowercase							:     Union[str, Any]       	=      image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
           lowercase							:     Dict       	=      image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

           for model_class in self.all_model_classes:
                  lowercase							:     Optional[int]       	=      True
                  self.check_hidden_states_output(snake_case		,snake_case		,snake_case		,(padded_height, padded_width)      )

                  # check that output_hidden_states also work using config
                  del inputs_dict["output_hidden_states"]
                  lowercase							:     Union[str, Any]       	=      True
                  self.check_hidden_states_output(snake_case		,snake_case		,snake_case		,(padded_height, padded_width)      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*snake_case      )
    @slow
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowercase							:     Union[str, Any]       	=      SwinvaModel.from_pretrained(snake_case      )
                  self.assertIsNotNone(snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     str       	=      self.model_tester.prepare_config_and_inputs_for_common()

           lowercase							:     Tuple       	=      _config_zero_init(snake_case      )
           for model_class in self.all_model_classes:
                  lowercase							:     str       	=      model_class(config=snake_case      )
                  for name, param in model.named_parameters():
                         if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
                                self.assertIn(
                                    ((param.data.mean() * 1e9).round() / 1e9).item()		,[0.0, 1.0]		,msg=f"Parameter {name} of model {model_class} seems not properly initialized"		,)






@require_vision
@require_torch
class __snake_case		(      unittest.TestCase     ):
    @cached_property
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           return (
               AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256"""      )
               if is_vision_available()
               else None
           )
    @slow
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256"""      ).to(
               snake_case      )
           lowercase							:     Optional[int]       	=      self.default_image_processor

           lowercase							:     Optional[Any]       	=      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
           lowercase							:     Dict       	=      image_processor(images=snake_case		,return_tensors="""pt"""      ).to(snake_case      )

           # forward pass
           with torch.no_grad():
                  lowercase							:     Optional[Any]       	=      model(**snake_case      )

           # verify the logits
           lowercase							:     Optional[Any]       	=      torch.Size((1, 1000)      )
           self.assertEqual(outputs.logits.shape		,snake_case      )
           lowercase							:     Optional[Any]       	=      torch.tensor([-0.3_947, -0.4_306, 0.0_026]      ).to(snake_case      )
           self.assertTrue(torch.allclose(outputs.logits[0, :3]		,snake_case		,atol=1e-4      )      )


import argparse
import datetime




def 	_SCREAMING_SNAKE_CASE					(		_lowerCamelCase :			str)					->    str:






							'''simple docstring'''





							__UpperCamelCase	:   str			   =					{
							    "0": "Sunday",
							    "1": "Monday",
							    "2": "Tuesday",
							    "3": "Wednesday",
							    "4": "Thursday",
							    "5": "Friday",
							    "6": "Saturday",
							}

							__UpperCamelCase	:   List[str]			   =					{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0}

							# Validate
							if not 0 < len(_lowerCamelCase) < 11:
														raise ValueError("Must be 10 characters long")

							# Get month
							__UpperCamelCase	:   int			   =					int(date_input[0] + date_input[1])
							# Validate
							if not 0 < m < 13:
														raise ValueError("Month must be between 1 - 12")

							__UpperCamelCase	:   str			   =					date_input[2]
							# Validate
							if sep_a not in ["-", "/"]:
														raise ValueError("Date separator must be '-' or '/'")

							# Get day
							__UpperCamelCase	:   int			   =					int(date_input[3] + date_input[4])
							# Validate
							if not 0 < d < 32:
														raise ValueError("Date must be between 1 - 31")

							# Get second separator
							__UpperCamelCase	:   str			   =					date_input[5]
							# Validate
							if sep_a not in ["-", "/"]:
														raise ValueError("Date separator must be '-' or '/'")

							# Get year
							__UpperCamelCase	:   int			   =					int(date_input[6] + date_input[7] + date_input[8] + date_input[9])
							# Arbitrary year range
							if not 45 < y < 8_500:
														raise ValueError(
														    "Year out of range. There has to be some sort of limit...right?")

							# Get datetime obj for validation
							__UpperCamelCase	:   Union[str, Any]			   =					datetime.date(int(_lowerCamelCase)						,  int(_lowerCamelCase)						,  int(_lowerCamelCase))

							# Start math
							if m <= 2:
														__UpperCamelCase	:   Any			   =					y - 1
														__UpperCamelCase	:   Optional[Any]			   =					m + 12
							# maths var
							__UpperCamelCase	:   int			   =					int(str(_lowerCamelCase)[:2])
							__UpperCamelCase	:   int			   =					int(str(_lowerCamelCase)[2:])
							__UpperCamelCase	:   int			   =					int(2.6 * m - 5.3_9)
							__UpperCamelCase	:   int			   =					int(c / 4)
							__UpperCamelCase	:   int			   =					int(k / 4)
							__UpperCamelCase	:   int			   =					int(d + k)
							__UpperCamelCase	:   int			   =					int(t + u + v + x)
							__UpperCamelCase	:   int			   =					int(z - (2 * c))
							__UpperCamelCase	:   int			   =					round(w % 7)
							# End math

							# Validate math
							if f != convert_datetime_days[dt_ck.weekday()]:
														raise AssertionError("The date was evaluated incorrectly. Contact developer.")

							# Response
							__UpperCamelCase	:   str			   =					F'Your date {date_input}, is a {days[str(_lowerCamelCase)]}!'
							return response


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		lowercase  :					Optional[int]													=       argparse.ArgumentParser(
		    description=(
		        'Find out what day of the week nearly any date is or was. Enter '
		        'date as a string in the mm-dd-yyyy or mm/dd/yyyy format'
		    )
		)
		parser.add_argument(
		    'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)'
		)
		lowercase  :					Tuple													=       parser.parse_args()
		zeller(args.date_input)