






'''simple docstring'''
import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import CvtForImageClassification, CvtModel
  from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):




 def        __magic_name__		( self		:							List[Any] )		->  Dict:
       SCREAMING_SNAKE_CASE__       :			List[str]													=self.config_class(**self.inputs_dict )
       self.parent.assertTrue(hasattr(__lowercase   , '''embed_dim''' ) )
       self.parent.assertTrue(hasattr(__lowercase   , '''num_heads''' ) )






class        __SCREAMING_SNAKE_CASE :




 def __init__( self		:							List[str]   , __lowercase		:							Optional[Any]   , __lowercase		:							Any=13   , __lowercase		:							Optional[Any]=64   , __lowercase		:							Optional[int]=3   , __lowercase		:							List[Any]=[16, 48, 96]   , __lowercase		:							str=[1, 3, 6]   , __lowercase		:							Any=[1, 2, 10]   , __lowercase		:							Optional[Any]=[7, 3, 3]   , __lowercase		:							Optional[int]=[4, 2, 2]   , __lowercase		:							str=[2, 1, 1]   , __lowercase		:							Union[str, Any]=[2, 2, 2]   , __lowercase		:							int=[False, False, True]   , __lowercase		:							str=[0.0, 0.0, 0.0]   , __lowercase		:							List[str]=0.02   , __lowercase		:							Tuple=1e-12   , __lowercase		:							List[Any]=True   , __lowercase		:							Dict=True   , __lowercase		:							str=2   , )		->  str:
       SCREAMING_SNAKE_CASE__       :			List[Any]													=parent
       SCREAMING_SNAKE_CASE__       :			List[str]													=batch_size
       SCREAMING_SNAKE_CASE__       :			Any													=image_size
       SCREAMING_SNAKE_CASE__       :			Any													=patch_sizes
       SCREAMING_SNAKE_CASE__       :			Dict													=patch_stride
       SCREAMING_SNAKE_CASE__       :			List[Any]													=patch_padding
       SCREAMING_SNAKE_CASE__       :			Dict													=is_training
       SCREAMING_SNAKE_CASE__       :			Any													=use_labels
       SCREAMING_SNAKE_CASE__       :			int													=num_labels
       SCREAMING_SNAKE_CASE__       :			str													=num_channels
       SCREAMING_SNAKE_CASE__       :			str													=embed_dim
       SCREAMING_SNAKE_CASE__       :			str													=num_heads
       SCREAMING_SNAKE_CASE__       :			Tuple													=stride_kv
       SCREAMING_SNAKE_CASE__       :			Tuple													=depth
       SCREAMING_SNAKE_CASE__       :			Dict													=cls_token
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=attention_drop_rate
       SCREAMING_SNAKE_CASE__       :			Tuple													=initializer_range
       SCREAMING_SNAKE_CASE__       :			List[Any]													=layer_norm_eps




 def        __magic_name__		( self		:							Union[str, Any] )		->  Any:
       SCREAMING_SNAKE_CASE__       :			Dict													=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

       SCREAMING_SNAKE_CASE__       :			List[Any]													=None
       if self.use_labels:
             SCREAMING_SNAKE_CASE__       :			str													=ids_tensor([self.batch_size]   , self.num_labels )

       SCREAMING_SNAKE_CASE__       :			Any													=self.get_config()
       return config, pixel_values, labels




 def        __magic_name__		( self		:							int )		->  Dict:
       return CvtConfig(
           image_size=self.image_size   , num_labels=self.num_labels   , num_channels=self.num_channels   , embed_dim=self.embed_dim   , num_heads=self.num_heads   , patch_sizes=self.patch_sizes   , patch_padding=self.patch_padding   , patch_stride=self.patch_stride   , stride_kv=self.stride_kv   , depth=self.depth   , cls_token=self.cls_token   , attention_drop_rate=self.attention_drop_rate   , initializer_range=self.initializer_range   , )




 def        __magic_name__		( self		:							Tuple   , __lowercase		:							int   , __lowercase		:							List[str]   , __lowercase		:							Dict )		->  Union[str, Any]:
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=CvtModel(config=__lowercase )
       model.to(__lowercase )
       model.eval()
       SCREAMING_SNAKE_CASE__       :			Tuple													=model(__lowercase )
       SCREAMING_SNAKE_CASE__       :			Tuple													=(self.image_size, self.image_size)
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=image_size[0], image_size[1]
       for i in range(len(self.depth ) ):
             SCREAMING_SNAKE_CASE__       :			List[Any]													=floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
             SCREAMING_SNAKE_CASE__       :			Any													=floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
       self.parent.assertEqual(result.last_hidden_state.shape   , (self.batch_size, self.embed_dim[-1], height, width) )




 def        __magic_name__		( self		:							Tuple   , __lowercase		:							int   , __lowercase		:							List[str]   , __lowercase		:							Dict )		->  str:
       SCREAMING_SNAKE_CASE__       :			List[Any]													=self.num_labels
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=CvtForImageClassification(__lowercase )
       model.to(__lowercase )
       model.eval()
       SCREAMING_SNAKE_CASE__       :			Any													=model(__lowercase   , labels=__lowercase )
       self.parent.assertEqual(result.logits.shape   , (self.batch_size, self.num_labels) )




 def        __magic_name__		( self		:							List[Any] )		->  Tuple:
       SCREAMING_SNAKE_CASE__       :			Dict													=self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			Any													=config_and_inputs
       SCREAMING_SNAKE_CASE__       :			Dict													={'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_torch
class        __SCREAMING_SNAKE_CASE (     lowerCamelCase		,			lowerCamelCase		,			unittest.TestCase			):
 snake_case_												=							(CvtModel, CvtForImageClassification) if is_torch_available() else ()
 snake_case_												=							(
     {"""feature-extraction""": CvtModel, """image-classification""": CvtForImageClassification}
     if is_torch_available()
     else {}
 )

 snake_case_												=							False
 snake_case_												=							False
 snake_case_												=							False
 snake_case_												=							False
 snake_case_												=							False




 def        __magic_name__		( self		:							int )		->  List[Any]:
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=CvtModelTester(self )
       SCREAMING_SNAKE_CASE__       :			Dict													=ConfigTester(self   , config_class=__lowercase   , has_text_modality=__lowercase   , hidden_size=37 )




 def        __magic_name__		( self		:							Any )		->  List[Any]:
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()




 def        __magic_name__		( self		:							str )		->  int:
       return




 @unittest.skip(reason='''Cvt does not output attentions''' )
 def        __magic_name__		( self		:							Tuple )		->  Any:
       pass




 @unittest.skip(reason='''Cvt does not use inputs_embeds''' )
 def        __magic_name__		( self		:							Optional[Any] )		->  str:
       pass




 @unittest.skip(reason='''Cvt does not support input and output embeddings''' )
 def        __magic_name__		( self		:							List[Any] )		->  str:
       pass




 def        __magic_name__		( self		:							Optional[Any] )		->  int:
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			List[str]													=self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__       :			str													=model_class(__lowercase )
             SCREAMING_SNAKE_CASE__       :			Tuple													=inspect.signature(model.forward )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=[*signature.parameters.keys()]

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




 def        __magic_name__		( self		:							Any )		->  Dict:
       SCREAMING_SNAKE_CASE__       :			Dict													=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowercase )




 def        __magic_name__		( self		:							Any )		->  Tuple:
       def check_hidden_states_output(__lowercase		:							Dict   , __lowercase		:							List[Any]   , __lowercase		:							Any ):
             SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=model_class(__lowercase )
             model.to(__lowercase )
             model.eval()

             with torch.no_grad():
                   SCREAMING_SNAKE_CASE__       :			List[Any]													=model(**self._prepare_for_class(__lowercase   , __lowercase ) )

             SCREAMING_SNAKE_CASE__       :			int													=outputs.hidden_states

             SCREAMING_SNAKE_CASE__       :			Dict													=len(self.model_tester.depth )
             self.assertEqual(len(__lowercase )   , __lowercase )

             # verify the first hidden states (first block)
             self.assertListEqual(
                 list(hidden_states[0].shape[-3:] )   , [
                     self.model_tester.embed_dim[0],
                     self.model_tester.image_size // 4,
                     self.model_tester.image_size // 4,
                 ]   , )

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

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__       :			Any													=True
             check_hidden_states_output(__lowercase   , __lowercase   , __lowercase )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             SCREAMING_SNAKE_CASE__       :			List[str]													=True

             check_hidden_states_output(__lowercase   , __lowercase   , __lowercase )




 def        __magic_name__		( self		:							Any )		->  int:
       SCREAMING_SNAKE_CASE__       :			str													=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__lowercase )




 @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
 def        __magic_name__		( self		:							str )		->  List[str]:
       pass




 @slow
 def        __magic_name__		( self		:							Any )		->  Optional[int]:
       for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE__       :			str													=CvtModel.from_pretrained(__lowercase )
             self.assertIsNotNone(__lowercase )





def 	_a(					):




      '''simple docstring'''






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







@require_torch
@require_vision
class        __SCREAMING_SNAKE_CASE (     unittest.TestCase			):




 @cached_property
 def        __magic_name__		( self		:							int )		->  Tuple:
       return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )




 @slow
 def        __magic_name__		( self		:							List[Any] )		->  Union[str, Any]:
       SCREAMING_SNAKE_CASE__       :			str													=CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__lowercase )

       SCREAMING_SNAKE_CASE__       :			List[Any]													=self.default_image_processor
       SCREAMING_SNAKE_CASE__       :			List[str]													=prepare_img()
       SCREAMING_SNAKE_CASE__       :			int													=image_processor(images=__lowercase   , return_tensors='''pt''' ).to(__lowercase )

       # forward pass
       with torch.no_grad():
             SCREAMING_SNAKE_CASE__       :			Dict													=model(**__lowercase )

       # verify the logits
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=torch.Size((1, 10_00) )
       self.assertEqual(outputs.logits.shape   , __lowercase )

       SCREAMING_SNAKE_CASE__       :			str													=torch.tensor([0.9285, 0.9015, -0.3150] ).to(__lowercase )

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







'''simple docstring'''
# 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        __SCREAMING_SNAKE_CASE (     lowerCamelCase			):
 snake_case_												=							"""facebook/bart-large-mnli"""
 snake_case_												=							(
     """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."""
 )
 snake_case_												=							"""text_classifier"""
 snake_case_												=							AutoTokenizer
 snake_case_												=							AutoModelForSequenceClassification

 snake_case_												=							["""text""", ["""text"""]]
 snake_case_												=							["""text"""]




 def        __magic_name__		( self		:							Any )		->  Any:
       super().setup()
       SCREAMING_SNAKE_CASE__       :			int													=self.model.config
       SCREAMING_SNAKE_CASE__       :			int													=-1
       for idx, label in config.idalabel.items():
             if label.lower().startswith('''entail''' ):
                   SCREAMING_SNAKE_CASE__       :			Any													=int(__lowercase )
       if self.entailment_id == -1:
             raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''' )




 def        __magic_name__		( self		:							str   , __lowercase		:							Any   , __lowercase		:							Optional[Any] )		->  Optional[Any]:
       SCREAMING_SNAKE_CASE__       :			Dict													=labels
       return self.pre_processor(
           [text] * len(__lowercase )   , [F"This example is {label}" for label in labels]   , return_tensors='''pt'''   , padding='''max_length'''   , )




 def        __magic_name__		( self		:							List[Any]   , __lowercase		:							str )		->  List[Any]:
       SCREAMING_SNAKE_CASE__       :			int													=outputs.logits
       SCREAMING_SNAKE_CASE__       :			Any													=torch.argmax(logits[:, 2] ).item()
       return self._labels[label_id]