




'''simple docstring'''







import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding


class     _a						(			__a				):
       __a       :  List[Any]            =      ["""image_processor""", """tokenizer"""]
       __a       :  Any            =      """CLIPImageProcessor"""
       __a       :  Any            =      ("""CLIPTokenizer""", """CLIPTokenizerFast""")
       def __init__(			self		:			Optional[int]     ,       lowercase		:			Union[str, Any]=None     ,       lowercase		:			Optional[int]=None     ,       **lowercase		:			Dict       ):



           '''simple docstring'''

           UpperCAmelCase     =	None
           if "feature_extractor" in kwargs:
               warnings.warn(
                   '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
                   ''' instead.'''     ,       lowercase     ,       )
               UpperCAmelCase     =	kwargs.pop('''feature_extractor'''       )

           UpperCAmelCase     =	image_processor if image_processor is not None else feature_extractor
           if image_processor is None:
               raise ValueError('''You need to specify an `image_processor`.'''       )
           if tokenizer is None:
               raise ValueError('''You need to specify a `tokenizer`.'''       )

           super().__init__(lowercase     ,       lowercase       )
       def __call__(			self		:			List[Any]     ,       lowercase		:			int=None     ,       lowercase		:			Union[str, Any]=None     ,       lowercase		:			str=None     ,       **lowercase		:			str       ):



           '''simple docstring'''

           if text is None and images is None:
               raise ValueError('''You have to specify either text or images. Both cannot be none.'''       )

           if text is not None:
               UpperCAmelCase     =	self.tokenizer(lowercase     ,       return_tensors=lowercase     ,       **lowercase       )

           if images is not None:
               UpperCAmelCase     =	self.image_processor(lowercase     ,       return_tensors=lowercase     ,       **lowercase       )

           if text is not None and images is not None:
               UpperCAmelCase     =	image_features.pixel_values
               return encoding
           elif text is not None:
               return encoding
           else:
               return BatchEncoding(data=dict(**lowercase       )     ,       tensor_type=lowercase       )
       def 					A   (			self		:			List[str]     ,       *lowercase		:			Dict     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           return self.tokenizer.batch_decode(*lowercase     ,       **lowercase       )
       def 					A   (			self		:			str     ,       *lowercase		:			Any     ,       **lowercase		:			List[str]       ):



           '''simple docstring'''

           return self.tokenizer.decode(*lowercase     ,       **lowercase       )
       @property
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.tokenizer.model_input_names
           UpperCAmelCase     =	self.image_processor.model_input_names
           return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names       )       )
       @property
       def 					A   (			self		:			List[str]       ):



           '''simple docstring'''

           warnings.warn(
               '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''     ,       lowercase     ,       )
           return self.image_processor_class







       @property
       def 					A   (			self		:			Optional[int]       ):



           '''simple docstring'''

           warnings.warn(
               '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''     ,       lowercase     ,       )
           return self.image_processor










'''simple docstring'''







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

A									=logging.get_logger(__name__)


@add_end_docstrings(__a				)
class     _a						(			__a				):
       def __init__(			self		:			Optional[int]     ,       *lowercase		:			Any     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           super().__init__(*lowercase     ,       **lowercase       )
           self.check_model_type(lowercase       )
       def 					A   (			self		:			List[str]     ,       lowercase		:			str=None     ,       lowercase		:			List[str]=None     ,       lowercase		:			List[str]=None     ,       **lowercase		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase ,  UpperCAmelCase     =	{}, {}
           if padding is not None:
               UpperCAmelCase     =	padding
           if truncation is not None:
               UpperCAmelCase     =	truncation
           if top_k is not None:
               UpperCAmelCase     =	top_k
           return preprocess_params, {}, postprocess_params
       def __call__(			self		:			Optional[Any]     ,       lowercase		:			Union["Image.Image", str]     ,       lowercase		:			str = None     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           if isinstance(lowercase     ,       (Image.Image, str)       ) and isinstance(lowercase     ,       lowercase       ):
               UpperCAmelCase     =	{'''image''': image, '''question''': question}
           else:
               UpperCAmelCase     =	image
           UpperCAmelCase     =	super().__call__(lowercase     ,       **lowercase       )
           return results
       def 					A   (			self		:			List[Any]     ,       lowercase		:			List[str]     ,       lowercase		:			Any=False     ,       lowercase		:			Any=False       ):



           '''simple docstring'''

           UpperCAmelCase     =	load_image(inputs['''image''']       )
           UpperCAmelCase     =	self.tokenizer(
               inputs['''question''']     ,       return_tensors=self.framework     ,       padding=lowercase     ,       truncation=lowercase       )
           UpperCAmelCase     =	self.image_processor(images=lowercase     ,       return_tensors=self.framework       )
           model_inputs.update(lowercase       )
           return model_inputs
       def 					A   (			self		:			Dict     ,       lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model(**lowercase       )
           return model_outputs







       def 					A   (			self		:			Union[str, Any]     ,       lowercase		:			int     ,       lowercase		:			Optional[Any]=5       ):



           '''simple docstring'''

           if top_k > self.model.config.num_labels:
               UpperCAmelCase     =	self.model.config.num_labels

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

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




