
"""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  lowerCAmelCase__							(		A_      ):







     def 	lowercase      (				self     :     Optional[Any]     ):
       _snake_case   	=			self.config_class(**self.inputs_dict     )
       self.parent.assertTrue(hasattr(lowerCAmelCase__       , '''embed_dim'''     )     )
       self.parent.assertTrue(hasattr(lowerCAmelCase__       , '''num_heads'''     )     )






class  lowerCAmelCase__							:







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







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

       _snake_case   	=			None
       if self.use_labels:
         _snake_case   	=			ids_tensor([self.batch_size]       , self.num_labels     )

       _snake_case   	=			self.get_config()
       return config, pixel_values, labels







     def 	lowercase      (				self     :     Optional[int]     ):
       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 	lowercase      (				self     :     List[Any]       , _lowerCamelCase     :     Optional[Any]       , _lowerCamelCase     :     str       , _lowerCamelCase     :     str     ):
       _snake_case   	=			CvtModel(config=lowerCAmelCase__     )
       model.to(lowerCAmelCase__     )
       model.eval()
       _snake_case   	=			model(lowerCAmelCase__     )
       _snake_case   	=			(self.image_size, self.image_size)
       _snake_case	,   _snake_case   	=			image_size[0], image_size[1]
       for i in range(len(self.depth     )     ):
         _snake_case   	=			floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1     )
         _snake_case   	=			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 	lowercase      (				self     :     Optional[int]       , _lowerCamelCase     :     Dict       , _lowerCamelCase     :     Tuple       , _lowerCamelCase     :     Dict     ):
       _snake_case   	=			self.num_labels
       _snake_case   	=			CvtForImageClassification(lowerCAmelCase__     )
       model.to(lowerCAmelCase__     )
       model.eval()
       _snake_case   	=			model(lowerCAmelCase__       , labels=lowerCAmelCase__     )
       self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.num_labels)     )







     def 	lowercase      (				self     :     Tuple     ):
       _snake_case   	=			self.prepare_config_and_inputs()
       _snake_case	,   _snake_case	,   _snake_case   	=			config_and_inputs
       _snake_case   	=			{'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_torch
class  lowerCAmelCase__							(		A_					,      A_					,      unittest.TestCase      ):
     __a         =   (CvtModel, CvtForImageClassification) if is_torch_available() else ()
     __a         =   (
         {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
         if is_torch_available()
         else {}
     )

     __a         =   False
     __a         =   False
     __a         =   False
     __a         =   False
     __a         =   False







     def 	lowercase      (				self     :     str     ):
       _snake_case   	=			CvtModelTester(self     )
       _snake_case   	=			ConfigTester(self       , config_class=lowerCAmelCase__       , has_text_modality=lowerCAmelCase__       , hidden_size=37     )







     def 	lowercase      (				self     :     str     ):
       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 	lowercase      (				self     :     Optional[int]     ):
       return







     @unittest.skip(reason='''Cvt does not output attentions'''     )
     def 	lowercase      (				self     :     int     ):
       pass







     @unittest.skip(reason='''Cvt does not use inputs_embeds'''     )
     def 	lowercase      (				self     :     Optional[int]     ):
       pass







     @unittest.skip(reason='''Cvt does not support input and output embeddings'''     )
     def 	lowercase      (				self     :     Tuple     ):
       pass







     def 	lowercase      (				self     :     Dict     ):
       _snake_case	,   _snake_case   	=			self.model_tester.prepare_config_and_inputs_for_common()

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

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







     def 	lowercase      (				self     :     List[str]     ):
       _snake_case   	=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCAmelCase__     )







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




       def check_hidden_states_output(_lowerCamelCase     :     Dict       , _lowerCamelCase     :     Optional[int]       , _lowerCamelCase     :     str     ):
         _snake_case   	=			model_class(lowerCAmelCase__     )
         model.to(lowerCAmelCase__     )
         model.eval()

         with torch.no_grad():
           _snake_case   	=			model(**self._prepare_for_class(lowerCAmelCase__       , lowerCAmelCase__     )     )

         _snake_case   	=			outputs.hidden_states

         _snake_case   	=			len(self.model_tester.depth     )
         self.assertEqual(len(lowerCAmelCase__     )       , lowerCAmelCase__     )

         # 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,
             ]       , )

       _snake_case	,   _snake_case   	=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         _snake_case   	=			True
         check_hidden_states_output(lowerCAmelCase__       , lowerCAmelCase__       , lowerCAmelCase__     )

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         _snake_case   	=			True

         check_hidden_states_output(lowerCAmelCase__       , lowerCAmelCase__       , lowerCAmelCase__     )







     def 	lowercase      (				self     :     int     ):
       _snake_case   	=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__     )







     @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''     )
     def 	lowercase      (				self     :     Union[str, Any]     ):
       pass







     @slow
     def 	lowercase      (				self     :     Dict     ):




       for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _snake_case   	=			CvtModel.from_pretrained(lowerCAmelCase__     )
         self.assertIsNotNone(lowerCAmelCase__     )






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

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







     @cached_property
     def 	lowercase      (				self     :     Dict     ):
       return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )







     @slow
     def 	lowercase      (				self     :     Any     ):
       _snake_case   	=			CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]     ).to(lowerCAmelCase__     )

       _snake_case   	=			self.default_image_processor
       _snake_case   	=			prepare_img()
       _snake_case   	=			image_processor(images=lowerCAmelCase__       , return_tensors='''pt'''     ).to(lowerCAmelCase__     )

       # forward pass
       with torch.no_grad():
         _snake_case   	=			model(**lowerCAmelCase__     )

       # verify the logits
       _snake_case   	=			torch.Size((1, 1000)     )
       self.assertEqual(outputs.logits.shape       , lowerCAmelCase__     )

       _snake_case   	=			torch.tensor([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]     ).to(lowerCAmelCase__     )

       self.assertTrue(torch.allclose(outputs.logits[0, :3]       , lowerCAmelCase__       , 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.
from typing import TYPE_CHECKING

from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
   from PIL import Image
class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""
       _snake_case      :	str									=       'Salesforce/blip-image-captioning-base'
       _snake_case      :	Union[str, Any]									=       (
           'This is a tool that generates a description of an image. It takes an input named `image` which should be the '
           'image to caption, and returns a text that contains the description in English.'
       )
       _snake_case      :	List[Any]									=       'image_captioner'
       _snake_case      :	Union[str, Any]									=       AutoModelForVisionaSeq

       _snake_case      :	Dict									=       ['image']
       _snake_case      :	Optional[int]									=       ['text']





       def __init__(				self  :						Union[str, Any]			,					*lowerCAmelCase__  :						Optional[Any]			,					**lowerCAmelCase__  :						Optional[int]	)       ->	Tuple:

            '''simple docstring'''




            requires_backends(self			,					['''vision''']	)
            super().__init__(*lowerCAmelCase__			,					**lowerCAmelCase__	)





       def snake_case__		(				self  :						Tuple			,					lowerCAmelCase__  :						"Image"	)       ->	Optional[int]:

            '''simple docstring'''




            return self.pre_processor(images=lowerCAmelCase__			,					return_tensors='''pt'''	)





       def snake_case__		(				self  :						Any			,					lowerCAmelCase__  :						Union[str, Any]	)       ->	Union[str, Any]:

            '''simple docstring'''




            return self.model.generate(**lowerCAmelCase__	)







       def snake_case__		(				self  :						int			,					lowerCAmelCase__  :						List[str]	)       ->	List[str]:

            '''simple docstring'''




            return self.pre_processor.batch_decode(lowerCAmelCase__			,					skip_special_tokens=lowerCAmelCase__	)[0].strip()



