




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


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

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


						def   __lowercase (							self				:			List[Any]					):
										lowerCAmelCase  =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

										lowerCAmelCase  =				self.get_config()

										return config, pixel_values, labels


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


						def   __lowercase (							self				:			Optional[Any]						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			Optional[int]						,						lowerCAmelCase				:			List[str]					):
										lowerCAmelCase  =				TFDeiTForMaskedImageModeling(config=lowerCAmelCase					)
										lowerCAmelCase  =				model(lowerCAmelCase					)
										self.parent.assertEqual(
										    result.reconstruction.shape						,						(self.batch_size, self.num_channels, self.image_size, self.image_size)					)

										# test greyscale images
										lowerCAmelCase  =				1
										lowerCAmelCase  =				TFDeiTForMaskedImageModeling(lowerCAmelCase					)

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


						def   __lowercase (							self				:			str						,						lowerCAmelCase				:			Union[str, Any]						,						lowerCAmelCase				:			Union[str, Any]						,						lowerCAmelCase				:			Optional[int]					):
										lowerCAmelCase  =				self.type_sequence_label_size
										lowerCAmelCase  =				TFDeiTForImageClassification(lowerCAmelCase					)
										lowerCAmelCase  =				model(lowerCAmelCase						,						labels=lowerCAmelCase					)
										self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.type_sequence_label_size)					)

										# test greyscale images
										lowerCAmelCase  =				1
										lowerCAmelCase  =				TFDeiTForImageClassification(lowerCAmelCase					)

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




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






@require_tf
class       SCREAMING_SNAKE_CASE__					(					_a						,				_a						,				unittest.TestCase					):
						_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   __lowercase (							self				:			Optional[Any]					):
										lowerCAmelCase  =				TFDeiTModelTester(self					)
										lowerCAmelCase  =				ConfigTester(self						,						config_class=lowerCAmelCase						,						has_text_modality=lowerCAmelCase						,						hidden_size=37					)


						def   __lowercase (							self				:			Union[str, Any]					):
										self.config_tester.run_common_tests()


						@unittest.skip(reason="""DeiT does not use inputs_embeds"""					)
						def   __lowercase (							self				:			str					):
										pass


						def   __lowercase (							self				:			List[str]					):
										lowerCAmelCase ,						lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs_for_common()

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


						def   __lowercase (							self				:			Dict					):
										lowerCAmelCase ,						lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs_for_common()

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

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


						def   __lowercase (							self				:			Any					):
										lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase					)


						def   __lowercase (							self				:			Tuple					):
										lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase					)


						def   __lowercase (							self				:			int					):
										lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase					)


						def   __lowercase (							self				:			str						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			List[str]=False					):
										lowerCAmelCase  =				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   __lowercase (							self				:			Any					):
										for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowerCAmelCase  =				TFDeiTModel.from_pretrained(lowerCAmelCase					)
														self.assertIsNotNone(lowerCAmelCase					)





def 							lowercase					()     ->  Optional[Any]:


				'''simple docstring'''






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






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


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




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

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

										# forward pass
										lowerCAmelCase  =				model(**lowerCAmelCase					)

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

										lowerCAmelCase  =				tf.constant([-1.0266, 0.1912, -1.2861]					)

										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_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


a      =							{
    'configuration_owlvit': [
        'OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'OwlViTConfig',
        'OwlViTOnnxConfig',
        'OwlViTTextConfig',
        'OwlViTVisionConfig',
    ],
    'processing_owlvit': ['OwlViTProcessor'],
}


try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		a      =							['OwlViTFeatureExtractor']
		a      =							['OwlViTImageProcessor']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		a      =							[
		    'OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'OwlViTModel',
		    'OwlViTPreTrainedModel',
		    'OwlViTTextModel',
		    'OwlViTVisionModel',
		    'OwlViTForObjectDetection',
		]

if TYPE_CHECKING:
		from .configuration_owlvit import (
		    OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
		    OwlViTConfig,
		    OwlViTOnnxConfig,
		    OwlViTTextConfig,
		    OwlViTVisionConfig,
		)
		from .processing_owlvit import OwlViTProcessor

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_owlvit import OwlViTFeatureExtractor
				from .image_processing_owlvit import OwlViTImageProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_owlvit import (
				    OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    OwlViTForObjectDetection,
				    OwlViTModel,
				    OwlViTPreTrainedModel,
				    OwlViTTextModel,
				    OwlViTVisionModel,
				)

else:
		import sys

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





