


# 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      (			A__       ):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__				:			Tuple						=		'''Salesforce/blip-image-captioning-base'''
				SCREAMING_SNAKE_CASE__				:			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.'''
				)
				SCREAMING_SNAKE_CASE__				:			Tuple						=		'''image_captioner'''
				SCREAMING_SNAKE_CASE__				:			Optional[int]						=		AutoModelForVisionaSeq

				SCREAMING_SNAKE_CASE__				:			List[str]						=		['''image''']
				SCREAMING_SNAKE_CASE__				:			Dict						=		['''text''']


				def __init__(       self			:Tuple			,			*lowerCAmelCase__			:Union[str, Any]			,			**lowerCAmelCase__			:Optional[Any]	)		->			Dict:
										requires_backends(self			,			['''vision''']	)
										super().__init__(*lowerCAmelCase__			,			**lowerCAmelCase__	)


				def 		__magic_name__(       self			:List[str]			,			lowerCAmelCase__			:"Image"	)		->			Optional[Any]:
										return self.pre_processor(images=lowerCAmelCase__			,			return_tensors='''pt'''	)


				def 		__magic_name__(       self			:Optional[Any]			,			lowerCAmelCase__			:Union[str, Any]	)		->			str:
										return self.model.generate(**lowerCAmelCase__	)



				def 		__magic_name__(       self			:Optional[Any]			,			lowerCAmelCase__			:List[str]	)		->			int:
										return self.pre_processor.batch_decode(lowerCAmelCase__			,			skip_special_tokens=lowerCAmelCase__	)[0].strip()




from importlib import import_module

from .logging import get_logger


__lowerCAmelCase	: str  				=get_logger(__name__)
class        _lowercase      :






				'''simple docstring'''



				def __init__(       self			:List[Any]			,			lowerCAmelCase__			:List[Any]			,			lowerCAmelCase__			:str=None	)		->			int:
										__SCREAMING_SNAKE_CASE						:     List[str]					=		attrs or []
										if module is not None:
																for key in module.__dict__:
																						if key in attrs or not key.startswith('''__'''	):
																												setattr(self			,			lowerCAmelCase__			,			getattr(lowerCAmelCase__			,			lowerCAmelCase__	)	)
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		module._original_module if isinstance(lowerCAmelCase__			,			_PatchedModuleObj	) else module




class        _lowercase      :






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__				:			Optional[int]						=		[]


				def __init__(       self			:Tuple			,			lowerCAmelCase__			:Optional[Any]			,			lowerCAmelCase__			:str			,			lowerCAmelCase__			:Any			,			lowerCAmelCase__			:Dict=None	)		->			List[Any]:
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		obj
										__SCREAMING_SNAKE_CASE						:     str					=		target
										__SCREAMING_SNAKE_CASE						:     Dict					=		new
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		target.split('''.'''	)[0]
										__SCREAMING_SNAKE_CASE						:     List[str]					=		{}
										__SCREAMING_SNAKE_CASE						:     Tuple					=		attrs or []


				def __enter__(       self			:int	)		->			Dict:
										*__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		self.target.split('''.'''	)

										# Patch modules:
										# it's used to patch attributes of submodules like "os.path.join";
										# in this case we need to patch "os" and "os.path"

										for i in range(len(lowerCAmelCase__	)	):
																try:
																						__SCREAMING_SNAKE_CASE						:     Any					=		import_module('''.'''.join(submodules[: i + 1]	)	)
																except ModuleNotFoundError:
																						continue
																# We iterate over all the globals in self.obj in case we find "os" or "os.path"
																for attr in self.obj.__dir__():
																						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		getattr(self.obj			,			lowerCAmelCase__	)
																						# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
																						# This allows to patch renamed modules like "from os import path as ospath".
																						if obj_attr is submodule or (
																						    (isinstance(lowerCAmelCase__			,			_PatchedModuleObj	) and obj_attr._original_module is submodule)
																						):
																												__SCREAMING_SNAKE_CASE						:     int					=		obj_attr
																												# patch at top level
																												setattr(self.obj			,			lowerCAmelCase__			,			_PatchedModuleObj(lowerCAmelCase__			,			attrs=self.attrs	)	)
																												__SCREAMING_SNAKE_CASE						:     List[str]					=		getattr(self.obj			,			lowerCAmelCase__	)
																												# construct lower levels patches
																												for key in submodules[i + 1 :]:
																																		setattr(lowerCAmelCase__			,			lowerCAmelCase__			,			_PatchedModuleObj(getattr(lowerCAmelCase__			,			lowerCAmelCase__			,			lowerCAmelCase__	)			,			attrs=self.attrs	)	)
																																		__SCREAMING_SNAKE_CASE						:     Tuple					=		getattr(lowerCAmelCase__			,			lowerCAmelCase__	)
																												# finally set the target attribute
																												setattr(lowerCAmelCase__			,			lowerCAmelCase__			,			self.new	)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

										if submodules:  # if it's an attribute of a submodule like "os.path.join"
																try:
																						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		getattr(import_module('''.'''.join(lowerCAmelCase__	)	)			,			lowerCAmelCase__	)
																except (AttributeError, ModuleNotFoundError):
																						return
																# We iterate over all the globals in self.obj in case we find "os.path.join"
																for attr in self.obj.__dir__():
																						# We don't check for the name of the global, but rather if its value *is* "os.path.join".
																						# This allows to patch renamed attributes like "from os.path import join as pjoin".
																						if getattr(self.obj			,			lowerCAmelCase__	) is attr_value:
																												__SCREAMING_SNAKE_CASE						:     Any					=		getattr(self.obj			,			lowerCAmelCase__	)
																												setattr(self.obj			,			lowerCAmelCase__			,			self.new	)
										elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		globals()['''__builtins__'''][target_attr]
																setattr(self.obj			,			lowerCAmelCase__			,			self.new	)
										else:
																raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''	)


				def __exit__(       self			:str			,			*lowerCAmelCase__			:Union[str, Any]	)		->			Optional[int]:
										for attr in list(self.original	):
																setattr(self.obj			,			lowerCAmelCase__			,			self.original.pop(lowerCAmelCase__	)	)


				def 		__magic_name__(       self			:List[Any]	)		->			List[Any]:
										self.__enter__()
										self._active_patches.append(self	)



				def 		__magic_name__(       self			:Optional[int]	)		->			int:
										try:
																self._active_patches.remove(self	)
										except ValueError:
																# If the patch hasn't been started this will fail
																return None

										return self.__exit__()
