




'''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     A					:







							def __init__(						self :						Optional[Any]							,    lowerCAmelCase_ :						Union[str, Any]							,    lowerCAmelCase_ :						Union[str, Any]=13							,    lowerCAmelCase_ :						Dict=30							,    lowerCAmelCase_ :						str=2							,    lowerCAmelCase_ :						List[Any]=3							,    lowerCAmelCase_ :						int=True							,    lowerCAmelCase_ :						Any=True							,    lowerCAmelCase_ :						Union[str, Any]=32							,    lowerCAmelCase_ :						int=2							,    lowerCAmelCase_ :						Optional[Any]=4							,    lowerCAmelCase_ :						Dict=37							,    lowerCAmelCase_ :						str="gelu"							,    lowerCAmelCase_ :						List[Any]=0.1							,    lowerCAmelCase_ :						str=0.1							,    lowerCAmelCase_ :						Optional[Any]=10							,    lowerCAmelCase_ :						Union[str, Any]=0.0_2							,    lowerCAmelCase_ :						int=3							,    lowerCAmelCase_ :						Optional[int]=None							,    lowerCAmelCase_ :						str=2							,    )    ->							Tuple:


														"""simple docstring"""


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

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







							def      __lowerCAmelCase    (						self :						int      )    ->							str:


														"""simple docstring"""


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

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

														_a			  =       self.get_config()

														return config, pixel_values, labels







							def      __lowerCAmelCase    (						self :						str      )    ->							Optional[int]:


														"""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=lowerCAmelCase_							,    initializer_range=self.initializer_range							,    encoder_stride=self.encoder_stride							,    )







							def      __lowerCAmelCase    (						self :						Union[str, Any]							,    lowerCAmelCase_ :						int							,    lowerCAmelCase_ :						Optional[Any]							,    lowerCAmelCase_ :						Optional[Any]      )    ->							Dict:


														"""simple docstring"""


														_a			  =       TFDeiTModel(config=lowerCAmelCase_      )
														_a			  =       model(lowerCAmelCase_      )
														self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, self.seq_length, self.hidden_size)      )







							def      __lowerCAmelCase    (						self :						Any							,    lowerCAmelCase_ :						Dict							,    lowerCAmelCase_ :						str							,    lowerCAmelCase_ :						Optional[int]      )    ->							Any:


														"""simple docstring"""


														_a			  =       TFDeiTForMaskedImageModeling(config=lowerCAmelCase_      )
														_a			  =       model(lowerCAmelCase_      )
														self.parent.assertEqual(
														    result.reconstruction.shape							,    (self.batch_size, self.num_channels, self.image_size, self.image_size)      )

														# test greyscale images
														_a			  =       1
														_a			  =       TFDeiTForMaskedImageModeling(lowerCAmelCase_      )

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







							def      __lowerCAmelCase    (						self :						List[str]							,    lowerCAmelCase_ :						str							,    lowerCAmelCase_ :						Optional[int]							,    lowerCAmelCase_ :						int      )    ->							int:


														"""simple docstring"""


														_a			  =       self.type_sequence_label_size
														_a			  =       TFDeiTForImageClassification(lowerCAmelCase_      )
														_a			  =       model(lowerCAmelCase_							,    labels=lowerCAmelCase_      )
														self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.type_sequence_label_size)      )

														# test greyscale images
														_a			  =       1
														_a			  =       TFDeiTForImageClassification(lowerCAmelCase_      )

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







							def      __lowerCAmelCase    (						self :						Dict      )    ->							List[Any]:


														"""simple docstring"""


														_a			  =       self.prepare_config_and_inputs()
														_a			  =       config_and_inputs
														_a			  =       {'pixel_values': pixel_values}
														return config, inputs_dict



@require_tf
class     A					(	__A  ,__A  ,unittest.TestCase					):
							lowercase_           =       (
							    (
							        TFDeiTModel,
							        TFDeiTForImageClassification,
							        TFDeiTForImageClassificationWithTeacher,
							        TFDeiTForMaskedImageModeling,
							    )
							    if is_tf_available()
							    else ()
							)
							lowercase_           =       (
							    {
							        'feature-extraction': TFDeiTModel,
							        'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
							    }
							    if is_tf_available()
							    else {}
							)

							lowercase_           =       False
							lowercase_           =       False
							lowercase_           =       False
							lowercase_           =       False







							def      __lowerCAmelCase    (						self :						List[Any]      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       TFDeiTModelTester(self      )
														_a			  =       ConfigTester(self							,    config_class=lowerCAmelCase_							,    has_text_modality=lowerCAmelCase_							,    hidden_size=37      )







							def      __lowerCAmelCase    (						self :						Optional[int]      )    ->							Any:


														"""simple docstring"""


														self.config_tester.run_common_tests()







							@unittest.skip(reason='''DeiT does not use inputs_embeds'''      )
							def      __lowerCAmelCase    (						self :						Optional[int]      )    ->							Union[str, Any]:


														"""simple docstring"""


														pass







							def      __lowerCAmelCase    (						self :						Any      )    ->							Union[str, Any]:


														"""simple docstring"""


														_a			  =       self.model_tester.prepare_config_and_inputs_for_common()

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







							def      __lowerCAmelCase    (						self :						Union[str, Any]      )    ->							Dict:


														"""simple docstring"""


														_a			  =       self.model_tester.prepare_config_and_inputs_for_common()

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

																					_a			  =       ['pixel_values']
																					self.assertListEqual(arg_names[:1]							,    lowerCAmelCase_      )







							def      __lowerCAmelCase    (						self :						Dict      )    ->							Any:


														"""simple docstring"""


														_a			  =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*lowerCAmelCase_      )







							def      __lowerCAmelCase    (						self :						List[str]      )    ->							Union[str, Any]:


														"""simple docstring"""


														_a			  =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase_      )







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							Optional[int]:


														"""simple docstring"""


														_a			  =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_      )







							def      __lowerCAmelCase    (						self :						str							,    lowerCAmelCase_ :						Dict							,    lowerCAmelCase_ :						List[str]							,    lowerCAmelCase_ :						Dict=False      )    ->							Any:


														"""simple docstring"""


														_a			  =       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      __lowerCAmelCase    (						self :						Tuple      )    ->							Union[str, Any]:


														"""simple docstring"""


														for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					_a			  =       TFDeiTModel.from_pretrained(lowerCAmelCase_      )
																					self.assertIsNotNone(lowerCAmelCase_      )



def 	snake_case_					():





							'''simple docstring'''


							_a			  =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
							return image

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







							@cached_property
							def      __lowerCAmelCase    (						self :						Any      )    ->							Tuple:


														"""simple docstring"""


														return (
														    DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224'''      )
														    if is_vision_available()
														    else None
														)







							@slow
							def      __lowerCAmelCase    (						self :						Optional[Any]      )    ->							str:


														"""simple docstring"""


														_a			  =       TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''      )

														_a			  =       self.default_image_processor
														_a			  =       prepare_img()
														_a			  =       image_processor(images=lowerCAmelCase_							,    return_tensors='''tf'''      )

														# forward pass
														_a			  =       model(**lowerCAmelCase_      )

														# verify the logits
														_a			  =       tf.TensorShape((1, 10_00)      )
														self.assertEqual(outputs.logits.shape							,    lowerCAmelCase_      )

														_a			  =       tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1]      )

														self.assertTrue(np.allclose(outputs.logits[0, :3]							,    lowerCAmelCase_							,    atol=1e-4      )      )







'''simple docstring'''


import math
import unittest
def 	snake_case_					(UpperCamelCase :						int   ):





							'''simple docstring'''


							assert isinstance(UpperCamelCase				,		UpperCamelCase   ) and (
							    number >= 0
							), "'number' must been an int and positive"

							if 1 < number < 4:
														# 2 and 3 are primes
														return True
							elif number < 2 or number % 2 == 0 or number % 3 == 0:
														# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
														return False

							# All primes number are in format of 6k +/- 1
							for i in range(5				,		int(math.sqrt(UpperCamelCase   ) + 1   )				,		6   ):
														if number % i == 0 or number % (i + 2) == 0:
																					return False
							return True

class     A					(	unittest.TestCase					):







							def      __lowerCAmelCase    (						self :						Union[str, Any]      )    ->							Optional[Any]:


														"""simple docstring"""


														self.assertTrue(is_prime(2      )      )
														self.assertTrue(is_prime(3      )      )
														self.assertTrue(is_prime(5      )      )
														self.assertTrue(is_prime(7      )      )
														self.assertTrue(is_prime(11      )      )
														self.assertTrue(is_prime(13      )      )
														self.assertTrue(is_prime(17      )      )
														self.assertTrue(is_prime(19      )      )
														self.assertTrue(is_prime(23      )      )
														self.assertTrue(is_prime(29      )      )







							def      __lowerCAmelCase    (						self :						Any      )    ->							Dict:


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					is_prime(-19      )
														self.assertFalse(
														    is_prime(0      )							,    '''Zero doesn\'t have any positive factors, primes must have exactly two.'''							,    )
														self.assertFalse(
														    is_prime(1      )							,    '''One only has 1 positive factor, primes must have exactly two.'''							,    )
														self.assertFalse(is_prime(2 * 2      )      )
														self.assertFalse(is_prime(2 * 3      )      )
														self.assertFalse(is_prime(3 * 3      )      )
														self.assertFalse(is_prime(3 * 5      )      )
														self.assertFalse(is_prime(3 * 5 * 7      )      )


if __name__ == "__main__":
				unittest.main()

