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


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

class  _a					(SCREAMING_SNAKE_CASE__):





       """simple docstring"""




       def 							UpperCamelCase					(				self							,				A__   )     ->      int:

          if isinstance(snake_case__							,				snake_case__   ):
             _SCREAMING_SNAKE_CASE  			=					[label.strip() for label in labels.split(""","""   ) if label.strip()]
          return labels






       def __call__(				self							,				A__							,				A__							,				A__   )     ->      str:

          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__   ):
             _SCREAMING_SNAKE_CASE  			=					[sequences]

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

          return sequence_pairs, sequences






@add_end_docstrings(SCREAMING_SNAKE_CASE__)
class  _a					(SCREAMING_SNAKE_CASE__):





       """simple docstring"""




       def __init__(				self							,				A__=ZeroShotClassificationArgumentHandler()							,				*A__							,				**A__   )     ->      str:
          _SCREAMING_SNAKE_CASE  			=					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 							UpperCamelCase					(				self   )     ->      str:

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






       def 							UpperCamelCase					(				self							,				A__							,				A__=True							,				A__=True							,				A__=TruncationStrategy.ONLY_FIRST							,				**A__   )     ->      Optional[int]:
          _SCREAMING_SNAKE_CASE  			=					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`"""   )
             _SCREAMING_SNAKE_CASE  			=					self.tokenizer.eos_token
          try:
             _SCREAMING_SNAKE_CASE  			=					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.

                _SCREAMING_SNAKE_CASE  			=					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 							UpperCamelCase					(				self							,				**A__   )     ->      Tuple:

          if kwargs.get("""multi_class"""							,				snake_case__   ) is not None:
             _SCREAMING_SNAKE_CASE  			=					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."""   )
          _SCREAMING_SNAKE_CASE  			=					{}
          if "candidate_labels" in kwargs:
             _SCREAMING_SNAKE_CASE  			=					self._args_parser._parse_labels(kwargs["""candidate_labels"""]   )
          if "hypothesis_template" in kwargs:
             _SCREAMING_SNAKE_CASE  			=					kwargs["""hypothesis_template"""]

          _SCREAMING_SNAKE_CASE  			=					{}
          if "multi_label" in kwargs:
             _SCREAMING_SNAKE_CASE  			=					kwargs["""multi_label"""]
          return preprocess_params, {}, postprocess_params






       def __call__(				self							,				A__							,				*A__							,				**A__							,				)     ->      int:

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

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






       def 							UpperCamelCase					(				self							,				A__							,				A__=None							,				A__="This example is {}."   )     ->      Any:
          _SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE  			=					self._args_parser(snake_case__							,				snake_case__							,				snake_case__   )

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

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






       def 							UpperCamelCase					(				self							,				A__   )     ->      Dict:
          _SCREAMING_SNAKE_CASE  			=					inputs["""candidate_label"""]
          _SCREAMING_SNAKE_CASE  			=					inputs["""sequence"""]
          _SCREAMING_SNAKE_CASE  			=					{k: inputs[k] for k in self.tokenizer.model_input_names}
          _SCREAMING_SNAKE_CASE  			=					self.model(**snake_case__   )

          _SCREAMING_SNAKE_CASE  			=					{
              """candidate_label""": candidate_label,
              """sequence""": sequence,
              """is_last""": inputs["""is_last"""],
              **outputs,
          }
          return model_outputs






       def 							UpperCamelCase					(				self							,				A__							,				A__=False   )     ->      Tuple:
          _SCREAMING_SNAKE_CASE  			=					[outputs["""candidate_label"""] for outputs in model_outputs]
          _SCREAMING_SNAKE_CASE  			=					[outputs["""sequence"""] for outputs in model_outputs]
          _SCREAMING_SNAKE_CASE  			=					np.concatenate([output["""logits"""].numpy() for output in model_outputs]   )
          _SCREAMING_SNAKE_CASE  			=					logits.shape[0]
          _SCREAMING_SNAKE_CASE  			=					len(snake_case__   )
          _SCREAMING_SNAKE_CASE  			=					N // n
          _SCREAMING_SNAKE_CASE  			=					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
             _SCREAMING_SNAKE_CASE  			=					self.entailment_id
             _SCREAMING_SNAKE_CASE  			=					-1 if entailment_id == 0 else 0
             _SCREAMING_SNAKE_CASE  			=					reshaped_outputs[..., [contradiction_id, entailment_id]]
             _SCREAMING_SNAKE_CASE  			=					np.exp(snake_case__   ) / np.exp(snake_case__   ).sum(-1							,				keepdims=snake_case__   )
             _SCREAMING_SNAKE_CASE  			=					scores[..., 1]
          else:
             # softmax the "entailment" logits over all candidate labels
             _SCREAMING_SNAKE_CASE  			=					reshaped_outputs[..., self.entailment_id]
             _SCREAMING_SNAKE_CASE  			=					np.exp(snake_case__   ) / np.exp(snake_case__   ).sum(-1							,				keepdims=snake_case__   )

          _SCREAMING_SNAKE_CASE  			=					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


SCREAMING_SNAKE_CASE:     Any									= {
    '''configuration_pegasus_x''': ['''PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PegasusXConfig'''],
}

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						SCREAMING_SNAKE_CASE:     List[Any]									= [
						    '''PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST''',
						    '''PegasusXForConditionalGeneration''',
						    '''PegasusXModel''',
						    '''PegasusXPreTrainedModel''',
						]


if TYPE_CHECKING:
						from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_pegasus_x import (
												    PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST,
												    PegasusXForConditionalGeneration,
												    PegasusXModel,
												    PegasusXPreTrainedModel,
												)


else:
						import sys

						SCREAMING_SNAKE_CASE:     List[Any]									= _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)