






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    lowercase_    (_UpperCAmelCase     ):






      def 			lowerCamelCase__    (    self	)	->Optional[Any]:







        '''simple docstring'''


        _a							=	self.config_class(**self.inputs_dict	)
        self.parent.assertTrue(hasattr(a_     ,     "embed_dim"	)	)
        self.parent.assertTrue(hasattr(a_     ,     "num_heads"	)	)







class    lowercase_    :






      def __init__(    self     ,     a_     ,     a_=1_3     ,     a_=6_4     ,     a_=3     ,     a_=[1_6, 4_8, 9_6]     ,     a_=[1, 3, 6]     ,     a_=[1, 2, 1_0]     ,     a_=[7, 3, 3]     ,     a_=[4, 2, 2]     ,     a_=[2, 1, 1]     ,     a_=[2, 2, 2]     ,     a_=[False, False, True]     ,     a_=[0.0, 0.0, 0.0]     ,     a_=0.02     ,     a_=1E-12     ,     a_=True     ,     a_=True     ,     a_=2     ,     )	->Any:







        '''simple docstring'''


        _a							=	parent
        _a							=	batch_size
        _a							=	image_size
        _a							=	patch_sizes
        _a							=	patch_stride
        _a							=	patch_padding
        _a							=	is_training
        _a							=	use_labels
        _a							=	num_labels
        _a							=	num_channels
        _a							=	embed_dim
        _a							=	num_heads
        _a							=	stride_kv
        _a							=	depth
        _a							=	cls_token
        _a							=	attention_drop_rate
        _a							=	initializer_range
        _a							=	layer_norm_eps






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


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

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

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






      def 			lowerCamelCase__    (    self	)	->Any:







        '''simple docstring'''


        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 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_	)	->Union[str, Any]:







        '''simple docstring'''


        _a							=	CvtModel(config=a_	)
        model.to(a_	)
        model.eval()
        _a							=	model(a_	)
        _a							=	(self.image_size, self.image_size)
        _a			,	_a							=	image_size[0], image_size[1]
        for i in range(len(self.depth	)	):
          _a							=	floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
          _a							=	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 			lowerCamelCase__    (    self     ,     a_     ,     a_     ,     a_	)	->Optional[Any]:







        '''simple docstring'''


        _a							=	self.num_labels
        _a							=	CvtForImageClassification(a_	)
        model.to(a_	)
        model.eval()
        _a							=	model(a_     ,     labels=a_	)
        self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.num_labels)	)






      def 			lowerCamelCase__    (    self	)	->Any:







        '''simple docstring'''


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







@require_torch
class    lowercase_    (_UpperCAmelCase,    _UpperCAmelCase,    unittest.TestCase     ):
      A__	:		Dict       			=				(CvtModel, CvtForImageClassification) if is_torch_available() else ()
      A__	:		Optional[int]       			=				(
          {'''feature-extraction''': CvtModel, '''image-classification''': CvtForImageClassification}
          if is_torch_available()
          else {}
      )

      A__	:		Any       			=				False
      A__	:		Tuple       			=				False
      A__	:		Dict       			=				False
      A__	:		str       			=				False
      A__	:		List[str]       			=				False






      def 			lowerCamelCase__    (    self	)	->Dict:







        '''simple docstring'''


        _a							=	CvtModelTester(self	)
        _a							=	ConfigTester(self     ,     config_class=a_     ,     has_text_modality=a_     ,     hidden_size=3_7	)






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        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 			lowerCamelCase__    (    self	)	->List[Any]:







        '''simple docstring'''


        return






      @unittest.skip(reason="Cvt does not output attentions"	)
      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        pass






      @unittest.skip(reason="Cvt does not use inputs_embeds"	)
      def 			lowerCamelCase__    (    self	)	->Optional[int]:







        '''simple docstring'''


        pass






      @unittest.skip(reason="Cvt does not support input and output embeddings"	)
      def 			lowerCamelCase__    (    self	)	->Optional[int]:







        '''simple docstring'''


        pass






      def 			lowerCamelCase__    (    self	)	->List[Any]:







        '''simple docstring'''


        _a			,	_a							=	self.model_tester.prepare_config_and_inputs_for_common()

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

          _a							=	["pixel_values"]
          self.assertListEqual(arg_names[:1]     ,     a_	)






      def 			lowerCamelCase__    (    self	)	->Optional[Any]:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*a_	)






      def 			lowerCamelCase__    (    self	)	->Optional[int]:







        '''simple docstring'''


        def check_hidden_states_output(a_     ,     a_     ,     a_	):
          _a							=	model_class(a_	)
          model.to(a_	)
          model.eval()

          with torch.no_grad():
            _a							=	model(**self._prepare_for_class(a_     ,     a_	)	)

          _a							=	outputs.hidden_states

          _a							=	len(self.model_tester.depth	)
          self.assertEqual(len(a_	)     ,     a_	)

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

        _a			,	_a							=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          _a							=	True
          check_hidden_states_output(a_     ,     a_     ,     a_	)

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

          check_hidden_states_output(a_     ,     a_     ,     a_	)






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        _a							=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*a_	)






      @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."	)
      def 			lowerCamelCase__    (    self	)	->str:







        '''simple docstring'''


        pass






      @slow
      def 			lowerCamelCase__    (    self	)	->Union[str, Any]:







        '''simple docstring'''


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







def        lowerCAmelCase (      )       ->							List[Any]:







  '''simple docstring'''







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




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






      @cached_property
      def 			lowerCamelCase__    (    self	)	->Optional[int]:







        '''simple docstring'''


        return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)






      @slow
      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        _a							=	CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	).to(a_	)

        _a							=	self.default_image_processor
        _a							=	prepare_img()
        _a							=	image_processor(images=a_     ,     return_tensors="pt"	).to(a_	)

        # forward pass
        with torch.no_grad():
          _a							=	model(**a_	)

        # verify the logits
        _a							=	torch.Size((1, 1_0_0_0)	)
        self.assertEqual(outputs.logits.shape     ,     a_	)

        _a							=	torch.tensor([0.9_285, 0.9_015, -0.3_150]	).to(a_	)

        self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,     a_     ,     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    lowercase_    (_UpperCAmelCase     ):
      A__	:		str       			=				'''Salesforce/blip-image-captioning-base'''
      A__	:		Optional[int]       			=				(
          '''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.'''
      )
      A__	:		str       			=				'''image_captioner'''
      A__	:		Tuple       			=				AutoModelForVisionaSeq

      A__	:		Tuple       			=				['''image''']
      A__	:		List[Any]       			=				['''text''']






      def __init__(    self     ,     *a_     ,     **a_	)	->Union[str, Any]:







        '''simple docstring'''


        requires_backends(self     ,     ["vision"]	)
        super().__init__(*a_     ,     **a_	)






      def 			lowerCamelCase__    (    self     ,     a_	)	->Union[str, Any]:







        '''simple docstring'''


        return self.pre_processor(images=a_     ,     return_tensors="pt"	)






      def 			lowerCamelCase__    (    self     ,     a_	)	->List[Any]:







        '''simple docstring'''


        return self.model.generate(**a_	)






      def 			lowerCamelCase__    (    self     ,     a_	)	->Tuple:







        '''simple docstring'''


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


