
"""simple docstring"""







import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
       from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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




def       A_      (       lowercase   )  ->				str:


     """simple docstring"""







     return 1.0 / (1.0 + np.exp(-_outputs   ))




def       A_      (       lowercase   )  ->				List[str]:


     """simple docstring"""







     UpperCAmelCase_    :     Dict            =	np.max(_outputs    ,			axis=-1    ,			keepdims=lowercase   )
     UpperCAmelCase_    :     Any            =	np.exp(_outputs - maxes   )
     return shifted_exp / shifted_exp.sum(axis=-1    ,			keepdims=lowercase   )



class 		UpperCAmelCase_						(lowerCamelCase_    ):
 """simple docstring"""




 UpperCamelCase_    :  Tuple					 =     """sigmoid"""
 UpperCamelCase_    :  Dict					 =     """softmax"""
 UpperCamelCase_    :  Optional[int]					 =     """none"""



@add_end_docstrings(
    lowerCamelCase_	,			r"""
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `\"default\"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `\"sigmoid\"`: Applies the sigmoid function on the output.
            - `\"softmax\"`: Applies the softmax function on the output.
            - `\"none\"`: Does not apply any function on the output.
    """	,			)
class 		UpperCAmelCase_						(lowerCamelCase_    ):
 """simple docstring"""




 UpperCamelCase_    :  Dict					 =     False
 UpperCamelCase_    :  Union[str, Any]					 =     ClassificationFunction.NONE




 def __init__(			self							:			Any  , **a_							:			Union[str, Any]			)->       Dict:



      """simple docstring"""

      super().__init__(**a_			)

      self.check_model_type(
          TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
          if self.framework == """tf"""
          else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING			)




 def 	a   (			self							:			int  , a_							:			Dict=None  , a_							:			List[str]=None  , a_							:			Optional[Any]=""  , **a_							:			Optional[int]			)->       Optional[Any]:



      """simple docstring"""

      UpperCAmelCase_    :     Union[str, Any]            =	tokenizer_kwargs

      UpperCAmelCase_    :     Optional[Any]            =	{}
      if hasattr(self.model.config  , """return_all_scores"""			) and return_all_scores is None:
           UpperCAmelCase_    :     Dict            =	self.model.config.return_all_scores

      if isinstance(a_  , a_			) or top_k is None:
           UpperCAmelCase_    :     Any            =	top_k
           UpperCAmelCase_    :     List[Any]            =	False
      elif return_all_scores is not None:
           warnings.warn(
               """`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of"""
               """ `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`."""  , a_  , )
           if return_all_scores:
                UpperCAmelCase_    :     List[str]            =	None
           else:
                UpperCAmelCase_    :     List[Any]            =	1

      if isinstance(a_  , a_			):
           UpperCAmelCase_    :     str            =	ClassificationFunction[function_to_apply.upper()]

      if function_to_apply is not None:
           UpperCAmelCase_    :     List[str]            =	function_to_apply
      return preprocess_params, {}, postprocess_params




 def __call__(			self							:			Any  , *a_							:			str  , **a_							:			Optional[int]			)->       Any:



      """simple docstring"""

      UpperCAmelCase_    :     List[str]            =	super().__call__(*a_  , **a_			)
      # TODO try and retrieve it in a nicer way from _sanitize_parameters.
      UpperCAmelCase_    :     Optional[Any]            =	"""top_k""" not in kwargs
      if isinstance(args[0]  , a_			) and _legacy:
           # This pipeline is odd, and return a list when single item is run
           return [result]
      else:
           return result




 def 	a   (			self							:			Dict  , a_							:			List[str]  , **a_							:			Dict			)->       Dict[str, GenericTensor]:



      """simple docstring"""

      UpperCAmelCase_    :     Optional[int]            =	self.framework
      if isinstance(a_  , a_			):
           return self.tokenizer(**a_  , return_tensors=a_  , **a_			)
      elif isinstance(a_  , a_			) and len(a_			) == 1 and isinstance(inputs[0]  , a_			) and len(inputs[0]			) == 2:
           # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
           return self.tokenizer(
               text=inputs[0][0]  , text_pair=inputs[0][1]  , return_tensors=a_  , **a_			)
      elif isinstance(a_  , a_			):
           # This is likely an invalid usage of the pipeline attempting to pass text pairs.
           raise ValueError(
               """The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"""
               """ dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair."""			)
      return self.tokenizer(a_  , return_tensors=a_  , **a_			)




 def 	a   (			self							:			Any  , a_							:			Optional[Any]			)->       int:



      """simple docstring"""

      return self.model(**a_			)






 def 	a   (			self							:			Tuple  , a_							:			List[Any]  , a_							:			Any=None  , a_							:			Any=1  , a_							:			List[str]=True			)->       str:



      """simple docstring"""

      if function_to_apply is None:
           if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                UpperCAmelCase_    :     str            =	ClassificationFunction.SIGMOID
           elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                UpperCAmelCase_    :     List[Any]            =	ClassificationFunction.SOFTMAX
           elif hasattr(self.model.config  , """function_to_apply"""			) and function_to_apply is None:
                UpperCAmelCase_    :     List[str]            =	self.model.config.function_to_apply
           else:
                UpperCAmelCase_    :     Any            =	ClassificationFunction.NONE

      UpperCAmelCase_    :     Optional[Any]            =	model_outputs["""logits"""][0]
      UpperCAmelCase_    :     Optional[Any]            =	outputs.numpy()

      if function_to_apply == ClassificationFunction.SIGMOID:
           UpperCAmelCase_    :     List[str]            =	sigmoid(a_			)
      elif function_to_apply == ClassificationFunction.SOFTMAX:
           UpperCAmelCase_    :     Dict            =	softmax(a_			)
      elif function_to_apply == ClassificationFunction.NONE:
           UpperCAmelCase_    :     str            =	outputs
      else:
           raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}'''			)

      if top_k == 1 and _legacy:
           return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

      UpperCAmelCase_    :     List[str]            =	[
          {"""label""": self.model.config.idalabel[i], """score""": score.item()} for i, score in enumerate(a_			)
      ]
      if not _legacy:
           dict_scores.sort(key=lambda a_			: x["score"]  , reverse=a_			)
           if top_k is not None:
                UpperCAmelCase_    :     Optional[Any]            =	dict_scores[:top_k]
      return dict_scores



"""simple docstring"""







import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available



class 		UpperCAmelCase_						(lowerCamelCase_    ):
 """simple docstring"""




 UpperCamelCase_    :  str					 =     ["""image_processor""", """tokenizer"""]
 UpperCamelCase_    :  List[str]					 =     """OwlViTImageProcessor"""
 UpperCamelCase_    :  str					 =     ("""CLIPTokenizer""", """CLIPTokenizerFast""")




 def __init__(			self							:			Any  , a_							:			Any=None  , a_							:			str=None  , **a_							:			List[str]			)->       List[Any]:



      """simple docstring"""

      UpperCAmelCase_    :     List[Any]            =	None
      if "feature_extractor" in kwargs:
           warnings.warn(
               """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
               """ instead."""  , a_  , )
           UpperCAmelCase_    :     List[Any]            =	kwargs.pop("""feature_extractor"""			)

      UpperCAmelCase_    :     str            =	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__(a_  , a_			)




 def __call__(			self							:			Any  , a_							:			Optional[int]=None  , a_							:			Optional[int]=None  , a_							:			Dict=None  , a_							:			int="max_length"  , a_							:			List[Any]="np"  , **a_							:			int			)->       Tuple:



      """simple docstring"""

      if text is None and query_images is None and images is None:
           raise ValueError(
               """You have to specify at least one text or query image or image. All three cannot be none."""			)

      if text is not None:
           if isinstance(a_  , a_			) or (isinstance(a_  , a_			) and not isinstance(text[0]  , a_			)):
                UpperCAmelCase_    :     List[str]            =	[self.tokenizer(a_  , padding=a_  , return_tensors=a_  , **a_			)]

           elif isinstance(a_  , a_			) and isinstance(text[0]  , a_			):
                UpperCAmelCase_    :     Optional[int]            =	[]

                # Maximum number of queries across batch
                UpperCAmelCase_    :     Union[str, Any]            =	max([len(a_			) for t in text]			)

                # Pad all batch samples to max number of text queries
                for t in text:
                     if len(a_			) != max_num_queries:
                          UpperCAmelCase_    :     str            =	t + [""" """] * (max_num_queries - len(a_			))

                     UpperCAmelCase_    :     Optional[int]            =	self.tokenizer(a_  , padding=a_  , return_tensors=a_  , **a_			)
                     encodings.append(a_			)
           else:
                raise TypeError("""Input text should be a string, a list of strings or a nested list of strings"""			)

           if return_tensors == "np":
                UpperCAmelCase_    :     List[Any]            =	np.concatenate([encoding["""input_ids"""] for encoding in encodings]  , axis=0			)
                UpperCAmelCase_    :     Tuple            =	np.concatenate([encoding["""attention_mask"""] for encoding in encodings]  , axis=0			)

           elif return_tensors == "jax" and is_flax_available():
                import jax.numpy as jnp

                UpperCAmelCase_    :     Tuple            =	jnp.concatenate([encoding["""input_ids"""] for encoding in encodings]  , axis=0			)
                UpperCAmelCase_    :     Tuple            =	jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings]  , axis=0			)

           elif return_tensors == "pt" and is_torch_available():
                import torch

                UpperCAmelCase_    :     str            =	torch.cat([encoding["""input_ids"""] for encoding in encodings]  , dim=0			)
                UpperCAmelCase_    :     str            =	torch.cat([encoding["""attention_mask"""] for encoding in encodings]  , dim=0			)

           elif return_tensors == "tf" and is_tf_available():
                import tensorflow as tf

                UpperCAmelCase_    :     Union[str, Any]            =	tf.stack([encoding["""input_ids"""] for encoding in encodings]  , axis=0			)
                UpperCAmelCase_    :     Optional[int]            =	tf.stack([encoding["""attention_mask"""] for encoding in encodings]  , axis=0			)

           else:
                raise ValueError("""Target return tensor type could not be returned"""			)

           UpperCAmelCase_    :     Union[str, Any]            =	BatchEncoding()
           UpperCAmelCase_    :     int            =	input_ids
           UpperCAmelCase_    :     List[str]            =	attention_mask

      if query_images is not None:
           UpperCAmelCase_    :     Optional[int]            =	BatchEncoding()
           UpperCAmelCase_    :     Any            =	self.image_processor(
               a_  , return_tensors=a_  , **a_			).pixel_values
           UpperCAmelCase_    :     Optional[Any]            =	query_pixel_values

      if images is not None:
           UpperCAmelCase_    :     str            =	self.image_processor(a_  , return_tensors=a_  , **a_			)

      if text is not None and images is not None:
           UpperCAmelCase_    :     List[Any]            =	image_features.pixel_values
           return encoding
      elif query_images is not None and images is not None:
           UpperCAmelCase_    :     int            =	image_features.pixel_values
           return encoding
      elif text is not None or query_images is not None:
           return encoding
      else:
           return BatchEncoding(data=dict(**a_			)  , tensor_type=a_			)




 def 	a   (			self							:			Any  , *a_							:			Optional[Any]  , **a_							:			List[str]			)->       Union[str, Any]:



      """simple docstring"""

      return self.image_processor.post_process(*a_  , **a_			)




 def 	a   (			self							:			Tuple  , *a_							:			List[str]  , **a_							:			Dict			)->       Optional[int]:



      """simple docstring"""

      return self.image_processor.post_process_object_detection(*a_  , **a_			)




 def 	a   (			self							:			Optional[int]  , *a_							:			Tuple  , **a_							:			Optional[int]			)->       Optional[Any]:



      """simple docstring"""

      return self.image_processor.post_process_image_guided_detection(*a_  , **a_			)




 def 	a   (			self							:			str  , *a_							:			Optional[int]  , **a_							:			str			)->       Optional[int]:



      """simple docstring"""

      return self.tokenizer.batch_decode(*a_  , **a_			)




 def 	a   (			self							:			str  , *a_							:			List[Any]  , **a_							:			List[str]			)->       Union[str, Any]:



      """simple docstring"""

      return self.tokenizer.decode(*a_  , **a_			)




 @property
 def 	a   (			self							:			Tuple			)->       int:



      """simple docstring"""

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






 @property
 def 	a   (			self							:			Optional[Any]			)->       int:



      """simple docstring"""

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

