



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


__snake_case       :	int            =logging.get_logger(__name__)



class  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    List[Any]:

						"""simple docstring"""






						if isinstance(__lowerCamelCase	,__lowerCamelCase				):
										lowerCAmelCase__  :       Dict				=  [label.strip() for label in labels.split(''','''				) if label.strip()]
						return labels



		def __call__(self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase				)  ->    Any:

						"""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				):
										lowerCAmelCase__  :       Optional[Any]				=  [sequences]

						lowerCAmelCase__  :       Tuple				=  []
						for sequence in sequences:
										sequence_pairs.extend([[sequence, hypothesis_template.format(__lowerCamelCase				)] for label in labels]				)

						return sequence_pairs, sequences



@add_end_docstrings(lowerCamelCase__)
class  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		def __init__(self	,__lowerCamelCase=ZeroShotClassificationArgumentHandler()	,*__lowerCamelCase	,**__lowerCamelCase				)  ->    Tuple:

						"""simple docstring"""






						lowerCAmelCase__  :       Optional[int]				=  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 	lowerCAmelCase__   (self				)  ->    List[Any]:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase=True	,__lowerCamelCase=True	,__lowerCamelCase=TruncationStrategy.ONLY_FIRST	,**__lowerCamelCase				)  ->    Optional[int]:

						"""simple docstring"""






						lowerCAmelCase__  :       Dict				=  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__  :       List[Any]				=  self.tokenizer.eos_token
						try:
										lowerCAmelCase__  :       str				=  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.

														lowerCAmelCase__  :       Optional[int]				=  self.tokenizer(
														    __lowerCamelCase	,add_special_tokens=__lowerCamelCase	,return_tensors=__lowerCamelCase	,padding=__lowerCamelCase	,truncation=TruncationStrategy.DO_NOT_TRUNCATE	,)
										else:
														raise e

						return inputs



		def 	lowerCAmelCase__   (self	,**__lowerCamelCase				)  ->    Union[str, Any]:

						"""simple docstring"""






						if kwargs.get('''multi_class'''	,__lowerCamelCase				) is not None:
										lowerCAmelCase__  :       Tuple				=  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__  :       Tuple				=  {}
						if "candidate_labels" in kwargs:
										lowerCAmelCase__  :       Dict				=  self._args_parser._parse_labels(kwargs['''candidate_labels''']				)
						if "hypothesis_template" in kwargs:
										lowerCAmelCase__  :       List[str]				=  kwargs['''hypothesis_template''']

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



		def __call__(self	,__lowerCamelCase	,*__lowerCamelCase	,**__lowerCamelCase	,)  ->    Dict:

						"""simple docstring"""






						if len(__lowerCamelCase				) == 0:
										pass
						elif len(__lowerCamelCase				) == 1 and "candidate_labels" not in kwargs:
										lowerCAmelCase__  :       Union[str, Any]				=  args[0]
						else:
										raise ValueError(f"""Unable to understand extra arguments {args}"""				)

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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase=None	,__lowerCamelCase="This example is {}."				)  ->    Optional[Any]:

						"""simple docstring"""






						lowerCAmelCase__		,	lowerCAmelCase__  :       int				=  self._args_parser(__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase				)

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

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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    Tuple:

						"""simple docstring"""






						lowerCAmelCase__  :       Any				=  inputs['''candidate_label''']
						lowerCAmelCase__  :       List[Any]				=  inputs['''sequence''']
						lowerCAmelCase__  :       Dict				=  {k: inputs[k] for k in self.tokenizer.model_input_names}
						lowerCAmelCase__  :       List[str]				=  self.model(**__lowerCamelCase				)

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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase=False				)  ->    Dict:

						"""simple docstring"""






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

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

						lowerCAmelCase__  :       List[Any]				=  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__	(					lowerCamelCase_	:	int):





				'''simple docstring'''

				if not isinstance(lowerCamelCase_ ,lowerCamelCase_):
								lowerCAmelCase__  :       Dict				=  f"""Input value of [number={number}] must be an integer"""
								raise TypeError(lowerCamelCase_)

				if number < 1:
								lowerCAmelCase__  :       Any				=  f"""Input value of [number={number}] must be > 0"""
								raise ValueError(lowerCamelCase_)

				lowerCAmelCase__  :       List[str]				=  1

				for i in range(1 ,lowerCamelCase_):
								current_number *= 4 * i - 2
								current_number //= i + 1

				return current_number


if __name__ == "__main__":
							import doctest

							doctest.testmod()

