

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 	UpperCAmelCase__		:






  """simple docstring"""


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

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






  def 				lowercase_		(							self						:		List[Any] )		->							List[Any]:
       SCREAMING_SNAKE_CASE__   =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

       SCREAMING_SNAKE_CASE__   =   self.get_config()

       return config, pixel_values, labels






  def 				lowercase_		(							self						:		List[Any] )		->							Union[str, 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=__lowerCamelCase     ,       initializer_range=self.initializer_range     ,       encoder_stride=self.encoder_stride     ,       )






  def 				lowercase_		(							self						:		int     ,       __lowerCamelCase						:		Optional[int]     ,       __lowerCamelCase						:		List[str]     ,       __lowerCamelCase						:		int )		->							Optional[Any]:
       SCREAMING_SNAKE_CASE__   =   TFDeiTModel(config=__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   model(__lowerCamelCase )
       self.parent.assertEqual(result.last_hidden_state.shape     ,       (self.batch_size, self.seq_length, self.hidden_size) )






  def 				lowercase_		(							self						:		Optional[int]     ,       __lowerCamelCase						:		Union[str, Any]     ,       __lowerCamelCase						:		Dict     ,       __lowerCamelCase						:		int )		->							Dict:
       SCREAMING_SNAKE_CASE__   =   TFDeiTForMaskedImageModeling(config=__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   model(__lowerCamelCase )
       self.parent.assertEqual(
           result.reconstruction.shape     ,       (self.batch_size, self.num_channels, self.image_size, self.image_size) )

       # test greyscale images
       SCREAMING_SNAKE_CASE__   =   1
       SCREAMING_SNAKE_CASE__   =   TFDeiTForMaskedImageModeling(__lowerCamelCase )

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






  def 				lowercase_		(							self						:		Optional[int]     ,       __lowerCamelCase						:		Any     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		List[Any] )		->							List[str]:
       SCREAMING_SNAKE_CASE__   =   self.type_sequence_label_size
       SCREAMING_SNAKE_CASE__   =   TFDeiTForImageClassification(__lowerCamelCase )
       SCREAMING_SNAKE_CASE__   =   model(__lowerCamelCase     ,       labels=__lowerCamelCase )
       self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.type_sequence_label_size) )

       # test greyscale images
       SCREAMING_SNAKE_CASE__   =   1
       SCREAMING_SNAKE_CASE__   =   TFDeiTForImageClassification(__lowerCamelCase )

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







  def 				lowercase_		(							self						:		Optional[int] )		->							int:
       SCREAMING_SNAKE_CASE__   =   self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   config_and_inputs
       SCREAMING_SNAKE_CASE__   =   {'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_tf
class 	UpperCAmelCase__		(	A__						,					A__						,					unittest.TestCase	):






  """simple docstring"""


  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						:		int )		->							List[Any]:
       SCREAMING_SNAKE_CASE__   =   TFDeiTModelTester(self )
       SCREAMING_SNAKE_CASE__   =   ConfigTester(self     ,       config_class=__lowerCamelCase     ,       has_text_modality=__lowerCamelCase     ,       hidden_size=37 )






  def 				lowercase_		(							self						:		Optional[int] )		->							Any:
       self.config_tester.run_common_tests()






  @unittest.skip(reason='''DeiT does not use inputs_embeds''' )
  def 				lowercase_		(							self						:		Optional[int] )		->							int:
       pass






  def 				lowercase_		(							self						:		List[Any] )		->							List[Any]:
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   self.model_tester.prepare_config_and_inputs_for_common()

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






  def 				lowercase_		(							self						:		Dict )		->							List[Any]:
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__   =   self.model_tester.prepare_config_and_inputs_for_common()

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

            SCREAMING_SNAKE_CASE__   =   ['''pixel_values''']
            self.assertListEqual(arg_names[:1]     ,       __lowerCamelCase )






  def 				lowercase_		(							self						:		Any )		->							Optional[Any]:
       SCREAMING_SNAKE_CASE__   =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCamelCase )






  def 				lowercase_		(							self						:		List[str] )		->							Dict:
       SCREAMING_SNAKE_CASE__   =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCamelCase )






  def 				lowercase_		(							self						:		int )		->							int:
       SCREAMING_SNAKE_CASE__   =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase )






  def 				lowercase_		(							self						:		Any     ,       __lowerCamelCase						:		Tuple     ,       __lowerCamelCase						:		Optional[int]     ,       __lowerCamelCase						:		List[Any]=False )		->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__   =   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						:		str )		->							Any:
       for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            SCREAMING_SNAKE_CASE__   =   TFDeiTModel.from_pretrained(__lowerCamelCase )
            self.assertIsNotNone(__lowerCamelCase )



def     UpperCAmelCase_       (						):





     '''simple docstring'''




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







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






  """simple docstring"""


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







  @slow
  def 				lowercase_		(							self						:		List[Any] )		->							Optional[int]:
       SCREAMING_SNAKE_CASE__   =   TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' )

       SCREAMING_SNAKE_CASE__   =   self.default_image_processor
       SCREAMING_SNAKE_CASE__   =   prepare_img()
       SCREAMING_SNAKE_CASE__   =   image_processor(images=__lowerCamelCase     ,       return_tensors='''tf''' )

       # forward pass
       SCREAMING_SNAKE_CASE__   =   model(**__lowerCamelCase )

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

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

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





def     UpperCAmelCase_       (						_A    ):





     '''simple docstring'''




     if divisor % 5 == 0 or divisor % 2 == 0:
          return 0
     SCREAMING_SNAKE_CASE__   =   1
     SCREAMING_SNAKE_CASE__   =   1
     while repunit:
          SCREAMING_SNAKE_CASE__   =   (10 * repunit + 1) % divisor
          repunit_index += 1
     return repunit_index
def     UpperCAmelCase_       (						_A = 1_00_00_00    ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__   =   limit - 1
     if divisor % 2 == 0:
          divisor += 1
     while least_divisible_repunit(_A    ) <= limit:
          divisor += 2
     return divisor


if __name__ == "__main__":
       print(F"{solution() = }")


