


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


class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def 					_snake_case     (    self:	Tuple						,				a:	Dict    ):
       if isinstance(a						,				a    ):
        __lowerCamelCase		:							Union[str, Any]		 =						[label.strip() for label in labels.split(','    ) if label.strip()]
       return labels




      def __call__(    self:	Optional[Any]						,				a:	int						,				a:	Dict						,				a:	Optional[Any]    ):
       if len(a    ) == 0 or len(a    ) == 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(a    )    )

       if isinstance(a						,				a    ):
        __lowerCamelCase		:							int		 =						[sequences]

       __lowerCamelCase		:							List[str]		 =						[]
       for sequence in sequences:
        sequence_pairs.extend([[sequence, hypothesis_template.format(a    )] for label in labels]    )

       return sequence_pairs, sequences



@add_end_docstrings(__UpperCamelCase   )
class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Optional[Any]						,				a:	Optional[Any]=ZeroShotClassificationArgumentHandler()						,				*a:	Optional[Any]						,				**a:	int    ):
       __lowerCamelCase		:							Tuple		 =						args_parser
       super().__init__(*a						,				**a    )
       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 					_snake_case     (    self:	Dict    ):
       for label, ind in self.model.config.labelaid.items():
        if label.lower().startswith('entail'    ):
         return ind
       return -1




      def 					_snake_case     (    self:	Any						,				a:	Dict						,				a:	Tuple=True						,				a:	List[str]=True						,				a:	Dict=TruncationStrategy.ONLY_FIRST						,				**a:	Tuple    ):
       __lowerCamelCase		:							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`'    )
        __lowerCamelCase		:							List[Any]		 =						self.tokenizer.eos_token
       try:
        __lowerCamelCase		:							List[str]		 =						self.tokenizer(
            a						,				add_special_tokens=a						,				return_tensors=a						,				padding=a						,				truncation=a						,				)
       except Exception as e:
        if "too short" in str(a    ):
         # 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		:							str		 =						self.tokenizer(
             a						,				add_special_tokens=a						,				return_tensors=a						,				padding=a						,				truncation=TruncationStrategy.DO_NOT_TRUNCATE						,				)
        else:
         raise e

       return inputs




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

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




      def __call__(    self:	Any						,				a:	Union[str, List[str]]						,				*a:	str						,				**a:	Optional[int]						,				):
       if len(a    ) == 0:
        pass
       elif len(a    ) == 1 and "candidate_labels" not in kwargs:
        __lowerCamelCase		:							Any		 =						args[0]
       else:
        raise ValueError(F'Unable to understand extra arguments {args}'    )

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




      def 					_snake_case     (    self:	int						,				a:	Optional[int]						,				a:	List[str]=None						,				a:	List[str]="This example is {}."    ):
       __lowerCamelCase		:							Dict		 =						self._args_parser(a						,				a						,				a    )

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

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




      def 					_snake_case     (    self:	Any						,				a:	str    ):
       __lowerCamelCase		:							List[str]		 =						inputs['candidate_label']
       __lowerCamelCase		:							Optional[int]		 =						inputs['sequence']
       __lowerCamelCase		:							Tuple		 =						{k: inputs[k] for k in self.tokenizer.model_input_names}
       __lowerCamelCase		:							Dict		 =						self.model(**a    )

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




      def 					_snake_case     (    self:	List[str]						,				a:	Optional[int]						,				a:	List[Any]=False    ):
       __lowerCamelCase		:							Any		 =						[outputs['candidate_label'] for outputs in model_outputs]
       __lowerCamelCase		:							str		 =						[outputs['sequence'] for outputs in model_outputs]
       __lowerCamelCase		:							List[Any]		 =						np.concatenate([output['logits'].numpy() for output in model_outputs]    )
       __lowerCamelCase		:							List[Any]		 =						logits.shape[0]
       __lowerCamelCase		:							List[Any]		 =						len(a    )
       __lowerCamelCase		:							List[str]		 =						N // n
       __lowerCamelCase		:							List[Any]		 =						logits.reshape((num_sequences, n, -1)    )

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

       __lowerCamelCase		:							Optional[int]		 =						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_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowercase_	   =     {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']}

try:
       if not is_sentencepiece_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowercase_	   =     ['MBartTokenizer']

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowercase_	   =     ['MBartTokenizerFast']

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowercase_	   =     [
           'MBART_PRETRAINED_MODEL_ARCHIVE_LIST',
           'MBartForCausalLM',
           'MBartForConditionalGeneration',
           'MBartForQuestionAnswering',
           'MBartForSequenceClassification',
           'MBartModel',
           'MBartPreTrainedModel',
       ]

try:
       if not is_tf_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowercase_	   =     [
           'TFMBartForConditionalGeneration',
           'TFMBartModel',
           'TFMBartPreTrainedModel',
       ]

try:
       if not is_flax_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowercase_	   =     [
           'FlaxMBartForConditionalGeneration',
           'FlaxMBartForQuestionAnswering',
           'FlaxMBartForSequenceClassification',
           'FlaxMBartModel',
           'FlaxMBartPreTrainedModel',
       ]


if TYPE_CHECKING:
       from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig

       try:
              if not is_sentencepiece_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_mbart import MBartTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_mbart_fast import MBartTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_mbart import (
                  MBART_PRETRAINED_MODEL_ARCHIVE_LIST,
                  MBartForCausalLM,
                  MBartForConditionalGeneration,
                  MBartForQuestionAnswering,
                  MBartForSequenceClassification,
                  MBartModel,
                  MBartPreTrainedModel,
              )

       try:
              if not is_tf_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel

       try:
              if not is_flax_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_flax_mbart import (
                  FlaxMBartForConditionalGeneration,
                  FlaxMBartForQuestionAnswering,
                  FlaxMBartForSequenceClassification,
                  FlaxMBartModel,
                  FlaxMBartPreTrainedModel,
              )

else:
       import sys

       lowercase_	   =     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)

