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





class 		_lowercase						(					snake_case_       ):

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Dict   ,      snake_case	:							Dict			)   ->						Union[str, Any]:

  """simple docstring"""





  if isinstance(snake_case   ,      snake_case			):
   UpperCamelCase_					:						Dict =					[label.strip() for label in labels.split(','			) if label.strip()]
  return labels


 def __call__( self	:							Union[str, Any]   ,      snake_case	:							Dict   ,      snake_case	:							Union[str, Any]   ,      snake_case	:							int			)   ->						Tuple:

  """simple docstring"""





  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			):
   UpperCamelCase_					:						Optional[int] =					[sequences]

  UpperCamelCase_					:						Optional[int] =					[]
  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 		_lowercase						(					snake_case_       ):

 def __init__( self	:							Any   ,      snake_case	:							Optional[Any]=ZeroShotClassificationArgumentHandler()   ,      *snake_case	:							Optional[Any]   ,      **snake_case	:							List[Any]			)   ->						List[Any]:

  """simple docstring"""





  UpperCamelCase_					:						Any =					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 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[Any]			)   ->						List[Any]:

  """simple docstring"""





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

 def 						SCREAMING_SNAKE_CASE__   ( self	:							List[str]   ,      snake_case	:							Optional[Any]   ,      snake_case	:							int=True   ,      snake_case	:							Any=True   ,      snake_case	:							Optional[int]=TruncationStrategy.ONLY_FIRST   ,      **snake_case	:							str			)   ->						Any:

  """simple docstring"""





  UpperCamelCase_					:						List[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_					:						Tuple =					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.

    UpperCamelCase_					:						List[Any] =					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 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[Any]   ,      **snake_case	:							Union[str, Any]			)   ->						Optional[int]:

  """simple docstring"""





  if kwargs.get('multi_class'   ,      snake_case			) is not None:
   UpperCamelCase_					:						Tuple =					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_					:						Optional[Any] =					{}
  if "candidate_labels" in kwargs:
   UpperCamelCase_					:						Union[str, Any] =					self._args_parser._parse_labels(kwargs['candidate_labels']			)
  if "hypothesis_template" in kwargs:
   UpperCamelCase_					:						List[str] =					kwargs['hypothesis_template']

  UpperCamelCase_					:						int =					{}
  if "multi_label" in kwargs:
   UpperCamelCase_					:						int =					kwargs['multi_label']
  return preprocess_params, {}, postprocess_params

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

  """simple docstring"""





  if len(snake_case			) == 0:
   pass
  elif len(snake_case			) == 1 and "candidate_labels" not in kwargs:
   UpperCamelCase_					:						Union[str, Any] =					args[0]
  else:
   raise ValueError(f"Unable to understand extra arguments {args}"			)

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

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Union[str, Any]   ,      snake_case	:							int   ,      snake_case	:							List[Any]=None   ,      snake_case	:							Union[str, Any]="This example is {}."			)   ->						List[Any]:

  """simple docstring"""





  UpperCamelCase_, UpperCamelCase_					:						str =					self._args_parser(snake_case   ,      snake_case   ,      snake_case			)

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

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

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Union[str, Any]   ,      snake_case	:							Dict			)   ->						str:

  """simple docstring"""





  UpperCamelCase_					:						Dict =					inputs['candidate_label']
  UpperCamelCase_					:						Optional[int] =					inputs['sequence']
  UpperCamelCase_					:						Tuple =					{k: inputs[k] for k in self.tokenizer.model_input_names}
  UpperCamelCase_					:						Tuple =					self.model(**snake_case			)

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


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

  """simple docstring"""





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

  UpperCamelCase_					:						Dict =					list(reversed(scores[0].argsort()			)			)
  return {
      "sequence": sequences[0],
      "labels": [candidate_labels[i] for i in top_inds],
      "scores": scores[0, top_inds].tolist(),
  }




def    __lowercase     (						lowerCamelCase					:     str	):
 UpperCamelCase_					:						Dict =					0
 for ch in input_str:
  UpperCamelCase_					:						Tuple =					ord(lowerCamelCase	)
  UpperCamelCase_					:						str =					pow(2  ,  lowerCamelCase	)

  # If we already turned on bit for current character's unicode
  if bitmap >> ch_unicode & 1 == 1:
   return False
  bitmap |= ch_bit_index_on
 return True


if __name__ == "__main__":
   import doctest

   doctest.testmod()



