



"""simple docstring"""





import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


__lowerCAmelCase							:       str          =       logging.get_logger(__name__)

__lowerCAmelCase							:       Optional[int]          =       {
    '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''',
}



class  _lowerCAmelCase     (					SCREAMING_SNAKE_CASE__		):





		"""simple docstring"""






		_lowerCamelCase      	=							'''blip_2_vision_model'''





		def __init__(       self				,     _lowercase=1_4_0_8				,     _lowercase=6_1_4_4				,     _lowercase=3_9				,     _lowercase=1_6				,     _lowercase=2_2_4				,     _lowercase=1_4				,     _lowercase="gelu"				,     _lowercase=0.0_0001				,     _lowercase=0.0				,     _lowercase=1E-10				,     _lowercase=True				,     **_lowercase				,     )			->    Any:







								'''simple docstring'''

								super().__init__(**_lowercase )

								snake_case_ :			int            =      hidden_size
								snake_case_ :			Any            =      intermediate_size
								snake_case_ :			Any            =      num_hidden_layers
								snake_case_ :			Union[str, Any]            =      num_attention_heads
								snake_case_ :			Any            =      patch_size
								snake_case_ :			Dict            =      image_size
								snake_case_ :			Union[str, Any]            =      initializer_range
								snake_case_ :			Union[str, Any]            =      attention_dropout
								snake_case_ :			Optional[Any]            =      layer_norm_eps
								snake_case_ :			int            =      hidden_act
								snake_case_ :			Optional[Any]            =      qkv_bias





		@classmethod
		def  UpperCAmelCase__				(       cls				,     _lowercase				,     **_lowercase )			->    "PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(_lowercase )

								snake_case_      ,		snake_case_ :			Tuple            =      cls.get_config_dict(_lowercase				,     **_lowercase )

								# get the vision config dict if we are loading from Blip2Config
								if config_dict.get("""model_type""" ) == "blip-2":
														snake_case_ :			str            =      config_dict["""vision_config"""]

								if "model_type" in config_dict and hasattr(cls				,     """model_type""" ) and config_dict["model_type"] != cls.model_type:
														logger.warning(
														    f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
														    f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )

								return cls.from_dict(_lowercase				,     **_lowercase )




class  _lowerCAmelCase     (					SCREAMING_SNAKE_CASE__		):





		"""simple docstring"""






		_lowerCamelCase      	=							'''blip_2_qformer'''





		def __init__(       self				,     _lowercase=3_0_5_2_2				,     _lowercase=7_6_8				,     _lowercase=1_2				,     _lowercase=1_2				,     _lowercase=3_0_7_2				,     _lowercase="gelu"				,     _lowercase=0.1				,     _lowercase=0.1				,     _lowercase=5_1_2				,     _lowercase=0.02				,     _lowercase=1E-12				,     _lowercase=0				,     _lowercase="absolute"				,     _lowercase=2				,     _lowercase=1_4_0_8				,     **_lowercase				,     )			->    Optional[int]:







								'''simple docstring'''

								super().__init__(pad_token_id=_lowercase				,     **_lowercase )

								snake_case_ :			Optional[Any]            =      vocab_size
								snake_case_ :			Optional[int]            =      hidden_size
								snake_case_ :			Union[str, Any]            =      num_hidden_layers
								snake_case_ :			Any            =      num_attention_heads
								snake_case_ :			str            =      hidden_act
								snake_case_ :			int            =      intermediate_size
								snake_case_ :			Tuple            =      hidden_dropout_prob
								snake_case_ :			Any            =      attention_probs_dropout_prob
								snake_case_ :			Dict            =      max_position_embeddings
								snake_case_ :			List[str]            =      initializer_range
								snake_case_ :			Union[str, Any]            =      layer_norm_eps
								snake_case_ :			str            =      position_embedding_type
								snake_case_ :			List[str]            =      cross_attention_frequency
								snake_case_ :			Union[str, Any]            =      encoder_hidden_size





		@classmethod
		def  UpperCAmelCase__				(       cls				,     _lowercase				,     **_lowercase )			->    "PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(_lowercase )

								snake_case_      ,		snake_case_ :			Optional[int]            =      cls.get_config_dict(_lowercase				,     **_lowercase )

								# get the qformer config dict if we are loading from Blip2Config
								if config_dict.get("""model_type""" ) == "blip-2":
														snake_case_ :			str            =      config_dict["""qformer_config"""]

								if "model_type" in config_dict and hasattr(cls				,     """model_type""" ) and config_dict["model_type"] != cls.model_type:
														logger.warning(
														    f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
														    f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' )

								return cls.from_dict(_lowercase				,     **_lowercase )




class  _lowerCAmelCase     (					SCREAMING_SNAKE_CASE__		):





		"""simple docstring"""






		_lowerCamelCase      	=							'''blip-2'''
		_lowerCamelCase      	=							True





		def __init__(       self				,     _lowercase=None				,     _lowercase=None				,     _lowercase=None				,     _lowercase=3_2				,     **_lowercase )			->    Any:







								'''simple docstring'''

								super().__init__(**_lowercase )

								if vision_config is None:
														snake_case_ :			Optional[int]            =      {}
														logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""" )

								if qformer_config is None:
														snake_case_ :			Union[str, Any]            =      {}
														logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""" )

								if text_config is None:
														snake_case_ :			Tuple            =      {}
														logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" )

								snake_case_ :			Tuple            =      BlipaVisionConfig(**_lowercase )
								snake_case_ :			Union[str, Any]            =      BlipaQFormerConfig(**_lowercase )
								snake_case_ :			Union[str, Any]            =      text_config["""model_type"""] if """model_type""" in text_config else """opt"""
								snake_case_ :			Optional[int]            =      CONFIG_MAPPING[text_model_type](**_lowercase )

								snake_case_ :			Optional[int]            =      self.text_config.tie_word_embeddings
								snake_case_ :			Dict            =      self.text_config.is_encoder_decoder

								snake_case_ :			Any            =      num_query_tokens
								snake_case_ :			List[str]            =      self.vision_config.hidden_size
								snake_case_ :			Union[str, Any]            =      self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
								snake_case_ :			Dict            =      1.0
								snake_case_ :			Optional[Any]            =      0.02





		@classmethod
		def  UpperCAmelCase__				(       cls				,     _lowercase				,     _lowercase				,     _lowercase				,     **_lowercase				,     )			->    Dict:







								'''simple docstring'''

								return cls(
								    vision_config=vision_config.to_dict()				,     qformer_config=qformer_config.to_dict()				,     text_config=text_config.to_dict()				,     **_lowercase				,     )





		def  UpperCAmelCase__				(       self )			->    List[str]:







								'''simple docstring'''

								snake_case_ :			Optional[Any]            =      copy.deepcopy(self.__dict__ )
								snake_case_ :			Optional[int]            =      self.vision_config.to_dict()
								snake_case_ :			Union[str, Any]            =      self.qformer_config.to_dict()
								snake_case_ :			Dict            =      self.text_config.to_dict()
								snake_case_ :			Tuple            =      self.__class__.model_type
								return output




"""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 							SCREAMING_SNAKE_CASE   (						a_			):






					"""simple docstring"""



					lowercase__												=			"Salesforce/blip-image-captioning-base"
					lowercase__												=			(
					    "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."
					)
					lowercase__												=			"image_captioner"
					lowercase__												=			AutoModelForVisionaSeq

					lowercase__												=			["image"]
					lowercase__												=			["text"]







					def __init__(			self     :							int  ,*lowercase_     :							int  ,**lowercase_     :							List[str]						):
						requires_backends(self  ,['''vision''']						)
						super().__init__(*lowercase_  ,**lowercase_						)







					def 			__lowerCAmelCase					(			self     :							List[str]  ,lowercase_     :							"Image"						):
						return self.pre_processor(images=lowercase_  ,return_tensors='''pt'''						)







					def 			__lowerCAmelCase					(			self     :							List[Any]  ,lowercase_     :							Any						):
						return self.model.generate(**lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Dict  ,lowercase_     :							Union[str, Any]						):
						return self.pre_processor.batch_decode(lowercase_  ,skip_special_tokens=lowercase_						)[0].strip()




