


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[Any]					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=1_3					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=3_0					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]=2					,							SCREAMING_SNAKE_CASE__    :	str=3					,							SCREAMING_SNAKE_CASE__    :	Optional[int]=True					,							SCREAMING_SNAKE_CASE__    :	Any=True					,							SCREAMING_SNAKE_CASE__    :	List[str]=3_2					,							SCREAMING_SNAKE_CASE__    :	Dict=2					,							SCREAMING_SNAKE_CASE__    :	List[Any]=4					,							SCREAMING_SNAKE_CASE__    :	str=3_7					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]="gelu"					,							SCREAMING_SNAKE_CASE__    :	Any=0.1					,							SCREAMING_SNAKE_CASE__    :	Dict=0.1					,							SCREAMING_SNAKE_CASE__    :	List[str]=1_0					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]=0.02					,							SCREAMING_SNAKE_CASE__    :	str=3					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]=None					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]=2					,							)		->      Tuple:
             a_ :		List[str]							=  parent
             a_ :		Optional[int]							=  batch_size
             a_ :		str							=  image_size
             a_ :		Dict							=  patch_size
             a_ :		Optional[Any]							=  num_channels
             a_ :		int							=  is_training
             a_ :		str							=  use_labels
             a_ :		List[Any]							=  hidden_size
             a_ :		Optional[Any]							=  num_hidden_layers
             a_ :		List[str]							=  num_attention_heads
             a_ :		List[Any]							=  intermediate_size
             a_ :		str							=  hidden_act
             a_ :		Union[str, Any]							=  hidden_dropout_prob
             a_ :		int							=  attention_probs_dropout_prob
             a_ :		Dict							=  type_sequence_label_size
             a_ :		Optional[int]							=  initializer_range
             a_ :		Tuple							=  scope
             a_ :		Any							=  encoder_stride

             # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
             a_ :		Optional[int]							=  (image_size // patch_size) ** 2
             a_ :		int							=  num_patches + 2
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[str]					)		->      Any:
             a_ :		Tuple							=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

             a_ :		Optional[Any]							=  None
             if self.use_labels:
                    a_ :		str							=  ids_tensor([self.batch_size]					,							self.type_sequence_label_size					)

             a_ :		Tuple							=  self.get_config()

             return config, pixel_values, labels
      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					)		->      List[Any]:
             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 	SCREAMING_SNAKE_CASE							(	self    :	Dict					,							SCREAMING_SNAKE_CASE__    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	Union[str, Any]					)		->      str:
             a_ :		List[Any]							=  TFDeiTModel(config=UpperCamelCase__					)
             a_ :		Any							=  model(UpperCamelCase__					)
             self.parent.assertEqual(result.last_hidden_state.shape					,							(self.batch_size, self.seq_length, self.hidden_size)					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	Tuple					)		->      Optional[int]:
             a_ :		Optional[Any]							=  TFDeiTForMaskedImageModeling(config=UpperCamelCase__					)
             a_ :		Union[str, Any]							=  model(UpperCamelCase__					)
             self.parent.assertEqual(
                 result.reconstruction.shape					,							(self.batch_size, self.num_channels, self.image_size, self.image_size)					)

             # test greyscale images
             a_ :		List[Any]							=  1
             a_ :		Tuple							=  TFDeiTForMaskedImageModeling(UpperCamelCase__					)

             a_ :		Tuple							=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
             a_ :		Tuple							=  model(UpperCamelCase__					)
             self.parent.assertEqual(result.reconstruction.shape					,							(self.batch_size, 1, self.image_size, self.image_size)					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					,							SCREAMING_SNAKE_CASE__    :	int					)		->      int:
             a_ :		str							=  self.type_sequence_label_size
             a_ :		Any							=  TFDeiTForImageClassification(UpperCamelCase__					)
             a_ :		Any							=  model(UpperCamelCase__					,							labels=UpperCamelCase__					)
             self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.type_sequence_label_size)					)

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

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

      def 	SCREAMING_SNAKE_CASE							(	self    :	int					)		->      Dict:
             a_ :		int							=  self.prepare_config_and_inputs()
             a_							,		a_							,		a_ :		Tuple							=  config_and_inputs
             a_ :		List[Any]							=  {'pixel_values': pixel_values}
             return config, inputs_dict
@require_tf
class 			SCREAMING_SNAKE_CASE__  (    __a						,   __a						,   unittest.TestCase      ):
      snake_case__    :					Optional[int]					       =						(
          (
              TFDeiTModel,
              TFDeiTForImageClassification,
              TFDeiTForImageClassificationWithTeacher,
              TFDeiTForMaskedImageModeling,
          )
          if is_tf_available()
          else ()
      )
      snake_case__    :					Optional[Any]					       =						(
          {
              '''feature-extraction''': TFDeiTModel,
              '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
          }
          if is_tf_available()
          else {}
      )

      snake_case__    :					Dict					       =						False
      snake_case__    :					List[Any]					       =						False
      snake_case__    :					Dict					       =						False
      snake_case__    :					Any					       =						False
      def 	SCREAMING_SNAKE_CASE							(	self    :	Tuple					)		->      str:
             a_ :		List[str]							=  TFDeiTModelTester(self					)
             a_ :		int							=  ConfigTester(self					,							config_class=UpperCamelCase__					,							has_text_modality=UpperCamelCase__					,							hidden_size=3_7					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					)		->      Optional[Any]:
             self.config_tester.run_common_tests()
      @unittest.skip(reason='DeiT does not use inputs_embeds'					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	int					)		->      Dict:
             pass
      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					)		->      Union[str, Any]:
             a_							,		a_ :		List[Any]							=  self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    a_ :		str							=  model_class(UpperCamelCase__					)
                    self.assertIsInstance(model.get_input_embeddings()					,							(tf.keras.layers.Layer)					)
                    a_ :		Any							=  model.get_output_embeddings()
                    self.assertTrue(x is None or isinstance(UpperCamelCase__					,							tf.keras.layers.Dense					)					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					)		->      int:
             a_							,		a_ :		Union[str, Any]							=  self.model_tester.prepare_config_and_inputs_for_common()

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

                    a_ :		List[str]							=  ['pixel_values']
                    self.assertListEqual(arg_names[:1]					,							UpperCamelCase__					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	int					)		->      List[Any]:
             a_ :		Any							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*UpperCamelCase__					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					)		->      Optional[int]:
             a_ :		str							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					)		->      List[str]:
             a_ :		int							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	List[str]					,							SCREAMING_SNAKE_CASE__    :	Dict					,							SCREAMING_SNAKE_CASE__    :	int=False					)		->      Union[str, Any]:
             a_ :		Optional[Any]							=  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 	SCREAMING_SNAKE_CASE							(	self    :	Tuple					)		->      Optional[int]:



             for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    a_ :		str							=  TFDeiTModel.from_pretrained(UpperCamelCase__					)
                    self.assertIsNotNone(UpperCamelCase__					)







def 	SCREAMING_SNAKE_CASE_						(			)     ->		Optional[int]:

       """simple docstring"""

       a_ :		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 	SCREAMING_SNAKE_CASE							(	self    :	Any					)		->      Tuple:
             return (
                 DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224'					)
                 if is_vision_available()
                 else None
             )

      @slow
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					)		->      Union[str, Any]:
             a_ :		Any							=  TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224'					)

             a_ :		Union[str, Any]							=  self.default_image_processor
             a_ :		Optional[int]							=  prepare_img()
             a_ :		Optional[int]							=  image_processor(images=UpperCamelCase__					,							return_tensors='tf'					)

             # forward pass
             a_ :		Optional[Any]							=  model(**UpperCamelCase__					)

             # verify the logits
             a_ :		Union[str, Any]							=  tf.TensorShape((1, 1_0_0_0)					)
             self.assertEqual(outputs.logits.shape					,							UpperCamelCase__					)

             a_ :		Any							=  tf.constant([-1.0266, 0.1912, -1.2861]					)

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






from __future__ import annotations

UpperCAmelCase_				:			Dict   =	[True] * 100_0001
UpperCAmelCase_				:			Any   =	2
while i * i <= 100_0000:
   if seive[i]:
      for j in range(i * i, 100_0001, i):
         UpperCAmelCase_				:			Tuple   =	False
   i += 1







def 	SCREAMING_SNAKE_CASE_						(      __A			:      int    )     ->		bool:

       """simple docstring"""

       return seive[n]







def 	SCREAMING_SNAKE_CASE_						(      __A			:      int    )     ->		bool:

       """simple docstring"""

       return any(digit in '02468' for digit in str(__A    )    )







def 	SCREAMING_SNAKE_CASE_						(      __A			:      int = 1_00_00_00    )     ->		list[int]:

       """simple docstring"""

       a_ :		Dict							=  [2]  # result already includes the number 2.
       for num in range(3  ,   limit + 1  ,   2    ):
              if is_prime(__A    ) and not contains_an_even_digit(__A    ):
                     a_ :		Dict							=  str(__A    )
                     a_ :		Any							=  [int(str_num[j:] + str_num[:j]    ) for j in range(len(__A    )    )]
                     if all(is_prime(__A    ) for i in list_nums    ):
                            result.append(__A    )
       return result







def 	SCREAMING_SNAKE_CASE_						(      )     ->		int:

       """simple docstring"""

       return len(find_circular_primes()    )


if __name__ == "__main__":
   print(F'{len(find_circular_primes()) = }')


