

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	:						Union[str, Any]		,	lowerCAmelCase	:						Optional[Any]		,	lowerCAmelCase	:						Dict=13		,	lowerCAmelCase	:						Union[str, Any]=30		,	lowerCAmelCase	:						Any=2		,	lowerCAmelCase	:						str=3		,	lowerCAmelCase	:						Optional[int]=True		,	lowerCAmelCase	:						Optional[Any]=True		,	lowerCAmelCase	:						List[Any]=32		,	lowerCAmelCase	:						Tuple=2		,	lowerCAmelCase	:						Any=4		,	lowerCAmelCase	:						Dict=37		,	lowerCAmelCase	:						List[Any]="gelu"		,	lowerCAmelCase	:						List[Any]=0.1		,	lowerCAmelCase	:						Any=0.1		,	lowerCAmelCase	:						Any=10		,	lowerCAmelCase	:						str=0.02		,	lowerCAmelCase	:						int=3		,	lowerCAmelCase	:						Optional[int]=None		,	):


		'''simple docstring'''







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

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




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







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

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

		UpperCAmelCase_       				=			self.get_config()

		return config, pixel_values, labels




	def       __A					(		self	:						List[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=lowerCamelCase_		,	initializer_range=self.initializer_range		,	)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						Dict		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFViTModel(config=lowerCamelCase_							)
		UpperCAmelCase_       				=			model(lowerCamelCase_		,	training=lowerCamelCase_							)
		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.
		UpperCAmelCase_       				=			self.image_size // 2
		UpperCAmelCase_       				=			pixel_values[:, :, :image_size, :image_size]
		UpperCAmelCase_       				=			model(lowerCamelCase_		,	interpolate_pos_encoding=lowerCamelCase_		,	training=lowerCamelCase_							)
		UpperCAmelCase_       				=			(image_size // self.patch_size) ** 2 + 1
		self.parent.assertEqual(result.last_hidden_state.shape		,	(self.batch_size, seq_length, self.hidden_size)							)




	def       __A					(		self	:						Union[str, Any]		,	lowerCAmelCase	:						Dict		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.type_sequence_label_size
		UpperCAmelCase_       				=			TFViTForImageClassification(lowerCamelCase_							)
		UpperCAmelCase_       				=			model(lowerCamelCase_		,	labels=lowerCamelCase_		,	training=lowerCamelCase_							)
		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.
		UpperCAmelCase_       				=			self.image_size // 2
		UpperCAmelCase_       				=			pixel_values[:, :, :image_size, :image_size]
		UpperCAmelCase_       				=			model(lowerCamelCase_		,	interpolate_pos_encoding=lowerCamelCase_		,	training=lowerCamelCase_							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.type_sequence_label_size)							)

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




	def       __A					(		self	:						int							):


		'''simple docstring'''







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


@require_tf
class 						__UpperCamelCase    (					lowercase_     ,     lowercase_     ,     unittest.TestCase						):
	SCREAMING_SNAKE_CASE__    				=     (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
	SCREAMING_SNAKE_CASE__    				=     (
	    {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
	    if is_tf_available()
	    else {}
	)

	SCREAMING_SNAKE_CASE__    				=     False
	SCREAMING_SNAKE_CASE__    				=     False
	SCREAMING_SNAKE_CASE__    				=     False




	def       __A					(		self	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFViTModelTester(self							)
		UpperCAmelCase_       				=			ConfigTester(self		,	config_class=lowerCamelCase_		,	has_text_modality=lowerCamelCase_		,	hidden_size=37							)




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		self.config_tester.run_common_tests()




	@unittest.skip(reason="ViT does not use inputs_embeds"							)
	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		pass




	@unittest.skip(reason="ViT does not use inputs_embeds"							)
	def       __A					(		self	:						int							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs_for_common()

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




	def       __A					(		self	:						int							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs_for_common()

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

			UpperCAmelCase_       				=			["""pixel_values"""]
			self.assertListEqual(arg_names[:1]		,	lowerCamelCase_							)




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*lowerCamelCase_							)




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_							)




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


		'''simple docstring'''







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



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




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




	@cached_property
	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







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




	@slow
	def       __A					(		self	:						str							):


		'''simple docstring'''







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

		UpperCAmelCase_       				=			self.default_image_processor
		UpperCAmelCase_       				=			prepare_img()
		UpperCAmelCase_       				=			image_processor(images=lowerCamelCase_		,	return_tensors="tf"							)

		# forward pass
		UpperCAmelCase_       				=			model(**lowerCamelCase_							)

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

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

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


from typing import TYPE_CHECKING

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


_a:    List[str] 							=			{
    """configuration_encodec""": [
        """ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """EncodecConfig""",
    ],
    """feature_extraction_encodec""": ["""EncodecFeatureExtractor"""],
}

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_a:    List[Any] 							=			[
				    """ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST""",
				    """EncodecModel""",
				    """EncodecPreTrainedModel""",
				]

if TYPE_CHECKING:
				from .configuration_encodec import (
				    ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP,
				    EncodecConfig,
				)
				from .feature_extraction_encodec import EncodecFeatureExtractor

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_encodec import (
								    ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST,
								    EncodecModel,
								    EncodecPreTrainedModel,
								)

else:
				import sys

				_a:    int 							=			_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)