





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





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   def 							__lowercase		(					self					,  lowercase)			->						List[str]:







          '''simple docstring'''

          if isinstance(lowercase					,  lowercase):
                 a__						:	int =				[label.strip() for label in labels.split(',') if label.strip()]
          return labels

   def __call__(					self					,  lowercase					,  lowercase					,  lowercase)			->						Union[str, Any]:







          '''simple docstring'''

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

          if isinstance(lowercase					,  lowercase):
                 a__						:	List[Any] =				[sequences]

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

          return sequence_pairs, sequences





@add_end_docstrings(__UpperCAmelCase	)
class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   def __init__(					self					,  lowercase=ZeroShotClassificationArgumentHandler()					,  *lowercase					,  **lowercase)			->						Dict:







          '''simple docstring'''

          a__						:	List[Any] =				args_parser
          super().__init__(*lowercase					,  **lowercase)
          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 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

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

   def 							__lowercase		(					self					,  lowercase					,  lowercase=True					,  lowercase=True					,  lowercase=TruncationStrategy.ONLY_FIRST					,  **lowercase)			->						Optional[int]:







          '''simple docstring'''

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

          return inputs

   def 							__lowercase		(					self					,  **lowercase)			->						str:







          '''simple docstring'''

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

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

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







          '''simple docstring'''

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

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

   def 							__lowercase		(					self					,  lowercase					,  lowercase=None					,  lowercase="This example is {}.")			->						Optional[int]:







          '''simple docstring'''

          a__ ,							a__						:	Any =				self._args_parser(lowercase					,  lowercase					,  lowercase)

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

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

   def 							__lowercase		(					self					,  lowercase)			->						List[str]:







          '''simple docstring'''

          a__						:	Any =				inputs['candidate_label']
          a__						:	int =				inputs['sequence']
          a__						:	Tuple =				{k: inputs[k] for k in self.tokenizer.model_input_names}
          a__						:	Optional[int] =				self.model(**lowercase)

          a__						:	Union[str, Any] =				{
              'candidate_label': candidate_label,
              'sequence': sequence,
              'is_last': inputs['is_last'],
              **outputs,
          }
          return model_outputs

   def 							__lowercase		(					self					,  lowercase					,  lowercase=False)			->						Dict:







          '''simple docstring'''

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

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

          a__						:	Union[str, 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(),
          }








from ...processing_utils import ProcessorMixin


class 				UpperCamelCase_    ( UpperCAmelCase__     ):

    '''simple docstring'''






    UpperCAmelCase__							  =      '''SpeechT5FeatureExtractor'''
    UpperCAmelCase__							  =      '''SpeechT5Tokenizer'''


    def __init__(			self      :	Any					, UpperCAmelCase__      :	Dict					, UpperCAmelCase__      :	Tuple)						->Union[str, Any]:





           '''simple docstring'''

           super().__init__(UpperCAmelCase__					, UpperCAmelCase__)


    def __call__(			self      :	Dict					, *UpperCAmelCase__      :	List[str]					, **UpperCAmelCase__      :	Any)						->Optional[Any]:





           '''simple docstring'''

           A__       =    kwargs.pop('''audio'''					, UpperCAmelCase__)
           A__       =    kwargs.pop('''text'''					, UpperCAmelCase__)
           A__       =    kwargs.pop('''text_target'''					, UpperCAmelCase__)
           A__       =    kwargs.pop('''audio_target'''					, UpperCAmelCase__)
           A__       =    kwargs.pop('''sampling_rate'''					, UpperCAmelCase__)

           if audio is not None and text is not None:
                  raise ValueError(
                      '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''')
           if audio_target is not None and text_target is not None:
                  raise ValueError(
                      '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''')
           if audio is None and audio_target is None and text is None and text_target is None:
                  raise ValueError(
                      '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''')

           if audio is not None:
                  A__       =    self.feature_extractor(UpperCAmelCase__					, *UpperCAmelCase__					, sampling_rate=UpperCAmelCase__					, **UpperCAmelCase__)
           elif text is not None:
                  A__       =    self.tokenizer(UpperCAmelCase__					, **UpperCAmelCase__)
           else:
                  A__       =    None

           if audio_target is not None:
                  A__       =    self.feature_extractor(audio_target=UpperCAmelCase__					, *UpperCAmelCase__					, sampling_rate=UpperCAmelCase__					, **UpperCAmelCase__)
                  A__       =    targets['''input_values''']
           elif text_target is not None:
                  A__       =    self.tokenizer(UpperCAmelCase__					, **UpperCAmelCase__)
                  A__       =    targets['''input_ids''']
           else:
                  A__       =    None

           if inputs is None:
                  return targets

           if targets is not None:
                  A__       =    labels

                  A__       =    targets.get('''attention_mask''')
                  if decoder_attention_mask is not None:
                         A__       =    decoder_attention_mask

           return inputs


    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[Any]					, *UpperCAmelCase__      :	Tuple					, **UpperCAmelCase__      :	int)						->Optional[int]:





           '''simple docstring'''

           A__       =    kwargs.pop('''input_values'''					, UpperCAmelCase__)
           A__       =    kwargs.pop('''input_ids'''					, UpperCAmelCase__)
           A__       =    kwargs.pop('''labels'''					, UpperCAmelCase__)

           if input_values is not None and input_ids is not None:
                  raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''')
           if input_values is None and input_ids is None and labels is None:
                  raise ValueError(
                      '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''')

           if input_values is not None:
                  A__       =    self.feature_extractor.pad(UpperCAmelCase__					, *UpperCAmelCase__					, **UpperCAmelCase__)
           elif input_ids is not None:
                  A__       =    self.tokenizer.pad(UpperCAmelCase__					, **UpperCAmelCase__)
           else:
                  A__       =    None

           if labels is not None:
                  if "input_ids" in labels or (isinstance(UpperCAmelCase__					, UpperCAmelCase__) and "input_ids" in labels[0]):
                         A__       =    self.tokenizer.pad(UpperCAmelCase__					, **UpperCAmelCase__)
                         A__       =    targets['''input_ids''']
                  else:
                         A__       =    self.feature_extractor.feature_size
                         A__       =    self.feature_extractor.num_mel_bins
                         A__       =    self.feature_extractor.pad(UpperCAmelCase__					, *UpperCAmelCase__					, **UpperCAmelCase__)
                         A__       =    feature_size_hack
                         A__       =    targets['''input_values''']
           else:
                  A__       =    None

           if inputs is None:
                  return targets

           if targets is not None:
                  A__       =    labels

                  A__       =    targets.get('''attention_mask''')
                  if decoder_attention_mask is not None:
                         A__       =    decoder_attention_mask

           return inputs


    def        SCREAMING_SNAKE_CASE							(			self      :	Any					, *UpperCAmelCase__      :	Dict					, **UpperCAmelCase__      :	Optional[Any])						->Optional[Any]:





           '''simple docstring'''

           return self.tokenizer.batch_decode(*UpperCAmelCase__					, **UpperCAmelCase__)





    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[Any]					, *UpperCAmelCase__      :	List[Any]					, **UpperCAmelCase__      :	Union[str, Any])						->Dict:





           '''simple docstring'''

           return self.tokenizer.decode(*UpperCAmelCase__					, **UpperCAmelCase__)


