





'''simple docstring'''






from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


lowerCAmelCase       		=      logging.get_logger(__name__)
class 		lowerCamelCase  (      _UpperCAmelCase       ):



	def   _lowerCamelCase    (   self		,      a_	):






							if isinstance(lowercase__		,      lowercase__	):
													lowerCAmelCase     :    Union[str, Any]						=   [label.strip() for label in labels.split(","	) if label.strip()]
							return labels





	def __call__(   self		,      a_		,      a_		,      a_	):






							if len(lowercase__	) == 0 or len(lowercase__	) == 0:
													raise ValueError("You must include at least one label and at least one sequence."	)
							if hypothesis_template.format(labels[0]	) == hypothesis_template:
													raise ValueError(
													    (
													        "The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. "
													        "Make sure the passed template includes formatting syntax such as {{}} where the label should go."
													    ).format(lowercase__	)	)

							if isinstance(lowercase__		,      lowercase__	):
													lowerCAmelCase     :    Optional[int]						=   [sequences]

							lowerCAmelCase     :    Optional[Any]						=   []
							for sequence in sequences:
													sequence_pairs.extend([[sequence, hypothesis_template.format(lowercase__	)] for label in labels]	)

							return sequence_pairs, sequences






@add_end_docstrings(_UpperCAmelCase       )
class 		lowerCamelCase  (      _UpperCAmelCase       ):



	def __init__(   self		,      a_=ZeroShotClassificationArgumentHandler()		,      *a_		,      **a_	):
							lowerCAmelCase     :    List[str]						=   args_parser
							super().__init__(*lowercase__		,      **lowercase__	)
							if self.entailment_id == -1:
													logger.warning(
													    "Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to "
													    "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."	)



	@property
	def   _lowerCamelCase    (   self	):






							for label, ind in self.model.config.labelaid.items():
													if label.lower().startswith("entail"	):
																			return ind
							return -1



	def   _lowerCamelCase    (   self		,      a_		,      a_=True		,      a_=True		,      a_=TruncationStrategy.ONLY_FIRST		,      **a_	):
							lowerCAmelCase     :    List[Any]						=   self.framework
							if self.tokenizer.pad_token is None:
													# Override for tokenizers not supporting padding
													logger.error(
													    "Tokenizer was not supporting padding necessary for zero-shot, attempting to use "
													    " `pad_token=eos_token`"	)
													lowerCAmelCase     :    Optional[int]						=   self.tokenizer.eos_token
							try:
													lowerCAmelCase     :    Optional[int]						=   self.tokenizer(
													    lowercase__		,      add_special_tokens=lowercase__		,      return_tensors=lowercase__		,      padding=lowercase__		,      truncation=lowercase__		,      )
							except Exception as e:
													if "too short" in str(lowercase__	):
																			# tokenizers might yell that we want to truncate
																			# to a value that is not even reached by the input.
																			# In that case we don't want to truncate.
																			# It seems there's not a really better way to catch that
																			# exception.

																			lowerCAmelCase     :    Optional[Any]						=   self.tokenizer(
																			    lowercase__		,      add_special_tokens=lowercase__		,      return_tensors=lowercase__		,      padding=lowercase__		,      truncation=TruncationStrategy.DO_NOT_TRUNCATE		,      )
													else:
																			raise e

							return inputs



	def   _lowerCamelCase    (   self		,      **a_	):






							if kwargs.get("multi_class"		,      lowercase__	) is not None:
													lowerCAmelCase     :    Optional[int]						=   kwargs["multi_class"]
													logger.warning(
													    "The `multi_class` argument has been deprecated and renamed to `multi_label`. "
													    "`multi_class` will be removed in a future version of Transformers."	)
							lowerCAmelCase     :    Optional[int]						=   {}
							if "candidate_labels" in kwargs:
													lowerCAmelCase     :    Union[str, Any]						=   self._args_parser._parse_labels(kwargs["candidate_labels"]	)
							if "hypothesis_template" in kwargs:
													lowerCAmelCase     :    int						=   kwargs["hypothesis_template"]

							lowerCAmelCase     :    List[Any]						=   {}
							if "multi_label" in kwargs:
													lowerCAmelCase     :    Tuple						=   kwargs["multi_label"]
							return preprocess_params, {}, postprocess_params



	def __call__(   self		,      a_		,      *a_		,      **a_		,      ):






							if len(lowercase__	) == 0:
													pass
							elif len(lowercase__	) == 1 and "candidate_labels" not in kwargs:
													lowerCAmelCase     :    Any						=   args[0]
							else:
													raise ValueError(F'''Unable to understand extra arguments {args}'''	)

							return super().__call__(lowercase__		,      **lowercase__	)



	def   _lowerCamelCase    (   self		,      a_		,      a_=None		,      a_="This example is {}."	):
							lowerCAmelCase     :    List[Any]						=   self._args_parser(lowercase__		,      lowercase__		,      lowercase__	)

							for i, (candidate_label, sequence_pair) in enumerate(zip(lowercase__		,      lowercase__	)	):
													lowerCAmelCase     :    Dict						=   self._parse_and_tokenize([sequence_pair]	)

													yield {
													    "candidate_label": candidate_label,
													    "sequence": sequences[0],
													    "is_last": i == len(lowercase__	) - 1,
													    **model_input,
													}



	def   _lowerCamelCase    (   self		,      a_	):
							lowerCAmelCase     :    List[Any]						=   inputs["candidate_label"]
							lowerCAmelCase     :    Union[str, Any]						=   inputs["sequence"]
							lowerCAmelCase     :    Any						=   {k: inputs[k] for k in self.tokenizer.model_input_names}
							lowerCAmelCase     :    List[Any]						=   self.model(**lowercase__	)

							lowerCAmelCase     :    str						=   {
							    "candidate_label": candidate_label,
							    "sequence": sequence,
							    "is_last": inputs["is_last"],
							    **outputs,
							}
							return model_outputs





	def   _lowerCamelCase    (   self		,      a_		,      a_=False	):
							lowerCAmelCase     :    Tuple						=   [outputs["candidate_label"] for outputs in model_outputs]
							lowerCAmelCase     :    Tuple						=   [outputs["sequence"] for outputs in model_outputs]
							lowerCAmelCase     :    Optional[Any]						=   np.concatenate([output["logits"].numpy() for output in model_outputs]	)
							lowerCAmelCase     :    Any						=   logits.shape[0]
							lowerCAmelCase     :    str						=   len(lowercase__	)
							lowerCAmelCase     :    str						=   N // n
							lowerCAmelCase     :    List[str]						=   logits.reshape((num_sequences, n, -1)	)

							if multi_label or len(lowercase__	) == 1:
													# softmax over the entailment vs. contradiction dim for each label independently
													lowerCAmelCase     :    Optional[Any]						=   self.entailment_id
													lowerCAmelCase     :    Optional[Any]						=   -1 if entailment_id == 0 else 0
													lowerCAmelCase     :    str						=   reshaped_outputs[..., [contradiction_id, entailment_id]]
													lowerCAmelCase     :    Optional[int]						=   np.exp(lowercase__	) / np.exp(lowercase__	).sum(-1		,      keepdims=lowercase__	)
													lowerCAmelCase     :    Tuple						=   scores[..., 1]
							else:
													# softmax the "entailment" logits over all candidate labels
													lowerCAmelCase     :    List[Any]						=   reshaped_outputs[..., self.entailment_id]
													lowerCAmelCase     :    List[Any]						=   np.exp(lowercase__	) / np.exp(lowercase__	).sum(-1		,      keepdims=lowercase__	)

							lowerCAmelCase     :    Dict						=   list(reversed(scores[0].argsort()	)	)
							return {
							    "sequence": sequences[0],
							    "labels": [candidate_labels[i] for i in top_inds],
							    "scores": scores[0, top_inds].tolist(),
							}










'''simple docstring'''






import numpy as np






def      __A						(							a_						:  np.array	):
		return (2 / (1 + np.exp(-2 * vector	))) - 1


if __name__ == "__main__":
					import doctest

					doctest.testmod()



