


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:			Union[str, Any]		, a:			Dict							):
       if isinstance(__lowerCamelCase		, __lowerCamelCase							):
        __lowerCamelCase						:				Optional[Any]						   =		[label.strip() for label in labels.split(','							) if label.strip()]
       return labels




      def __call__(							self:			Dict		, a:			List[Any]		, a:			List[str]		, a:			Optional[int]							):
       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							):
        __lowerCamelCase						:				str						   =		[sequences]

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

       return sequence_pairs, sequences



@add_end_docstrings(UpperCamelCase__       )
class 			A_   (			UpperCamelCase__       ):




      '''simple docstring'''


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




      def 	_snake_case      (							self:			Union[str, Any]		, a:			Any		, a:			Optional[int]=True		, a:			Tuple=True		, a:			Optional[Any]=TruncationStrategy.ONLY_FIRST		, **a:			str							):
       __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						:				Tuple						   =		self.tokenizer.eos_token
       try:
        __lowerCamelCase						:				Any						   =		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.

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

       return inputs




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

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




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

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




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

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

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




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

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




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

       __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_torch_available,
)


a__: str							   =						{
    'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a__: Union[str, Any]							   =						[
           'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
           'MegaForCausalLM',
           'MegaForMaskedLM',
           'MegaForMultipleChoice',
           'MegaForQuestionAnswering',
           'MegaForSequenceClassification',
           'MegaForTokenClassification',
           'MegaModel',
           'MegaPreTrainedModel',
       ]

if TYPE_CHECKING:
       from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_mega import (
                  MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
                  MegaForCausalLM,
                  MegaForMaskedLM,
                  MegaForMultipleChoice,
                  MegaForQuestionAnswering,
                  MegaForSequenceClassification,
                  MegaForTokenClassification,
                  MegaModel,
                  MegaPreTrainedModel,
              )

else:
       import sys

       a__: Union[str, Any]							   =						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)





