


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


_SCREAMING_SNAKE_CASE      :			Union[str, Any]      				=   logging.get_logger(__name__)

class   A__ (   snake_case__     ):







    """simple docstring"""

    def 		a_      (	self      , __snake_case   ):
         if isinstance(__snake_case      , __snake_case   ):
              snake_case					=    [label.strip() for label in labels.split(''','''   ) if label.strip()]
         return labels




    def __call__(	self      , __snake_case      , __snake_case      , __snake_case   ):
         if len(__snake_case   ) == 0 or len(__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(__snake_case   )   )

         if isinstance(__snake_case      , __snake_case   ):
              snake_case					=    [sequences]

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

         return sequence_pairs, sequences






@add_end_docstrings(snake_case__     )
class   A__ (   snake_case__     ):







    """simple docstring"""

    def __init__(	self      , __snake_case=ZeroShotClassificationArgumentHandler()      , *__snake_case      , **__snake_case   ):
         snake_case					=    args_parser
         super().__init__(*__snake_case      , **__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   ):
         for label, ind in self.model.config.labelaid.items():
              if label.lower().startswith('''entail'''   ):
                   return ind
         return -1
    def 		a_      (	self      , __snake_case      , __snake_case=True      , __snake_case=True      , __snake_case=TruncationStrategy.ONLY_FIRST      , **__snake_case   ):
         snake_case					=    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`'''   )
              snake_case					=    self.tokenizer.eos_token
         try:
              snake_case					=    self.tokenizer(
                  __snake_case      , add_special_tokens=__snake_case      , return_tensors=__snake_case      , padding=__snake_case      , truncation=__snake_case      , )
         except Exception as e:
              if "too short" in str(__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.

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

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

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

         return super().__call__(__snake_case      , **__snake_case   )
    def 		a_      (	self      , __snake_case      , __snake_case=None      , __snake_case="This example is {}."   ):
         snake_case			,  snake_case					=    self._args_parser(__snake_case      , __snake_case      , __snake_case   )

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

              yield {
                  "candidate_label": candidate_label,
                  "sequence": sequences[0],
                  "is_last": i == len(__snake_case   ) - 1,
                  **model_input,
              }
    def 		a_      (	self      , __snake_case   ):
         snake_case					=    inputs['''candidate_label''']
         snake_case					=    inputs['''sequence''']
         snake_case					=    {k: inputs[k] for k in self.tokenizer.model_input_names}
         snake_case					=    self.model(**__snake_case   )

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




    def 		a_      (	self      , __snake_case      , __snake_case=False   ):
         snake_case					=    [outputs['''candidate_label'''] for outputs in model_outputs]
         snake_case					=    [outputs['''sequence'''] for outputs in model_outputs]
         snake_case					=    np.concatenate([output['''logits'''].numpy() for output in model_outputs]   )
         snake_case					=    logits.shape[0]
         snake_case					=    len(__snake_case   )
         snake_case					=    N // n
         snake_case					=    logits.reshape((num_sequences, n, -1)   )

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

         snake_case					=    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_torch_available


_SCREAMING_SNAKE_CASE      :			int      				=   {
    "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _SCREAMING_SNAKE_CASE      :			Dict      				=   [
     "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
     "TimesformerModel",
     "TimesformerForVideoClassification",
     "TimesformerPreTrainedModel",
 ]

if TYPE_CHECKING:
 from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_timesformer import (
      TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      TimesformerForVideoClassification,
      TimesformerModel,
      TimesformerPreTrainedModel,
  )

else:
 import sys

 _SCREAMING_SNAKE_CASE      :			int      				=   _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




