


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


lowercase				=logging.get_logger(__name__)






class    __magic_name__				(						lowerCAmelCase							):






       def      lowerCAmelCase						(     self    ,				snake_case)		->    int:




          '''simple docstring'''
          if isinstance(snake_case    ,				snake_case):
             _UpperCAmelCase  :  str				       =[label.strip() for label in labels.split(',') if label.strip()]
          return labels






       def __call__(     self    ,				snake_case    ,				snake_case    ,				snake_case)		->    List[Any]:




          '''simple docstring'''
          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):
             _UpperCAmelCase  :  Any				       =[sequences]

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

          return sequence_pairs, sequences






@add_end_docstrings(lowerCAmelCase							)
class    __magic_name__				(						lowerCAmelCase							):






       def __init__(     self    ,				snake_case=ZeroShotClassificationArgumentHandler()    ,				*snake_case    ,				**snake_case)		->    Union[str, Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  Any				       =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      lowerCAmelCase						(     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      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case=True    ,				snake_case=True    ,				snake_case=TruncationStrategy.ONLY_FIRST    ,				**snake_case)		->    List[str]:




          '''simple docstring'''
          _UpperCAmelCase  :  List[str]				       =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  :  Optional[int]				       =self.tokenizer.eos_token
          try:
             _UpperCAmelCase  :  Optional[Any]				       =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.

                _UpperCAmelCase  :  Dict				       =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      lowerCAmelCase						(     self    ,				**snake_case)		->    Any:




          '''simple docstring'''
          if kwargs.get('multi_class'    ,				snake_case) is not None:
             _UpperCAmelCase  :  Tuple				       =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  :  Optional[int]				       ={}
          if "candidate_labels" in kwargs:
             _UpperCAmelCase  :  Dict				       =self._args_parser._parse_labels(kwargs['candidate_labels'])
          if "hypothesis_template" in kwargs:
             _UpperCAmelCase  :  Optional[Any]				       =kwargs['hypothesis_template']

          _UpperCAmelCase  :  List[str]				       ={}
          if "multi_label" in kwargs:
             _UpperCAmelCase  :  Dict				       =kwargs['multi_label']
          return preprocess_params, {}, postprocess_params






       def __call__(     self    ,				snake_case    ,				*snake_case    ,				**snake_case    ,				)		->    Any:




          '''simple docstring'''
          if len(snake_case) == 0:
             pass
          elif len(snake_case) == 1 and "candidate_labels" not in kwargs:
             _UpperCAmelCase  :  Optional[int]				       =args[0]
          else:
             raise ValueError(f"Unable to understand extra arguments {args}")

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






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




          '''simple docstring'''
          _UpperCAmelCase       ,			_UpperCAmelCase  :  Tuple				       =self._args_parser(snake_case    ,				snake_case    ,				snake_case)

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

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






       def      lowerCAmelCase						(     self    ,				snake_case)		->    Optional[Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  Dict				       =inputs['candidate_label']
          _UpperCAmelCase  :  List[Any]				       =inputs['sequence']
          _UpperCAmelCase  :  Optional[Any]				       ={k: inputs[k] for k in self.tokenizer.model_input_names}
          _UpperCAmelCase  :  int				       =self.model(**snake_case)

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






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case=False)		->    Tuple:




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

          _UpperCAmelCase  :  Dict				       =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 math import ceil
from typing import List, Optional, Union

import numpy as np

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


lowercase				=logging.get_logger(__name__)






class    __magic_name__				(						lowerCAmelCase							):
       UpperCAmelCase		 =["audio_values", "audio_mask"]






       def __init__(     self    ,				snake_case=2_0_4_8    ,				snake_case=1    ,				snake_case=[1_6, 1_6]    ,				snake_case=1_2_8    ,				snake_case=4_4_1_0_0    ,				snake_case=8_6    ,				snake_case=2_0_4_8    ,				snake_case=0.0    ,				**snake_case    ,				)		->    Optional[int]:




          '''simple docstring'''
          super().__init__(
              feature_size=snake_case    ,				sampling_rate=snake_case    ,				padding_value=snake_case    ,				**snake_case    ,				)

          _UpperCAmelCase  :  Dict				       =spectrogram_length
          _UpperCAmelCase  :  Any				       =num_channels
          _UpperCAmelCase  :  Optional[int]				       =patch_size
          _UpperCAmelCase  :  List[str]				       =feature_size // self.patch_size[1]
          _UpperCAmelCase  :  Optional[int]				       =n_fft
          _UpperCAmelCase  :  int				       =sampling_rate // hop_length_to_sampling_rate
          _UpperCAmelCase  :  int				       =sampling_rate
          _UpperCAmelCase  :  List[Any]				       =padding_value
          _UpperCAmelCase  :  Optional[int]				       =mel_filter_bank(
              num_frequency_bins=1 + n_fft // 2    ,				num_mel_filters=snake_case    ,				min_frequency=0.0    ,				max_frequency=2_20_50.0    ,				sampling_rate=snake_case    ,				norm='slaney'    ,				mel_scale='slaney'    ,				).T






       def      lowerCAmelCase						(     self    ,				snake_case)		->    np.ndarray:




          '''simple docstring'''
          _UpperCAmelCase  :  Any				       =spectrogram(
              snake_case    ,				window_function(self.n_fft    ,				'hann')    ,				frame_length=self.n_fft    ,				hop_length=self.hop_length    ,				power=2.0    ,				mel_filters=self.mel_filters.T    ,				log_mel='dB'    ,				db_range=80.0    ,				)
          _UpperCAmelCase  :  Any				       =log_spec[:, :-1]
          _UpperCAmelCase  :  List[str]				       =log_spec - 20.0
          _UpperCAmelCase  :  Union[str, Any]				       =np.clip(log_spec / 40.0    ,				-2.0    ,				0.0) + 1.0
          return log_spec






       def __call__(     self    ,				snake_case    ,				snake_case = None    ,				snake_case = True    ,				snake_case = None    ,				snake_case = False    ,				snake_case = False    ,				**snake_case    ,				)		->    BatchFeature:




          '''simple docstring'''

          if sampling_rate is not None:
             if sampling_rate != self.sampling_rate:
                raise ValueError(
                    'This feature extractor is set to support sampling rate'
                    f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"
                    f" 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.')

          _UpperCAmelCase  :  Tuple				       =isinstance(snake_case    ,				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}")
          _UpperCAmelCase  :  str				       =is_batched_numpy or (
              isinstance(snake_case    ,				(list, tuple)) and (isinstance(raw_speech[0]    ,				(np.ndarray, tuple, list)))
          )
          if is_batched:
             _UpperCAmelCase  :  List[str]				       =[np.asarray([speech]    ,				dtype=np.floataa).T for speech in raw_speech]
          elif not is_batched and not isinstance(snake_case    ,				np.ndarray):
             _UpperCAmelCase  :  List[Any]				       =np.asarray(snake_case    ,				dtype=np.floataa)
          elif isinstance(snake_case    ,				np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
             _UpperCAmelCase  :  List[Any]				       =raw_speech.astype(np.floataa)
          # always return batch
          if not is_batched:
             _UpperCAmelCase  :  Dict				       =[np.asarray([raw_speech]).T]

          # Convert audio signals to log mel spectrograms, truncate by time axis
          _UpperCAmelCase  :  List[Any]				       =[
              self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech
          ]
          if isinstance(audio_features[0]    ,				snake_case):
             _UpperCAmelCase  :  Dict				       =[np.asarray(snake_case    ,				dtype=np.floataa) for feature in audio_features]

          # Create audio attention mask
          _UpperCAmelCase  :  Tuple				       =max(
              [ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features])  # The maximum number of audio patches in a batch
          if return_attention_mask:
             _UpperCAmelCase  :  Any				       =[
                 (ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1]
                 + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0]
                 for feature in audio_features
             ]
             _UpperCAmelCase  :  int				       =np.array(snake_case).astype(np.floataa)

          # convert into correct format for padding
          _UpperCAmelCase  :  List[Any]				       =max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
          _UpperCAmelCase  :  List[str]				       =np.ones([len(snake_case), 1, max_time_len, self.feature_size]).astype(np.floataa)
          _UpperCAmelCase  :  Any				       =padded_audio_features * self.padding_value
          for i in range(len(snake_case)):
             _UpperCAmelCase  :  List[str]				       =audio_features[i]
             _UpperCAmelCase  :  Dict				       =feature

          # return as BatchFeature
          if return_attention_mask:
             _UpperCAmelCase  :  List[str]				       ={'audio_values': padded_audio_features, 'audio_mask': audio_mask}
          else:
             _UpperCAmelCase  :  Optional[int]				       ={'audio_values': padded_audio_features}

          _UpperCAmelCase  :  Any				       =BatchFeature(data=snake_case    ,				tensor_type=snake_case)
          return encoded_inputs

