

'''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     :		Any		,					UpperCAmelCase__     :		Tuple		,					UpperCAmelCase__     :		int=13		,					UpperCAmelCase__     :		Dict=30		,					UpperCAmelCase__     :		Any=2		,					UpperCAmelCase__     :		Any=3		,					UpperCAmelCase__     :		Any=True		,					UpperCAmelCase__     :		List[str]=True		,					UpperCAmelCase__     :		str=32		,					UpperCAmelCase__     :		Optional[int]=2		,					UpperCAmelCase__     :		Dict=4		,					UpperCAmelCase__     :		Dict=37		,					UpperCAmelCase__     :		List[str]="gelu"		,					UpperCAmelCase__     :		Union[str, Any]=0.1		,					UpperCAmelCase__     :		Any=0.1		,					UpperCAmelCase__     :		Union[str, Any]=10		,					UpperCAmelCase__     :		Any=0.02		,					UpperCAmelCase__     :		Dict=3		,					UpperCAmelCase__     :		int=None		,					UpperCAmelCase__     :		Union[str, Any]=2		,					):
										'''simple docstring'''
										lowercase :							Dict    		=parent
										lowercase :							Any    		=batch_size
										lowercase :							Optional[Any]    		=image_size
										lowercase :							Optional[int]    		=patch_size
										lowercase :							Tuple    		=num_channels
										lowercase :							str    		=is_training
										lowercase :							Optional[Any]    		=use_labels
										lowercase :							Union[str, Any]    		=hidden_size
										lowercase :							int    		=num_hidden_layers
										lowercase :							Optional[int]    		=num_attention_heads
										lowercase :							int    		=intermediate_size
										lowercase :							str    		=hidden_act
										lowercase :							str    		=hidden_dropout_prob
										lowercase :							int    		=attention_probs_dropout_prob
										lowercase :							int    		=type_sequence_label_size
										lowercase :							Optional[int]    		=initializer_range
										lowercase :							Union[str, Any]    		=scope
										lowercase :							List[str]    		=encoder_stride

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







				def  lowerCamelCase_	(       self     :		List[str]   ):
										'''simple docstring'''
										lowercase :							List[Any]    		=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

										lowercase :							Optional[int]    		=None
										if self.use_labels:
																lowercase :							Tuple    		=ids_tensor([self.batch_size]		,					self.type_sequence_label_size   )

										lowercase :							Optional[Any]    		=self.get_config()

										return config, pixel_values, labels







				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										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=UpperCAmelCase__		,					initializer_range=self.initializer_range		,					encoder_stride=self.encoder_stride		,					)







				def  lowerCamelCase_	(       self     :		List[str]		,					UpperCAmelCase__     :		Dict		,					UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		Any   ):
										'''simple docstring'''
										lowercase :							int    		=TFDeiTModel(config=UpperCAmelCase__   )
										lowercase :							List[str]    		=model(UpperCAmelCase__   )
										self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)   )







				def  lowerCamelCase_	(       self     :		Dict		,					UpperCAmelCase__     :		Tuple		,					UpperCAmelCase__     :		str		,					UpperCAmelCase__     :		Union[str, Any]   ):
										'''simple docstring'''
										lowercase :							Dict    		=TFDeiTForMaskedImageModeling(config=UpperCAmelCase__   )
										lowercase :							List[str]    		=model(UpperCAmelCase__   )
										self.parent.assertEqual(
										    result.reconstruction.shape		,					(self.batch_size, self.num_channels, self.image_size, self.image_size)   )

										# test greyscale images
										lowercase :							Optional[int]    		=1
										lowercase :							str    		=TFDeiTForMaskedImageModeling(UpperCAmelCase__   )

										lowercase :							Optional[Any]    		=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
										lowercase :							str    		=model(UpperCAmelCase__   )
										self.parent.assertEqual(result.reconstruction.shape		,					(self.batch_size, 1, self.image_size, self.image_size)   )







				def  lowerCamelCase_	(       self     :		Dict		,					UpperCAmelCase__     :		Union[str, Any]		,					UpperCAmelCase__     :		Any		,					UpperCAmelCase__     :		List[str]   ):
										'''simple docstring'''
										lowercase :							Tuple    		=self.type_sequence_label_size
										lowercase :							Optional[Any]    		=TFDeiTForImageClassification(UpperCAmelCase__   )
										lowercase :							Optional[Any]    		=model(UpperCAmelCase__		,					labels=UpperCAmelCase__   )
										self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.type_sequence_label_size)   )

										# test greyscale images
										lowercase :							Union[str, Any]    		=1
										lowercase :							str    		=TFDeiTForImageClassification(UpperCAmelCase__   )

										lowercase :							List[str]    		=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
										lowercase :							Any    		=model(UpperCAmelCase__		,					labels=UpperCAmelCase__   )
										self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.type_sequence_label_size)   )







				def  lowerCamelCase_	(       self     :		Optional[int]   ):
										'''simple docstring'''
										lowercase :							Optional[int]    		=self.prepare_config_and_inputs()
										lowercase		,	lowercase		,	lowercase :							Optional[Any]    		=config_and_inputs
										lowercase :							int    		={'''pixel_values''': pixel_values}
										return config, inputs_dict





@require_tf
class 		__SCREAMING_SNAKE_CASE							(			lowercase__						,							lowercase__						,							unittest.TestCase      ):
				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  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							Optional[Any]    		=TFDeiTModelTester(self   )
										lowercase :							Optional[int]    		=ConfigTester(self		,					config_class=UpperCAmelCase__		,					has_text_modality=UpperCAmelCase__		,					hidden_size=37   )







				def  lowerCamelCase_	(       self     :		int   ):
										'''simple docstring'''
										self.config_tester.run_common_tests()







				@unittest.skip(reason='''DeiT does not use inputs_embeds'''   )
				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										pass







				def  lowerCamelCase_	(       self     :		Tuple   ):
										'''simple docstring'''
										lowercase		,	lowercase :							Union[str, Any]    		=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																lowercase :							List[str]    		=model_class(UpperCAmelCase__   )
																self.assertIsInstance(model.get_input_embeddings()		,					(tf.keras.layers.Layer)   )
																lowercase :							Optional[int]    		=model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(UpperCAmelCase__		,					tf.keras.layers.Dense   )   )







				def  lowerCamelCase_	(       self     :		Union[str, Any]   ):
										'''simple docstring'''
										lowercase		,	lowercase :							Any    		=self.model_tester.prepare_config_and_inputs_for_common()

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

																lowercase :							Any    		=['''pixel_values''']
																self.assertListEqual(arg_names[:1]		,					UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							str    		=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										lowercase :							Any    		=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		Dict   ):
										'''simple docstring'''
										lowercase :							int    		=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__   )







				def  lowerCamelCase_	(       self     :		Dict		,					UpperCAmelCase__     :		List[Any]		,					UpperCAmelCase__     :		List[str]		,					UpperCAmelCase__     :		int=False   ):
										'''simple docstring'''
										lowercase :							int    		=super()._prepare_for_class(UpperCAmelCase__		,					UpperCAmelCase__		,					return_labels=UpperCAmelCase__   )

										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  lowerCamelCase_	(       self     :		List[str]   ):
										'''simple docstring'''
										for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																lowercase :							str    		=TFDeiTModel.from_pretrained(UpperCAmelCase__   )
																self.assertIsNotNone(UpperCAmelCase__   )






def 				_lowerCAmelCase			(   )				->  Optional[Any]:
						lowercase :							str    		=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
						return image







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







				@cached_property
				def  lowerCamelCase_	(       self     :		List[Any]   ):
										'''simple docstring'''
										return (
										    DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224'''   )
										    if is_vision_available()
										    else None
										)







				@slow
				def  lowerCamelCase_	(       self     :		Dict   ):
										'''simple docstring'''
										lowercase :							Union[str, Any]    		=TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''   )

										lowercase :							Union[str, Any]    		=self.default_image_processor
										lowercase :							Dict    		=prepare_img()
										lowercase :							List[str]    		=image_processor(images=UpperCAmelCase__		,					return_tensors='''tf'''   )

										# forward pass
										lowercase :							Optional[int]    		=model(**UpperCAmelCase__   )

										# verify the logits
										lowercase :							Optional[int]    		=tf.TensorShape((1, 1000)   )
										self.assertEqual(outputs.logits.shape		,					UpperCAmelCase__   )

										lowercase :							int    		=tf.constant([-1.02_66, 0.19_12, -1.28_61]   )

										self.assertTrue(np.allclose(outputs.logits[0, :3]		,					UpperCAmelCase__		,					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,
)


lowerCAmelCase     :  int											=    {
    """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:
       lowerCAmelCase     :  Dict											=    ["""OwlViTFeatureExtractor"""]
       lowerCAmelCase     :  int											=    ["""OwlViTImageProcessor"""]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCAmelCase     :  Optional[Any]											=    [
           """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

       lowerCAmelCase     :  Union[str, Any]											=    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

