






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			(     UpperCamelCase				):
    """simple docstring"""

    def _a							(				self      :     List[Any] ,     __SCREAMING_SNAKE_CASE      :     Union[str, Any]      )      ->							Tuple:
           if isinstance(__SCREAMING_SNAKE_CASE ,     __SCREAMING_SNAKE_CASE      ):
                  __UpperCAmelCase     				=[label.strip() for label in labels.split(""","""      ) if label.strip()]
           return labels



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

           if isinstance(__SCREAMING_SNAKE_CASE ,     __SCREAMING_SNAKE_CASE      ):
                  __UpperCAmelCase     				=[sequences]

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

           return sequence_pairs, sequences




@add_end_docstrings(UpperCamelCase				)
class 				_A			(     UpperCamelCase				):
    """simple docstring"""

    def __init__(				self      :     Optional[int] ,     __SCREAMING_SNAKE_CASE      :     Tuple=ZeroShotClassificationArgumentHandler() ,     *__SCREAMING_SNAKE_CASE      :     str ,     **__SCREAMING_SNAKE_CASE      :     Any      )      ->							List[str]:
           __UpperCAmelCase     				=args_parser
           super().__init__(*__SCREAMING_SNAKE_CASE ,     **__SCREAMING_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 _a							(				self      :     Any      )      ->							Optional[int]:
           for label, ind in self.model.config.labelaid.items():
                  if label.lower().startswith("""entail"""      ):
                         return ind
           return -1



    def _a							(				self      :     int ,     __SCREAMING_SNAKE_CASE      :     str ,     __SCREAMING_SNAKE_CASE      :     Union[str, Any]=True ,     __SCREAMING_SNAKE_CASE      :     List[Any]=True ,     __SCREAMING_SNAKE_CASE      :     Optional[int]=TruncationStrategy.ONLY_FIRST ,     **__SCREAMING_SNAKE_CASE      :     Optional[Any]      )      ->							Tuple:
           __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(
                      __SCREAMING_SNAKE_CASE ,     add_special_tokens=__SCREAMING_SNAKE_CASE ,     return_tensors=__SCREAMING_SNAKE_CASE ,     padding=__SCREAMING_SNAKE_CASE ,     truncation=__SCREAMING_SNAKE_CASE ,     )
           except Exception as e:
                  if "too short" in str(__SCREAMING_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(
                             __SCREAMING_SNAKE_CASE ,     add_special_tokens=__SCREAMING_SNAKE_CASE ,     return_tensors=__SCREAMING_SNAKE_CASE ,     padding=__SCREAMING_SNAKE_CASE ,     truncation=TruncationStrategy.DO_NOT_TRUNCATE ,     )
                  else:
                         raise e

           return inputs



    def _a							(				self      :     Tuple ,     **__SCREAMING_SNAKE_CASE      :     Dict      )      ->							Optional[int]:
           if kwargs.get("""multi_class""" ,     __SCREAMING_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      :     int ,     __SCREAMING_SNAKE_CASE      :     Union[str, List[str]] ,     *__SCREAMING_SNAKE_CASE      :     List[str] ,     **__SCREAMING_SNAKE_CASE      :     Optional[int] ,     )      ->							List[Any]:
           if len(__SCREAMING_SNAKE_CASE      ) == 0:
                  pass
           elif len(__SCREAMING_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__(__SCREAMING_SNAKE_CASE ,     **__SCREAMING_SNAKE_CASE      )



    def _a							(				self      :     Tuple ,     __SCREAMING_SNAKE_CASE      :     Dict ,     __SCREAMING_SNAKE_CASE      :     Dict=None ,     __SCREAMING_SNAKE_CASE      :     Optional[int]="This example is {}."      )      ->							Optional[Any]:
           __UpperCAmelCase				, __UpperCAmelCase     				=self._args_parser(__SCREAMING_SNAKE_CASE ,     __SCREAMING_SNAKE_CASE ,     __SCREAMING_SNAKE_CASE      )

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

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



    def _a							(				self      :     Optional[Any] ,     __SCREAMING_SNAKE_CASE      :     List[Any]      )      ->							str:
           __UpperCAmelCase     				=inputs["""candidate_label"""]
           __UpperCAmelCase     				=inputs["""sequence"""]
           __UpperCAmelCase     				={k: inputs[k] for k in self.tokenizer.model_input_names}
           __UpperCAmelCase     				=self.model(**__SCREAMING_SNAKE_CASE      )

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



    def _a							(				self      :     Optional[int] ,     __SCREAMING_SNAKE_CASE      :     int ,     __SCREAMING_SNAKE_CASE      :     Any=False      )      ->							List[Any]:
           __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(__SCREAMING_SNAKE_CASE      )
           __UpperCAmelCase     				=N // n
           __UpperCAmelCase     				=logits.reshape((num_sequences, n, -1)      )

           if multi_label or len(__SCREAMING_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(__SCREAMING_SNAKE_CASE      ) / np.exp(__SCREAMING_SNAKE_CASE      ).sum(-1 ,     keepdims=__SCREAMING_SNAKE_CASE      )
                  __UpperCAmelCase     				=scores[..., 1]
           else:
                  # softmax the "entailment" logits over all candidate labels
                  __UpperCAmelCase     				=reshaped_outputs[..., self.entailment_id]
                  __UpperCAmelCase     				=np.exp(__SCREAMING_SNAKE_CASE      ) / np.exp(__SCREAMING_SNAKE_CASE      ).sum(-1 ,     keepdims=__SCREAMING_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(),
           }












SCREAMING_SNAKE_CASE__   :      Tuple				=		{
    """a""": """AAAAA""",
    """b""": """AAAAB""",
    """c""": """AAABA""",
    """d""": """AAABB""",
    """e""": """AABAA""",
    """f""": """AABAB""",
    """g""": """AABBA""",
    """h""": """AABBB""",
    """i""": """ABAAA""",
    """j""": """BBBAA""",
    """k""": """ABAAB""",
    """l""": """ABABA""",
    """m""": """ABABB""",
    """n""": """ABBAA""",
    """o""": """ABBAB""",
    """p""": """ABBBA""",
    """q""": """ABBBB""",
    """r""": """BAAAA""",
    """s""": """BAAAB""",
    """t""": """BAABA""",
    """u""": """BAABB""",
    """v""": """BBBAB""",
    """w""": """BABAA""",
    """x""": """BABAB""",
    """y""": """BABBA""",
    """z""": """BABBB""",
    """ """: """ """,
}


SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		{value: key for key, value in encode_dict.items()}

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Tuple   =   ''''''
				for letter in word.lower():
								if letter.isalpha() or letter == " ":
												encoded += encode_dict[letter]
								else:
												raise Exception('''encode() accepts only letters of the alphabet and spaces'''			)
				return encoded

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if set(snake_case			) - {"A", "B", " "} != set():
								raise Exception('''decode() accepts only \'A\', \'B\' and spaces'''			)
				__magic_name__		:Dict   =   ''''''
				for word in coded.split():
								while len(snake_case			) != 0:
												decoded += decode_dict[word[:5]]
												__magic_name__		:int   =   word[5:]
								decoded += " "
				return decoded.strip()


if __name__ == "__main__":
					from doctest import testmod

					testmod()






