



"""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 	__SCREAMING_SNAKE_CASE     :


					'''simple docstring'''





					def __init__(	self							:  Union[str, Any],  lowerCamelCase							:  Tuple,  lowerCamelCase							:  int=13,  lowerCamelCase							:  List[str]=30,  lowerCamelCase							:  int=2,  lowerCamelCase							:  Optional[Any]=3,  lowerCamelCase							:  str=True,  lowerCamelCase							:  int=True,  lowerCamelCase							:  Optional[int]=32,  lowerCamelCase							:  str=2,  lowerCamelCase							:  Optional[Any]=4,  lowerCamelCase							:  int=37,  lowerCamelCase							:  List[Any]="gelu",  lowerCamelCase							:  List[Any]=0.1,  lowerCamelCase							:  Optional[Any]=0.1,  lowerCamelCase							:  List[Any]=10,  lowerCamelCase							:  Any=0.02,  lowerCamelCase							:  Union[str, Any]=3,  lowerCamelCase							:  Dict=None,  lowerCamelCase							:  Any=2,  )-> List[Any]:
								lowerCamelCase__		:		Any		     =parent
								lowerCamelCase__		:		Any		     =batch_size
								lowerCamelCase__		:		List[str]		     =image_size
								lowerCamelCase__		:		Dict		     =patch_size
								lowerCamelCase__		:		int		     =num_channels
								lowerCamelCase__		:		Tuple		     =is_training
								lowerCamelCase__		:		Optional[int]		     =use_labels
								lowerCamelCase__		:		str		     =hidden_size
								lowerCamelCase__		:		Optional[Any]		     =num_hidden_layers
								lowerCamelCase__		:		Any		     =num_attention_heads
								lowerCamelCase__		:		Optional[Any]		     =intermediate_size
								lowerCamelCase__		:		Optional[int]		     =hidden_act
								lowerCamelCase__		:		Union[str, Any]		     =hidden_dropout_prob
								lowerCamelCase__		:		Any		     =attention_probs_dropout_prob
								lowerCamelCase__		:		Optional[int]		     =type_sequence_label_size
								lowerCamelCase__		:		Optional[int]		     =initializer_range
								lowerCamelCase__		:		Optional[int]		     =scope
								lowerCamelCase__		:		int		     =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__		:		str		     =num_patches + 2



					def 		snake_case	(	self							:  Optional[Any]					)-> str:
								lowerCamelCase__		:		Dict		     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

								lowerCamelCase__		:		Optional[int]		     =self.get_config()

								return config, pixel_values, labels



					def 		snake_case	(	self							:  List[Any]					)-> str:
								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 		snake_case	(	self							:  Any,  lowerCamelCase							:  List[str],  lowerCamelCase							:  List[str],  lowerCamelCase							:  int					)-> Union[str, Any]:
								lowerCamelCase__		:		Optional[int]		     =TFDeiTModel(config=lowerCamelCase					)
								lowerCamelCase__		:		int		     =model(lowerCamelCase					)
								self.parent.assertEqual(result.last_hidden_state.shape,  (self.batch_size, self.seq_length, self.hidden_size)					)



					def 		snake_case	(	self							:  List[Any],  lowerCamelCase							:  Tuple,  lowerCamelCase							:  Any,  lowerCamelCase							:  str					)-> Optional[int]:
								lowerCamelCase__		:		List[str]		     =TFDeiTForMaskedImageModeling(config=lowerCamelCase					)
								lowerCamelCase__		:		List[Any]		     =model(lowerCamelCase					)
								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(lowerCamelCase					)

								lowerCamelCase__		:		Dict		     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
								lowerCamelCase__		:		Optional[Any]		     =model(lowerCamelCase					)
								self.parent.assertEqual(result.reconstruction.shape,  (self.batch_size, 1, self.image_size, self.image_size)					)



					def 		snake_case	(	self							:  List[str],  lowerCamelCase							:  Any,  lowerCamelCase							:  Dict,  lowerCamelCase							:  Optional[int]					)-> Optional[Any]:
								lowerCamelCase__		:		Dict		     =self.type_sequence_label_size
								lowerCamelCase__		:		Optional[int]		     =TFDeiTForImageClassification(lowerCamelCase					)
								lowerCamelCase__		:		int		     =model(lowerCamelCase,  labels=lowerCamelCase					)
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.type_sequence_label_size)					)

								# test greyscale images
								lowerCamelCase__		:		str		     =1
								lowerCamelCase__		:		Optional[Any]		     =TFDeiTForImageClassification(lowerCamelCase					)

								lowerCamelCase__		:		Any		     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
								lowerCamelCase__		:		Tuple		     =model(lowerCamelCase,  labels=lowerCamelCase					)
								self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.type_sequence_label_size)					)




					def 		snake_case	(	self							:  Dict					)-> Optional[int]:
								lowerCamelCase__		:		str		     =self.prepare_config_and_inputs()
								lowerCamelCase__     ,       lowerCamelCase__     ,       lowerCamelCase__		:		str		     =config_and_inputs
								lowerCamelCase__		:		Optional[Any]		     ={'''pixel_values''': pixel_values}
								return config, inputs_dict





@require_tf
class 	__SCREAMING_SNAKE_CASE     (				lowerCAmelCase_		,       lowerCAmelCase_		,       unittest.TestCase       ):


					'''simple docstring'''





					_a             =							(
					    (
					        TFDeiTModel,
					        TFDeiTForImageClassification,
					        TFDeiTForImageClassificationWithTeacher,
					        TFDeiTForMaskedImageModeling,
					    )
					    if is_tf_available()
					    else ()
					)
					_a             =							(
					    {
					        'feature-extraction': TFDeiTModel,
					        'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
					    }
					    if is_tf_available()
					    else {}
					)

					_a             =							False
					_a             =							False
					_a             =							False
					_a             =							False



					def 		snake_case	(	self							:  int					)-> Optional[Any]:
								lowerCamelCase__		:		Optional[Any]		     =TFDeiTModelTester(self					)
								lowerCamelCase__		:		List[str]		     =ConfigTester(self,  config_class=lowerCamelCase,  has_text_modality=lowerCamelCase,  hidden_size=37					)



					def 		snake_case	(	self							:  str					)-> Dict:
								self.config_tester.run_common_tests()



					@unittest.skip(reason='''DeiT does not use inputs_embeds'''					)
					def 		snake_case	(	self							:  Optional[int]					)-> List[Any]:
								pass



					def 		snake_case	(	self							:  Tuple					)-> Union[str, Any]:
								lowerCamelCase__     ,       lowerCamelCase__		:		Optional[int]		     =self.model_tester.prepare_config_and_inputs_for_common()

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



					def 		snake_case	(	self							:  List[Any]					)-> Tuple:
								lowerCamelCase__     ,       lowerCamelCase__		:		int		     =self.model_tester.prepare_config_and_inputs_for_common()

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

											lowerCamelCase__		:		List[Any]		     =['''pixel_values''']
											self.assertListEqual(arg_names[:1],  lowerCamelCase					)



					def 		snake_case	(	self							:  int					)-> Dict:
								lowerCamelCase__		:		Dict		     =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase					)



					def 		snake_case	(	self							:  Any					)-> str:
								lowerCamelCase__		:		List[Any]		     =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase					)



					def 		snake_case	(	self							:  Dict					)-> Union[str, Any]:
								lowerCamelCase__		:		str		     =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCamelCase					)



					def 		snake_case	(	self							:  int,  lowerCamelCase							:  int,  lowerCamelCase							:  Dict,  lowerCamelCase							:  int=False					)-> Tuple:
								lowerCamelCase__		:		int		     =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 		snake_case	(	self							:  List[Any]					)-> str:
								for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCamelCase__		:		Optional[Any]		     =TFDeiTModel.from_pretrained(lowerCamelCase					)
											self.assertIsNotNone(lowerCamelCase					)






def 					snake_case__       (		):
			"""simple docstring"""
			lowerCamelCase__		:		List[Any]		     =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''     )
			return image

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


					'''simple docstring'''





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




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

								lowerCamelCase__		:		Any		     =self.default_image_processor
								lowerCamelCase__		:		str		     =prepare_img()
								lowerCamelCase__		:		Optional[Any]		     =image_processor(images=lowerCamelCase,  return_tensors='''tf'''					)

								# forward pass
								lowerCamelCase__		:		Union[str, Any]		     =model(**lowerCamelCase					)

								# verify the logits
								lowerCamelCase__		:		List[str]		     =tf.TensorShape((1, 1000)					)
								self.assertEqual(outputs.logits.shape,  lowerCamelCase					)

								lowerCamelCase__		:		Union[str, Any]		     =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"""






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


_lowercase			:			Any										=						{
    "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"],
    "processing_trocr": ["TrOCRProcessor"],
}


try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		_lowercase			:			List[Any]										=						[
		    "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST",
		    "TrOCRForCausalLM",
		    "TrOCRPreTrainedModel",
		]


if TYPE_CHECKING:
		from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
		from .processing_trocr import TrOCRProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel

else:
		import sys

		_lowercase			:			Tuple										=						_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




