


from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
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 (
				    TFDeiTForImageClassification,
				    TFDeiTForImageClassificationWithTeacher,
				    TFDeiTForMaskedImageModeling,
				    TFDeiTModel,
				)
				from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import DeiTImageProcessor




class 							lowerCamelCase   :


	def __init__(    self				,     lowercase__				,     lowercase__=1_3				,     lowercase__=3_0				,     lowercase__=2				,     lowercase__=3				,     lowercase__=True				,     lowercase__=True				,     lowercase__=3_2				,     lowercase__=2				,     lowercase__=4				,     lowercase__=3_7				,     lowercase__="gelu"				,     lowercase__=0.1				,     lowercase__=0.1				,     lowercase__=1_0				,     lowercase__=0.0_2				,     lowercase__=3				,     lowercase__=None				,     lowercase__=2				,     ):
							__UpperCAmelCase			:							Tuple	    =	parent
							__UpperCAmelCase			:							Optional[int]	    =	batch_size
							__UpperCAmelCase			:							int	    =	image_size
							__UpperCAmelCase			:							Union[str, Any]	    =	patch_size
							__UpperCAmelCase			:							List[str]	    =	num_channels
							__UpperCAmelCase			:							str	    =	is_training
							__UpperCAmelCase			:							str	    =	use_labels
							__UpperCAmelCase			:							Dict	    =	hidden_size
							__UpperCAmelCase			:							int	    =	num_hidden_layers
							__UpperCAmelCase			:							Any	    =	num_attention_heads
							__UpperCAmelCase			:							List[str]	    =	intermediate_size
							__UpperCAmelCase			:							int	    =	hidden_act
							__UpperCAmelCase			:							Union[str, Any]	    =	hidden_dropout_prob
							__UpperCAmelCase			:							Any	    =	attention_probs_dropout_prob
							__UpperCAmelCase			:							int	    =	type_sequence_label_size
							__UpperCAmelCase			:							Optional[Any]	    =	initializer_range
							__UpperCAmelCase			:							Any	    =	scope
							__UpperCAmelCase			:							List[str]	    =	encoder_stride

							# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
							__UpperCAmelCase			:							Tuple	    =	(image_size // patch_size) ** 2
							__UpperCAmelCase			:							Dict	    =	num_patches + 2


	def  A(    self):
							__UpperCAmelCase			:							List[Any]	    =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

							__UpperCAmelCase			:							Optional[Any]	    =	self.get_config()

							return config, pixel_values, labels


	def  A(    self):
							return DeiTConfig(
							    image_size=self.image_size				,     patch_size=self.patch_size				,     num_channels=self.num_channels				,     hidden_size=self.hidden_size				,     num_hidden_layers=self.num_hidden_layers				,     num_attention_heads=self.num_attention_heads				,     intermediate_size=self.intermediate_size				,     hidden_act=self.hidden_act				,     hidden_dropout_prob=self.hidden_dropout_prob				,     attention_probs_dropout_prob=self.attention_probs_dropout_prob				,     is_decoder=lowercase__				,     initializer_range=self.initializer_range				,     encoder_stride=self.encoder_stride				,     )


	def  A(    self				,     lowercase__				,     lowercase__				,     lowercase__):
							__UpperCAmelCase			:							Tuple	    =	TFDeiTModel(config=lowercase__)
							__UpperCAmelCase			:							Tuple	    =	model(lowercase__)
							self.parent.assertEqual(result.last_hidden_state.shape				,     (self.batch_size, self.seq_length, self.hidden_size))


	def  A(    self				,     lowercase__				,     lowercase__				,     lowercase__):
							__UpperCAmelCase			:							int	    =	TFDeiTForMaskedImageModeling(config=lowercase__)
							__UpperCAmelCase			:							Optional[int]	    =	model(lowercase__)
							self.parent.assertEqual(
							    result.reconstruction.shape				,     (self.batch_size, self.num_channels, self.image_size, self.image_size))

							# test greyscale images
							__UpperCAmelCase			:							List[Any]	    =	1
							__UpperCAmelCase			:							Union[str, Any]	    =	TFDeiTForMaskedImageModeling(lowercase__)

							__UpperCAmelCase			:							Any	    =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
							__UpperCAmelCase			:							Tuple	    =	model(lowercase__)
							self.parent.assertEqual(result.reconstruction.shape				,     (self.batch_size, 1, self.image_size, self.image_size))


	def  A(    self				,     lowercase__				,     lowercase__				,     lowercase__):
							__UpperCAmelCase			:							Optional[Any]	    =	self.type_sequence_label_size
							__UpperCAmelCase			:							Union[str, Any]	    =	TFDeiTForImageClassification(lowercase__)
							__UpperCAmelCase			:							int	    =	model(lowercase__				,     labels=lowercase__)
							self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.type_sequence_label_size))

							# test greyscale images
							__UpperCAmelCase			:							Union[str, Any]	    =	1
							__UpperCAmelCase			:							Optional[Any]	    =	TFDeiTForImageClassification(lowercase__)

							__UpperCAmelCase			:							Union[str, Any]	    =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
							__UpperCAmelCase			:							Union[str, Any]	    =	model(lowercase__				,     labels=lowercase__)
							self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.type_sequence_label_size))


	def  A(    self):
							__UpperCAmelCase			:							Dict	    =	self.prepare_config_and_inputs()
							__UpperCAmelCase    ,      __UpperCAmelCase    ,      __UpperCAmelCase			:							str	    =	config_and_inputs
							__UpperCAmelCase			:							Any	    =	{'''pixel_values''': pixel_values}
							return config, inputs_dict






@require_tf
class 							lowerCamelCase   (  _UpperCamelCase							,						_UpperCamelCase							,						unittest.TestCase ):
	_lowerCAmelCase     :		Optional[int]										=						(
	    (
	        TFDeiTModel,
	        TFDeiTForImageClassification,
	        TFDeiTForImageClassificationWithTeacher,
	        TFDeiTForMaskedImageModeling,
	    )
	    if is_tf_available()
	    else ()
	)
	_lowerCAmelCase     :		Dict										=						(
	    {
	        '''feature-extraction''': TFDeiTModel,
	        '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
	    }
	    if is_tf_available()
	    else {}
	)

	_lowerCAmelCase     :		Any										=						False
	_lowerCAmelCase     :		Union[str, Any]										=						False
	_lowerCAmelCase     :		Any										=						False
	_lowerCAmelCase     :		Optional[Any]										=						False


	def  A(    self):
							__UpperCAmelCase			:							Tuple	    =	TFDeiTModelTester(self)
							__UpperCAmelCase			:							str	    =	ConfigTester(self				,     config_class=lowercase__				,     has_text_modality=lowercase__				,     hidden_size=3_7)


	def  A(    self):
							self.config_tester.run_common_tests()


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


	def  A(    self):
							__UpperCAmelCase    ,      __UpperCAmelCase			:							List[Any]	    =	self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													__UpperCAmelCase			:							Any	    =	model_class(lowercase__)
													self.assertIsInstance(model.get_input_embeddings()				,     (tf.keras.layers.Layer))
													__UpperCAmelCase			:							Any	    =	model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowercase__				,     tf.keras.layers.Dense))


	def  A(    self):
							__UpperCAmelCase    ,      __UpperCAmelCase			:							Union[str, Any]	    =	self.model_tester.prepare_config_and_inputs_for_common()

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

													__UpperCAmelCase			:							int	    =	['''pixel_values''']
													self.assertListEqual(arg_names[:1]				,     lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							int	    =	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							Optional[Any]	    =	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*lowercase__)


	def  A(    self):
							__UpperCAmelCase			:							Any	    =	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowercase__)


	def  A(    self				,     lowercase__				,     lowercase__				,     lowercase__=False):
							__UpperCAmelCase			:							Tuple	    =	super()._prepare_for_class(lowercase__				,     lowercase__				,     return_labels=lowercase__)

							if return_labels:
													if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters:
																			del inputs_dict["labels"]

							return inputs_dict


	@slow
	def  A(    self):
							for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__UpperCAmelCase			:							List[str]	    =	TFDeiTModel.from_pretrained(lowercase__)
													self.assertIsNotNone(lowercase__)






def     __SCREAMING_SNAKE_CASE							(       )		->     Dict:




						'''simple docstring'''







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





@require_tf
@require_vision
class 							lowerCamelCase   (  unittest.TestCase ):


	@cached_property
	def  A(    self):
							return (
							    DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''')
							    if is_vision_available()
							    else None
							)


	@slow
	def  A(    self):
							__UpperCAmelCase			:							str	    =	TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''')

							__UpperCAmelCase			:							Union[str, Any]	    =	self.default_image_processor
							__UpperCAmelCase			:							int	    =	prepare_img()
							__UpperCAmelCase			:							Any	    =	image_processor(images=lowercase__				,     return_tensors='''tf''')

							# forward pass
							__UpperCAmelCase			:							Any	    =	model(**lowercase__)

							# verify the logits
							__UpperCAmelCase			:							List[Any]	    =	tf.TensorShape((1, 1_0_0_0))
							self.assertEqual(outputs.logits.shape				,     lowercase__)

							__UpperCAmelCase			:							Tuple	    =	tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1])

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





def     __SCREAMING_SNAKE_CASE							(       )		->     Optional[int]:




						'''simple docstring'''







						__UpperCAmelCase			:							str	    =	[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

						__UpperCAmelCase			:							Union[str, Any]	    =	6
						__UpperCAmelCase			:							Optional[Any]	    =	1
						__UpperCAmelCase			:							Tuple	    =	1901

						__UpperCAmelCase			:							Any	    =	0

						while year < 2001:
												day += 7

												if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
																		if day > days_per_month[month - 1] and month != 2:
																								month += 1
																								__UpperCAmelCase			:							Optional[int]	    =	day - days_per_month[month - 2]
																		elif day > 29 and month == 2:
																								month += 1
																								__UpperCAmelCase			:							Optional[Any]	    =	day - 29
												else:
																		if day > days_per_month[month - 1]:
																								month += 1
																								__UpperCAmelCase			:							Optional[Any]	    =	day - days_per_month[month - 2]

												if month > 12:
																		year += 1
																		__UpperCAmelCase			:							int	    =	1

												if year < 2001 and day == 1:
																		sundays += 1
						return sundays


if __name__ == "__main__":
				print(solution())

