
"""simple docstring"""







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 			A__	:

		def __init__(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=13	,		_SCREAMING_SNAKE_CASE=30	,		_SCREAMING_SNAKE_CASE=2	,		_SCREAMING_SNAKE_CASE=3	,		_SCREAMING_SNAKE_CASE=True	,		_SCREAMING_SNAKE_CASE=True	,		_SCREAMING_SNAKE_CASE=32	,		_SCREAMING_SNAKE_CASE=2	,		_SCREAMING_SNAKE_CASE=4	,		_SCREAMING_SNAKE_CASE=37	,		_SCREAMING_SNAKE_CASE="gelu"	,		_SCREAMING_SNAKE_CASE=0.1	,		_SCREAMING_SNAKE_CASE=0.1	,		_SCREAMING_SNAKE_CASE=10	,		_SCREAMING_SNAKE_CASE=0.02	,		_SCREAMING_SNAKE_CASE=3	,		_SCREAMING_SNAKE_CASE=None	,		_SCREAMING_SNAKE_CASE=2	,		):
			__lowerCAmelCase      :						str						      =				parent
			__lowerCAmelCase      :						Any						      =				batch_size
			__lowerCAmelCase      :						Optional[int]						      =				image_size
			__lowerCAmelCase      :						Union[str, Any]						      =				patch_size
			__lowerCAmelCase      :						Optional[Any]						      =				num_channels
			__lowerCAmelCase      :						Optional[Any]						      =				is_training
			__lowerCAmelCase      :						Tuple						      =				use_labels
			__lowerCAmelCase      :						Union[str, Any]						      =				hidden_size
			__lowerCAmelCase      :						Optional[Any]						      =				num_hidden_layers
			__lowerCAmelCase      :						Dict						      =				num_attention_heads
			__lowerCAmelCase      :						Tuple						      =				intermediate_size
			__lowerCAmelCase      :						Any						      =				hidden_act
			__lowerCAmelCase      :						List[Any]						      =				hidden_dropout_prob
			__lowerCAmelCase      :						int						      =				attention_probs_dropout_prob
			__lowerCAmelCase      :						Dict						      =				type_sequence_label_size
			__lowerCAmelCase      :						List[str]						      =				initializer_range
			__lowerCAmelCase      :						str						      =				scope
			__lowerCAmelCase      :						List[str]						      =				encoder_stride

			# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
			__lowerCAmelCase      :						List[str]						      =				(image_size // patch_size) ** 2
			__lowerCAmelCase      :						Optional[int]						      =				num_patches + 2

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Optional[Any]						      =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

			__lowerCAmelCase      :						Tuple						      =				None
			if self.use_labels:
				__lowerCAmelCase      :						Union[str, Any]						      =				ids_tensor([self.batch_size]	,		self.type_sequence_label_size			)

			__lowerCAmelCase      :						Tuple						      =				self.get_config()

			return config, pixel_values, labels

		def 							__lowerCamelCase							(				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=_SCREAMING_SNAKE_CASE	,		initializer_range=self.initializer_range	,		encoder_stride=self.encoder_stride	,		)

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						str						      =				TFDeiTModel(config=_SCREAMING_SNAKE_CASE			)
			__lowerCAmelCase      :						str						      =				model(_SCREAMING_SNAKE_CASE			)
			self.parent.assertEqual(result.last_hidden_state.shape	,		(self.batch_size, self.seq_length, self.hidden_size)			)

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						str						      =				TFDeiTForMaskedImageModeling(config=_SCREAMING_SNAKE_CASE			)
			__lowerCAmelCase      :						Optional[int]						      =				model(_SCREAMING_SNAKE_CASE			)
			self.parent.assertEqual(
			    result.reconstruction.shape	,		(self.batch_size, self.num_channels, self.image_size, self.image_size)			)

			# test greyscale images
			__lowerCAmelCase      :						int						      =				1
			__lowerCAmelCase      :						int						      =				TFDeiTForMaskedImageModeling(_SCREAMING_SNAKE_CASE			)

			__lowerCAmelCase      :						int						      =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
			__lowerCAmelCase      :						Any						      =				model(_SCREAMING_SNAKE_CASE			)
			self.parent.assertEqual(result.reconstruction.shape	,		(self.batch_size, 1, self.image_size, self.image_size)			)

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						str						      =				self.type_sequence_label_size
			__lowerCAmelCase      :						Optional[Any]						      =				TFDeiTForImageClassification(_SCREAMING_SNAKE_CASE			)
			__lowerCAmelCase      :						List[Any]						      =				model(_SCREAMING_SNAKE_CASE	,		labels=_SCREAMING_SNAKE_CASE			)
			self.parent.assertEqual(result.logits.shape	,		(self.batch_size, self.type_sequence_label_size)			)

			# test greyscale images
			__lowerCAmelCase      :						str						      =				1
			__lowerCAmelCase      :						Tuple						      =				TFDeiTForImageClassification(_SCREAMING_SNAKE_CASE			)

			__lowerCAmelCase      :						int						      =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
			__lowerCAmelCase      :						List[str]						      =				model(_SCREAMING_SNAKE_CASE	,		labels=_SCREAMING_SNAKE_CASE			)
			self.parent.assertEqual(result.logits.shape	,		(self.batch_size, self.type_sequence_label_size)			)







		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Optional[int]						      =				self.prepare_config_and_inputs()
			__lowerCAmelCase      :						Tuple						      =				config_and_inputs
			__lowerCAmelCase      :						Optional[Any]						      =				{'pixel_values': pixel_values}
			return config, inputs_dict




@require_tf
class 			A__	(     _lowerCamelCase	,					_lowerCamelCase	,					unittest.TestCase):
		A_						:	Any           =     (
		    (
		        TFDeiTModel,
		        TFDeiTForImageClassification,
		        TFDeiTForImageClassificationWithTeacher,
		        TFDeiTForMaskedImageModeling,
		    )
		    if is_tf_available()
		    else ()
		)
		A_						:	str           =     (
		    {
		        'feature-extraction': TFDeiTModel,
		        'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
		    }
		    if is_tf_available()
		    else {}
		)

		A_						:	Optional[int]           =     False
		A_						:	Union[str, Any]           =     False
		A_						:	Tuple           =     False
		A_						:	Union[str, Any]           =     False

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						str						      =				TFDeiTModelTester(self			)
			__lowerCAmelCase      :						Union[str, Any]						      =				ConfigTester(self	,		config_class=_SCREAMING_SNAKE_CASE	,		has_text_modality=_SCREAMING_SNAKE_CASE	,		hidden_size=37			)

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

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

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Optional[int]						      =				self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				__lowerCAmelCase      :						Tuple						      =				model_class(_SCREAMING_SNAKE_CASE			)
				self.assertIsInstance(model.get_input_embeddings()	,		(tf.keras.layers.Layer)			)
				__lowerCAmelCase      :						List[Any]						      =				model.get_output_embeddings()
				self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE	,		tf.keras.layers.Dense			)			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						str						      =				self.model_tester.prepare_config_and_inputs_for_common()

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

				__lowerCAmelCase      :						str						      =				['pixel_values']
				self.assertListEqual(arg_names[:1]	,		_SCREAMING_SNAKE_CASE			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Dict						      =				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Tuple						      =				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_masked_image_modeling(*_SCREAMING_SNAKE_CASE			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Optional[Any]						      =				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE			)

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=False			):
			__lowerCAmelCase      :						List[str]						      =				super()._prepare_for_class(_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		return_labels=_SCREAMING_SNAKE_CASE			)

			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 							__lowerCamelCase							(				self			):
			for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__lowerCAmelCase      :						int						      =				TFDeiTModel.from_pretrained(_SCREAMING_SNAKE_CASE			)
				self.assertIsNotNone(_SCREAMING_SNAKE_CASE			)



def    __lowerCAmelCase    ():
	__lowerCAmelCase      :						Optional[Any]						      =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
	return image




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

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







		@slow
		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Dict						      =				TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224'			)

			__lowerCAmelCase      :						List[str]						      =				self.default_image_processor
			__lowerCAmelCase      :						str						      =				prepare_img()
			__lowerCAmelCase      :						Dict						      =				image_processor(images=_SCREAMING_SNAKE_CASE	,		return_tensors='tf'			)

			# forward pass
			__lowerCAmelCase      :						str						      =				model(**_SCREAMING_SNAKE_CASE			)

			# verify the logits
			__lowerCAmelCase      :						Union[str, Any]						      =				tf.TensorShape((1, 10_00)			)
			self.assertEqual(outputs.logits.shape	,		_SCREAMING_SNAKE_CASE			)

			__lowerCAmelCase      :						Any						      =				tf.constant([-1.0266, 0.1912, -1.2861]			)

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

"""simple docstring"""







from typing import Optional
from urllib.parse import quote

import huggingface_hub as hfh
from packaging import version
def    __lowerCAmelCase    (_UpperCamelCase	,  _UpperCamelCase	,  _UpperCamelCase = None		):
	if version.parse(hfh.__version__		).release < version.parse('0.11.0'		).release:
		# old versions of hfh don't url-encode the file path
		__lowerCAmelCase      :						List[str]						      =				quote(_UpperCamelCase		)
	return hfh.hf_hub_url(_UpperCamelCase	,  _UpperCamelCase	,  repo_type='dataset'	,  revision=_UpperCamelCase		)