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


__lowercase							:   Dict					=     logging.get_logger(__name__)

class 	__lowercase				(  _lowercase    ):

			def        UpperCAmelCase__ (self			,   A      ):
								if isinstance(A			,   A      ):
													lowerCamelCase_					:      Union[str, Any]     =		[label.strip() for label in labels.split(''','''      ) if label.strip()]
								return labels






			def __call__(self			,   A			,   A			,   A      ):
								if len(A      ) == 0 or len(A      ) == 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(A      )      )

								if isinstance(A			,   A      ):
													lowerCamelCase_					:      Optional[Any]     =		[sequences]

								lowerCamelCase_					:      int     =		[]
								for sequence in sequences:
													sequence_pairs.extend([[sequence, hypothesis_template.format(A      )] for label in labels]      )

								return sequence_pairs, sequences

@add_end_docstrings(_lowercase    )
class 	__lowercase				(  _lowercase    ):

			def __init__(self			,   A=ZeroShotClassificationArgumentHandler()			,   *A			,   **A      ):
								lowerCamelCase_					:      Optional[Any]     =		args_parser
								super().__init__(*A			,   **A      )
								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      ):
								for label, ind in self.model.config.labelaid.items():
													if label.lower().startswith('''entail'''      ):
																		return ind
								return -1

			def        UpperCAmelCase__ (self			,   A			,   A=True			,   A=True			,   A=TruncationStrategy.ONLY_FIRST			,   **A      ):
								lowerCamelCase_					:      Union[str, 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_					:      str     =		self.tokenizer.eos_token
								try:
													lowerCamelCase_					:      Tuple     =		self.tokenizer(
													    A			,   add_special_tokens=A			,   return_tensors=A			,   padding=A			,   truncation=A			,   )
								except Exception as e:
													if "too short" in str(A      ):
																		# 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_					:      Tuple     =		self.tokenizer(
																		    A			,   add_special_tokens=A			,   return_tensors=A			,   padding=A			,   truncation=TruncationStrategy.DO_NOT_TRUNCATE			,   )
													else:
																		raise e

								return inputs

			def        UpperCAmelCase__ (self			,   **A      ):
								if kwargs.get('''multi_class'''			,   A      ) is not None:
													lowerCamelCase_					:      str     =		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_					:      Any     =		{}
								if "candidate_labels" in kwargs:
													lowerCamelCase_					:      Any     =		self._args_parser._parse_labels(kwargs['''candidate_labels''']      )
								if "hypothesis_template" in kwargs:
													lowerCamelCase_					:      Optional[Any]     =		kwargs['''hypothesis_template''']

								lowerCamelCase_					:      Tuple     =		{}
								if "multi_label" in kwargs:
													lowerCamelCase_					:      Optional[int]     =		kwargs['''multi_label''']
								return preprocess_params, {}, postprocess_params

			def __call__(self			,   A			,   *A			,   **A			,   ):
								if len(A      ) == 0:
													pass
								elif len(A      ) == 1 and "candidate_labels" not in kwargs:
													lowerCamelCase_					:      Tuple     =		args[0]
								else:
													raise ValueError(F"""Unable to understand extra arguments {args}"""      )

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

			def        UpperCAmelCase__ (self			,   A			,   A=None			,   A="This example is {}."      ):
								lowerCamelCase_					:      int     =		self._args_parser(A			,   A			,   A      )

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

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

			def        UpperCAmelCase__ (self			,   A      ):
								lowerCamelCase_					:      Tuple     =		inputs['''candidate_label''']
								lowerCamelCase_					:      Optional[int]     =		inputs['''sequence''']
								lowerCamelCase_					:      List[Any]     =		{k: inputs[k] for k in self.tokenizer.model_input_names}
								lowerCamelCase_					:      List[Any]     =		self.model(**A      )

								lowerCamelCase_					:      Any     =		{
								    '''candidate_label''': candidate_label,
								    '''sequence''': sequence,
								    '''is_last''': inputs['''is_last'''],
								    **outputs,
								}
								return model_outputs






			def        UpperCAmelCase__ (self			,   A			,   A=False      ):
								lowerCamelCase_					:      int     =		[outputs['''candidate_label'''] for outputs in model_outputs]
								lowerCamelCase_					:      Dict     =		[outputs['''sequence'''] for outputs in model_outputs]
								lowerCamelCase_					:      Optional[int]     =		np.concatenate([output['''logits'''].numpy() for output in model_outputs]      )
								lowerCamelCase_					:      List[Any]     =		logits.shape[0]
								lowerCamelCase_					:      Union[str, Any]     =		len(A      )
								lowerCamelCase_					:      Dict     =		N // n
								lowerCamelCase_					:      Tuple     =		logits.reshape((num_sequences, n, -1)      )

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

								lowerCamelCase_					:      List[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'''


def lowercase_	(   _lowercase			,       _lowercase				)     ->							Dict:
					'''simple docstring'''

					lowerCamelCase_					:      List[Any]     =		0
					while b > 0:
										if b & 1:
															res += a

										a += a
										b >>= 1

					return res




def lowercase_	(   _lowercase			,       _lowercase			,       _lowercase				)     ->							Optional[Any]:
					'''simple docstring'''

					lowerCamelCase_					:      str     =		0
					while b > 0:
										if b & 1:
															lowerCamelCase_					:      Optional[int]     =		((res % c) + (a % c)) % c

										a += a
										b >>= 1

					return res


