


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







class        lowerCamelCase__	(							UpperCAmelCase      ):






			"""simple docstring"""






			def 				snake_case__				(							self      ,						snake_case     ):

						'''simple docstring'''


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







			def __call__(							self      ,						snake_case      ,						snake_case      ,						snake_case     ):

						'''simple docstring'''


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

						if isinstance(snake_case      ,						snake_case     ):
									UpperCamelCase__					=       [sequences]

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

						return sequence_pairs, sequences







@add_end_docstrings(UpperCAmelCase      )
class        lowerCamelCase__	(							UpperCAmelCase      ):






			"""simple docstring"""






			def __init__(							self      ,						snake_case=ZeroShotClassificationArgumentHandler()      ,						*snake_case      ,						**snake_case     ):

						'''simple docstring'''


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

						'''simple docstring'''


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




			def 				snake_case__				(							self      ,						snake_case      ,						snake_case=True      ,						snake_case=True      ,						snake_case=TruncationStrategy.ONLY_FIRST      ,						**snake_case     ):

						'''simple docstring'''


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

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

						return inputs




			def 				snake_case__				(							self      ,						**snake_case     ):

						'''simple docstring'''


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

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




			def __call__(							self      ,						snake_case      ,						*snake_case      ,						**snake_case      ,						):

						'''simple docstring'''


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

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




			def 				snake_case__				(							self      ,						snake_case      ,						snake_case=None      ,						snake_case="This example is {}."     ):

						'''simple docstring'''


						UpperCamelCase__,      UpperCamelCase__					=       self._args_parser(snake_case      ,						snake_case      ,						snake_case     )

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

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




			def 				snake_case__				(							self      ,						snake_case     ):

						'''simple docstring'''


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

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







			def 				snake_case__				(							self      ,						snake_case      ,						snake_case=False     ):

						'''simple docstring'''


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

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

						UpperCamelCase__					=       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        UpperCamelCase_(				_A   :List[str]				,     _A   :Tuple				,     _A   :Any				,     _A   :Tuple				,     _A   :Optional[int]				,     _A   :str  )->		List[str]:
			if index == r:
						for j in range(_A  ):
									print(data[j]				,     end=" "  )
						print(" "  )
						return
			#  When no more elements are there to put in data[]
			if i >= n:
						return
			# current is included, put next at next location
			UpperCamelCase__					=       arr[i]
			combination_util(_A				,     _A				,     _A				,     index + 1				,     _A				,     i + 1  )
			# current is excluded, replace it with
			# next (Note that i+1 is passed, but
			# index is not changed)
			combination_util(_A				,     _A				,     _A				,     _A				,     _A				,     i + 1  )
			# The main function that prints all combinations
			# of size r in arr[] of size n. This function
			# mainly uses combinationUtil()
def        UpperCamelCase_(				_A   :Dict				,     _A   :Optional[Any]				,     _A   :Union[str, Any]  )->		Optional[int]:
			# A temporary array to store all combination one by one
			UpperCamelCase__					=       [0] * r
			# Print all combination using temporary array 'data[]'
			combination_util(_A				,     _A				,     _A				,     0				,     _A				,     0  )


if __name__ == "__main__":
						# Driver code to check the function above
						__UpperCamelCase    		=       [1_0, 2_0, 3_0, 4_0, 5_0]
						print_combination(arr, len(arr), 3)
						# This code is contributed by Ambuj sahu


