



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




       """simple docstring"""






       def __init__(     self     ,lowercase     ,lowercase=13     ,lowercase=30     ,lowercase=2     ,lowercase=3     ,lowercase=True     ,lowercase=True     ,lowercase=32     ,lowercase=2     ,lowercase=4     ,lowercase=37     ,lowercase="gelu"     ,lowercase=0.1     ,lowercase=0.1     ,lowercase=10     ,lowercase=0.02     ,lowercase=3     ,lowercase=None     ,):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		parent
             UpperCAmelCase_  :	Any				      =		batch_size
             UpperCAmelCase_  :	str				      =		image_size
             UpperCAmelCase_  :	int				      =		patch_size
             UpperCAmelCase_  :	Union[str, Any]				      =		num_channels
             UpperCAmelCase_  :	int				      =		is_training
             UpperCAmelCase_  :	int				      =		use_labels
             UpperCAmelCase_  :	List[Any]				      =		hidden_size
             UpperCAmelCase_  :	Dict				      =		num_hidden_layers
             UpperCAmelCase_  :	Any				      =		num_attention_heads
             UpperCAmelCase_  :	int				      =		intermediate_size
             UpperCAmelCase_  :	Any				      =		hidden_act
             UpperCAmelCase_  :	Tuple				      =		hidden_dropout_prob
             UpperCAmelCase_  :	Union[str, Any]				      =		attention_probs_dropout_prob
             UpperCAmelCase_  :	List[str]				      =		type_sequence_label_size
             UpperCAmelCase_  :	Any				      =		initializer_range
             UpperCAmelCase_  :	Any				      =		scope

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



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

             UpperCAmelCase_  :	List[Any]				      =		None
             if self.use_labels:
                   UpperCAmelCase_  :	List[Any]				      =		ids_tensor([self.batch_size]     ,self.type_sequence_label_size)

             UpperCAmelCase_  :	Tuple				      =		self.get_config()

             return config, pixel_values, labels



       def  A_   (     self):

             """simple docstring"""





             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=lowercase     ,initializer_range=self.initializer_range     ,)



       def  A_   (     self     ,lowercase     ,lowercase     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		TFViTModel(config=lowercase)
             UpperCAmelCase_  :	int				      =		model(lowercase     ,training=lowercase)
             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.
             UpperCAmelCase_  :	str				      =		self.image_size // 2
             UpperCAmelCase_  :	int				      =		pixel_values[:, :, :image_size, :image_size]
             UpperCAmelCase_  :	Optional[Any]				      =		model(lowercase     ,interpolate_pos_encoding=lowercase     ,training=lowercase)
             UpperCAmelCase_  :	str				      =		(image_size // self.patch_size) ** 2 + 1
             self.parent.assertEqual(result.last_hidden_state.shape     ,(self.batch_size, seq_length, self.hidden_size))



       def  A_   (     self     ,lowercase     ,lowercase     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		self.type_sequence_label_size
             UpperCAmelCase_  :	Tuple				      =		TFViTForImageClassification(lowercase)
             UpperCAmelCase_  :	Optional[int]				      =		model(lowercase     ,labels=lowercase     ,training=lowercase)
             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.
             UpperCAmelCase_  :	int				      =		self.image_size // 2
             UpperCAmelCase_  :	Optional[Any]				      =		pixel_values[:, :, :image_size, :image_size]
             UpperCAmelCase_  :	int				      =		model(lowercase     ,interpolate_pos_encoding=lowercase     ,training=lowercase)
             self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.type_sequence_label_size))

             # test greyscale images
             UpperCAmelCase_  :	Optional[Any]				      =		1
             UpperCAmelCase_  :	List[str]				      =		TFViTForImageClassification(lowercase)
             UpperCAmelCase_  :	Any				      =		floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
             UpperCAmelCase_  :	int				      =		model(lowercase)
             self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.type_sequence_label_size))



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		self.prepare_config_and_inputs()
             UpperCAmelCase_      ,      UpperCAmelCase_      ,      UpperCAmelCase_  :	str				      =		config_and_inputs
             UpperCAmelCase_  :	Union[str, Any]				      =		{"pixel_values": pixel_values}
             return config, inputs_dict


@require_tf
class   snake_case_ (lowercase__ , lowercase__ , unittest.TestCase  ):




       """simple docstring"""






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

       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False
       _lowerCamelCase			    =				False



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		TFViTModelTester(self)
             UpperCAmelCase_  :	Any				      =		ConfigTester(self     ,config_class=lowercase     ,has_text_modality=lowercase     ,hidden_size=37)



       def  A_   (     self):

             """simple docstring"""





             self.config_tester.run_common_tests()



       @unittest.skip(reason="ViT does not use inputs_embeds")
       def  A_   (     self):

             """simple docstring"""





             pass



       @unittest.skip(reason="ViT does not use inputs_embeds")
       def  A_   (     self):

             """simple docstring"""





             pass



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_      ,      UpperCAmelCase_  :	Dict				      =		self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_  :	str				      =		model_class(lowercase)
                   self.assertIsInstance(model.get_input_embeddings()     ,(tf.keras.layers.Layer))
                   UpperCAmelCase_  :	Any				      =		model.get_output_embeddings()
                   self.assertTrue(x is None or isinstance(lowercase     ,tf.keras.layers.Layer))



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_      ,      UpperCAmelCase_  :	Tuple				      =		self.model_tester.prepare_config_and_inputs_for_common()

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

                   UpperCAmelCase_  :	Union[str, Any]				      =		["pixel_values"]
                   self.assertListEqual(arg_names[:1]     ,lowercase)



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Tuple				      =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase)



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	List[str]				      =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*lowercase)



       @slow
       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	Optional[int]				      =		TFViTModel.from_pretrained("google/vit-base-patch16-224")
             self.assertIsNotNone(lowercase)







def    _snake_case (       )     ->     Tuple:






      '''simple docstring'''







      UpperCAmelCase_  :	List[Any]				      =		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
      return image





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




       """simple docstring"""






       @cached_property
       def  A_   (     self):

             """simple docstring"""





             return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224") if is_vision_available() else None



       @slow
       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224")

             UpperCAmelCase_  :	Dict				      =		self.default_image_processor
             UpperCAmelCase_  :	Dict				      =		prepare_img()
             UpperCAmelCase_  :	List[str]				      =		image_processor(images=lowercase     ,return_tensors="tf")

             # forward pass
             UpperCAmelCase_  :	Optional[Any]				      =		model(**lowercase)

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

             UpperCAmelCase_  :	Optional[Any]				      =		tf.constant([-0.2744, 0.8215, -0.0836])

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





# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
   import torch


class   snake_case_ (TensorFormatter[Mapping, """torch.Tensor""", Mapping]  ):




       """simple docstring"""






       def __init__(     self     ,lowercase=None     ,**lowercase):

             """simple docstring"""





             super().__init__(features=lowercase)
             UpperCAmelCase_  :	Union[str, Any]				      =		torch_tensor_kwargs
             import torch  # noqa import torch at initialization



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             import torch

             if isinstance(lowercase     ,lowercase) and column:
                   if all(
                       isinstance(lowercase     ,torch.Tensor) and x.shape == column[0].shape and x.dtype == column[0].dtype
                       for x in column):
                         return torch.stack(lowercase)
             return column



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             import torch

             if isinstance(lowercase     ,(str, bytes, type(lowercase))):
                   return value
             elif isinstance(lowercase     ,(np.character, np.ndarray)) and np.issubdtype(value.dtype     ,np.character):
                   return value.tolist()

             UpperCAmelCase_  :	List[str]				      =		{}

             if isinstance(lowercase     ,(np.number, np.ndarray)) and np.issubdtype(value.dtype     ,np.integer):
                   UpperCAmelCase_  :	Dict				      =		{"dtype": torch.intaa}
             elif isinstance(lowercase     ,(np.number, np.ndarray)) and np.issubdtype(value.dtype     ,np.floating):
                   UpperCAmelCase_  :	Optional[Any]				      =		{"dtype": torch.floataa}
             elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                   import PIL.Image

                   if isinstance(lowercase     ,PIL.Image.Image):
                         UpperCAmelCase_  :	List[str]				      =		np.asarray(lowercase)
             return torch.tensor(lowercase     ,**{**default_dtype, **self.torch_tensor_kwargs})



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             import torch

             # support for torch, tf, jax etc.
             if hasattr(lowercase     ,"__array__") and not isinstance(lowercase     ,torch.Tensor):
                   UpperCAmelCase_  :	int				      =		data_struct.__array__()
             # support for nested types like struct of list of struct
             if isinstance(lowercase     ,np.ndarray):
                   if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                         return self._consolidate([self.recursive_tensorize(lowercase) for substruct in data_struct])
             elif isinstance(lowercase     ,(list, tuple)):
                   return self._consolidate([self.recursive_tensorize(lowercase) for substruct in data_struct])
             return self._tensorize(lowercase)



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             return map_nested(self._recursive_tensorize     ,lowercase     ,map_list=lowercase)



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		self.numpy_arrow_extractor().extract_row(lowercase)
             UpperCAmelCase_  :	Tuple				      =		self.python_features_decoder.decode_row(lowercase)
             return self.recursive_tensorize(lowercase)



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	str				      =		self.numpy_arrow_extractor().extract_column(lowercase)
             UpperCAmelCase_  :	List[Any]				      =		self.python_features_decoder.decode_column(lowercase     ,pa_table.column_names[0])
             UpperCAmelCase_  :	List[Any]				      =		self.recursive_tensorize(lowercase)
             UpperCAmelCase_  :	List[str]				      =		self._consolidate(lowercase)
             return column



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		self.numpy_arrow_extractor().extract_batch(lowercase)
             UpperCAmelCase_  :	Optional[int]				      =		self.python_features_decoder.decode_batch(lowercase)
             UpperCAmelCase_  :	List[Any]				      =		self.recursive_tensorize(lowercase)
             for column_name in batch:
                   UpperCAmelCase_  :	Optional[int]				      =		self._consolidate(batch[column_name])
             return batch
