
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								=  logging.get_logger(__name__)




class 						lowercase__  (						_UpperCAmelCase  ):
	def      A_				(			self							:   Union[str, Any]       ,   UpperCAmelCase_							:   Tuple							):
						if isinstance(UpperCAmelCase_       ,   UpperCAmelCase_							):
											SCREAMING_SNAKE_CASE__													= [label.strip() for label in labels.split(','							) if label.strip()]
						return labels





	def __call__(			self							:   str       ,   UpperCAmelCase_							:   str       ,   UpperCAmelCase_							:   Dict       ,   UpperCAmelCase_							:   List[Any]							):
						if len(UpperCAmelCase_							) == 0 or len(UpperCAmelCase_							) == 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(UpperCAmelCase_							)							)

						if isinstance(UpperCAmelCase_       ,   UpperCAmelCase_							):
											SCREAMING_SNAKE_CASE__													= [sequences]

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

						return sequence_pairs, sequences





@add_end_docstrings(_UpperCAmelCase  )
class 						lowercase__  (						_UpperCAmelCase  ):
	def __init__(			self							:   Dict       ,   UpperCAmelCase_							:   str=ZeroShotClassificationArgumentHandler()       ,   *UpperCAmelCase_							:   Optional[int]       ,   **UpperCAmelCase_							:   int							):
						SCREAMING_SNAKE_CASE__													= args_parser
						super().__init__(*UpperCAmelCase_       ,   **UpperCAmelCase_							)
						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							:   Any							):
						for label, ind in self.model.config.labelaid.items():
											if label.lower().startswith('entail'							):
																return ind
						return -1
	def      A_				(			self							:   Dict       ,   UpperCAmelCase_							:   List[str]       ,   UpperCAmelCase_							:   int=True       ,   UpperCAmelCase_							:   Any=True       ,   UpperCAmelCase_							:   Any=TruncationStrategy.ONLY_FIRST       ,   **UpperCAmelCase_							:   Union[str, Any]							):
						SCREAMING_SNAKE_CASE__													= 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__													= self.tokenizer.eos_token
						try:
											SCREAMING_SNAKE_CASE__													= self.tokenizer(
											    UpperCAmelCase_       ,   add_special_tokens=UpperCAmelCase_       ,   return_tensors=UpperCAmelCase_       ,   padding=UpperCAmelCase_       ,   truncation=UpperCAmelCase_       ,   )
						except Exception as e:
											if "too short" in str(UpperCAmelCase_							):
																# 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__													= self.tokenizer(
																    UpperCAmelCase_       ,   add_special_tokens=UpperCAmelCase_       ,   return_tensors=UpperCAmelCase_       ,   padding=UpperCAmelCase_       ,   truncation=TruncationStrategy.DO_NOT_TRUNCATE       ,   )
											else:
																raise e

						return inputs
	def      A_				(			self							:   List[str]       ,   **UpperCAmelCase_							:   Optional[Any]							):
						if kwargs.get('multi_class'       ,   UpperCAmelCase_							) is not None:
											SCREAMING_SNAKE_CASE__													= 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__													= {}
						if "candidate_labels" in kwargs:
											SCREAMING_SNAKE_CASE__													= self._args_parser._parse_labels(kwargs['candidate_labels']							)
						if "hypothesis_template" in kwargs:
											SCREAMING_SNAKE_CASE__													= kwargs['hypothesis_template']

						SCREAMING_SNAKE_CASE__													= {}
						if "multi_label" in kwargs:
											SCREAMING_SNAKE_CASE__													= kwargs['multi_label']
						return preprocess_params, {}, postprocess_params
	def __call__(			self							:   Optional[int]       ,   UpperCAmelCase_							:   Union[str, List[str]]       ,   *UpperCAmelCase_							:   Optional[Any]       ,   **UpperCAmelCase_							:   Tuple       ,   ):
						if len(UpperCAmelCase_							) == 0:
											pass
						elif len(UpperCAmelCase_							) == 1 and "candidate_labels" not in kwargs:
											SCREAMING_SNAKE_CASE__													= args[0]
						else:
											raise ValueError(F'Unable to understand extra arguments {args}'							)

						return super().__call__(UpperCAmelCase_       ,   **UpperCAmelCase_							)
	def      A_				(			self							:   Optional[int]       ,   UpperCAmelCase_							:   Optional[int]       ,   UpperCAmelCase_							:   Optional[int]=None       ,   UpperCAmelCase_							:   Union[str, Any]="This example is {}."							):
						SCREAMING_SNAKE_CASE__						, SCREAMING_SNAKE_CASE__													= self._args_parser(UpperCAmelCase_       ,   UpperCAmelCase_       ,   UpperCAmelCase_							)

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

											yield {
											    "candidate_label": candidate_label,
											    "sequence": sequences[0],
											    "is_last": i == len(UpperCAmelCase_							) - 1,
											    **model_input,
											}
	def      A_				(			self							:   Union[str, Any]       ,   UpperCAmelCase_							:   Dict							):
						SCREAMING_SNAKE_CASE__													= inputs['candidate_label']
						SCREAMING_SNAKE_CASE__													= inputs['sequence']
						SCREAMING_SNAKE_CASE__													= {k: inputs[k] for k in self.tokenizer.model_input_names}
						SCREAMING_SNAKE_CASE__													= self.model(**UpperCAmelCase_							)

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





	def      A_				(			self							:   Union[str, Any]       ,   UpperCAmelCase_							:   Optional[Any]       ,   UpperCAmelCase_							:   Any=False							):
						SCREAMING_SNAKE_CASE__													= [outputs['candidate_label'] for outputs in model_outputs]
						SCREAMING_SNAKE_CASE__													= [outputs['sequence'] for outputs in model_outputs]
						SCREAMING_SNAKE_CASE__													= np.concatenate([output['logits'].numpy() for output in model_outputs]							)
						SCREAMING_SNAKE_CASE__													= logits.shape[0]
						SCREAMING_SNAKE_CASE__													= len(UpperCAmelCase_							)
						SCREAMING_SNAKE_CASE__													= N // n
						SCREAMING_SNAKE_CASE__													= logits.reshape((num_sequences, n, -1)							)

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

						SCREAMING_SNAKE_CASE__													= 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 							_lowercase							(     UpperCamelCase_	,	UpperCamelCase_		)		->		str:
					'''simple docstring'''


					if not isinstance(UpperCamelCase_	,	UpperCamelCase_		):
										raise ValueError('iterations must be defined as integers'		)
					if not isinstance(UpperCamelCase_	,	UpperCamelCase_		) or not number >= 1:
										raise ValueError(
										    'starting number must be\n                         and integer and be more than 0'		)
					if not iterations >= 1:
										raise ValueError('Iterations must be done more than 0 times to play FizzBuzz'		)

					SCREAMING_SNAKE_CASE__													= ''
					while number <= iterations:
										if number % 3 == 0:
															out += "Fizz"
										if number % 5 == 0:
															out += "Buzz"
										if 0 not in (number % 3, number % 5):
															out += str(UpperCamelCase_		)

										# print(out)
										number += 1
										out += " "
					return out


if __name__ == "__main__":
				import doctest

				doctest.testmod()





