





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


A       :   Any					= logging.get_logger(__name__)


class     A     (SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




			def   a_			(     self  :       Optional[int]				,      __lowerCAmelCase  :       Dict  )      ->      List[Any]:







					"""simple docstring"""






					if isinstance(__lowerCAmelCase				,      __lowerCAmelCase  ):
							A__     =  [label.strip() for label in labels.split(""","""  ) if label.strip()]
					return labels







			def __call__(     self  :       Dict				,      __lowerCAmelCase  :       Union[str, Any]				,      __lowerCAmelCase  :       Any				,      __lowerCAmelCase  :       str  )      ->      Tuple:







					"""simple docstring"""






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

					if isinstance(__lowerCAmelCase				,      __lowerCAmelCase  ):
							A__     =  [sequences]

					A__     =  []
					for sequence in sequences:
							sequence_pairs.extend([[sequence, hypothesis_template.format(__lowerCAmelCase  )] for label in labels]  )

					return sequence_pairs, sequences


@add_end_docstrings(SCREAMING_SNAKE_CASE       )
class     A     (SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




			def __init__(     self  :       Any				,      __lowerCAmelCase  :       Optional[Any]=ZeroShotClassificationArgumentHandler()				,      *__lowerCAmelCase  :       int				,      **__lowerCAmelCase  :       str  )      ->      Optional[Any]:







					"""simple docstring"""






					A__     =  args_parser
					super().__init__(*__lowerCAmelCase				,      **__lowerCAmelCase  )
					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   a_			(     self  :       List[str]  )      ->      Dict:







					"""simple docstring"""






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






			def   a_			(     self  :       Union[str, Any]				,      __lowerCAmelCase  :       List[str]				,      __lowerCAmelCase  :       Dict=True				,      __lowerCAmelCase  :       Tuple=True				,      __lowerCAmelCase  :       str=TruncationStrategy.ONLY_FIRST				,      **__lowerCAmelCase  :       Optional[Any]  )      ->      List[str]:







					"""simple docstring"""






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

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

					return inputs






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







					"""simple docstring"""






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

					A__     =  {}
					if "multi_label" in kwargs:
							A__     =  kwargs["""multi_label"""]
					return preprocess_params, {}, postprocess_params






			def __call__(     self  :       Union[str, Any]				,      __lowerCAmelCase  :       Union[str, List[str]]				,      *__lowerCAmelCase  :       Dict				,      **__lowerCAmelCase  :       str				,      )      ->      int:







					"""simple docstring"""






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

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






			def   a_			(     self  :       Any				,      __lowerCAmelCase  :       Dict				,      __lowerCAmelCase  :       Union[str, Any]=None				,      __lowerCAmelCase  :       int="This example is {}."  )      ->      List[Any]:







					"""simple docstring"""






					A__ ,     A__     =  self._args_parser(__lowerCAmelCase				,      __lowerCAmelCase				,      __lowerCAmelCase  )

					for i, (candidate_label, sequence_pair) in enumerate(zip(__lowerCAmelCase				,      __lowerCAmelCase  )  ):
							A__     =  self._parse_and_tokenize([sequence_pair]  )

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






			def   a_			(     self  :       Any				,      __lowerCAmelCase  :       int  )      ->      List[Any]:







					"""simple docstring"""






					A__     =  inputs["""candidate_label"""]
					A__     =  inputs["""sequence"""]
					A__     =  {k: inputs[k] for k in self.tokenizer.model_input_names}
					A__     =  self.model(**__lowerCAmelCase  )

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







			def   a_			(     self  :       str				,      __lowerCAmelCase  :       int				,      __lowerCAmelCase  :       List[Any]=False  )      ->      Union[str, Any]:







					"""simple docstring"""






					A__     =  [outputs["""candidate_label"""] for outputs in model_outputs]
					A__     =  [outputs["""sequence"""] for outputs in model_outputs]
					A__     =  np.concatenate([output["""logits"""].numpy() for output in model_outputs]  )
					A__     =  logits.shape[0]
					A__     =  len(__lowerCAmelCase  )
					A__     =  N // n
					A__     =  logits.reshape((num_sequences, n, -1)  )

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

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










def   __lowerCamelCase   (				__a  :str       )						->							bool:






		"""simple docstring"""

		A__     =  0
		for ch in input_str:
				A__     =  ord(__a       )
				A__     =  pow(2       ,	__a       )

				# If we already turned on bit for current character's unicode
				if bitmap >> ch_unicode & 1 == 1:
						return False
				bitmap |= ch_bit_index_on
		return True


if __name__ == "__main__":
					import doctest

					doctest.testmod()



