
'''simple docstring'''



from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
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 TFViTForImageClassification, TFViTModel


if is_vision_available():
     from PIL import Image

     from transformers import ViTImageProcessor

class    _a				:





       """simple docstring"""




       def __init__(							self       ,							A__       ,							A__=13       ,							A__=30       ,							A__=2       ,							A__=3       ,							A__=True       ,							A__=True       ,							A__=32       ,							A__=2       ,							A__=4       ,							A__=37       ,							A__="gelu"       ,							A__=0.1       ,							A__=0.1       ,							A__=10       ,							A__=0.02       ,							A__=3       ,							A__=None       ,							)    ->			Optional[int]:
          _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

          # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
          _SCREAMING_SNAKE_CASE      =				(image_size // patch_size) ** 2
          _SCREAMING_SNAKE_CASE      =				num_patches + 1






       def        UpperCamelCase				(							self      )    ->			str:
          _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        UpperCamelCase				(							self      )    ->			Any:
          return ViTConfig(
              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       ,							)






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__      )    ->			List[str]:
          _SCREAMING_SNAKE_CASE      =				TFViTModel(config=UpperCAmelCase__      )
          _SCREAMING_SNAKE_CASE      =				model(UpperCAmelCase__       ,							training=UpperCAmelCase__      )
          self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.hidden_size)      )

          # Test with an image with different size than the one specified in config.
          _SCREAMING_SNAKE_CASE      =				self.image_size // 2
          _SCREAMING_SNAKE_CASE      =				pixel_values[:, :, :image_size, :image_size]
          _SCREAMING_SNAKE_CASE      =				model(UpperCAmelCase__       ,							interpolate_pos_encoding=UpperCAmelCase__       ,							training=UpperCAmelCase__      )
          _SCREAMING_SNAKE_CASE      =				(image_size // self.patch_size) ** 2 + 1
          self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, seq_length, self.hidden_size)      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__       ,							A__      )    ->			Tuple:
          _SCREAMING_SNAKE_CASE      =				self.type_sequence_label_size
          _SCREAMING_SNAKE_CASE      =				TFViTForImageClassification(UpperCAmelCase__      )
          _SCREAMING_SNAKE_CASE      =				model(UpperCAmelCase__       ,							labels=UpperCAmelCase__       ,							training=UpperCAmelCase__      )
          self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.type_sequence_label_size)      )

          # Test with an image with different size than the one specified in config.
          _SCREAMING_SNAKE_CASE      =				self.image_size // 2
          _SCREAMING_SNAKE_CASE      =				pixel_values[:, :, :image_size, :image_size]
          _SCREAMING_SNAKE_CASE      =				model(UpperCAmelCase__       ,							interpolate_pos_encoding=UpperCAmelCase__       ,							training=UpperCAmelCase__      )
          self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.type_sequence_label_size)      )

          # test greyscale images
          _SCREAMING_SNAKE_CASE      =				1
          _SCREAMING_SNAKE_CASE      =				TFViTForImageClassification(UpperCAmelCase__      )
          _SCREAMING_SNAKE_CASE      =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
          _SCREAMING_SNAKE_CASE      =				model(UpperCAmelCase__      )
          self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.type_sequence_label_size)      )






       def        UpperCamelCase				(							self      )    ->			Dict:
          _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    _a				(_lowerCamelCase  ,					_lowerCamelCase  ,					unittest.TestCase):





       """simple docstring"""




       SCREAMING_SNAKE_CASE      =  (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
       SCREAMING_SNAKE_CASE      =  (
           {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
           if is_tf_available()
           else {}
       )

       SCREAMING_SNAKE_CASE      =  False
       SCREAMING_SNAKE_CASE      =  False
       SCREAMING_SNAKE_CASE      =  False






       def        UpperCamelCase				(							self      )    ->			int:
          _SCREAMING_SNAKE_CASE      =				TFViTModelTester(self      )
          _SCREAMING_SNAKE_CASE      =				ConfigTester(self       ,							config_class=UpperCAmelCase__       ,							has_text_modality=UpperCAmelCase__       ,							hidden_size=37      )






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






       @unittest.skip(reason="""ViT does not use inputs_embeds"""      )
       def        UpperCamelCase				(							self      )    ->			Tuple:
          pass






       @unittest.skip(reason="""ViT does not use inputs_embeds"""      )
       def        UpperCamelCase				(							self      )    ->			List[str]:
          pass






       def        UpperCamelCase				(							self      )    ->			Tuple:
          _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(UpperCAmelCase__      )
             self.assertIsInstance(model.get_input_embeddings()       ,							(tf.keras.layers.Layer)      )
             _SCREAMING_SNAKE_CASE      =				model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(UpperCAmelCase__       ,							tf.keras.layers.Layer      )      )






       def        UpperCamelCase				(							self      )    ->			int:
          _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(UpperCAmelCase__      )
             _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]       ,							UpperCAmelCase__      )






       def        UpperCamelCase				(							self      )    ->			List[Any]:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*UpperCAmelCase__      )






       def        UpperCamelCase				(							self      )    ->			Any:
          _SCREAMING_SNAKE_CASE      =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__      )






       @slow
       def        UpperCamelCase				(							self      )    ->			int:
          _SCREAMING_SNAKE_CASE      =				TFViTModel.from_pretrained("""google/vit-base-patch16-224"""      )
          self.assertIsNotNone(UpperCAmelCase__      )






def    lowerCAmelCase_	(				)     ->     Dict:




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







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





       """simple docstring"""




       @cached_property
       def        UpperCamelCase				(							self      )    ->			str:
          return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""      ) if is_vision_available() else None






       @slow
       def        UpperCamelCase				(							self      )    ->			Union[str, Any]:
          _SCREAMING_SNAKE_CASE      =				TFViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""      )

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

          # forward pass
          _SCREAMING_SNAKE_CASE      =				model(**UpperCAmelCase__      )

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

          _SCREAMING_SNAKE_CASE      =				tf.constant([-0.2744, 0.8215, -0.0836]      )

          tf.debugging.assert_near(outputs.logits[0, :3]       ,							UpperCAmelCase__       ,							atol=1E-4      )

'''simple docstring'''



def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     int:




   """simple docstring"""

   if not isinstance(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						):
      raise ValueError("""multiplicative_persistence() only accepts integral values"""						)
   if num < 0:
      raise ValueError("""multiplicative_persistence() does not accept negative values"""						)

   _SCREAMING_SNAKE_CASE      =				0
   _SCREAMING_SNAKE_CASE      =				str(SCREAMING_SNAKE_CASE_						)

   while len(SCREAMING_SNAKE_CASE_						) != 1:
      _SCREAMING_SNAKE_CASE      =				[int(SCREAMING_SNAKE_CASE_						) for i in num_string]

      _SCREAMING_SNAKE_CASE      =				1
      for i in range(0    ,      len(SCREAMING_SNAKE_CASE_						)						):
         total *= numbers[i]

      _SCREAMING_SNAKE_CASE      =				str(SCREAMING_SNAKE_CASE_						)

      steps += 1
   return steps
def    lowerCAmelCase_	(				SCREAMING_SNAKE_CASE_						)     ->     int:




   """simple docstring"""

   if not isinstance(SCREAMING_SNAKE_CASE_    ,      SCREAMING_SNAKE_CASE_						):
      raise ValueError("""additive_persistence() only accepts integral values"""						)
   if num < 0:
      raise ValueError("""additive_persistence() does not accept negative values"""						)

   _SCREAMING_SNAKE_CASE      =				0
   _SCREAMING_SNAKE_CASE      =				str(SCREAMING_SNAKE_CASE_						)

   while len(SCREAMING_SNAKE_CASE_						) != 1:
      _SCREAMING_SNAKE_CASE      =				[int(SCREAMING_SNAKE_CASE_						) for i in num_string]

      _SCREAMING_SNAKE_CASE      =				0
      for i in range(0    ,      len(SCREAMING_SNAKE_CASE_						)						):
         total += numbers[i]

      _SCREAMING_SNAKE_CASE      =				str(SCREAMING_SNAKE_CASE_						)

      steps += 1
   return steps


if __name__ == "__main__":
     import doctest

     doctest.testmod()






