





import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch
	from torch import nn

	from transformers import SwiftFormerForImageClassification, SwiftFormerModel
	from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import ViTImageProcessor




class 	UpperCamelCase_							:


							def __init__(				self     :Optional[Any]				,					__A     :List[Any]				,					__A     :int=13				,					__A     :Tuple=3				,					__A     :Any=True				,					__A     :Any=True				,					__A     :Optional[Any]=0.1				,					__A     :List[Any]=0.1				,					__A     :Dict=224				,					__A     :Optional[Any]=1000				,					__A     :List[Any]=[3, 3, 6, 4]				,					__A     :List[Any]=[48, 56, 112, 220]				,					) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   parent
									SCREAMING_SNAKE_CASE__								=   batch_size
									SCREAMING_SNAKE_CASE__								=   num_channels
									SCREAMING_SNAKE_CASE__								=   is_training
									SCREAMING_SNAKE_CASE__								=   use_labels
									SCREAMING_SNAKE_CASE__								=   hidden_dropout_prob
									SCREAMING_SNAKE_CASE__								=   attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE__								=   num_labels
									SCREAMING_SNAKE_CASE__								=   image_size
									SCREAMING_SNAKE_CASE__								=   layer_depths
									SCREAMING_SNAKE_CASE__								=   embed_dims


							def   _snake_case	(				self     :Dict		) -> Optional[int]:



									"""simple docstring"""



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

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

									SCREAMING_SNAKE_CASE__								=   self.get_config()

									return config, pixel_values, labels


							def   _snake_case	(				self     :Union[str, Any]		) -> int:



									"""simple docstring"""



									return SwiftFormerConfig(
									    depths=self.layer_depths				,					embed_dims=self.embed_dims				,					mlp_ratio=4				,					downsamples=[True, True, True, True]				,					hidden_act="""gelu"""				,					num_labels=self.num_labels				,					down_patch_size=3				,					down_stride=2				,					down_pad=1				,					drop_rate=0.0				,					drop_path_rate=0.0				,					use_layer_scale=__A				,					layer_scale_init_value=1E-5				,					)


							def   _snake_case	(				self     :Tuple				,					__A     :Dict				,					__A     :str				,					__A     :List[Any]		) -> Any:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   SwiftFormerModel(config=__A		)
									model.to(__A		)
									model.eval()
									SCREAMING_SNAKE_CASE__								=   model(__A		)
									self.parent.assertEqual(result.last_hidden_state.shape				,					(self.batch_size, self.embed_dims[-1], 7, 7)		)


							def   _snake_case	(				self     :Tuple				,					__A     :str				,					__A     :List[str]				,					__A     :List[str]		) -> Any:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.num_labels
									SCREAMING_SNAKE_CASE__								=   SwiftFormerForImageClassification(__A		)
									model.to(__A		)
									model.eval()
									SCREAMING_SNAKE_CASE__								=   model(__A				,					labels=__A		)
									self.parent.assertEqual(result.logits.shape				,					(self.batch_size, self.num_labels)		)

									SCREAMING_SNAKE_CASE__								=   SwiftFormerForImageClassification(__A		)
									model.to(__A		)
									model.eval()

									SCREAMING_SNAKE_CASE__								=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)
									SCREAMING_SNAKE_CASE__								=   model(__A		)
									self.parent.assertEqual(result.logits.shape				,					(self.batch_size, self.num_labels)		)


							def   _snake_case	(				self     :int		) -> str:



									"""simple docstring"""



									((SCREAMING_SNAKE_CASE__)						,    (SCREAMING_SNAKE_CASE__)						,    (SCREAMING_SNAKE_CASE__))								=   self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE__								=   {"""pixel_values""": pixel_values}
									return config, inputs_dict




@require_torch
class 	UpperCamelCase_							(  UpperCamelCase__					,	UpperCamelCase__					,	unittest.TestCase     ):
							lowerCamelCase_							     =       (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
							lowerCamelCase_							     =       (
							    {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification}
							    if is_torch_available()
							    else {}
							)

							lowerCamelCase_							     =       False
							lowerCamelCase_							     =       False
							lowerCamelCase_							     =       False
							lowerCamelCase_							     =       False
							lowerCamelCase_							     =       False


							def   _snake_case	(				self     :Tuple		) -> Dict:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   SwiftFormerModelTester(self		)
									SCREAMING_SNAKE_CASE__								=   ConfigTester(
									    self				,					config_class=__A				,					has_text_modality=__A				,					hidden_size=37				,					num_attention_heads=12				,					num_hidden_layers=12				,					)


							def   _snake_case	(				self     :Dict		) -> Tuple:



									"""simple docstring"""



									self.config_tester.run_common_tests()


							@unittest.skip(reason="""SwiftFormer does not use inputs_embeds"""		)
							def   _snake_case	(				self     :Tuple		) -> Union[str, Any]:



									"""simple docstring"""



									pass


							def   _snake_case	(				self     :Optional[Any]		) -> Optional[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											SCREAMING_SNAKE_CASE__								=   model_class(__A		)
											SCREAMING_SNAKE_CASE__								=   model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(__A				,					nn.Linear		)		)


							def   _snake_case	(				self     :List[str]		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs_for_common()

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

											SCREAMING_SNAKE_CASE__								=   ["""pixel_values"""]
											self.assertListEqual(arg_names[:1]				,					__A		)


							def   _snake_case	(				self     :List[str]		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__A		)


							def   _snake_case	(				self     :List[str]		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*__A		)


							@slow
							def   _snake_case	(				self     :Dict		) -> str:



									"""simple docstring"""



									for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											SCREAMING_SNAKE_CASE__								=   SwiftFormerModel.from_pretrained(__A		)
											self.assertIsNotNone(__A		)


							@unittest.skip(reason="""SwiftFormer does not output attentions"""		)
							def   _snake_case	(				self     :Tuple		) -> Optional[Any]:



									"""simple docstring"""



									pass


							def   _snake_case	(				self     :Union[str, Any]		) -> List[Any]:



									"""simple docstring"""



									def check_hidden_states_output(__A     :List[Any]				,					__A     :str				,					__A     :List[str]		):
											SCREAMING_SNAKE_CASE__								=   model_class(__A		)
											model.to(__A		)
											model.eval()

											with torch.no_grad():
													SCREAMING_SNAKE_CASE__								=   model(**self._prepare_for_class(__A				,					__A		)		)

											SCREAMING_SNAKE_CASE__								=   outputs.hidden_states

											SCREAMING_SNAKE_CASE__								=   8
											self.assertEqual(len(__A		)				,					__A		)  # TODO

											# SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
											# with the width and height being successively divided by 2, after every 2 blocks
											for i in range(len(__A		)		):
													self.assertEqual(
													    hidden_states[i].shape				,					torch.Size(
													        [
													            self.model_tester.batch_size,
													            self.model_tester.embed_dims[i // 2],
													            (self.model_tester.image_size // 4) // 2 ** (i // 2),
													            (self.model_tester.image_size // 4) // 2 ** (i // 2),
													        ]		)				,					)

									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											SCREAMING_SNAKE_CASE__								=   True
											check_hidden_states_output(__A				,					__A				,					__A		)

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

											check_hidden_states_output(__A				,					__A				,					__A		)


							def   _snake_case	(				self     :Optional[int]		) -> Optional[Any]:



									"""simple docstring"""



									def _config_zero_init(__A     :Optional[int]		):
											SCREAMING_SNAKE_CASE__								=   copy.deepcopy(__A		)
											for key in configs_no_init.__dict__.keys():
													if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
															setattr(__A				,					__A				,					1E-10		)
													if isinstance(getattr(__A				,					__A				,					__A		)				,					__A		):
															SCREAMING_SNAKE_CASE__								=   _config_zero_init(getattr(__A				,					__A		)		)
															setattr(__A				,					__A				,					__A		)
											return configs_no_init

									SCREAMING_SNAKE_CASE__						,    SCREAMING_SNAKE_CASE__								=   self.model_tester.prepare_config_and_inputs_for_common()

									SCREAMING_SNAKE_CASE__								=   _config_zero_init(__A		)
									for model_class in self.all_model_classes:
											SCREAMING_SNAKE_CASE__								=   model_class(config=__A		)
											for name, param in model.named_parameters():
													if param.requires_grad:
															self.assertIn(
															    ((param.data.mean() * 1E9) / 1E9).round().item()				,					[0.0, 1.0]				,					msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''				,					)


							@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""		)
							def   _snake_case	(				self     :str		) -> str:



									"""simple docstring"""



									pass






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




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


							@cached_property
							def   _snake_case	(				self     :Optional[int]		) -> List[Any]:



									"""simple docstring"""



									return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs"""		) if is_vision_available() else None


							@slow
							def   _snake_case	(				self     :List[Any]		) -> str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs"""		).to(__A		)

									SCREAMING_SNAKE_CASE__								=   self.default_image_processor
									SCREAMING_SNAKE_CASE__								=   prepare_img()
									SCREAMING_SNAKE_CASE__								=   image_processor(images=__A				,					return_tensors="""pt"""		).to(__A		)

									# forward pass
									with torch.no_grad():
											SCREAMING_SNAKE_CASE__								=   model(**__A		)

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

									SCREAMING_SNAKE_CASE__								=   torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]]		).to(__A		)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]				,					__A				,					atol=1E-4		)		)






import argparse
import datetime






def 					SCREAMING_SNAKE_CASE__				(							UpperCamelCase__:				str     ):
		SCREAMING_SNAKE_CASE__								=   {
		    """0""": """Sunday""",
		    """1""": """Monday""",
		    """2""": """Tuesday""",
		    """3""": """Wednesday""",
		    """4""": """Thursday""",
		    """5""": """Friday""",
		    """6""": """Saturday""",
		}

		SCREAMING_SNAKE_CASE__								=   {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0}

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

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

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

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

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

		# Get year
		SCREAMING_SNAKE_CASE__								=   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
		SCREAMING_SNAKE_CASE__								=   datetime.date(int(UpperCamelCase__     )       , int(UpperCamelCase__     )       , int(UpperCamelCase__     )     )

		# Start math
		if m <= 2:
				SCREAMING_SNAKE_CASE__								=   y - 1
				SCREAMING_SNAKE_CASE__								=   m + 12
		# maths var
		SCREAMING_SNAKE_CASE__								=   int(str(UpperCamelCase__     )[:2]     )
		SCREAMING_SNAKE_CASE__								=   int(str(UpperCamelCase__     )[2:]     )
		SCREAMING_SNAKE_CASE__								=   int(2.6 * m - 5.3_9     )
		SCREAMING_SNAKE_CASE__								=   int(c / 4     )
		SCREAMING_SNAKE_CASE__								=   int(k / 4     )
		SCREAMING_SNAKE_CASE__								=   int(d + k     )
		SCREAMING_SNAKE_CASE__								=   int(t + u + v + x     )
		SCREAMING_SNAKE_CASE__								=   int(z - (2 * c)     )
		SCREAMING_SNAKE_CASE__								=   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
		SCREAMING_SNAKE_CASE__								=   f'''Your date {date_input}, is a {days[str(UpperCamelCase__     )]}!'''
		return response


if __name__ == "__main__":
	import doctest

	doctest.testmod()
	_lowerCamelCase 					=      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)'
	)
	_lowerCamelCase 					=      parser.parse_args()
	zeller(args.date_input)