



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



class       UpperCAmelCase__(							lowerCamelCase	):

   '''simple docstring'''




   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Optional[int])	->				Optional[int]:




         """simple docstring"""

         if isinstance(lowerCAmelCase			,				lowerCAmelCase):
               lowercase__     =  [label.strip() for label in labels.split(',') if label.strip()]
         return labels



   def __call__(						self  :			Optional[int]			,				lowerCAmelCase  :			List[Any]			,				lowerCAmelCase  :			Optional[int]			,				lowerCAmelCase  :			Optional[Any])	->				List[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):
               lowercase__     =  [sequences]

         lowercase__     =  []
         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       UpperCAmelCase__(							lowerCamelCase	):

   '''simple docstring'''




   def __init__(						self  :			Optional[Any]			,				lowerCAmelCase  :			Dict=ZeroShotClassificationArgumentHandler()			,				*lowerCAmelCase  :			Tuple			,				**lowerCAmelCase  :			Union[str, Any])	->				Dict:




         """simple docstring"""

         lowercase__     =  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 			UpperCAmelCase		(						self  :			Union[str, Any])	->				List[str]:




         """simple docstring"""

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


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			int			,				lowerCAmelCase  :			Optional[int]=True			,				lowerCAmelCase  :			int=True			,				lowerCAmelCase  :			Dict=TruncationStrategy.ONLY_FIRST			,				**lowerCAmelCase  :			Any)	->				Tuple:




         """simple docstring"""

         lowercase__     =  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`')
               lowercase__     =  self.tokenizer.eos_token
         try:
               lowercase__     =  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.

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

         return inputs


   def 			UpperCAmelCase		(						self  :			str			,				**lowerCAmelCase  :			List[str])	->				int:




         """simple docstring"""

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

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


   def __call__(						self  :			Optional[int]			,				lowerCAmelCase  :			Union[str, List[str]]			,				*lowerCAmelCase  :			List[str]			,				**lowerCAmelCase  :			Tuple			,				)	->				List[Any]:




         """simple docstring"""

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

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


   def 			UpperCAmelCase		(						self  :			List[Any]			,				lowerCAmelCase  :			List[Any]			,				lowerCAmelCase  :			List[Any]=None			,				lowerCAmelCase  :			str="This example is {}.")	->				str:




         """simple docstring"""

         lowercase__,	lowercase__     =  self._args_parser(lowerCAmelCase			,				lowerCAmelCase			,				lowerCAmelCase)

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

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


   def 			UpperCAmelCase		(						self  :			List[Any]			,				lowerCAmelCase  :			Union[str, Any])	->				List[Any]:




         """simple docstring"""

         lowercase__     =  inputs['candidate_label']
         lowercase__     =  inputs['sequence']
         lowercase__     =  {k: inputs[k] for k in self.tokenizer.model_input_names}
         lowercase__     =  self.model(**lowerCAmelCase)

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



   def 			UpperCAmelCase		(						self  :			Tuple			,				lowerCAmelCase  :			List[str]			,				lowerCAmelCase  :			int=False)	->				List[str]:




         """simple docstring"""

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

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

         lowercase__     =  list(reversed(scores[0].argsort()))
         return {
             "sequence": sequences[0],
             "labels": [candidate_labels[i] for i in top_inds],
             "scores": scores[0, top_inds].tolist(),
         }





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


a__      :				Any   	=			{"configuration_reformer": ["REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ReformerConfig"]}

try:
       if not is_sentencepiece_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a__      :				Optional[int]   	=			["ReformerTokenizer"]

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a__      :				Union[str, Any]   	=			["ReformerTokenizerFast"]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a__      :				Any   	=			[
           "REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
           "ReformerAttention",
           "ReformerForMaskedLM",
           "ReformerForQuestionAnswering",
           "ReformerForSequenceClassification",
           "ReformerLayer",
           "ReformerModel",
           "ReformerModelWithLMHead",
           "ReformerPreTrainedModel",
       ]


if TYPE_CHECKING:
       from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig

       try:
              if not is_sentencepiece_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_reformer import ReformerTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_reformer_fast import ReformerTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_reformer import (
                  REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
                  ReformerAttention,
                  ReformerForMaskedLM,
                  ReformerForQuestionAnswering,
                  ReformerForSequenceClassification,
                  ReformerLayer,
                  ReformerModel,
                  ReformerModelWithLMHead,
                  ReformerPreTrainedModel,
              )

else:
       import sys

       a__      :				Tuple   	=			_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
