


from typing import Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
	from PIL import Image

	from ..image_utils import load_image

if is_torch_available():
	from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING

_lowerCAmelCase:						Any   				=       logging.get_logger(__name__)




@add_end_docstrings(lowercase__   )
class       lowercase_					(lowercase__   ):





				def __init__(				self       ,  *lowercase_       ,  **lowercase_)  -> Union[str, Any]:
											super().__init__(*lowercase_       ,  **lowercase_)
											self.check_model_type(lowercase_)





				def 						__UpperCamelCase    (				self       ,  lowercase_=None       ,  lowercase_=None       ,  lowercase_=None       ,  **lowercase_)  -> str:
											a__    ,     a__      ={}, {}
											if padding is not None:
																		a__      =padding
											if truncation is not None:
																		a__      =truncation
											if top_k is not None:
																		a__      =top_k
											return preprocess_params, {}, postprocess_params





				def __call__(				self       ,  lowercase_       ,  lowercase_ = None       ,  **lowercase_)  -> List[Any]:
											if isinstance(lowercase_       ,  (Image.Image, str)) and isinstance(lowercase_       ,  lowercase_):
																		a__      ={'image': image, 'question': question}
											else:
																		a__      =image
											a__      =super().__call__(lowercase_       ,  **lowercase_)
											return results





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_=False       ,  lowercase_=False)  -> Optional[int]:
											a__      =load_image(inputs['image'])
											a__      =self.tokenizer(
											    inputs['question']       ,  return_tensors=self.framework       ,  padding=lowercase_       ,  truncation=lowercase_)
											a__      =self.image_processor(images=lowercase_       ,  return_tensors=self.framework)
											model_inputs.update(lowercase_)
											return model_inputs





				def 						__UpperCamelCase    (				self       ,  lowercase_)  -> Optional[Any]:
											a__      =self.model(**lowercase_)
											return model_outputs





				def 						__UpperCamelCase    (				self       ,  lowercase_       ,  lowercase_=5)  -> Union[str, Any]:
											if top_k > self.model.config.num_labels:
																		a__      =self.model.config.num_labels

											if self.framework == "pt":
																		a__      =model_outputs.logits.sigmoid()[0]
																		a__    ,     a__      =probs.topk(lowercase_)
											else:
																		raise ValueError(F"""Unsupported framework: {self.framework}""")

											a__      =scores.tolist()
											a__      =ids.tolist()
											return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowercase_       ,  lowercase_)]





from importlib import import_module

from .logging import get_logger


_lowerCAmelCase:						str   				=       get_logger(__name__)




class       lowercase_					:





				def __init__(				self       ,  lowercase_       ,  lowercase_=None)  -> Tuple:
											a__      =attrs or []
											if module is not None:
																		for key in module.__dict__:
																									if key in attrs or not key.startswith('__'):
																																setattr(self       ,  lowercase_       ,  getattr(lowercase_       ,  lowercase_))
											a__      =module._original_module if isinstance(lowercase_       ,  _PatchedModuleObj) else module







class       lowercase_					:
				snake_case	    =[]





				def __init__(				self       ,  lowercase_       ,  lowercase_       ,  lowercase_       ,  lowercase_=None)  -> List[str]:
											a__      =obj
											a__      =target
											a__      =new
											a__      =target.split('.')[0]
											a__      ={}
											a__      =attrs or []





				def __enter__(				self)  -> Optional[int]:
											*a__    ,     a__      =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(lowercase_)):
																		try:
																									a__      =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__():
																									a__      =getattr(self.obj       ,  lowercase_)
																									# 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(lowercase_       ,  _PatchedModuleObj) and obj_attr._original_module is submodule)
																									):
																																a__      =obj_attr
																																# patch at top level
																																setattr(self.obj       ,  lowercase_       ,  _PatchedModuleObj(lowercase_       ,  attrs=self.attrs))
																																a__      =getattr(self.obj       ,  lowercase_)
																																# construct lower levels patches
																																for key in submodules[i + 1 :]:
																																							setattr(lowercase_       ,  lowercase_       ,  _PatchedModuleObj(getattr(lowercase_       ,  lowercase_       ,  lowercase_)       ,  attrs=self.attrs))
																																							a__      =getattr(lowercase_       ,  lowercase_)
																																# finally set the target attribute
																																setattr(lowercase_       ,  lowercase_       ,  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:
																									a__      =getattr(import_module('.'.join(lowercase_))       ,  lowercase_)
																		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       ,  lowercase_) is attr_value:
																																a__      =getattr(self.obj       ,  lowercase_)
																																setattr(self.obj       ,  lowercase_       ,  self.new)
											elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																		a__      =globals()['__builtins__'][target_attr]
																		setattr(self.obj       ,  lowercase_       ,  self.new)
											else:
																		raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule.""")





				def __exit__(				self       ,  *lowercase_)  -> str:
											for attr in list(self.original):
																		setattr(self.obj       ,  lowercase_       ,  self.original.pop(lowercase_))





				def 						__UpperCamelCase    (				self)  -> Any:
											self.__enter__()
											self._active_patches.append(self)





				def 						__UpperCamelCase    (				self)  -> Union[str, Any]:
											try:
																		self._active_patches.remove(self)
											except ValueError:
																		# If the patch hasn't been started this will fail
																		return None

											return self.__exit__()

