




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



class      a__				(	__magic_name__   ):


			def       a_     (      self      :    str      ,  UpperCamelCase_      :    List[str]):


						"""simple docstring"""




						if isinstance(UpperCamelCase_      ,  UpperCamelCase_):
									__UpperCAmelCase	: List[Any]		=					[label.strip() for label in labels.split(",") if label.strip()]
						return labels


			def __call__(      self      :    str      ,  UpperCamelCase_      :    Union[str, Any]      ,  UpperCamelCase_      :    Optional[Any]      ,  UpperCamelCase_      :    Optional[int]):


						"""simple docstring"""




						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_):
									__UpperCAmelCase	: Union[str, Any]		=					[sequences]

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

						return sequence_pairs, sequences






@add_end_docstrings(__magic_name__   )
class      a__				(	__magic_name__   ):


			def __init__(      self      :    int      ,  UpperCamelCase_      :    Dict=ZeroShotClassificationArgumentHandler()      ,  *UpperCamelCase_      :    List[str]      ,  **UpperCamelCase_      :    List[Any]):


						"""simple docstring"""




						__UpperCAmelCase	: List[Any]		=					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      :    Tuple):


						"""simple docstring"""




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


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


						"""simple docstring"""




						__UpperCAmelCase	: List[str]		=					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	: List[str]		=					self.tokenizer.eos_token
						try:
									__UpperCAmelCase	: List[str]		=					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.

												__UpperCAmelCase	: Any		=					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      :    Union[str, Any]      ,  **UpperCamelCase_      :    int):


						"""simple docstring"""




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

						__UpperCAmelCase	: Dict		=					{}
						if "multi_label" in kwargs:
									__UpperCAmelCase	: Optional[Any]		=					kwargs["multi_label"]
						return preprocess_params, {}, postprocess_params


			def __call__(      self      :    Tuple      ,  UpperCamelCase_      :    Union[str, List[str]]      ,  *UpperCamelCase_      :    Optional[Any]      ,  **UpperCamelCase_      :    List[Any]      ,  ):


						"""simple docstring"""




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

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


			def       a_     (      self      :    List[Any]      ,  UpperCamelCase_      :    Dict      ,  UpperCamelCase_      :    List[Any]=None      ,  UpperCamelCase_      :    int="This example is {}."):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[int]		=					self._args_parser(UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_)

						for i, (candidate_label, sequence_pair) in enumerate(zip(UpperCamelCase_      ,  UpperCamelCase_)):
									__UpperCAmelCase	: Union[str, Any]		=					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      :    Tuple      ,  UpperCamelCase_      :    List[str]):


						"""simple docstring"""




						__UpperCAmelCase	: List[str]		=					inputs["candidate_label"]
						__UpperCAmelCase	: Dict		=					inputs["sequence"]
						__UpperCAmelCase	: Tuple		=					{k: inputs[k] for k in self.tokenizer.model_input_names}
						__UpperCAmelCase	: Union[str, Any]		=					self.model(**UpperCamelCase_)

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


			def       a_     (      self      :    int      ,  UpperCamelCase_      :    int      ,  UpperCamelCase_      :    Optional[Any]=False):


						"""simple docstring"""




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

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

						__UpperCAmelCase	: 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"""





import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format



class      a__				:
			lowercase_    =	None


			def       a_     (      self      :    List[Any]):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					self.feature_extraction_class(**self.feat_extract_dict)
						__UpperCAmelCase	: Any		=					json.loads(feat_extract.to_json_string())
						for key, value in self.feat_extract_dict.items():
									self.assertEqual(obj[key]      ,  UpperCamelCase_)


			def       a_     (      self      :    Tuple):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					self.feature_extraction_class(**self.feat_extract_dict)

						with tempfile.TemporaryDirectory() as tmpdirname:
									__UpperCAmelCase	: Dict		=					os.path.join(UpperCamelCase_      ,  "feat_extract.json")
									feat_extract_first.to_json_file(UpperCamelCase_)
									__UpperCAmelCase	: Optional[Any]		=					self.feature_extraction_class.from_json_file(UpperCamelCase_)

						self.assertEqual(feat_extract_second.to_dict()      ,  feat_extract_first.to_dict())


			def       a_     (      self      :    List[str]):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					self.feature_extraction_class(**self.feat_extract_dict)

						with tempfile.TemporaryDirectory() as tmpdirname:
									__UpperCAmelCase	: Tuple		=					feat_extract_first.save_pretrained(UpperCamelCase_)[0]
									check_json_file_has_correct_format(UpperCamelCase_)
									__UpperCAmelCase	: List[Any]		=					self.feature_extraction_class.from_pretrained(UpperCamelCase_)

						self.assertEqual(feat_extract_second.to_dict()      ,  feat_extract_first.to_dict())


			def       a_     (      self      :    Union[str, Any]):


						"""simple docstring"""




						__UpperCAmelCase	: Union[str, Any]		=					self.feature_extraction_class()
						self.assertIsNotNone(UpperCamelCase_)


