
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 				_lowercase				(	UpperCamelCase_						)						->						Union[str, Any]:
					'''simple docstring'''


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






def 				_lowercase				(	UpperCamelCase_						)						->						Any:
					'''simple docstring'''


					SCREAMING_SNAKE_CASE__						=					np.max(_outputs      ,      axis=-1      ,      keepdims=a__						)
					SCREAMING_SNAKE_CASE__						=					np.exp(_outputs - maxes						)
					return shifted_exp / shifted_exp.sum(axis=-1      ,      keepdims=a__						)




class 		lowercase__    (		_UpperCAmelCase    ):
	A__       :  Optional[int]										="""sigmoid"""
	A__       :  Dict										="""softmax"""
	A__       :  List[str]										="""none"""





@add_end_docstrings(
    _UpperCAmelCase	,			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 		lowercase__    (		_UpperCAmelCase    ):
	A__       :  Any										=False
	A__       :  int										=ClassificationFunction.NONE
	def __init__(     self				:  Dict			,  **UpperCAmelCase_				:  Dict				):
						super().__init__(**UpperCAmelCase_				)

						self.check_model_type(
						    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
						    if self.framework == 'tf'
						    else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING				)
	def 	A_							(     self				:  Tuple			,  UpperCAmelCase_				:  Optional[int]=None			,  UpperCAmelCase_				:  Tuple=None			,  UpperCAmelCase_				:  Optional[int]=""			,  **UpperCAmelCase_				:  Dict				):
						# Using "" as default argument because we're going to use `top_k=None` in user code to declare
						# "No top_k"
						SCREAMING_SNAKE_CASE__						=					tokenizer_kwargs

						SCREAMING_SNAKE_CASE__						=					{}
						if hasattr(self.model.config			,  'return_all_scores'				) and return_all_scores is None:
											SCREAMING_SNAKE_CASE__						=					self.model.config.return_all_scores

						if isinstance(UpperCAmelCase_			,  UpperCAmelCase_				) or top_k is None:
											SCREAMING_SNAKE_CASE__						=					top_k
											SCREAMING_SNAKE_CASE__						=					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`.'			,  UpperCAmelCase_			,  )
											if return_all_scores:
																SCREAMING_SNAKE_CASE__						=					None
											else:
																SCREAMING_SNAKE_CASE__						=					1

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

						if function_to_apply is not None:
											SCREAMING_SNAKE_CASE__						=					function_to_apply
						return preprocess_params, {}, postprocess_params
	def __call__(     self				:  Tuple			,  *UpperCAmelCase_				:  Optional[int]			,  **UpperCAmelCase_				:  Dict				):
						SCREAMING_SNAKE_CASE__						=					super().__call__(*UpperCAmelCase_			,  **UpperCAmelCase_				)
						# TODO try and retrieve it in a nicer way from _sanitize_parameters.
						SCREAMING_SNAKE_CASE__						=					'top_k' not in kwargs
						if isinstance(args[0]			,  UpperCAmelCase_				) and _legacy:
											# This pipeline is odd, and return a list when single item is run
											return [result]
						else:
											return result
	def 	A_							(     self				:  List[str]			,  UpperCAmelCase_				:  Union[str, Any]			,  **UpperCAmelCase_				:  Dict				):
						SCREAMING_SNAKE_CASE__						=					self.framework
						if isinstance(UpperCAmelCase_			,  UpperCAmelCase_				):
											return self.tokenizer(**UpperCAmelCase_			,  return_tensors=UpperCAmelCase_			,  **UpperCAmelCase_				)
						elif isinstance(UpperCAmelCase_			,  UpperCAmelCase_				) and len(UpperCAmelCase_				) == 1 and isinstance(inputs[0]			,  UpperCAmelCase_				) 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=UpperCAmelCase_			,  **UpperCAmelCase_				)
						elif isinstance(UpperCAmelCase_			,  UpperCAmelCase_				):
											# 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(UpperCAmelCase_			,  return_tensors=UpperCAmelCase_			,  **UpperCAmelCase_				)
	def 	A_							(     self				:  Optional[int]			,  UpperCAmelCase_				:  List[str]				):
						return self.model(**UpperCAmelCase_				)





	def 	A_							(     self				:  List[Any]			,  UpperCAmelCase_				:  str			,  UpperCAmelCase_				:  List[str]=None			,  UpperCAmelCase_				:  Any=1			,  UpperCAmelCase_				:  List[Any]=True				):
						# `_legacy` is used to determine if we're running the naked pipeline and in backward
						# compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
						# the more natural result containing the list.
						# Default value before `set_parameters`
						if function_to_apply is None:
											if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
																SCREAMING_SNAKE_CASE__						=					ClassificationFunction.SIGMOID
											elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																SCREAMING_SNAKE_CASE__						=					ClassificationFunction.SOFTMAX
											elif hasattr(self.model.config			,  'function_to_apply'				) and function_to_apply is None:
																SCREAMING_SNAKE_CASE__						=					self.model.config.function_to_apply
											else:
																SCREAMING_SNAKE_CASE__						=					ClassificationFunction.NONE

						SCREAMING_SNAKE_CASE__						=					model_outputs['logits'][0]
						SCREAMING_SNAKE_CASE__						=					outputs.numpy()

						if function_to_apply == ClassificationFunction.SIGMOID:
											SCREAMING_SNAKE_CASE__						=					sigmoid(UpperCAmelCase_				)
						elif function_to_apply == ClassificationFunction.SOFTMAX:
											SCREAMING_SNAKE_CASE__						=					softmax(UpperCAmelCase_				)
						elif function_to_apply == ClassificationFunction.NONE:
											SCREAMING_SNAKE_CASE__						=					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()}

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













"""simple docstring"""


from typing import Any, Dict, List, Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		import torch

		from transformers.modeling_outputs import BaseModelOutput

		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING

__SCREAMING_SNAKE_CASE   =   logging.get_logger(__name__)




@add_end_docstrings(UpperCamelCase						)
class 						__UpperCamelCase     (     UpperCamelCase						):
					def __init__(							self							:	Union[str, Any]     , **UpperCAmelCase							:	List[Any]   )	->       int:
											super().__init__(**UpperCAmelCase   )

											if self.framework == "tf":
																	raise ValueError(f"""The {self.__class__} is only available in PyTorch."""   )

											requires_backends(self     , 'vision'   )
											self.check_model_type(UpperCAmelCase   )
					def __call__(							self							:	Optional[Any]     , UpperCAmelCase							:	Union[str, "Image.Image", List[Dict[str, Any]]]     , UpperCAmelCase							:	Union[str, List[str]] = None     , **UpperCAmelCase							:	Dict     , )	->       Any:
											if "text_queries" in kwargs:
																	lowerCAmelCase   :Dict						=			kwargs.pop('text_queries'   )

											if isinstance(UpperCAmelCase     , (str, Image.Image)   ):
																	lowerCAmelCase   :List[str]						=			{'image': image, 'candidate_labels': candidate_labels}
											else:
																	lowerCAmelCase   :Union[str, Any]						=			image
											lowerCAmelCase   :Optional[int]						=			super().__call__(UpperCAmelCase     , **UpperCAmelCase   )
											return results
					def        UpperCAmelCase__ (							self							:	List[Any]     , **UpperCAmelCase							:	Tuple   )	->       Optional[int]:
											lowerCAmelCase   :Any						=			{}
											if "threshold" in kwargs:
																	lowerCAmelCase   :int						=			kwargs['threshold']
											if "top_k" in kwargs:
																	lowerCAmelCase   :str						=			kwargs['top_k']
											return {}, {}, postprocess_params
					def        UpperCAmelCase__ (							self							:	Any     , UpperCAmelCase							:	Union[str, Any]   )	->       str:
											lowerCAmelCase   :Dict						=			load_image(inputs['image']   )
											lowerCAmelCase   :Dict						=			inputs['candidate_labels']
											if isinstance(UpperCAmelCase     , UpperCAmelCase   ):
																	lowerCAmelCase   :str						=			candidate_labels.split(','   )

											lowerCAmelCase   :str						=			torch.tensor([[image.height, image.width]]     , dtype=torch.intaa   )
											for i, candidate_label in enumerate(UpperCAmelCase   ):
																	lowerCAmelCase   :Any						=			self.tokenizer(UpperCAmelCase     , return_tensors=self.framework   )
																	lowerCAmelCase   :Optional[Any]						=			self.image_processor(UpperCAmelCase     , return_tensors=self.framework   )
																	yield {
																	    "is_last": i == len(UpperCAmelCase   ) - 1,
																	    "target_size": target_size,
																	    "candidate_label": candidate_label,
																	    **text_inputs,
																	    **image_features,
																	}
					def        UpperCAmelCase__ (							self							:	Union[str, Any]     , UpperCAmelCase							:	str   )	->       List[Any]:
											lowerCAmelCase   :Union[str, Any]						=			model_inputs.pop('target_size'   )
											lowerCAmelCase   :List[str]						=			model_inputs.pop('candidate_label'   )
											lowerCAmelCase   :Union[str, Any]						=			model_inputs.pop('is_last'   )

											lowerCAmelCase   :int						=			self.model(**UpperCAmelCase   )

											lowerCAmelCase   :Any						=			{'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs}
											return model_outputs
					def        UpperCAmelCase__ (							self							:	Union[str, Any]     , UpperCAmelCase							:	Optional[int]     , UpperCAmelCase							:	int=0.1     , UpperCAmelCase							:	Optional[Any]=None   )	->       str:
											lowerCAmelCase   :int						=			[]
											for model_output in model_outputs:
																	lowerCAmelCase   :int						=			model_output['candidate_label']
																	lowerCAmelCase   :List[Any]						=			BaseModelOutput(UpperCAmelCase   )
																	lowerCAmelCase   :Dict						=			self.image_processor.post_process_object_detection(
																	    outputs=UpperCAmelCase     , threshold=UpperCAmelCase     , target_sizes=model_output['target_size']   )[0]

																	for index in outputs["scores"].nonzero():
																							lowerCAmelCase   :Tuple						=			outputs['scores'][index].item()
																							lowerCAmelCase   :int						=			self._get_bounding_box(outputs['boxes'][index][0]   )

																							lowerCAmelCase   :Optional[int]						=			{'score': score, 'label': label, 'box': box}
																							results.append(UpperCAmelCase   )

											lowerCAmelCase   :Tuple						=			sorted(UpperCAmelCase     , key=lambda UpperCAmelCase   : x["score"]     , reverse=UpperCAmelCase   )
											if top_k:
																	lowerCAmelCase   :Dict						=			results[:top_k]

											return results
					def        UpperCAmelCase__ (							self							:	Optional[Any]     , UpperCAmelCase							:	"torch.Tensor"   )	->       Dict[str, int]:
											if self.framework != "pt":
																	raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.'   )
											lowerCAmelCase	, lowerCAmelCase	, lowerCAmelCase	, lowerCAmelCase   :Optional[int]						=			box.int().tolist()
											lowerCAmelCase   :Union[str, Any]						=			{
											    'xmin': xmin,
											    'ymin': ymin,
											    'xmax': xmax,
											    'ymax': ymax,
											}
											return bbox