



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


A:     Optional[Any]										=	logging.get_logger(__name__)



class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__				):

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE		)						->   Any:





    '''simple docstring'''




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




   def __call__(     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Tuple:





    '''simple docstring'''




    if len(_SCREAMING_SNAKE_CASE		) == 0 or len(_SCREAMING_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(_SCREAMING_SNAKE_CASE		)		)

    if isinstance(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		):
     UpperCAmelCase			:      Dict			=			[sequences]

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

    return sequence_pairs, sequences



@add_end_docstrings(UpperCAmelCase__				)
class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__				):

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





    '''simple docstring'''




    UpperCAmelCase			:      Union[str, Any]			=			args_parser
    super().__init__(*_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_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		)						->   Union[str, 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   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE=TruncationStrategy.ONLY_FIRST   ,  **_SCREAMING_SNAKE_CASE		)						->   List[str]:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[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			:      str			=			self.tokenizer.eos_token
    try:
     UpperCAmelCase			:      Optional[Any]			=			self.tokenizer(
         _SCREAMING_SNAKE_CASE   ,  add_special_tokens=_SCREAMING_SNAKE_CASE   ,  return_tensors=_SCREAMING_SNAKE_CASE   ,  padding=_SCREAMING_SNAKE_CASE   ,  truncation=_SCREAMING_SNAKE_CASE   ,  )
    except Exception as e:
     if "too short" in str(_SCREAMING_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			:      str			=			self.tokenizer(
          _SCREAMING_SNAKE_CASE   ,  add_special_tokens=_SCREAMING_SNAKE_CASE   ,  return_tensors=_SCREAMING_SNAKE_CASE   ,  padding=_SCREAMING_SNAKE_CASE   ,  truncation=TruncationStrategy.DO_NOT_TRUNCATE   ,  )
     else:
      raise e

    return inputs

   def 			SCREAMING_SNAKE_CASE  (     self   ,  **_SCREAMING_SNAKE_CASE		)						->   str:





    '''simple docstring'''




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

    UpperCAmelCase			:      Tuple			=			{}
    if "multi_label" in kwargs:
     UpperCAmelCase			:      Optional[Any]			=			kwargs["""multi_label"""]
    return preprocess_params, {}, postprocess_params

   def __call__(     self   ,  _SCREAMING_SNAKE_CASE   ,  *_SCREAMING_SNAKE_CASE   ,  **_SCREAMING_SNAKE_CASE   ,  )						->   Dict:





    '''simple docstring'''




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

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

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE=None   ,  _SCREAMING_SNAKE_CASE="This example is {}."		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      int			=			self._args_parser(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)

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

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

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE		)						->   Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      str			=			inputs["""candidate_label"""]
    UpperCAmelCase			:      Any			=			inputs["""sequence"""]
    UpperCAmelCase			:      List[Any]			=			{k: inputs[k] for k in self.tokenizer.model_input_names}
    UpperCAmelCase			:      Optional[Any]			=			self.model(**_SCREAMING_SNAKE_CASE		)

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




   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE=False		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      Tuple			=			[outputs["""candidate_label"""] for outputs in model_outputs]
    UpperCAmelCase			:      List[str]			=			[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			:      Dict			=			len(_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      Union[str, Any]			=			N // n
    UpperCAmelCase			:      Any			=			logits.reshape((num_sequences, n, -1)		)

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

    UpperCAmelCase			:      Any			=			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"""
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_torch_available,
)


A:     Union[str, Any]										=	{
    "configuration_speecht5": [
        "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP",
        "SpeechT5Config",
        "SpeechT5HifiGanConfig",
    ],
    "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"],
    "processing_speecht5": ["SpeechT5Processor"],
}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      A:     List[str]										=	["SpeechT5Tokenizer"]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      A:     Dict										=	[
          "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST",
          "SpeechT5ForSpeechToText",
          "SpeechT5ForSpeechToSpeech",
          "SpeechT5ForTextToSpeech",
          "SpeechT5Model",
          "SpeechT5PreTrainedModel",
          "SpeechT5HifiGan",
      ]

if TYPE_CHECKING:
      from .configuration_speechta import (
          SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP,
          SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP,
          SpeechTaConfig,
          SpeechTaHifiGanConfig,
      )
      from .feature_extraction_speechta import SpeechTaFeatureExtractor
      from .processing_speechta import SpeechTaProcessor

      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_speechta import SpeechTaTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_speechta import (
                SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST,
                SpeechTaForSpeechToSpeech,
                SpeechTaForSpeechToText,
                SpeechTaForTextToSpeech,
                SpeechTaHifiGan,
                SpeechTaModel,
                SpeechTaPreTrainedModel,
            )

else:
      import sys

      A:     Dict										=	_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
