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







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     def  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					Dict:
          if isinstance(__UpperCamelCase ,			__UpperCamelCase  ):
               UpperCAmelCase__							: Optional[int] 							=						[label.strip() for label in labels.split(","  ) if label.strip()]
          return labels



     def __call__(      self ,			__UpperCamelCase ,			__UpperCamelCase ,			__UpperCamelCase  )->					Union[str, Any]:
          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__							: List[Any] 							=						[sequences]

          UpperCAmelCase__							: int 							=						[]
          for sequence in sequences:
               sequence_pairs.extend([[sequence, hypothesis_template.format(__UpperCamelCase  )] for label in labels]  )

          return sequence_pairs, sequences







@add_end_docstrings(lowerCAmelCase_				)
class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     def __init__(      self ,			__UpperCamelCase=ZeroShotClassificationArgumentHandler() ,			*__UpperCamelCase ,			**__UpperCamelCase  )->					Union[str, Any]:
          UpperCAmelCase__							: List[str] 							=						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  lowerCAmelCase__       (      self  )->					Tuple:
          for label, ind in self.model.config.labelaid.items():
               if label.lower().startswith("entail"  ):
                    return ind
          return -1



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase=True ,			__UpperCamelCase=True ,			__UpperCamelCase=TruncationStrategy.ONLY_FIRST ,			**__UpperCamelCase  )->					Optional[int]:
          UpperCAmelCase__							: Union[str, Any] 							=						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__							: Dict 							=						self.tokenizer.eos_token
          try:
               UpperCAmelCase__							: Optional[Any] 							=						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__							: Tuple 							=						self.tokenizer(
                        __UpperCamelCase ,			add_special_tokens=__UpperCamelCase ,			return_tensors=__UpperCamelCase ,			padding=__UpperCamelCase ,			truncation=TruncationStrategy.DO_NOT_TRUNCATE ,			)
               else:
                    raise e

          return inputs



     def  lowerCAmelCase__       (      self ,			**__UpperCamelCase  )->					List[Any]:
          if kwargs.get("multi_class" ,			__UpperCamelCase  ) is not None:
               UpperCAmelCase__							: List[str] 							=						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__							: Tuple 							=						{}
          if "candidate_labels" in kwargs:
               UpperCAmelCase__							: Dict 							=						self._args_parser._parse_labels(kwargs["candidate_labels"]  )
          if "hypothesis_template" in kwargs:
               UpperCAmelCase__							: Optional[Any] 							=						kwargs["hypothesis_template"]

          UpperCAmelCase__							: List[str] 							=						{}
          if "multi_label" in kwargs:
               UpperCAmelCase__							: str 							=						kwargs["multi_label"]
          return preprocess_params, {}, postprocess_params



     def __call__(      self ,			__UpperCamelCase ,			*__UpperCamelCase ,			**__UpperCamelCase ,			)->					List[Any]:
          if len(__UpperCamelCase  ) == 0:
               pass
          elif len(__UpperCamelCase  ) == 1 and "candidate_labels" not in kwargs:
               UpperCAmelCase__							: List[str] 							=						args[0]
          else:
               raise ValueError(F"Unable to understand extra arguments {args}"  )

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



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase=None ,			__UpperCamelCase="This example is {}."  )->					Optional[Any]:
          UpperCAmelCase__							,	UpperCAmelCase__							: 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  lowerCAmelCase__       (      self ,			__UpperCamelCase  )->					List[Any]:
          UpperCAmelCase__							: Dict 							=						inputs["candidate_label"]
          UpperCAmelCase__							: Optional[int] 							=						inputs["sequence"]
          UpperCAmelCase__							: List[str] 							=						{k: inputs[k] for k in self.tokenizer.model_input_names}
          UpperCAmelCase__							: int 							=						self.model(**__UpperCamelCase  )

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



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase=False  )->					List[str]:
          UpperCAmelCase__							: List[str] 							=						[outputs["candidate_label"] for outputs in model_outputs]
          UpperCAmelCase__							: int 							=						[outputs["sequence"] for outputs in model_outputs]
          UpperCAmelCase__							: Optional[Any] 							=						np.concatenate([output["logits"].numpy() for output in model_outputs]  )
          UpperCAmelCase__							: Dict 							=						logits.shape[0]
          UpperCAmelCase__							: Any 							=						len(__UpperCamelCase  )
          UpperCAmelCase__							: Any 							=						N // n
          UpperCAmelCase__							: Optional[int] 							=						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__							: List[Any] 							=						self.entailment_id
               UpperCAmelCase__							: List[str] 							=						-1 if entailment_id == 0 else 0
               UpperCAmelCase__							: Optional[Any] 							=						reshaped_outputs[..., [contradiction_id, entailment_id]]
               UpperCAmelCase__							: Optional[int] 							=						np.exp(__UpperCamelCase  ) / np.exp(__UpperCamelCase  ).sum(-1 ,			keepdims=__UpperCamelCase  )
               UpperCAmelCase__							: Union[str, Any] 							=						scores[..., 1]
          else:
               # softmax the "entailment" logits over all candidate labels
               UpperCAmelCase__							: Dict 							=						reshaped_outputs[..., self.entailment_id]
               UpperCAmelCase__							: List[Any] 							=						np.exp(__UpperCamelCase  ) / np.exp(__UpperCamelCase  ).sum(-1 ,			keepdims=__UpperCamelCase  )

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






     '''simple docstring'''
     if a < 0:
          raise ValueError("Input value must be a positive integer"		)
     elif isinstance(lowerCAmelCase       ,    lowerCAmelCase		):
          raise TypeError("Input value must be a 'int' type"		)
     return bin(lowerCAmelCase		).count("1"		)


if __name__ == "__main__":
    import doctest

    doctest.testmod()



