





'''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 							__UpperCAmelCase     :







		'''simple docstring'''







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

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







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

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

			A							     =					self.get_config()

			return config, pixel_values, labels







		def 				A   (self  :					Dict					):
			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 				A   (self  :					Any					,					_lowerCAmelCase  :					List[Any]					,					_lowerCAmelCase  :					List[Any]					,					_lowerCAmelCase  :					Any					):
			A							     =					TFDeiTModel(config=__lowerCAmelCase					)
			A							     =					model(__lowerCAmelCase					)
			self.parent.assertEqual(result.last_hidden_state.shape					,					(self.batch_size, self.seq_length, self.hidden_size)					)







		def 				A   (self  :					str					,					_lowerCAmelCase  :					Any					,					_lowerCAmelCase  :					int					,					_lowerCAmelCase  :					Dict					):
			A							     =					TFDeiTForMaskedImageModeling(config=__lowerCAmelCase					)
			A							     =					model(__lowerCAmelCase					)
			self.parent.assertEqual(
			    result.reconstruction.shape					,					(self.batch_size, self.num_channels, self.image_size, self.image_size)					)

			# test greyscale images
			A							     =					1
			A							     =					TFDeiTForMaskedImageModeling(__lowerCAmelCase					)

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







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

			# test greyscale images
			A							     =					1
			A							     =					TFDeiTForImageClassification(__lowerCAmelCase					)

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







		def 				A   (self  :					List[str]					):
			A							     =					self.prepare_config_and_inputs()
			A     ,			A     ,			A							     =					config_and_inputs
			A							     =					{"""pixel_values""": pixel_values}
			return config, inputs_dict






@require_tf
class 							__UpperCAmelCase     (				lowerCAmelCase__						,    lowerCAmelCase__						,    unittest.TestCase  ):







		'''simple docstring'''







		__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 				A   (self  :					Tuple					):
			A							     =					TFDeiTModelTester(self					)
			A							     =					ConfigTester(self					,					config_class=__lowerCAmelCase					,					has_text_modality=__lowerCAmelCase					,					hidden_size=37					)







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







		@unittest.skip(reason="""DeiT does not use inputs_embeds"""					)
		def 				A   (self  :					Optional[Any]					):
			pass







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

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







		def 				A   (self  :					str					):
			A     ,			A							     =					self.model_tester.prepare_config_and_inputs_for_common()

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

				A							     =					["""pixel_values"""]
				self.assertListEqual(arg_names[:1]					,					__lowerCAmelCase					)







		def 				A   (self  :					str					):
			A							     =					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*__lowerCAmelCase					)







		def 				A   (self  :					Dict					):
			A							     =					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCAmelCase					)







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







		def 				A   (self  :					Any					,					_lowerCAmelCase  :					List[str]					,					_lowerCAmelCase  :					Any					,					_lowerCAmelCase  :					Tuple=False					):
			A							     =					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 				A   (self  :					Optional[Any]					):


			for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				A							     =					TFDeiTModel.from_pretrained(__lowerCAmelCase					)
				self.assertIsNotNone(__lowerCAmelCase					)






def       __a       (   )					->List[Any]:



	"""simple docstring"""







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



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







		'''simple docstring'''







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







		@slow
		def 				A   (self  :					Optional[Any]					):
			A							     =					TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224"""					)

			A							     =					self.default_image_processor
			A							     =					prepare_img()
			A							     =					image_processor(images=__lowerCAmelCase					,					return_tensors="""tf"""					)

			# forward pass
			A							     =					model(**__lowerCAmelCase					)

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

			A							     =					tf.constant([-1.0_266, 0.1_912, -1.2_861]					)

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


'''simple docstring'''




import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


__lowercase          =  logging.get_logger(__name__)






class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     Union[str, Any]      =       ['''input_features''']



			def __init__(   self       ,    __lowerCAmelCase=80       ,    __lowerCAmelCase=16000       ,    __lowerCAmelCase=160       ,    __lowerCAmelCase=30       ,    __lowerCAmelCase=400       ,    __lowerCAmelCase=0.0       ,    __lowerCAmelCase=False       ,    **__lowerCAmelCase       ,    ):




					"""simple docstring"""


					super().__init__(
					    feature_size=__lowerCAmelCase       ,    sampling_rate=__lowerCAmelCase       ,    padding_value=__lowerCAmelCase       ,    return_attention_mask=__lowerCAmelCase       ,    **__lowerCAmelCase       ,    )
					lowerCAmelCase   					=  n_fft
					lowerCAmelCase   					=  hop_length
					lowerCAmelCase   					=  chunk_length
					lowerCAmelCase   					=  chunk_length * sampling_rate
					lowerCAmelCase   					=  self.n_samples // hop_length
					lowerCAmelCase   					=  sampling_rate
					lowerCAmelCase   					=  mel_filter_bank(
					    num_frequency_bins=1 + n_fft // 2       ,    num_mel_filters=__lowerCAmelCase       ,    min_frequency=0.0       ,    max_frequency=8000.0       ,    sampling_rate=__lowerCAmelCase       ,    norm="""slaney"""       ,    mel_scale="""slaney"""       ,    )



			def 							a_       (   self       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  spectrogram(
					    __lowerCAmelCase       ,    window_function(self.n_fft       ,    """hann""")       ,    frame_length=self.n_fft       ,    hop_length=self.hop_length       ,    power=2.0       ,    mel_filters=self.mel_filters       ,    log_mel="""log10"""       ,    )
					lowerCAmelCase   					=  log_spec[:, :-1]
					lowerCAmelCase   					=  np.maximum(__lowerCAmelCase       ,    log_spec.max() - 8.0)
					lowerCAmelCase   					=  (log_spec + 4.0) / 4.0
					return log_spec



			@staticmethod
			# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
			def 							a_       (   __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase = 0.0):




					"""simple docstring"""


					if attention_mask is not None:
							lowerCAmelCase   					=  np.array(__lowerCAmelCase       ,    np.intaa)
							lowerCAmelCase   					=  []

							for vector, length in zip(__lowerCAmelCase       ,    attention_mask.sum(-1)):
									lowerCAmelCase   					=  (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7)
									if length < normed_slice.shape[0]:
											lowerCAmelCase   					=  padding_value

									normed_input_values.append(__lowerCAmelCase)
					else:
							lowerCAmelCase   					=  [(x - x.mean()) / np.sqrt(x.var() + 1E-7) for x in input_values]

					return normed_input_values



			def __call__(   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase = True       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = "max_length"       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = None       ,    **__lowerCAmelCase       ,    ):




					"""simple docstring"""


					if sampling_rate is not None:
							if sampling_rate != self.sampling_rate:
									raise ValueError(
									    f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
									    f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
									    f" was sampled with {self.sampling_rate} and not {sampling_rate}.")
					else:
							logger.warning(
							    """It is strongly recommended to pass the `sampling_rate` argument to this function. """
							    """Failing to do so can result in silent errors that might be hard to debug.""")

					lowerCAmelCase   					=  isinstance(__lowerCAmelCase       ,    np.ndarray) and len(raw_speech.shape) > 1
					if is_batched_numpy and len(raw_speech.shape) > 2:
							raise ValueError(f"Only mono-channel audio is supported for input to {self}")
					lowerCAmelCase   					=  is_batched_numpy or (
					    isinstance(__lowerCAmelCase       ,    (list, tuple)) and (isinstance(raw_speech[0]       ,    (np.ndarray, tuple, list)))
					)

					if is_batched:
							lowerCAmelCase   					=  [np.asarray([speech]       ,    dtype=np.floataa).T for speech in raw_speech]
					elif not is_batched and not isinstance(__lowerCAmelCase       ,    np.ndarray):
							lowerCAmelCase   					=  np.asarray(__lowerCAmelCase       ,    dtype=np.floataa)
					elif isinstance(__lowerCAmelCase       ,    np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
							lowerCAmelCase   					=  raw_speech.astype(np.floataa)

					# always return batch
					if not is_batched:
							lowerCAmelCase   					=  [np.asarray([raw_speech]).T]

					lowerCAmelCase   					=  BatchFeature({"""input_features""": raw_speech})

					# convert into correct format for padding

					lowerCAmelCase   					=  self.pad(
					    __lowerCAmelCase       ,    padding=__lowerCAmelCase       ,    max_length=max_length if max_length else self.n_samples       ,    truncation=__lowerCAmelCase       ,    pad_to_multiple_of=__lowerCAmelCase       ,    return_attention_mask=return_attention_mask or do_normalize       ,    )

					# zero-mean and unit-variance normalization
					if do_normalize:
							lowerCAmelCase   					=  self.zero_mean_unit_var_norm(
							    padded_inputs["""input_features"""]       ,    attention_mask=padded_inputs["""attention_mask"""]       ,    padding_value=self.padding_value       ,    )
							lowerCAmelCase   					=  np.stack(padded_inputs["""input_features"""]       ,    axis=0)

					# make sure list is in array format
					lowerCAmelCase   					=  padded_inputs.get("""input_features""").transpose(2       ,    0       ,    1)

					lowerCAmelCase   					=  [self._np_extract_fbank_features(__lowerCAmelCase) for waveform in input_features[0]]

					if isinstance(input_features[0]       ,    __lowerCAmelCase):
							lowerCAmelCase   					=  [np.asarray(__lowerCAmelCase       ,    dtype=np.floataa) for feature in input_features]
					else:
							lowerCAmelCase   					=  input_features

					if return_attention_mask:
							# rescale from sample (48000) to feature (3000)
							lowerCAmelCase   					=  padded_inputs["""attention_mask"""][:, :: self.hop_length]

					if return_tensors is not None:
							lowerCAmelCase   					=  padded_inputs.convert_to_tensors(__lowerCAmelCase)

					return padded_inputs







			def 							a_       (   self):




					"""simple docstring"""


					lowerCAmelCase   					=  copy.deepcopy(self.__dict__)
					lowerCAmelCase   					=  self.__class__.__name__
					if "mel_filters" in output:
							del output["mel_filters"]
					return output




