


'''simple docstring'''






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




class 	a       (       __UpperCamelCase    ):
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							Union[str, Any]:
      if isinstance(__magic_name__ ,			__magic_name__  ):
           _a      =							[label.strip() for label in labels.split(','  ) if label.strip()]
      return labels




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

      if isinstance(__magic_name__ ,			__magic_name__  ):
           _a      =							[sequences]

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

      return sequence_pairs, sequences





@add_end_docstrings(__UpperCamelCase    )
class 	a       (       __UpperCamelCase    ):
 def __init__(	self ,			__magic_name__=ZeroShotClassificationArgumentHandler() ,			*__magic_name__ ,			**__magic_name__  )   ->							Dict:
      _a      =							args_parser
      super().__init__(*__magic_name__ ,			**__magic_name__  )
      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  )   ->							Tuple:
      for label, ind in self.model.config.labelaid.items():
           if label.lower().startswith('entail'  ):
                return ind
      return -1
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__=True ,			__magic_name__=True ,			__magic_name__=TruncationStrategy.ONLY_FIRST ,			**__magic_name__  )   ->							Any:
      _a      =							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`'  )
           _a      =							self.tokenizer.eos_token
      try:
           _a      =							self.tokenizer(
               __magic_name__ ,			add_special_tokens=__magic_name__ ,			return_tensors=__magic_name__ ,			padding=__magic_name__ ,			truncation=__magic_name__ ,			)
      except Exception as e:
           if "too short" in str(__magic_name__  ):
                # 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.

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

      return inputs
 def 							__UpperCAmelCase						(	self ,			**__magic_name__  )   ->							Optional[int]:
      if kwargs.get('multi_class' ,			__magic_name__  ) is not None:
           _a      =							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.'  )
      _a      =							{}
      if "candidate_labels" in kwargs:
           _a      =							self._args_parser._parse_labels(kwargs['candidate_labels']  )
      if "hypothesis_template" in kwargs:
           _a      =							kwargs["""hypothesis_template"""]

      _a      =							{}
      if "multi_label" in kwargs:
           _a      =							kwargs["""multi_label"""]
      return preprocess_params, {}, postprocess_params
 def __call__(	self ,			__magic_name__ ,			*__magic_name__ ,			**__magic_name__ ,			)   ->							Dict:
      if len(__magic_name__  ) == 0:
           pass
      elif len(__magic_name__  ) == 1 and "candidate_labels" not in kwargs:
           _a      =							args[0]
      else:
           raise ValueError(f'Unable to understand extra arguments {args}'  )

      return super().__call__(__magic_name__ ,			**__magic_name__  )
 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__=None ,			__magic_name__="This example is {}."  )   ->							int:
      _a      =							self._args_parser(__magic_name__ ,			__magic_name__ ,			__magic_name__  )

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

           yield {
               "candidate_label": candidate_label,
               "sequence": sequences[0],
               "is_last": i == len(__magic_name__  ) - 1,
               **model_input,
           }
 def 							__UpperCAmelCase						(	self ,			__magic_name__  )   ->							str:
      _a      =							inputs["""candidate_label"""]
      _a      =							inputs["""sequence"""]
      _a      =							{k: inputs[k] for k in self.tokenizer.model_input_names}
      _a      =							self.model(**__magic_name__  )

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




 def 							__UpperCAmelCase						(	self ,			__magic_name__ ,			__magic_name__=False  )   ->							Tuple:
      _a      =							[outputs["""candidate_label"""] for outputs in model_outputs]
      _a      =							[outputs["""sequence"""] for outputs in model_outputs]
      _a      =							np.concatenate([output['logits'].numpy() for output in model_outputs]  )
      _a      =							logits.shape[0]
      _a      =							len(__magic_name__  )
      _a      =							N // n
      _a      =							logits.reshape((num_sequences, n, -1)  )

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

      _a      =							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'''






def 		_A			(lowerCAmelCase__					:int						)				->					int:




     '''simple docstring'''



     assert (
         isinstance(lowerCAmelCase__			,  lowerCAmelCase__						) and number_of_steps > 0
     ), f'number_of_steps needs to be positive integer, your input {number_of_steps}'
     if number_of_steps == 1:
          return 1
     _a ,				_a      =							1, 1
     for _ in range(number_of_steps - 1						):
          _a ,				_a      =							current + previous, current
     return current


if __name__ == "__main__":
 import doctest

 doctest.testmod()

