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							:


   def __init__(self					:						Any	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						str=1_3	,  __UpperCAmelCase					:						Optional[Any]=3_0	,  __UpperCAmelCase					:						Optional[Any]=2	,  __UpperCAmelCase					:						Optional[int]=3	,  __UpperCAmelCase					:						str=True	,  __UpperCAmelCase					:						str=True	,  __UpperCAmelCase					:						Optional[Any]=3_2	,  __UpperCAmelCase					:						str=2	,  __UpperCAmelCase					:						List[Any]=4	,  __UpperCAmelCase					:						List[str]=3_7	,  __UpperCAmelCase					:						Tuple="gelu"	,  __UpperCAmelCase					:						List[str]=0.1	,  __UpperCAmelCase					:						Dict=0.1	,  __UpperCAmelCase					:						int=1_0	,  __UpperCAmelCase					:						Tuple=0.02	,  __UpperCAmelCase					:						Union[str, Any]=3	,  __UpperCAmelCase					:						Union[str, Any]=None	,  )						->    Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  parent
         UpperCAmelCase__								=  batch_size
         UpperCAmelCase__								=  image_size
         UpperCAmelCase__								=  patch_size
         UpperCAmelCase__								=  num_channels
         UpperCAmelCase__								=  is_training
         UpperCAmelCase__								=  use_labels
         UpperCAmelCase__								=  hidden_size
         UpperCAmelCase__								=  num_hidden_layers
         UpperCAmelCase__								=  num_attention_heads
         UpperCAmelCase__								=  intermediate_size
         UpperCAmelCase__								=  hidden_act
         UpperCAmelCase__								=  hidden_dropout_prob
         UpperCAmelCase__								=  attention_probs_dropout_prob
         UpperCAmelCase__								=  type_sequence_label_size
         UpperCAmelCase__								=  initializer_range
         UpperCAmelCase__								=  scope

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


   def       lowercase_				(self					:						List[str]		)						->    List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

         UpperCAmelCase__								=  self.get_config()

         return config, pixel_values, labels


   def       lowercase_				(self					:						Union[str, Any]		)						->    int:
         """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       lowercase_				(self					:						Tuple	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						List[str]	,  __UpperCAmelCase					:						Optional[Any]		)						->    Union[str, Any]:
         """simple docstring"""



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


   def       lowercase_				(self					:						int	,  __UpperCAmelCase					:						List[Any]	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						Dict		)						->    List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.type_sequence_label_size
         UpperCAmelCase__								=  TFViTForImageClassification(__UpperCAmelCase		)
         UpperCAmelCase__								=  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.
         UpperCAmelCase__								=  self.image_size // 2
         UpperCAmelCase__								=  pixel_values[:, :, :image_size, :image_size]
         UpperCAmelCase__								=  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
         UpperCAmelCase__								=  1
         UpperCAmelCase__								=  TFViTForImageClassification(__UpperCAmelCase		)
         UpperCAmelCase__								=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
         UpperCAmelCase__								=  model(__UpperCAmelCase		)
         self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.type_sequence_label_size)		)





   def       lowercase_				(self					:						List[str]		)						->    Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.prepare_config_and_inputs()
         UpperCAmelCase__		,				UpperCAmelCase__		,				UpperCAmelCase__								=  config_and_inputs
         UpperCAmelCase__								=  {"pixel_values": pixel_values}
         return config, inputs_dict





@require_tf
class 					A							(    UpperCAmelCase_		,    UpperCAmelCase_		,    unittest.TestCase					):
   __UpperCAmelCase			:			int              =      (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
   __UpperCAmelCase			:			Optional[Any]              =      (
       {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
       if is_tf_available()
       else {}
   )

   __UpperCAmelCase			:			Dict              =      False
   __UpperCAmelCase			:			Dict              =      False
   __UpperCAmelCase			:			List[Any]              =      False


   def       lowercase_				(self					:						int		)						->    Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  TFViTModelTester(self		)
         UpperCAmelCase__								=  ConfigTester(self	,  config_class=__UpperCAmelCase	,  has_text_modality=__UpperCAmelCase	,  hidden_size=3_7		)


   def       lowercase_				(self					:						Tuple		)						->    Optional[int]:
         """simple docstring"""



         self.config_tester.run_common_tests()


   @unittest.skip(reason="ViT does not use inputs_embeds"		)
   def       lowercase_				(self					:						Dict		)						->    List[str]:
         """simple docstring"""



         pass


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



         pass


   def       lowercase_				(self					:						Any		)						->    Tuple:
         """simple docstring"""



         UpperCAmelCase__		,				UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs_for_common()

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


   def       lowercase_				(self					:						int		)						->    int:
         """simple docstring"""



         UpperCAmelCase__		,				UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs_for_common()

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

               UpperCAmelCase__								=  ["pixel_values"]
               self.assertListEqual(arg_names[:1]	,  __UpperCAmelCase		)


   def       lowercase_				(self					:						Optional[Any]		)						->    List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__UpperCAmelCase		)


   def       lowercase_				(self					:						List[str]		)						->    Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase		)





   @slow
   def       lowercase_				(self					:						Optional[Any]		)						->    Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  TFViTModel.from_pretrained("google/vit-base-patch16-224"		)
         self.assertIsNotNone(__UpperCAmelCase		)




def        lowerCAmelCase_			(					)					->    str:







      '''simple docstring'''


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







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


   @cached_property
   def       lowercase_				(self					:						Optional[Any]		)						->    Optional[int]:
         """simple docstring"""



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





   @slow
   def       lowercase_				(self					:						Union[str, Any]		)						->    Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"		)

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

         # forward pass
         UpperCAmelCase__								=  model(**__UpperCAmelCase		)

         # verify the logits
         UpperCAmelCase__								=  tf.TensorShape((1, 1_0_0_0)		)
         self.assertEqual(outputs.logits.shape	,  __UpperCAmelCase		)

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

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




# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			List[Any]              =      'facebook/bart-large-mnli'
   __UpperCAmelCase			:			Optional[Any]              =      (
       'This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which '
       'should be the text to classify, and `labels`, which should be the list of labels to use for classification. '
       'It returns the most likely label in the list of provided `labels` for the input text.'
   )
   __UpperCAmelCase			:			Optional[int]              =      'text_classifier'
   __UpperCAmelCase			:			int              =      AutoTokenizer
   __UpperCAmelCase			:			Dict              =      AutoModelForSequenceClassification

   __UpperCAmelCase			:			int              =      ['text', ['text']]
   __UpperCAmelCase			:			Optional[int]              =      ['text']


   def       lowercase_				(self					:						List[Any]		)						->    List[str]:
         """simple docstring"""



         super().setup()
         UpperCAmelCase__								=  self.model.config
         UpperCAmelCase__								=  -1
         for idx, label in config.idalabel.items():
               if label.lower().startswith("entail"		):
                     UpperCAmelCase__								=  int(__UpperCAmelCase		)
         if self.entailment_id == -1:
               raise ValueError("Could not determine the entailment ID from the model config, please pass it at init."		)


   def       lowercase_				(self					:						Union[str, Any]	,  __UpperCAmelCase					:						Dict	,  __UpperCAmelCase					:						int		)						->    Optional[int]:
         """simple docstring"""



         UpperCAmelCase__								=  labels
         return self.pre_processor(
             [text] * len(__UpperCAmelCase		)	,  [f"""This example is {label}""" for label in labels]	,  return_tensors="pt"	,  padding="max_length"	,  )





   def       lowercase_				(self					:						Dict	,  __UpperCAmelCase					:						Tuple		)						->    int:
         """simple docstring"""



         UpperCAmelCase__								=  outputs.logits
         UpperCAmelCase__								=  torch.argmax(logits[:, 2]		).item()
         return self._labels[label_id]



