


'''simple docstring'''





from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
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 TFViTForImageClassification, TFViTModel


if is_vision_available():
							from PIL import Image

							from transformers import ViTImageProcessor







class        UpperCamelCase__   :

					def __init__(     self       :   List[Any]							,					UpperCamelCase__       :   Union[str, Any]							,					UpperCamelCase__       :   Optional[Any]=13							,					UpperCamelCase__       :   str=30							,					UpperCamelCase__       :   Any=2							,					UpperCamelCase__       :   str=3							,					UpperCamelCase__       :   List[Any]=True							,					UpperCamelCase__       :   List[Any]=True							,					UpperCamelCase__       :   str=32							,					UpperCamelCase__       :   List[Any]=2							,					UpperCamelCase__       :   Optional[int]=4							,					UpperCamelCase__       :   Optional[Any]=37							,					UpperCamelCase__       :   Dict="gelu"							,					UpperCamelCase__       :   Any=0.1							,					UpperCamelCase__       :   str=0.1							,					UpperCamelCase__       :   Optional[int]=10							,					UpperCamelCase__       :   Optional[Any]=0.02							,					UpperCamelCase__       :   List[str]=3							,					UpperCamelCase__       :   Optional[int]=None							,					):






										'''simple docstring'''






										lowercase_  							=			parent
										lowercase_  							=			batch_size
										lowercase_  							=			image_size
										lowercase_  							=			patch_size
										lowercase_  							=			num_channels
										lowercase_  							=			is_training
										lowercase_  							=			use_labels
										lowercase_  							=			hidden_size
										lowercase_  							=			num_hidden_layers
										lowercase_  							=			num_attention_heads
										lowercase_  							=			intermediate_size
										lowercase_  							=			hidden_act
										lowercase_  							=			hidden_dropout_prob
										lowercase_  							=			attention_probs_dropout_prob
										lowercase_  							=			type_sequence_label_size
										lowercase_  							=			initializer_range
										lowercase_  							=			scope

										# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
										lowercase_  							=			(image_size // patch_size) ** 2
										lowercase_  							=			num_patches + 1

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

										lowercase_  							=			self.get_config()

										return config, pixel_values, labels

					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										return ViTConfig(
										    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=UpperCamelCase__							,					initializer_range=self.initializer_range							,					)

					def   UpperCAmelCase__       (     self       :   Optional[Any]							,					UpperCamelCase__       :   Optional[Any]							,					UpperCamelCase__       :   Optional[int]							,					UpperCamelCase__       :   List[Any]       ):






										'''simple docstring'''






										lowercase_  							=			TFViTModel(config=UpperCamelCase__       )
										lowercase_  							=			model(UpperCamelCase__							,					training=UpperCamelCase__       )
										self.parent.assertEqual(result.last_hidden_state.shape							,					(self.batch_size, self.seq_length, self.hidden_size)       )

										# Test with an image with different size than the one specified in config.
										lowercase_  							=			self.image_size // 2
										lowercase_  							=			pixel_values[:, :, :image_size, :image_size]
										lowercase_  							=			model(UpperCamelCase__							,					interpolate_pos_encoding=UpperCamelCase__							,					training=UpperCamelCase__       )
										lowercase_  							=			(image_size // self.patch_size) ** 2 + 1
										self.parent.assertEqual(result.last_hidden_state.shape							,					(self.batch_size, seq_length, self.hidden_size)       )

					def   UpperCAmelCase__       (     self       :   Any							,					UpperCamelCase__       :   Union[str, Any]							,					UpperCamelCase__       :   Union[str, Any]							,					UpperCamelCase__       :   Any       ):






										'''simple docstring'''






										lowercase_  							=			self.type_sequence_label_size
										lowercase_  							=			TFViTForImageClassification(UpperCamelCase__       )
										lowercase_  							=			model(UpperCamelCase__							,					labels=UpperCamelCase__							,					training=UpperCamelCase__       )
										self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)       )

										# Test with an image with different size than the one specified in config.
										lowercase_  							=			self.image_size // 2
										lowercase_  							=			pixel_values[:, :, :image_size, :image_size]
										lowercase_  							=			model(UpperCamelCase__							,					interpolate_pos_encoding=UpperCamelCase__							,					training=UpperCamelCase__       )
										self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)       )

										# test greyscale images
										lowercase_  							=			1
										lowercase_  							=			TFViTForImageClassification(UpperCamelCase__       )
										lowercase_  							=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
										lowercase_  							=			model(UpperCamelCase__       )
										self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)       )







					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






										lowercase_  							=			self.prepare_config_and_inputs()
										lowercase_							,					lowercase_							,					lowercase_  							=			config_and_inputs
										lowercase_  							=			{"""pixel_values""": pixel_values}
										return config, inputs_dict







@require_tf
class        UpperCamelCase__   (	__magic_name__							,				__magic_name__							,				unittest.TestCase   ):
					__SCREAMING_SNAKE_CASE       :  List[str]						=   (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
					__SCREAMING_SNAKE_CASE       :  Dict						=   (
					    {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
					    if is_tf_available()
					    else {}
					)

					__SCREAMING_SNAKE_CASE       :  int						=   False
					__SCREAMING_SNAKE_CASE       :  Any						=   False
					__SCREAMING_SNAKE_CASE       :  Optional[Any]						=   False

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										lowercase_  							=			TFViTModelTester(self       )
										lowercase_  							=			ConfigTester(self							,					config_class=UpperCamelCase__							,					has_text_modality=UpperCamelCase__							,					hidden_size=37       )

					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






										self.config_tester.run_common_tests()

					@unittest.skip(reason="""ViT does not use inputs_embeds"""       )
					def   UpperCAmelCase__       (     self       :   Union[str, Any]       ):






										'''simple docstring'''






										pass

					@unittest.skip(reason="""ViT does not use inputs_embeds"""       )
					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






										pass

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										lowercase_							,					lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

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

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_							,					lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

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

															lowercase_  							=			["""pixel_values"""]
															self.assertListEqual(arg_names[:1]							,					UpperCamelCase__       )

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*UpperCamelCase__       )

					def   UpperCAmelCase__       (     self       :   int       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__       )







					@slow
					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										lowercase_  							=			TFViTModel.from_pretrained("""google/vit-base-patch16-224"""       )
										self.assertIsNotNone(UpperCamelCase__       )



def 			UpperCAmelCase_				(      ):
					lowercase_  							=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
					return image







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

					@cached_property
					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






										return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""       ) if is_vision_available() else None







					@slow
					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






										lowercase_  							=			TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""       )

										lowercase_  							=			self.default_image_processor
										lowercase_  							=			prepare_img()
										lowercase_  							=			image_processor(images=UpperCamelCase__							,					return_tensors="""tf"""       )

										# forward pass
										lowercase_  							=			model(**UpperCamelCase__       )

										# verify the logits
										lowercase_  							=			tf.TensorShape((1, 1_000)       )
										self.assertEqual(outputs.logits.shape							,					UpperCamelCase__       )

										lowercase_  							=			tf.constant([-0.2_744, 0.8_215, -0.0_836]       )

										tf.debugging.assert_near(outputs.logits[0, :3]							,					UpperCamelCase__							,					atol=1e-4       )






from typing import TYPE_CHECKING

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


a					  =     {
    'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'],
    'processing_trocr': ['TrOCRProcessor'],
}


try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a					  =     [
							    '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

							a					  =     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


