





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




					def __init__(		self				,						lowerCAmelCase_				,						lowerCAmelCase_=13				,						lowerCAmelCase_=30				,						lowerCAmelCase_=2				,						lowerCAmelCase_=3				,						lowerCAmelCase_=True				,						lowerCAmelCase_=True				,						lowerCAmelCase_=32				,						lowerCAmelCase_=2				,						lowerCAmelCase_=4				,						lowerCAmelCase_=37				,						lowerCAmelCase_="gelu"				,						lowerCAmelCase_=0.1				,						lowerCAmelCase_=0.1				,						lowerCAmelCase_=10				,						lowerCAmelCase_=0.02				,						lowerCAmelCase_=3				,						lowerCAmelCase_=None				,						lowerCAmelCase_=2				,						)		->							Optional[Any]:
										_snake_case									=				parent
										_snake_case									=				batch_size
										_snake_case									=				image_size
										_snake_case									=				patch_size
										_snake_case									=				num_channels
										_snake_case									=				is_training
										_snake_case									=				use_labels
										_snake_case									=				hidden_size
										_snake_case									=				num_hidden_layers
										_snake_case									=				num_attention_heads
										_snake_case									=				intermediate_size
										_snake_case									=				hidden_act
										_snake_case									=				hidden_dropout_prob
										_snake_case									=				attention_probs_dropout_prob
										_snake_case									=				type_sequence_label_size
										_snake_case									=				initializer_range
										_snake_case									=				scope
										_snake_case									=				encoder_stride

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




					def 	lowerCAmelCase			(		self  )		->							Tuple:
										_snake_case									=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

										_snake_case									=				None
										if self.use_labels:
															_snake_case									=				ids_tensor([self.batch_size]				,						self.type_sequence_label_size  )

										_snake_case									=				self.get_config()

										return config, pixel_values, labels




					def 	lowerCAmelCase			(		self  )		->							int:
										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=lowerCAmelCase_				,						initializer_range=self.initializer_range				,						encoder_stride=self.encoder_stride				,						)




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )		->							Dict:
										_snake_case									=				TFDeiTModel(config=lowerCAmelCase_  )
										_snake_case									=				model(lowerCAmelCase_  )
										self.parent.assertEqual(result.last_hidden_state.shape				,						(self.batch_size, self.seq_length, self.hidden_size)  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )		->							Any:
										_snake_case									=				TFDeiTForMaskedImageModeling(config=lowerCAmelCase_  )
										_snake_case									=				model(lowerCAmelCase_  )
										self.parent.assertEqual(
										    result.reconstruction.shape				,						(self.batch_size, self.num_channels, self.image_size, self.image_size)  )

										# test greyscale images
										_snake_case									=				1
										_snake_case									=				TFDeiTForMaskedImageModeling(lowerCAmelCase_  )

										_snake_case									=				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
										_snake_case									=				model(lowerCAmelCase_  )
										self.parent.assertEqual(result.reconstruction.shape				,						(self.batch_size, 1, self.image_size, self.image_size)  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_  )		->							Union[str, Any]:
										_snake_case									=				self.type_sequence_label_size
										_snake_case									=				TFDeiTForImageClassification(lowerCAmelCase_  )
										_snake_case									=				model(lowerCAmelCase_				,						labels=lowerCAmelCase_  )
										self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.type_sequence_label_size)  )

										# test greyscale images
										_snake_case									=				1
										_snake_case									=				TFDeiTForImageClassification(lowerCAmelCase_  )

										_snake_case									=				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
										_snake_case									=				model(lowerCAmelCase_				,						labels=lowerCAmelCase_  )
										self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.type_sequence_label_size)  )






					def 	lowerCAmelCase			(		self  )		->							Optional[Any]:
										_snake_case									=				self.prepare_config_and_inputs()
										_snake_case							,     _snake_case							,     _snake_case									=				config_and_inputs
										_snake_case									=				{'pixel_values': pixel_values}
										return config, inputs_dict





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

					lowerCAmelCase_							=	False
					lowerCAmelCase_							=	False
					lowerCAmelCase_							=	False
					lowerCAmelCase_							=	False




					def 	lowerCAmelCase			(		self  )		->							List[Any]:
										_snake_case									=				TFDeiTModelTester(self  )
										_snake_case									=				ConfigTester(self				,						config_class=lowerCAmelCase_				,						has_text_modality=lowerCAmelCase_				,						hidden_size=37  )




					def 	lowerCAmelCase			(		self  )		->							int:
										self.config_tester.run_common_tests()




					@unittest.skip(reason='DeiT does not use inputs_embeds'  )
					def 	lowerCAmelCase			(		self  )		->							Any:
										pass




					def 	lowerCAmelCase			(		self  )		->							int:
										_snake_case							,     _snake_case									=				self.model_tester.prepare_config_and_inputs_for_common()

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




					def 	lowerCAmelCase			(		self  )		->							Union[str, Any]:
										_snake_case							,     _snake_case									=				self.model_tester.prepare_config_and_inputs_for_common()

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

															_snake_case									=				['pixel_values']
															self.assertListEqual(arg_names[:1]				,						lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self  )		->							Optional[int]:
										_snake_case									=				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self  )		->							Any:
										_snake_case									=				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self  )		->							str:
										_snake_case									=				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_=False  )		->							Dict:
										_snake_case									=				super()._prepare_for_class(lowerCAmelCase_				,						lowerCAmelCase_				,						return_labels=lowerCAmelCase_  )

										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  )		->							Tuple:
										for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_snake_case									=				TFDeiTModel.from_pretrained(lowerCAmelCase_  )
															self.assertIsNotNone(lowerCAmelCase_  )





def 						lowerCamelCase__     (     )			-> str:



					'''simple docstring'''




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




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




					@cached_property
					def 	lowerCAmelCase			(		self  )		->							Optional[Any]:
										return (
										    DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224'  )
										    if is_vision_available()
										    else None
										)






					@slow
					def 	lowerCAmelCase			(		self  )		->							List[str]:
										_snake_case									=				TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224'  )

										_snake_case									=				self.default_image_processor
										_snake_case									=				prepare_img()
										_snake_case									=				image_processor(images=lowerCAmelCase_				,						return_tensors='tf'  )

										# forward pass
										_snake_case									=				model(**lowerCAmelCase_  )

										# verify the logits
										_snake_case									=				tf.TensorShape((1, 1000)  )
										self.assertEqual(outputs.logits.shape				,						lowerCAmelCase_  )

										_snake_case									=				tf.constant([-1.02_66, 0.19_12, -1.28_61]  )

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










from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
					import PIL

UpperCAmelCase_      							=     logging.get_logger(__name__)





def 						lowerCamelCase__     (     UpperCamelCase__			:       Tuple						)			-> List[List[ImageInput]]:



					'''simple docstring'''




					if isinstance(UpperCamelCase__       ,    (list, tuple)						) and isinstance(videos[0]       ,    (list, tuple)						) and is_valid_image(videos[0][0]						):
										return videos

					elif isinstance(UpperCamelCase__       ,    (list, tuple)						) and is_valid_image(videos[0]						):
										return [videos]

					elif is_valid_image(UpperCamelCase__						):
										return [[videos]]

					raise ValueError(F'''Could not make batched video from {videos}'''						)




class 			UpperCamelCase_		(  _lowerCamelCase					):
					lowerCAmelCase_							=	['''pixel_values''']




					def __init__(		self				,						lowerCAmelCase_ = True				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = PILImageResampling.BILINEAR				,						lowerCAmelCase_ = True				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = True				,						lowerCAmelCase_ = 1 / 255				,						lowerCAmelCase_ = True				,						lowerCAmelCase_ = True				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						**lowerCAmelCase_				,						)		->							None:
										super().__init__(**lowerCAmelCase_  )
										_snake_case									=				size if size is not None else {'shortest_edge': 256}
										_snake_case									=				get_size_dict(lowerCAmelCase_				,						default_to_square=lowerCAmelCase_  )
										_snake_case									=				crop_size if crop_size is not None else {'height': 224, 'width': 224}
										_snake_case									=				get_size_dict(lowerCAmelCase_				,						param_name='crop_size'  )

										_snake_case									=				do_resize
										_snake_case									=				size
										_snake_case									=				do_center_crop
										_snake_case									=				crop_size
										_snake_case									=				resample
										_snake_case									=				do_rescale
										_snake_case									=				rescale_factor
										_snake_case									=				offset
										_snake_case									=				do_normalize
										_snake_case									=				image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
										_snake_case									=				image_std if image_std is not None else IMAGENET_STANDARD_STD




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_ = PILImageResampling.BILINEAR				,						lowerCAmelCase_ = None				,						**lowerCAmelCase_				,						)		->							np.ndarray:
										_snake_case									=				get_size_dict(lowerCAmelCase_				,						default_to_square=lowerCAmelCase_  )
										if "shortest_edge" in size:
															_snake_case									=				get_resize_output_image_size(lowerCAmelCase_				,						size['shortest_edge']				,						default_to_square=lowerCAmelCase_  )
										elif "height" in size and "width" in size:
															_snake_case									=				(size['height'], size['width'])
										else:
															raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''  )
										return resize(lowerCAmelCase_				,						size=lowerCAmelCase_				,						resample=lowerCAmelCase_				,						data_format=lowerCAmelCase_				,						**lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_ = None				,						**lowerCAmelCase_				,						)		->							np.ndarray:
										_snake_case									=				get_size_dict(lowerCAmelCase_  )
										if "height" not in size or "width" not in size:
															raise ValueError(F'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}'''  )
										return center_crop(lowerCAmelCase_				,						size=(size['height'], size['width'])				,						data_format=lowerCAmelCase_				,						**lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_ = True				,						lowerCAmelCase_ = None				,						**lowerCAmelCase_				,						)		->							int:
										_snake_case									=				image.astype(np.floataa  )
										if offset:
															_snake_case									=				image - (scale / 2)
										return rescale(lowerCAmelCase_				,						scale=lowerCAmelCase_				,						data_format=lowerCAmelCase_				,						**lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_				,						lowerCAmelCase_ = None				,						**lowerCAmelCase_				,						)		->							np.ndarray:
										return normalize(lowerCAmelCase_				,						mean=lowerCAmelCase_				,						std=lowerCAmelCase_				,						data_format=lowerCAmelCase_				,						**lowerCAmelCase_  )




					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = ChannelDimension.FIRST				,						)		->							np.ndarray:
										if do_resize and size is None or resample is None:
															raise ValueError('Size and resample must be specified if do_resize is True.'  )

										if do_center_crop and crop_size is None:
															raise ValueError('Crop size must be specified if do_center_crop is True.'  )

										if do_rescale and rescale_factor is None:
															raise ValueError('Rescale factor must be specified if do_rescale is True.'  )

										if do_normalize and (image_mean is None or image_std is None):
															raise ValueError('Image mean and std must be specified if do_normalize is True.'  )

										if offset and not do_rescale:
															raise ValueError('For offset, do_rescale must also be set to True.'  )

										# All transformations expect numpy arrays.
										_snake_case									=				to_numpy_array(lowerCAmelCase_  )

										if do_resize:
															_snake_case									=				self.resize(image=lowerCAmelCase_				,						size=lowerCAmelCase_				,						resample=lowerCAmelCase_  )

										if do_center_crop:
															_snake_case									=				self.center_crop(lowerCAmelCase_				,						size=lowerCAmelCase_  )

										if do_rescale:
															_snake_case									=				self.rescale(image=lowerCAmelCase_				,						scale=lowerCAmelCase_				,						offset=lowerCAmelCase_  )

										if do_normalize:
															_snake_case									=				self.normalize(image=lowerCAmelCase_				,						mean=lowerCAmelCase_				,						std=lowerCAmelCase_  )

										_snake_case									=				to_channel_dimension_format(lowerCAmelCase_				,						lowerCAmelCase_  )
										return image






					def 	lowerCAmelCase			(		self				,						lowerCAmelCase_				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = None				,						lowerCAmelCase_ = ChannelDimension.FIRST				,						**lowerCAmelCase_				,						)		->							PIL.Image.Image:
										_snake_case									=				do_resize if do_resize is not None else self.do_resize
										_snake_case									=				resample if resample is not None else self.resample
										_snake_case									=				do_center_crop if do_center_crop is not None else self.do_center_crop
										_snake_case									=				do_rescale if do_rescale is not None else self.do_rescale
										_snake_case									=				rescale_factor if rescale_factor is not None else self.rescale_factor
										_snake_case									=				offset if offset is not None else self.offset
										_snake_case									=				do_normalize if do_normalize is not None else self.do_normalize
										_snake_case									=				image_mean if image_mean is not None else self.image_mean
										_snake_case									=				image_std if image_std is not None else self.image_std

										_snake_case									=				size if size is not None else self.size
										_snake_case									=				get_size_dict(lowerCAmelCase_				,						default_to_square=lowerCAmelCase_  )
										_snake_case									=				crop_size if crop_size is not None else self.crop_size
										_snake_case									=				get_size_dict(lowerCAmelCase_				,						param_name='crop_size'  )

										if not valid_images(lowerCAmelCase_  ):
															raise ValueError(
															    'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
															    'torch.Tensor, tf.Tensor or jax.ndarray.'  )

										_snake_case									=				make_batched(lowerCAmelCase_  )

										_snake_case									=				[
										    [
										        self._preprocess_image(
										            image=lowerCAmelCase_				,						do_resize=lowerCAmelCase_				,						size=lowerCAmelCase_				,						resample=lowerCAmelCase_				,						do_center_crop=lowerCAmelCase_				,						crop_size=lowerCAmelCase_				,						do_rescale=lowerCAmelCase_				,						rescale_factor=lowerCAmelCase_				,						offset=lowerCAmelCase_				,						do_normalize=lowerCAmelCase_				,						image_mean=lowerCAmelCase_				,						image_std=lowerCAmelCase_				,						data_format=lowerCAmelCase_				,						)
										        for img in video
										    ]
										    for video in videos
										]

										_snake_case									=				{'pixel_values': videos}
										return BatchFeature(data=lowerCAmelCase_				,						tensor_type=lowerCAmelCase_  )



