
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


UpperCAmelCase__		:     List[Any]     			=      logging.get_logger(__name__)






class UpperCAmelCase   (						SCREAMING_SNAKE_CASE__   ):





   '''simple docstring'''


   def  __magic_name__				(					self     :							Any			,			lowerCAmelCase_     :							Tuple     ):

      """simple docstring"""
      if isinstance(lowerCAmelCase_			,			lowerCAmelCase_     ):
         _A:  List[str]					=       [label.strip() for label in labels.split(''','''     ) if label.strip()]
      return labels


   def __call__(					self     :							Union[str, Any]			,			lowerCAmelCase_     :							List[str]			,			lowerCAmelCase_     :							Optional[int]			,			lowerCAmelCase_     :							int     ):

      """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_     ):
         _A:  Dict					=       [sequences]

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

      return sequence_pairs, sequences






@add_end_docstrings(SCREAMING_SNAKE_CASE__   )
class UpperCAmelCase   (						SCREAMING_SNAKE_CASE__   ):





   '''simple docstring'''


   def __init__(					self     :							Tuple			,			lowerCAmelCase_     :							Optional[int]=ZeroShotClassificationArgumentHandler()			,			*lowerCAmelCase_     :							List[str]			,			**lowerCAmelCase_     :							List[str]     ):

      """simple docstring"""
      _A:  Optional[Any]					=       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  __magic_name__				(					self     :							Any     ):

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


   def  __magic_name__				(					self     :							Any			,			lowerCAmelCase_     :							Tuple			,			lowerCAmelCase_     :							str=True			,			lowerCAmelCase_     :							Dict=True			,			lowerCAmelCase_     :							Union[str, Any]=TruncationStrategy.ONLY_FIRST			,			**lowerCAmelCase_     :							Union[str, Any]     ):

      """simple docstring"""
      _A:  int					=       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:  Union[str, Any]					=       self.tokenizer.eos_token
      try:
         _A:  Optional[int]					=       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.

            _A:  Tuple					=       self.tokenizer(
                lowerCAmelCase_			,			add_special_tokens=lowerCAmelCase_			,			return_tensors=lowerCAmelCase_			,			padding=lowerCAmelCase_			,			truncation=TruncationStrategy.DO_NOT_TRUNCATE			,			)
         else:
            raise e

      return inputs


   def  __magic_name__				(					self     :							str			,			**lowerCAmelCase_     :							List[Any]     ):

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

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


   def __call__(					self     :							Any			,			lowerCAmelCase_     :							Union[str, List[str]]			,			*lowerCAmelCase_     :							Dict			,			**lowerCAmelCase_     :							Dict			,			):

      """simple docstring"""
      if len(lowerCAmelCase_     ) == 0:
         pass
      elif len(lowerCAmelCase_     ) == 1 and "candidate_labels" not in kwargs:
         _A:  List[Any]					=       args[0]
      else:
         raise ValueError(F"""Unable to understand extra arguments {args}"""     )

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


   def  __magic_name__				(					self     :							Any			,			lowerCAmelCase_     :							Dict			,			lowerCAmelCase_     :							Any=None			,			lowerCAmelCase_     :							int="This example is {}."     ):

      """simple docstring"""
      _A			,  _A:  Union[str, Any]					=       self._args_parser(lowerCAmelCase_			,			lowerCAmelCase_			,			lowerCAmelCase_     )

      for i, (candidate_label, sequence_pair) in enumerate(zip(lowerCAmelCase_			,			lowerCAmelCase_     )     ):
         _A:  Optional[Any]					=       self._parse_and_tokenize([sequence_pair]     )

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


   def  __magic_name__				(					self     :							List[str]			,			lowerCAmelCase_     :							List[str]     ):

      """simple docstring"""
      _A:  List[str]					=       inputs['''candidate_label''']
      _A:  Optional[int]					=       inputs['''sequence''']
      _A:  Dict					=       {k: inputs[k] for k in self.tokenizer.model_input_names}
      _A:  List[Any]					=       self.model(**lowerCAmelCase_     )

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


   def  __magic_name__				(					self     :							List[Any]			,			lowerCAmelCase_     :							Dict			,			lowerCAmelCase_     :							str=False     ):

      """simple docstring"""
      _A:  Dict					=       [outputs['''candidate_label'''] for outputs in model_outputs]
      _A:  Optional[Any]					=       [outputs['''sequence'''] for outputs in model_outputs]
      _A:  Union[str, Any]					=       np.concatenate([output['''logits'''].numpy() for output in model_outputs]     )
      _A:  Optional[Any]					=       logits.shape[0]
      _A:  Optional[int]					=       len(lowerCAmelCase_     )
      _A:  Union[str, Any]					=       N // n
      _A:  int					=       logits.reshape((num_sequences, n, -1)     )

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

      _A:  Tuple					=       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 __future__ import annotations

import sys
from collections import deque
from typing import Generic, TypeVar

UpperCAmelCase__		:     Union[str, Any]     			=      TypeVar('T')






class UpperCAmelCase   (						Generic[T]   ):





   '''simple docstring'''
   __UpperCamelCase		:    deque[T]  # Cache store of keys
   __UpperCamelCase		:    set[T]  # References of the keys in cache
   __UpperCamelCase		:    int 				=    10  # Maximum capacity of cache


   def __init__(					self     :							List[str]			,			lowerCAmelCase_     :							int     ):

      """simple docstring"""
      _A:  Tuple					=       deque()
      _A:  List[Any]					=       set()
      if not n:
         _A:  str					=       sys.maxsize
      elif n < 0:
         raise ValueError('''n should be an integer greater than 0.'''     )
      else:
         _A:  Dict					=       n


   def  __magic_name__				(					self     :							Optional[int]			,			lowerCAmelCase_     :							T     ):

      """simple docstring"""
      if x not in self.key_reference:
         if len(self.dq_store     ) == LRUCache._MAX_CAPACITY:
            _A:  Optional[Any]					=       self.dq_store.pop()
            self.key_reference.remove(lowerCAmelCase_     )
      else:
         self.dq_store.remove(lowerCAmelCase_     )

      self.dq_store.appendleft(lowerCAmelCase_     )
      self.key_reference.add(lowerCAmelCase_     )


   def  __magic_name__				(					self     :							Optional[Any]     ):

      """simple docstring"""
      for k in self.dq_store:
         print(lowerCAmelCase_     )


   def __repr__(					self     :							Dict     ):

      """simple docstring"""
      return F"""LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store     )}"""


if __name__ == "__main__":
   import doctest

   doctest.testmod()

   UpperCAmelCase__		:     LRUCache[str | int]     			=      LRUCache(4)
   lru_cache.refer('A')
   lru_cache.refer(2)
   lru_cache.refer(3)
   lru_cache.refer('A')
   lru_cache.refer(4)
   lru_cache.refer(5)
   lru_cache.display()

   print(lru_cache)
   assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"



