





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


_lowerCamelCase      							=   logging.get_logger(__name__)







class       __A							(   lowerCamelCase__	):




      """simple docstring"""







      def 					__snake_case      (		self   ,				a__):



             """simple docstring"""





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



      def __call__(		self   ,				a__   ,				a__   ,				a__):



             """simple docstring"""





             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				:  List[Any]						=		[sequences]

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

             return sequence_pairs, sequences







@add_end_docstrings(lowerCamelCase__	)
class       __A							(   lowerCamelCase__	):




      """simple docstring"""







      def __init__(		self   ,				a__=ZeroShotClassificationArgumentHandler()   ,				*a__   ,				**a__):



             """simple docstring"""





             _lowerCamelCase				:  int						=		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):



             """simple docstring"""





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


      def 					__snake_case      (		self   ,				a__   ,				a__=True   ,				a__=True   ,				a__=TruncationStrategy.ONLY_FIRST   ,				**a__):



             """simple docstring"""





             _lowerCamelCase				:  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`''')
                    _lowerCamelCase				:  Optional[Any]						=		self.tokenizer.eos_token
             try:
                    _lowerCamelCase				:  Any						=		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				:  Optional[int]						=		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   ,				**a__):



             """simple docstring"""





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

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


      def __call__(		self   ,				a__   ,				*a__   ,				**a__   ,				):



             """simple docstring"""





             if len(a__) == 0:
                    pass
             elif len(a__) == 1 and "candidate_labels" not in kwargs:
                    _lowerCamelCase				:  Union[str, Any]						=		args[0]
             else:
                    raise ValueError(F"""Unable to understand extra arguments {args}""")

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


      def 					__snake_case      (		self   ,				a__   ,				a__=None   ,				a__="This example is {}."):



             """simple docstring"""





             _lowerCamelCase,	_lowerCamelCase				:  Union[str, Any]						=		self._args_parser(a__   ,				a__   ,				a__)

             for i, (candidate_label, sequence_pair) in enumerate(zip(a__   ,				a__)):
                    _lowerCamelCase				:  str						=		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   ,				a__):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		inputs['''candidate_label''']
             _lowerCamelCase				:  Tuple						=		inputs['''sequence''']
             _lowerCamelCase				:  Union[str, Any]						=		{k: inputs[k] for k in self.tokenizer.model_input_names}
             _lowerCamelCase				:  List[str]						=		self.model(**a__)

             _lowerCamelCase				:  Dict						=		{
                 '''candidate_label''': candidate_label,
                 '''sequence''': sequence,
                 '''is_last''': inputs['''is_last'''],
                 **outputs,
             }
             return model_outputs



      def 					__snake_case      (		self   ,				a__   ,				a__=False):



             """simple docstring"""





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

             _lowerCamelCase				:  List[str]						=		list(reversed(scores[0].argsort()))
             return {
                 "sequence": sequences[0],
                 "labels": [candidate_labels[i] for i in top_inds],
                 "scores": scores[0, top_inds].tolist(),
             }








import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


_lowerCamelCase      							=   logging.get_logger(__name__)







class       __A							(   lowerCamelCase__	):




      """simple docstring"""







      UpperCAmelCase__							=   ["""input_features"""]


      def __init__(		self   ,				a__=80   ,				a__=1_6000   ,				a__=160   ,				a__=30   ,				a__=400   ,				a__=0.0   ,				a__=False   ,				**a__   ,				):



             """simple docstring"""





             super().__init__(
                 feature_size=a__   ,				sampling_rate=a__   ,				padding_value=a__   ,				return_attention_mask=a__   ,				**a__   ,				)
             _lowerCamelCase				:  int						=		n_fft
             _lowerCamelCase				:  List[Any]						=		hop_length
             _lowerCamelCase				:  Tuple						=		chunk_length
             _lowerCamelCase				:  Optional[Any]						=		chunk_length * sampling_rate
             _lowerCamelCase				:  Optional[Any]						=		self.n_samples // hop_length
             _lowerCamelCase				:  List[str]						=		sampling_rate
             _lowerCamelCase				:  Optional[int]						=		mel_filter_bank(
                 num_frequency_bins=1 + n_fft // 2   ,				num_mel_filters=a__   ,				min_frequency=0.0   ,				max_frequency=8000.0   ,				sampling_rate=a__   ,				norm='''slaney'''   ,				mel_scale='''slaney'''   ,				)


      def 					__snake_case      (		self   ,				a__):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		spectrogram(
                 a__   ,				window_function(self.n_fft   ,				'''hann''')   ,				frame_length=self.n_fft   ,				hop_length=self.hop_length   ,				power=2.0   ,				mel_filters=self.mel_filters   ,				log_mel='''log10'''   ,				)
             _lowerCamelCase				:  str						=		log_spec[:, :-1]
             _lowerCamelCase				:  Union[str, Any]						=		np.maximum(a__   ,				log_spec.max() - 8.0)
             _lowerCamelCase				:  Optional[int]						=		(log_spec + 4.0) / 4.0
             return log_spec


      @staticmethod
      # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
      def 					__snake_case      (		a__   ,				a__   ,				a__ = 0.0):



             """simple docstring"""





             if attention_mask is not None:
                    _lowerCamelCase				:  Dict						=		np.array(a__   ,				np.intaa)
                    _lowerCamelCase				:  Any						=		[]

                    for vector, length in zip(a__   ,				attention_mask.sum(-1)):
                           _lowerCamelCase				:  Any						=		(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7)
                           if length < normed_slice.shape[0]:
                                  _lowerCamelCase				:  Optional[int]						=		padding_value

                           normed_input_values.append(a__)
             else:
                    _lowerCamelCase				:  Optional[int]						=		[(x - x.mean()) / np.sqrt(x.var() + 1e-7) for x in input_values]

             return normed_input_values


      def __call__(		self   ,				a__   ,				a__ = True   ,				a__ = None   ,				a__ = None   ,				a__ = None   ,				a__ = "max_length"   ,				a__ = None   ,				a__ = None   ,				a__ = None   ,				**a__   ,				):



             """simple docstring"""





             if sampling_rate is not None:
                    if sampling_rate != self.sampling_rate:
                           raise ValueError(
                               F"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"""
                               F""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"""
                               F""" was sampled with {self.sampling_rate} and not {sampling_rate}.""")
             else:
                    logger.warning(
                        '''It is strongly recommended to pass the `sampling_rate` argument to this function. '''
                        '''Failing to do so can result in silent errors that might be hard to debug.''')

             _lowerCamelCase				:  Dict						=		isinstance(a__   ,				np.ndarray) and len(raw_speech.shape) > 1
             if is_batched_numpy and len(raw_speech.shape) > 2:
                    raise ValueError(F"""Only mono-channel audio is supported for input to {self}""")
             _lowerCamelCase				:  int						=		is_batched_numpy or (
                 isinstance(a__   ,				(list, tuple)) and (isinstance(raw_speech[0]   ,				(np.ndarray, tuple, list)))
             )

             if is_batched:
                    _lowerCamelCase				:  List[Any]						=		[np.asarray([speech]   ,				dtype=np.floataa).T for speech in raw_speech]
             elif not is_batched and not isinstance(a__   ,				np.ndarray):
                    _lowerCamelCase				:  str						=		np.asarray(a__   ,				dtype=np.floataa)
             elif isinstance(a__   ,				np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
                    _lowerCamelCase				:  str						=		raw_speech.astype(np.floataa)

             # always return batch
             if not is_batched:
                    _lowerCamelCase				:  List[Any]						=		[np.asarray([raw_speech]).T]

             _lowerCamelCase				:  List[str]						=		BatchFeature({'''input_features''': raw_speech})

             # convert into correct format for padding

             _lowerCamelCase				:  Optional[Any]						=		self.pad(
                 a__   ,				padding=a__   ,				max_length=max_length if max_length else self.n_samples   ,				truncation=a__   ,				pad_to_multiple_of=a__   ,				return_attention_mask=return_attention_mask or do_normalize   ,				)

             # zero-mean and unit-variance normalization
             if do_normalize:
                    _lowerCamelCase				:  Dict						=		self.zero_mean_unit_var_norm(
                        padded_inputs['''input_features''']   ,				attention_mask=padded_inputs['''attention_mask''']   ,				padding_value=self.padding_value   ,				)
                    _lowerCamelCase				:  int						=		np.stack(padded_inputs['''input_features''']   ,				axis=0)

             # make sure list is in array format
             _lowerCamelCase				:  Optional[Any]						=		padded_inputs.get('''input_features''').transpose(2   ,				0   ,				1)

             _lowerCamelCase				:  Tuple						=		[self._np_extract_fbank_features(a__) for waveform in input_features[0]]

             if isinstance(input_features[0]   ,				a__):
                    _lowerCamelCase				:  str						=		[np.asarray(a__   ,				dtype=np.floataa) for feature in input_features]
             else:
                    _lowerCamelCase				:  Dict						=		input_features

             if return_attention_mask:
                    # rescale from sample (48000) to feature (3000)
                    _lowerCamelCase				:  Optional[int]						=		padded_inputs['''attention_mask'''][:, :: self.hop_length]

             if return_tensors is not None:
                    _lowerCamelCase				:  str						=		padded_inputs.convert_to_tensors(a__)

             return padded_inputs



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		copy.deepcopy(self.__dict__)
             _lowerCamelCase				:  int						=		self.__class__.__name__
             if "mel_filters" in output:
                    del output["mel_filters"]
             return output

