






import copy
import json
import os
import tempfile

from transformers import is_torch_available

from .test_configuration_utils import config_common_kwargs




class    lowercase_    (_UpperCAmelCase     ):






      def __init__(    self     ,     a_     ,     a_=None     ,     a_=True     ,     a_=None     ,     **a_	)	->int:







        '''simple docstring'''


        _a							=	parent
        _a							=	config_class
        _a							=	has_text_modality
        _a							=	kwargs
        _a							=	common_properties






      def 			lowerCamelCase__    (    self	)	->str:







        '''simple docstring'''


        _a							=	self.config_class(**self.inputs_dict	)
        _a							=	(
            ["hidden_size", "num_attention_heads", "num_hidden_layers"]
            if self.common_properties is None
            else self.common_properties
        )

        # Add common fields for text models
        if self.has_text_modality:
          common_properties.extend(["vocab_size"]	)

        # Test that config has the common properties as getters
        for prop in common_properties:
          self.parent.assertTrue(hasattr(a_     ,     a_	)     ,     msg=f'''`{prop}` does not exist'''	)

        # Test that config has the common properties as setter
        for idx, name in enumerate(a_	):
          try:
            setattr(a_     ,     a_     ,     a_	)
            self.parent.assertEqual(
                getattr(a_     ,     a_	)     ,     a_     ,     msg=f'''`{name} value {idx} expected, but was {getattr(a_     ,     a_	)}'''	)
          except NotImplementedError:
            # Some models might not be able to implement setters for common_properties
            # In that case, a NotImplementedError is raised
            pass

        # Test if config class can be called with Config(prop_name=..)
        for idx, name in enumerate(a_	):
          try:
            _a							=	self.config_class(**{name: idx}	)
            self.parent.assertEqual(
                getattr(a_     ,     a_	)     ,     a_     ,     msg=f'''`{name} value {idx} expected, but was {getattr(a_     ,     a_	)}'''	)
          except NotImplementedError:
            # Some models might not be able to implement setters for common_properties
            # In that case, a NotImplementedError is raised
            pass






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        _a							=	self.config_class(**self.inputs_dict	)
        _a							=	json.loads(config.to_json_string()	)
        for key, value in self.inputs_dict.items():
          self.parent.assertEqual(obj[key]     ,     a_	)






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







        '''simple docstring'''


        _a							=	self.config_class(**self.inputs_dict	)

        with tempfile.TemporaryDirectory() as tmpdirname:
          _a							=	os.path.join(a_     ,     "config.json"	)
          config_first.to_json_file(a_	)
          _a							=	self.config_class.from_json_file(a_	)

        self.parent.assertEqual(config_second.to_dict()     ,     config_first.to_dict()	)






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        _a							=	self.config_class(**self.inputs_dict	)

        with tempfile.TemporaryDirectory() as tmpdirname:
          config_first.save_pretrained(a_	)
          _a							=	self.config_class.from_pretrained(a_	)

        self.parent.assertEqual(config_second.to_dict()     ,     config_first.to_dict()	)






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        _a							=	self.config_class(**self.inputs_dict	)

        _a							=	"test"
        with tempfile.TemporaryDirectory() as tmpdirname:
          _a							=	os.path.join(a_     ,     a_	)
          config_first.save_pretrained(a_	)
          _a							=	self.config_class.from_pretrained(a_     ,     subfolder=a_	)

        self.parent.assertEqual(config_second.to_dict()     ,     config_first.to_dict()	)






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







        '''simple docstring'''


        _a							=	self.config_class(**self.inputs_dict     ,     num_labels=5	)
        self.parent.assertEqual(len(config.idalabel	)     ,     5	)
        self.parent.assertEqual(len(config.labelaid	)     ,     5	)

        _a							=	3
        self.parent.assertEqual(len(config.idalabel	)     ,     3	)
        self.parent.assertEqual(len(config.labelaid	)     ,     3	)






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







        '''simple docstring'''


        if self.config_class.is_composition:
          return
        _a							=	self.config_class()
        self.parent.assertIsNotNone(a_	)






      def 			lowerCamelCase__    (    self	)	->str:







        '''simple docstring'''


        _a							=	copy.deepcopy(a_	)
        _a							=	self.config_class(**a_	)
        _a							=	[]
        for key, value in config_common_kwargs.items():
          if key == "torch_dtype":
            if not is_torch_available():
              continue
            else:
              import torch

              if config.torch_dtype != torch.floataa:
                wrong_values.append(("torch_dtype", config.torch_dtype, torch.floataa)	)
          elif getattr(a_     ,     a_	) != value:
            wrong_values.append((key, getattr(a_     ,     a_	), value)	)

        if len(a_	) > 0:
          _a							=	"\n".join([f'''- {v[0]}: got {v[1]} instead of {v[2]}''' for v in wrong_values]	)
          raise ValueError(f'''The following keys were not properly set in the config:\n{errors}'''	)






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        self.create_and_test_config_common_properties()
        self.create_and_test_config_to_json_string()
        self.create_and_test_config_to_json_file()
        self.create_and_test_config_from_and_save_pretrained()
        self.create_and_test_config_from_and_save_pretrained_subfolder()
        self.create_and_test_config_with_num_labels()
        self.check_config_can_be_init_without_params()
        self.check_config_arguments_init()










"""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()


