






'''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							:							Any  							=		logging.get_logger(__name__)
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     str     )							->							Optional[Any]:

     '''simple docstring'''




     if isinstance(__lowerCamelCase				,     __lowerCamelCase     ):
      lowerCamelCase__  =     [label.strip() for label in labels.split(","     ) if label.strip()]
     return labels




    def __call__(					self     :     Union[str, Any]				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     int     )							->							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     ):
      lowerCamelCase__  =     [sequences]

     lowerCamelCase__  =     []
     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 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

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

     '''simple docstring'''




     lowerCamelCase__  =     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    a__				(					self     :     List[str]     )							->							str:

     '''simple docstring'''




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

    def    a__				(					self     :     Dict				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     Any=True				,     __lowerCamelCase     :     Dict=True				,     __lowerCamelCase     :     str=TruncationStrategy.ONLY_FIRST				,     **__lowerCamelCase     :     List[Any]     )							->							Dict:

     '''simple docstring'''




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

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

     return inputs

    def    a__				(					self     :     List[Any]				,     **__lowerCamelCase     :     Union[str, Any]     )							->							str:

     '''simple docstring'''




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

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

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

     '''simple docstring'''




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

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

    def    a__				(					self     :     Union[str, Any]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Tuple=None				,     __lowerCamelCase     :     Tuple="This example is {}."     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  ,	lowerCamelCase__  =     self._args_parser(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )

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

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

    def    a__				(					self     :     int				,     __lowerCamelCase     :     List[str]     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     inputs["candidate_label"]
     lowerCamelCase__  =     inputs["sequence"]
     lowerCamelCase__  =     {k: inputs[k] for k in self.tokenizer.model_input_names}
     lowerCamelCase__  =     self.model(**__lowerCamelCase     )

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




    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Union[str, Any]=False     )							->							Optional[int]:

     '''simple docstring'''




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

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

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





from __future__ import annotations






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__):
 lowerCamelCase__  =     list(range(len(lowercase__)))
 lowerCamelCase__  =     [v / w for v, w in zip(lowercase__				,     lowercase__)]
 index.sort(key=lambda lowercase__: ratio[i]				,     reverse=lowercase__)

 lowerCamelCase__  =     0
 lowerCamelCase__  =     [0] * len(lowercase__)
 for i in index:
  if weight[i] <= capacity:
   lowerCamelCase__  =     1
   max_value += value[i]
   capacity -= weight[i]
  else:
   lowerCamelCase__  =     capacity / weight[i]
   max_value += value[i] * capacity / weight[i]
   break

 return max_value, fractions


if __name__ == "__main__":
 import doctest

 doctest.testmod()

