





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


lowercase__       : Dict         =       logging.get_logger(__name__)


class 					SCREAMING_SNAKE_CASE       (a__				):


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase):

          '''simple docstring'''






          if isinstance(_UpperCAmelCase		,      _UpperCAmelCase):
               __A		:					List[Any]						=			[label.strip() for label in labels.split(',') if label.strip()]
          return labels


     def __call__(		self		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):

          '''simple docstring'''






          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):
               __A		:					Dict						=			[sequences]

          __A		:					Optional[int]						=			[]
          for sequence in sequences:
               sequence_pairs.extend([[sequence, hypothesis_template.format(_UpperCAmelCase)] for label in labels])

          return sequence_pairs, sequences




@add_end_docstrings(a__				)
class 					SCREAMING_SNAKE_CASE       (a__				):


     def __init__(		self		,      _UpperCAmelCase=ZeroShotClassificationArgumentHandler()		,      *_UpperCAmelCase		,      **_UpperCAmelCase):

          '''simple docstring'''






          __A		:					Optional[Any]						=			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 				SCREAMING_SNAKE_CASE    (		self):

          '''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		,      _UpperCAmelCase		,      _UpperCAmelCase=True		,      _UpperCAmelCase=True		,      _UpperCAmelCase=TruncationStrategy.ONLY_FIRST		,      **_UpperCAmelCase):

          '''simple docstring'''






          __A		:					List[str]						=			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		:					Any						=			self.tokenizer.eos_token
          try:
               __A		:					Dict						=			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.

                    __A		:					Optional[Any]						=			self.tokenizer(
                        _UpperCAmelCase		,      add_special_tokens=_UpperCAmelCase		,      return_tensors=_UpperCAmelCase		,      padding=_UpperCAmelCase		,      truncation=TruncationStrategy.DO_NOT_TRUNCATE		,      )
               else:
                    raise e

          return inputs


     def 				SCREAMING_SNAKE_CASE    (		self		,      **_UpperCAmelCase):

          '''simple docstring'''






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

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


     def __call__(		self		,      _UpperCAmelCase		,      *_UpperCAmelCase		,      **_UpperCAmelCase		,      ):

          '''simple docstring'''






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

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


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase=None		,      _UpperCAmelCase="This example is {}."):

          '''simple docstring'''






          __A					,__A		:					int						=			self._args_parser(_UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase)

          for i, (candidate_label, sequence_pair) in enumerate(zip(_UpperCAmelCase		,      _UpperCAmelCase)):
               __A		:					Optional[int]						=			self._parse_and_tokenize([sequence_pair])

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


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					List[str]						=			inputs['candidate_label']
          __A		:					Any						=			inputs['sequence']
          __A		:					List[str]						=			{k: inputs[k] for k in self.tokenizer.model_input_names}
          __A		:					Optional[int]						=			self.model(**_UpperCAmelCase)

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


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase=False):

          '''simple docstring'''






          __A		:					Optional[int]						=			[outputs['candidate_label'] for outputs in model_outputs]
          __A		:					List[Any]						=			[outputs['sequence'] for outputs in model_outputs]
          __A		:					int						=			np.concatenate([output['logits'].numpy() for output in model_outputs])
          __A		:					Optional[Any]						=			logits.shape[0]
          __A		:					Optional[int]						=			len(_UpperCAmelCase)
          __A		:					Tuple						=			N // n
          __A		:					List[Any]						=			logits.reshape((num_sequences, n, -1))

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

          __A		:					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(),
          }






'''simple docstring'''




def 			_lowerCAmelCase     (    __snake_case    :					str					,				__snake_case    :					str     )	->	int:
     if len(__snake_case     ) != len(__snake_case     ):
          raise ValueError('String lengths must match!'     )

     __A		:					Optional[Any]						=			0

     for chara, chara in zip(__snake_case					,				__snake_case     ):
          if chara != chara:
               count += 1

     return count


if __name__ == "__main__":
  import doctest

  doctest.testmod()