





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


  '''simple docstring'''







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


    '''simple docstring'''





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

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







  def UpperCamelCase_ (      self      :					Union[str, Any]							):


    '''simple docstring'''





    _snake_case   :				List[Any]														=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

    _snake_case   :				int														=	None
    if self.use_labels:
      _snake_case   :				Optional[int]														=	ids_tensor([self.batch_size]      ,				self.type_sequence_label_size							)

    _snake_case   :				Union[str, Any]														=	self.get_config()

    return config, pixel_values, labels







  def UpperCamelCase_ (      self      :					str							):


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







  def UpperCamelCase_ (      self      :					Dict      ,				UpperCamelCase      :					Optional[int]      ,				UpperCamelCase      :					Optional[int]      ,				UpperCamelCase      :					Optional[int]							):


    '''simple docstring'''





    _snake_case   :				str														=	TFViTModel(config=UpperCamelCase__							)
    _snake_case   :				Optional[int]														=	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.
    _snake_case   :				str														=	self.image_size // 2
    _snake_case   :				Union[str, Any]														=	pixel_values[:, :, :image_size, :image_size]
    _snake_case   :				int														=	model(UpperCamelCase__      ,				interpolate_pos_encoding=UpperCamelCase__      ,				training=UpperCamelCase__							)
    _snake_case   :				Union[str, Any]														=	(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      :					int      ,				UpperCamelCase      :					List[Any]      ,				UpperCamelCase      :					str      ,				UpperCamelCase      :					Optional[int]							):


    '''simple docstring'''





    _snake_case   :				Optional[Any]														=	self.type_sequence_label_size
    _snake_case   :				Optional[int]														=	TFViTForImageClassification(UpperCamelCase__							)
    _snake_case   :				Optional[Any]														=	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.
    _snake_case   :				Tuple														=	self.image_size // 2
    _snake_case   :				List[str]														=	pixel_values[:, :, :image_size, :image_size]
    _snake_case   :				Union[str, Any]														=	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
    _snake_case   :				Optional[int]														=	1
    _snake_case   :				str														=	TFViTForImageClassification(UpperCamelCase__							)
    _snake_case   :				List[Any]														=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
    _snake_case   :				List[Any]														=	model(UpperCamelCase__							)
    self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.type_sequence_label_size)							)







  def UpperCamelCase_ (      self      :					List[Any]							):


    '''simple docstring'''





    _snake_case   :				List[Any]														=	self.prepare_config_and_inputs()
    _snake_case							,					_snake_case							,					_snake_case   :				List[Any]														=	config_and_inputs
    _snake_case   :				List[Any]														=	{'pixel_values': pixel_values}
    return config, inputs_dict







@require_tf
class        _lowerCAmelCase    (			UpperCAmelCase_							,    UpperCAmelCase_							,    unittest.TestCase							):


  '''simple docstring'''
  a_							:       str      					=(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
  a_							:       Tuple      					=(
      {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification}
      if is_tf_available()
      else {}
  )

  a_							:       List[str]      					=False
  a_							:       Optional[int]      					=False
  a_							:       Any      					=False







  def UpperCamelCase_ (      self      :					str							):


    '''simple docstring'''





    _snake_case   :				int														=	TFViTModelTester(self							)
    _snake_case   :				Union[str, Any]														=	ConfigTester(self      ,				config_class=UpperCamelCase__      ,				has_text_modality=UpperCamelCase__      ,				hidden_size=37							)







  def UpperCamelCase_ (      self      :					Tuple							):


    '''simple docstring'''





    self.config_tester.run_common_tests()







  @unittest.skip(reason='ViT does not use inputs_embeds'							)
  def UpperCamelCase_ (      self      :					str							):


    '''simple docstring'''





    pass







  @unittest.skip(reason='ViT does not use inputs_embeds'							)
  def UpperCamelCase_ (      self      :					Optional[Any]							):


    '''simple docstring'''





    pass







  def UpperCamelCase_ (      self      :					List[str]							):


    '''simple docstring'''





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

    for model_class in self.all_model_classes:
      _snake_case   :				str														=	model_class(UpperCamelCase__							)
      self.assertIsInstance(model.get_input_embeddings()      ,				(tf.keras.layers.Layer)							)
      _snake_case   :				List[Any]														=	model.get_output_embeddings()
      self.assertTrue(x is None or isinstance(UpperCamelCase__      ,				tf.keras.layers.Layer							)							)







  def UpperCamelCase_ (      self      :					Union[str, Any]							):


    '''simple docstring'''





    _snake_case							,					_snake_case   :				Optional[int]														=	self.model_tester.prepare_config_and_inputs_for_common()

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

      _snake_case   :				Any														=	['pixel_values']
      self.assertListEqual(arg_names[:1]      ,				UpperCamelCase__							)







  def UpperCamelCase_ (      self      :					str							):


    '''simple docstring'''





    _snake_case   :				Union[str, Any]														=	self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCamelCase__							)







  def UpperCamelCase_ (      self      :					str							):


    '''simple docstring'''





    _snake_case   :				str														=	self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__							)







  @slow
  def UpperCamelCase_ (      self      :					Tuple							):


    '''simple docstring'''





    _snake_case   :				Optional[int]														=	TFViTModel.from_pretrained('google/vit-base-patch16-224'							)
    self.assertIsNotNone(UpperCamelCase__							)







def     lowerCamelCase_	(      )->		int:
  _snake_case   :				Any														=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
  return image







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


  '''simple docstring'''







  @cached_property
  def UpperCamelCase_ (      self      :					List[str]							):


    '''simple docstring'''





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







  @slow
  def UpperCamelCase_ (      self      :					int							):


    '''simple docstring'''





    _snake_case   :				Dict														=	TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224'							)

    _snake_case   :				str														=	self.default_image_processor
    _snake_case   :				str														=	prepare_img()
    _snake_case   :				Tuple														=	image_processor(images=UpperCamelCase__      ,				return_tensors='tf'							)

    # forward pass
    _snake_case   :				Optional[int]														=	model(**UpperCamelCase__							)

    # verify the logits
    _snake_case   :				int														=	tf.TensorShape((1, 10_00)							)
    self.assertEqual(outputs.logits.shape      ,				UpperCamelCase__							)

    _snake_case   :				Dict														=	tf.constant([-0.27_44, 0.82_15, -0.08_36]							)

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











import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding



class        _lowerCAmelCase    (			UpperCAmelCase_							):


  '''simple docstring'''
  a_							:       Union[str, Any]      					=["""image_processor""", """tokenizer"""]
  a_							:       Optional[int]      					="""CLIPImageProcessor"""
  a_							:       Optional[Any]      					=("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""")







  def __init__(      self      :					List[str]      ,				UpperCamelCase      :					Optional[int]=None      ,				UpperCamelCase      :					Optional[Any]=None      ,				**UpperCamelCase      :					Dict							):


    '''simple docstring'''





    _snake_case   :				int														=	None
    if "feature_extractor" in kwargs:
      warnings.warn(
          'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
          ' instead.'      ,				UpperCamelCase      ,				)
      _snake_case   :				Optional[Any]														=	kwargs.pop('feature_extractor'							)

    _snake_case   :				Dict														=	image_processor if image_processor is not None else feature_extractor
    if image_processor is None:
      raise ValueError('You need to specify an `image_processor`.'							)
    if tokenizer is None:
      raise ValueError('You need to specify a `tokenizer`.'							)

    super().__init__(UpperCamelCase      ,				UpperCamelCase							)







  def __call__(      self      :					Dict      ,				UpperCamelCase      :					Optional[Any]=None      ,				UpperCamelCase      :					Optional[Any]=None      ,				UpperCamelCase      :					Optional[int]=None      ,				**UpperCamelCase      :					Dict							):


    '''simple docstring'''





    if text is None and images is None:
      raise ValueError('You have to specify either text or images. Both cannot be none.'							)

    if text is not None:
      _snake_case   :				Optional[int]														=	self.tokenizer(UpperCamelCase      ,				return_tensors=UpperCamelCase      ,				**UpperCamelCase							)

    if images is not None:
      _snake_case   :				Optional[int]														=	self.image_processor(UpperCamelCase      ,				return_tensors=UpperCamelCase      ,				**UpperCamelCase							)

    if text is not None and images is not None:
      _snake_case   :				Optional[int]														=	image_features.pixel_values
      return encoding
    elif text is not None:
      return encoding
    else:
      return BatchEncoding(data=dict(**UpperCamelCase							)      ,				tensor_type=UpperCamelCase							)







  def UpperCamelCase_ (      self      :					Union[str, Any]      ,				*UpperCamelCase      :					Any      ,				**UpperCamelCase      :					Union[str, Any]							):


    '''simple docstring'''





    return self.tokenizer.batch_decode(*UpperCamelCase      ,				**UpperCamelCase							)







  def UpperCamelCase_ (      self      :					Union[str, Any]      ,				*UpperCamelCase      :					Union[str, Any]      ,				**UpperCamelCase      :					Optional[Any]							):


    '''simple docstring'''





    return self.tokenizer.decode(*UpperCamelCase      ,				**UpperCamelCase							)







  @property
  def UpperCamelCase_ (      self      :					Optional[int]							):


    '''simple docstring'''





    _snake_case   :				Any														=	self.tokenizer.model_input_names
    _snake_case   :				List[Any]														=	self.image_processor.model_input_names
    return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names							)							)




