import math

import tensorflow as tf
from packaging import version




def    lowerCAmelCase_ (     __A							)     ->				Union[str, Any]:







      '''simple docstring'''


      UpperCAmelCase__								=  tf.convert_to_tensor(__A							)
      UpperCAmelCase__								=  0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0							),  x.dtype							)							))

      return x * cdf




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      UpperCAmelCase__								=  tf.convert_to_tensor(__A							)
      UpperCAmelCase__								=  tf.cast(math.pi,  x.dtype							)
      UpperCAmelCase__								=  tf.cast(0.044715,  x.dtype							)
      UpperCAmelCase__								=  0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi							) * (x + coeff * tf.pow(__A,  3							))							))

      return x * cdf




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      UpperCAmelCase__								=  tf.convert_to_tensor(__A							)

      return x * tf.tanh(tf.math.softplus(__A							)							)




def    lowerCAmelCase_ (     __A							)     ->				List[Any]:







      '''simple docstring'''


      UpperCAmelCase__								=  tf.convert_to_tensor(__A							)
      UpperCAmelCase__								=  tf.cast(0.044715,  x.dtype							)
      UpperCAmelCase__								=  tf.cast(0.7978845608,  x.dtype							)

      return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x)							))




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      UpperCAmelCase__								=  tf.convert_to_tensor(__A							)
      UpperCAmelCase__								=  tf.cast(1.702,  x.dtype							)
      return x * tf.math.sigmoid(coeff * x							)




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


      return tf.clip_by_value(_gelu(__A							),  -10,  10							)




def    lowerCAmelCase_ (     __A,  __A=-1							)     ->				Dict:







      '''simple docstring'''


      UpperCAmelCase__		,      UpperCAmelCase__								=  tf.split(__A,  2,  axis=__A							)
      return a * tf.math.sigmoid(__A							)


if version.parse(tf.version.VERSION) >= version.parse('2.4'):




      def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







            '''simple docstring'''


            return tf.keras.activations.gelu(__A,  approximate=__A							)

      UpperCamelCase__											=					tf.keras.activations.gelu







      UpperCamelCase__											=					approximate_gelu_wrap
else:
      UpperCamelCase__											=					_gelu
      UpperCamelCase__											=					_gelu_new


UpperCamelCase__											=					{
    'gelu': gelu,
    'gelu_10': gelu_aa,
    'gelu_fast': gelu_fast,
    'gelu_new': gelu_new,
    'glu': glu,
    'mish': mish,
    'quick_gelu': quick_gelu,
    'relu': tf.keras.activations.relu,
    'sigmoid': tf.keras.activations.sigmoid,
    'silu': tf.keras.activations.swish,
    'swish': tf.keras.activations.swish,
    'tanh': tf.keras.activations.tanh,
}







def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      if activation_string in ACTaFN:
            return ACTaFN[activation_string]
      else:
            raise KeyError(f"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()							)}"""							)




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

import numpy as np

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


UpperCamelCase__											=					logging.get_logger(__name__)





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : int      =			['input_values', 'attention_mask']


   def __init__(self     :						Any       ,  __UpperCAmelCase     :						int = 1       ,  __UpperCAmelCase     :						int = 1_6_0_0_0       ,  __UpperCAmelCase     :						float = 0.0       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						int = 8_0       ,  __UpperCAmelCase     :						int = 1_6       ,  __UpperCAmelCase     :						int = 6_4       ,  __UpperCAmelCase     :						str = "hann_window"       ,  __UpperCAmelCase     :						float = 1.0       ,  __UpperCAmelCase     :						float = 8_0       ,  __UpperCAmelCase     :						float = 7_6_0_0       ,  __UpperCAmelCase     :						float = 1E-10       ,  __UpperCAmelCase     :						int = 2       ,  __UpperCAmelCase     :						bool = True       ,  **__UpperCAmelCase     :						Any       ,  )						->				str:
         """simple docstring"""



         super().__init__(feature_size=__UpperCAmelCase       ,  sampling_rate=__UpperCAmelCase       ,  padding_value=__UpperCAmelCase       ,  **__UpperCAmelCase		)
         UpperCAmelCase__								=  do_normalize
         UpperCAmelCase__								=  return_attention_mask

         UpperCAmelCase__								=  num_mel_bins
         UpperCAmelCase__								=  hop_length
         UpperCAmelCase__								=  win_length
         UpperCAmelCase__								=  win_function
         UpperCAmelCase__								=  frame_signal_scale
         UpperCAmelCase__								=  fmin
         UpperCAmelCase__								=  fmax
         UpperCAmelCase__								=  mel_floor
         UpperCAmelCase__								=  reduction_factor

         UpperCAmelCase__								=  win_length * sampling_rate // 1_0_0_0
         UpperCAmelCase__								=  hop_length * sampling_rate // 1_0_0_0
         UpperCAmelCase__								=  optimal_fft_length(self.sample_size		)
         UpperCAmelCase__								=  (self.n_fft // 2) + 1

         UpperCAmelCase__								=  window_function(window_length=self.sample_size       ,  name=self.win_function       ,  periodic=__UpperCAmelCase		)

         UpperCAmelCase__								=  mel_filter_bank(
             num_frequency_bins=self.n_freqs       ,  num_mel_filters=self.num_mel_bins       ,  min_frequency=self.fmin       ,  max_frequency=self.fmax       ,  sampling_rate=self.sampling_rate       ,  norm="slaney"       ,  mel_scale="slaney"       ,  )

         if frame_signal_scale != 1.0:
               warnings.warn(
                   "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers"       ,  __UpperCAmelCase       ,  )
         if reduction_factor != 2.0:
               warnings.warn(
                   "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"       ,  __UpperCAmelCase       ,  )


   @staticmethod
   # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
   def 			lowercase_      (__UpperCAmelCase     :						List[np.ndarray]       ,  __UpperCAmelCase     :						List[np.ndarray]       ,  __UpperCAmelCase     :						float = 0.0		)						->				List[np.ndarray]:
         """simple docstring"""



         if attention_mask is not None:
               UpperCAmelCase__								=  np.array(__UpperCAmelCase       ,  np.intaa		)
               UpperCAmelCase__								=  []

               for vector, length in zip(__UpperCAmelCase       ,  attention_mask.sum(-1		)		):
                     UpperCAmelCase__								=  (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7		)
                     if length < normed_slice.shape[0]:
                           UpperCAmelCase__								=  padding_value

                     normed_input_values.append(__UpperCAmelCase		)
         else:
               UpperCAmelCase__								=  [(x - x.mean()) / np.sqrt(x.var() + 1E-7		) for x in input_values]

         return normed_input_values


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						np.ndarray       ,  )						->				np.ndarray:
         """simple docstring"""



         UpperCAmelCase__								=  spectrogram(
             __UpperCAmelCase       ,  window=self.window       ,  frame_length=self.sample_size       ,  hop_length=self.sample_stride       ,  fft_length=self.n_fft       ,  mel_filters=self.mel_filters       ,  mel_floor=self.mel_floor       ,  log_mel="log10"       ,  )
         return log_mel_spec.T


   def __call__(self     :						Any       ,  __UpperCAmelCase     :						Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None       ,  __UpperCAmelCase     :						Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None       ,  __UpperCAmelCase     :						Union[bool, str, PaddingStrategy] = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						Optional[bool] = None       ,  __UpperCAmelCase     :						Optional[Union[str, TensorType]] = None       ,  __UpperCAmelCase     :						Optional[int] = None       ,  **__UpperCAmelCase     :						str       ,  )						->				BatchFeature:
         """simple docstring"""



         if audio is None and audio_target is None:
               raise ValueError("You must provide either `audio` or `audio_target` values."		)

         if sampling_rate is not None:
               if sampling_rate != self.sampling_rate:
                     raise ValueError(
                         f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of"""
                         f""" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"""
                         f""" {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."		)

         if audio is not None:
               UpperCAmelCase__								=  self._process_audio(
                   __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  **__UpperCAmelCase       ,  )
         else:
               UpperCAmelCase__								=  None

         if audio_target is not None:
               UpperCAmelCase__								=  self._process_audio(
                   __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  **__UpperCAmelCase       ,  )

               if inputs is None:
                     return inputs_target
               else:
                     UpperCAmelCase__								=  inputs_target["input_values"]
                     UpperCAmelCase__								=  inputs_target.get("attention_mask"		)
                     if decoder_attention_mask is not None:
                           UpperCAmelCase__								=  decoder_attention_mask

         return inputs


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Union[bool, str, PaddingStrategy] = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						Optional[bool] = None       ,  __UpperCAmelCase     :						Optional[Union[str, TensorType]] = None       ,  **__UpperCAmelCase     :						Any       ,  )						->				BatchFeature:
         """simple docstring"""



         UpperCAmelCase__								=  isinstance(__UpperCAmelCase       ,  np.ndarray		) and len(speech.shape		) > 1
         if is_batched_numpy and len(speech.shape		) > 2:
               raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""		)
         UpperCAmelCase__								=  is_batched_numpy or (
             isinstance(__UpperCAmelCase       ,  (list, tuple)		) and (isinstance(speech[0]       ,  (np.ndarray, tuple, list)		))
         )

         if is_batched:
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		) for speech in speech]
         elif not is_batched and not isinstance(__UpperCAmelCase       ,  np.ndarray		):
               UpperCAmelCase__								=  np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		)
         elif isinstance(__UpperCAmelCase       ,  np.ndarray		) and speech.dtype is np.dtype(np.floataa		):
               UpperCAmelCase__								=  speech.astype(np.floataa		)

         # always return batch
         if not is_batched:
               UpperCAmelCase__								=  [speech]

         # needed to make pad() work on spectrogram inputs
         UpperCAmelCase__								=  self.feature_size

         # convert into correct format for padding
         if is_target:
               UpperCAmelCase__								=  [self._extract_mel_features(__UpperCAmelCase		) for waveform in speech]
               UpperCAmelCase__								=  BatchFeature({"input_values": features}		)
               UpperCAmelCase__								=  self.num_mel_bins
         else:
               UpperCAmelCase__								=  BatchFeature({"input_values": speech}		)

         UpperCAmelCase__								=  self.pad(
             __UpperCAmelCase       ,  padding=__UpperCAmelCase       ,  max_length=__UpperCAmelCase       ,  truncation=__UpperCAmelCase       ,  pad_to_multiple_of=__UpperCAmelCase       ,  return_attention_mask=__UpperCAmelCase       ,  **__UpperCAmelCase       ,  )

         UpperCAmelCase__								=  feature_size_hack

         # convert input values to correct format
         UpperCAmelCase__								=  padded_inputs["input_values"]
         if not isinstance(input_values[0]       ,  np.ndarray		):
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		) for array in input_values]
         elif (
             not isinstance(__UpperCAmelCase       ,  np.ndarray		)
             and isinstance(input_values[0]       ,  np.ndarray		)
             and input_values[0].dtype is np.dtype(np.floataa		)
         ):
               UpperCAmelCase__								=  [array.astype(np.floataa		) for array in input_values]
         elif isinstance(__UpperCAmelCase       ,  np.ndarray		) and input_values.dtype is np.dtype(np.floataa		):
               UpperCAmelCase__								=  input_values.astype(np.floataa		)

         # convert attention_mask to correct format
         UpperCAmelCase__								=  padded_inputs.get("attention_mask"		)
         if attention_mask is not None:
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.intaa		) for array in attention_mask]

         # zero-mean and unit-variance normalization
         if not is_target and self.do_normalize:
               UpperCAmelCase__								=  (
                   attention_mask
                   if self._get_padding_strategies(__UpperCAmelCase       ,  max_length=__UpperCAmelCase		) is not PaddingStrategy.DO_NOT_PAD
                   else None
               )
               UpperCAmelCase__								=  self.zero_mean_unit_var_norm(
                   padded_inputs["input_values"]       ,  attention_mask=__UpperCAmelCase       ,  padding_value=self.padding_value		)

         if return_tensors is not None:
               UpperCAmelCase__								=  padded_inputs.convert_to_tensors(__UpperCAmelCase		)

         return padded_inputs





   def 			lowercase_      (self     :						Tuple		)						->				Dict[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  super().to_dict()

         # Don't serialize these as they are derived from the other properties.
         UpperCAmelCase__								=  ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"]
         for name in names:
               if name in output:
                     del output[name]

         return output



