



'''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


UpperCamelCase__ :			int												=				logging.get_logger(__name__)






class 		_UpperCamelCase						(							__UpperCAmelCase					):


			'''simple docstring'''

			def UpperCamelCase__      (							self  :				str							,  lowerCAmelCase__  :				Dict		):





					"""simple docstring"""






					if isinstance(__SCREAMING_SNAKE_CASE							,  __SCREAMING_SNAKE_CASE		):
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	[label.strip() for label in labels.split(""","""		) if label.strip()]
					return labels



			def __call__(							self  :				List[str]							,  lowerCAmelCase__  :				Optional[int]							,  lowerCAmelCase__  :				str							,  lowerCAmelCase__  :				List[Any]		):





					"""simple docstring"""






					if len(__SCREAMING_SNAKE_CASE		) == 0 or len(__SCREAMING_SNAKE_CASE		) == 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(__SCREAMING_SNAKE_CASE		)		)

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

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

					return sequence_pairs, sequences






@add_end_docstrings(__UpperCAmelCase					)
class 		_UpperCamelCase						(							__UpperCAmelCase					):


			'''simple docstring'''

			def __init__(							self  :				Any							,  lowerCAmelCase__  :				str=ZeroShotClassificationArgumentHandler()							,  *lowerCAmelCase__  :				Optional[Any]							,  **lowerCAmelCase__  :				List[str]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	int					 =	args_parser
					super().__init__(*__SCREAMING_SNAKE_CASE							,  **__SCREAMING_SNAKE_CASE		)
					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 UpperCamelCase__      (							self  :				Any		):





					"""simple docstring"""






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

			def UpperCamelCase__      (							self  :				Optional[Any]							,  lowerCAmelCase__  :				List[Any]							,  lowerCAmelCase__  :				Tuple=True							,  lowerCAmelCase__  :				Optional[Any]=True							,  lowerCAmelCase__  :				Optional[Any]=TruncationStrategy.ONLY_FIRST							,  **lowerCAmelCase__  :				str		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Optional[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`"""		)
							__SCREAMING_SNAKE_CASE :	List[str]					 =	self.tokenizer.eos_token
					try:
							__SCREAMING_SNAKE_CASE :	List[Any]					 =	self.tokenizer(
							    __SCREAMING_SNAKE_CASE							,  add_special_tokens=__SCREAMING_SNAKE_CASE							,  return_tensors=__SCREAMING_SNAKE_CASE							,  padding=__SCREAMING_SNAKE_CASE							,  truncation=__SCREAMING_SNAKE_CASE							,  )
					except Exception as e:
							if "too short" in str(__SCREAMING_SNAKE_CASE		):
									# 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.

									__SCREAMING_SNAKE_CASE :	Any					 =	self.tokenizer(
									    __SCREAMING_SNAKE_CASE							,  add_special_tokens=__SCREAMING_SNAKE_CASE							,  return_tensors=__SCREAMING_SNAKE_CASE							,  padding=__SCREAMING_SNAKE_CASE							,  truncation=TruncationStrategy.DO_NOT_TRUNCATE							,  )
							else:
									raise e

					return inputs

			def UpperCamelCase__      (							self  :				Optional[int]							,  **lowerCAmelCase__  :				Optional[int]		):





					"""simple docstring"""






					if kwargs.get("""multi_class"""							,  __SCREAMING_SNAKE_CASE		) is not None:
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	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."""		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	{}
					if "candidate_labels" in kwargs:
							__SCREAMING_SNAKE_CASE :	int					 =	self._args_parser._parse_labels(kwargs["""candidate_labels"""]		)
					if "hypothesis_template" in kwargs:
							__SCREAMING_SNAKE_CASE :	Optional[int]					 =	kwargs["""hypothesis_template"""]

					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	{}
					if "multi_label" in kwargs:
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	kwargs["""multi_label"""]
					return preprocess_params, {}, postprocess_params

			def __call__(							self  :				List[str]							,  lowerCAmelCase__  :				Union[str, List[str]]							,  *lowerCAmelCase__  :				Any							,  **lowerCAmelCase__  :				Any							,  ):





					"""simple docstring"""






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

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

			def UpperCamelCase__      (							self  :				Optional[int]							,  lowerCAmelCase__  :				int							,  lowerCAmelCase__  :				int=None							,  lowerCAmelCase__  :				int="This example is {}."		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	self._args_parser(__SCREAMING_SNAKE_CASE							,  __SCREAMING_SNAKE_CASE							,  __SCREAMING_SNAKE_CASE		)

					for i, (candidate_label, sequence_pair) in enumerate(zip(__SCREAMING_SNAKE_CASE							,  __SCREAMING_SNAKE_CASE		)		):
							__SCREAMING_SNAKE_CASE :	Optional[int]					 =	self._parse_and_tokenize([sequence_pair]		)

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

			def UpperCamelCase__      (							self  :				List[str]							,  lowerCAmelCase__  :				List[str]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	inputs["""candidate_label"""]
					__SCREAMING_SNAKE_CASE :	int					 =	inputs["""sequence"""]
					__SCREAMING_SNAKE_CASE :	Dict					 =	{k: inputs[k] for k in self.tokenizer.model_input_names}
					__SCREAMING_SNAKE_CASE :	int					 =	self.model(**__SCREAMING_SNAKE_CASE		)

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



			def UpperCamelCase__      (							self  :				Dict							,  lowerCAmelCase__  :				List[Any]							,  lowerCAmelCase__  :				Optional[int]=False		):





					"""simple docstring"""






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

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

					__SCREAMING_SNAKE_CASE :	str					 =	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'''




from ..utils import DummyObject, requires_backends






class 		_UpperCamelCase						(							metaclass=lowerCamelCase__					):


			'''simple docstring'''

			_A   :	Union[str, Any]    					=	['''torch''', '''transformers''', '''onnx''']

			def __init__(							self  :				Optional[int]							,  *lowerCAmelCase__  :				Optional[Any]							,  **lowerCAmelCase__  :				int		):





					"""simple docstring"""






					requires_backends(self							,  ["""torch""", """transformers""", """onnx"""]		)

			@classmethod
			def UpperCamelCase__      (							cls  :				Tuple							,  *lowerCAmelCase__  :				Union[str, Any]							,  **lowerCAmelCase__  :				Optional[int]		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)



			@classmethod
			def UpperCamelCase__      (							cls  :				str							,  *lowerCAmelCase__  :				int							,  **lowerCAmelCase__  :				Optional[Any]		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)






class 		_UpperCamelCase						(							metaclass=lowerCamelCase__					):


			'''simple docstring'''

			_A   :	Dict    					=	['''torch''', '''transformers''', '''onnx''']

			def __init__(							self  :				str							,  *lowerCAmelCase__  :				str							,  **lowerCAmelCase__  :				List[str]		):





					"""simple docstring"""






					requires_backends(self							,  ["""torch""", """transformers""", """onnx"""]		)

			@classmethod
			def UpperCamelCase__      (							cls  :				Optional[Any]							,  *lowerCAmelCase__  :				Dict							,  **lowerCAmelCase__  :				Dict		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)



			@classmethod
			def UpperCamelCase__      (							cls  :				str							,  *lowerCAmelCase__  :				List[str]							,  **lowerCAmelCase__  :				str		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)






class 		_UpperCamelCase						(							metaclass=lowerCamelCase__					):


			'''simple docstring'''

			_A   :	Tuple    					=	['''torch''', '''transformers''', '''onnx''']

			def __init__(							self  :				str							,  *lowerCAmelCase__  :				List[str]							,  **lowerCAmelCase__  :				Dict		):





					"""simple docstring"""






					requires_backends(self							,  ["""torch""", """transformers""", """onnx"""]		)

			@classmethod
			def UpperCamelCase__      (							cls  :				Any							,  *lowerCAmelCase__  :				Tuple							,  **lowerCAmelCase__  :				Any		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)



			@classmethod
			def UpperCamelCase__      (							cls  :				List[str]							,  *lowerCAmelCase__  :				Union[str, Any]							,  **lowerCAmelCase__  :				Dict		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)






class 		_UpperCamelCase						(							metaclass=lowerCamelCase__					):


			'''simple docstring'''

			_A   :	Optional[int]    					=	['''torch''', '''transformers''', '''onnx''']

			def __init__(							self  :				Optional[int]							,  *lowerCAmelCase__  :				Dict							,  **lowerCAmelCase__  :				List[Any]		):





					"""simple docstring"""






					requires_backends(self							,  ["""torch""", """transformers""", """onnx"""]		)

			@classmethod
			def UpperCamelCase__      (							cls  :				Any							,  *lowerCAmelCase__  :				List[Any]							,  **lowerCAmelCase__  :				List[str]		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)



			@classmethod
			def UpperCamelCase__      (							cls  :				List[str]							,  *lowerCAmelCase__  :				str							,  **lowerCAmelCase__  :				Optional[int]		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)






class 		_UpperCamelCase						(							metaclass=lowerCamelCase__					):


			'''simple docstring'''

			_A   :	Union[str, Any]    					=	['''torch''', '''transformers''', '''onnx''']

			def __init__(							self  :				Optional[int]							,  *lowerCAmelCase__  :				int							,  **lowerCAmelCase__  :				List[str]		):





					"""simple docstring"""






					requires_backends(self							,  ["""torch""", """transformers""", """onnx"""]		)

			@classmethod
			def UpperCamelCase__      (							cls  :				List[str]							,  *lowerCAmelCase__  :				int							,  **lowerCAmelCase__  :				int		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)



			@classmethod
			def UpperCamelCase__      (							cls  :				str							,  *lowerCAmelCase__  :				int							,  **lowerCAmelCase__  :				List[Any]		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)






class 		_UpperCamelCase						(							metaclass=lowerCamelCase__					):


			'''simple docstring'''

			_A   :	Optional[Any]    					=	['''torch''', '''transformers''', '''onnx''']

			def __init__(							self  :				Optional[int]							,  *lowerCAmelCase__  :				Tuple							,  **lowerCAmelCase__  :				List[str]		):





					"""simple docstring"""






					requires_backends(self							,  ["""torch""", """transformers""", """onnx"""]		)

			@classmethod
			def UpperCamelCase__      (							cls  :				Tuple							,  *lowerCAmelCase__  :				Dict							,  **lowerCAmelCase__  :				List[Any]		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)



			@classmethod
			def UpperCamelCase__      (							cls  :				List[str]							,  *lowerCAmelCase__  :				Dict							,  **lowerCAmelCase__  :				Tuple		):





					"""simple docstring"""






					requires_backends(cls							,  ["""torch""", """transformers""", """onnx"""]		)