



'''simple docstring'''




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






class 						_UpperCamelCase  (							lowerCamelCase__    ):


			'''simple docstring'''

			_A      :		Tuple			    =		['''input_values''', '''attention_mask''']

			def __init__(							self     : Dict							,     lowerCAmelCase__     : int = 1							,     lowerCAmelCase__     : int = 1_6_0_0_0							,     lowerCAmelCase__     : float = 0.0							,     lowerCAmelCase__     : bool = False							,     lowerCAmelCase__     : int = 8_0							,     lowerCAmelCase__     : int = 1_6							,     lowerCAmelCase__     : int = 6_4							,     lowerCAmelCase__     : str = "hann_window"							,     lowerCAmelCase__     : float = 1.0							,     lowerCAmelCase__     : float = 8_0							,     lowerCAmelCase__     : float = 7_6_0_0							,     lowerCAmelCase__     : float = 1E-10							,     lowerCAmelCase__     : int = 2							,     lowerCAmelCase__     : bool = True							,     **lowerCAmelCase__     : Union[str, Any]							,     ):





					"""simple docstring"""






					super().__init__(feature_size=lowerCAmelCase__							,     sampling_rate=lowerCAmelCase__							,     padding_value=lowerCAmelCase__							,     **lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE       :		str           =		do_normalize
					__SCREAMING_SNAKE_CASE       :		Tuple           =		return_attention_mask

					__SCREAMING_SNAKE_CASE       :		Optional[int]           =		num_mel_bins
					__SCREAMING_SNAKE_CASE       :		Dict           =		hop_length
					__SCREAMING_SNAKE_CASE       :		Optional[int]           =		win_length
					__SCREAMING_SNAKE_CASE       :		Any           =		win_function
					__SCREAMING_SNAKE_CASE       :		List[Any]           =		frame_signal_scale
					__SCREAMING_SNAKE_CASE       :		Tuple           =		fmin
					__SCREAMING_SNAKE_CASE       :		Dict           =		fmax
					__SCREAMING_SNAKE_CASE       :		int           =		mel_floor
					__SCREAMING_SNAKE_CASE       :		str           =		reduction_factor

					__SCREAMING_SNAKE_CASE       :		Optional[Any]           =		win_length * sampling_rate // 1_0_0_0
					__SCREAMING_SNAKE_CASE       :		Tuple           =		hop_length * sampling_rate // 1_0_0_0
					__SCREAMING_SNAKE_CASE       :		Union[str, Any]           =		optimal_fft_length(self.sample_size						)
					__SCREAMING_SNAKE_CASE       :		List[str]           =		(self.n_fft // 2) + 1

					__SCREAMING_SNAKE_CASE       :		Tuple           =		window_function(window_length=self.sample_size							,     name=self.win_function							,     periodic=lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE       :		Optional[int]           =		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"""							,     lowerCAmelCase__							,     )
					if reduction_factor != 2.0:
							warnings.warn(
							    """The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"""							,     lowerCAmelCase__							,     )

			@staticmethod
			# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
			def UpperCamelCase__					(							lowerCAmelCase__     : List[np.ndarray]							,     lowerCAmelCase__     : List[np.ndarray]							,     lowerCAmelCase__     : float = 0.0						):





					"""simple docstring"""






					if attention_mask is not None:
							__SCREAMING_SNAKE_CASE       :		str           =		np.array(lowerCAmelCase__							,     np.intaa						)
							__SCREAMING_SNAKE_CASE       :		List[Any]           =		[]

							for vector, length in zip(lowerCAmelCase__							,     attention_mask.sum(-1						)						):
									__SCREAMING_SNAKE_CASE       :		Union[str, Any]           =		(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7						)
									if length < normed_slice.shape[0]:
											__SCREAMING_SNAKE_CASE       :		Tuple           =		padding_value

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

					return normed_input_values

			def UpperCamelCase__					(							self     : Optional[Any]							,     lowerCAmelCase__     : np.ndarray							,     ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE       :		Tuple           =		spectrogram(
					    lowerCAmelCase__							,     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     : Tuple							,     lowerCAmelCase__     : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None							,     lowerCAmelCase__     : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None							,     lowerCAmelCase__     : Union[bool, str, PaddingStrategy] = False							,     lowerCAmelCase__     : Optional[int] = None							,     lowerCAmelCase__     : bool = False							,     lowerCAmelCase__     : Optional[int] = None							,     lowerCAmelCase__     : Optional[bool] = None							,     lowerCAmelCase__     : Optional[Union[str, TensorType]] = None							,     lowerCAmelCase__     : Optional[int] = None							,     **lowerCAmelCase__     : str							,     ):





					"""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:
							__SCREAMING_SNAKE_CASE       :		Union[str, Any]           =		self._process_audio(
							    lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     **lowerCAmelCase__							,     )
					else:
							__SCREAMING_SNAKE_CASE       :		Optional[int]           =		None

					if audio_target is not None:
							__SCREAMING_SNAKE_CASE       :		Union[str, Any]           =		self._process_audio(
							    lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     lowerCAmelCase__							,     **lowerCAmelCase__							,     )

							if inputs is None:
									return inputs_target
							else:
									__SCREAMING_SNAKE_CASE       :		Optional[Any]           =		inputs_target["""input_values"""]
									__SCREAMING_SNAKE_CASE       :		List[Any]           =		inputs_target.get("""attention_mask"""						)
									if decoder_attention_mask is not None:
											__SCREAMING_SNAKE_CASE       :		List[str]           =		decoder_attention_mask

					return inputs

			def UpperCamelCase__					(							self     : Union[str, Any]							,     lowerCAmelCase__     : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]							,     lowerCAmelCase__     : bool = False							,     lowerCAmelCase__     : Union[bool, str, PaddingStrategy] = False							,     lowerCAmelCase__     : Optional[int] = None							,     lowerCAmelCase__     : bool = False							,     lowerCAmelCase__     : Optional[int] = None							,     lowerCAmelCase__     : Optional[bool] = None							,     lowerCAmelCase__     : Optional[Union[str, TensorType]] = None							,     **lowerCAmelCase__     : int							,     ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE       :		Dict           =		isinstance(lowerCAmelCase__							,     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}"						)
					__SCREAMING_SNAKE_CASE       :		List[Any]           =		is_batched_numpy or (
					    isinstance(lowerCAmelCase__							,     (list, tuple)						) and (isinstance(speech[0]							,     (np.ndarray, tuple, list)						))
					)

					if is_batched:
							__SCREAMING_SNAKE_CASE       :		List[Any]           =		[np.asarray(lowerCAmelCase__							,     dtype=np.floataa						) for speech in speech]
					elif not is_batched and not isinstance(lowerCAmelCase__							,     np.ndarray						):
							__SCREAMING_SNAKE_CASE       :		List[str]           =		np.asarray(lowerCAmelCase__							,     dtype=np.floataa						)
					elif isinstance(lowerCAmelCase__							,     np.ndarray						) and speech.dtype is np.dtype(np.floataa						):
							__SCREAMING_SNAKE_CASE       :		Union[str, Any]           =		speech.astype(np.floataa						)

					# always return batch
					if not is_batched:
							__SCREAMING_SNAKE_CASE       :		Union[str, Any]           =		[speech]

					# needed to make pad() work on spectrogram inputs
					__SCREAMING_SNAKE_CASE       :		Optional[int]           =		self.feature_size

					# convert into correct format for padding
					if is_target:
							__SCREAMING_SNAKE_CASE       :		Optional[Any]           =		[self._extract_mel_features(lowerCAmelCase__						) for waveform in speech]
							__SCREAMING_SNAKE_CASE       :		str           =		BatchFeature({"""input_values""": features}						)
							__SCREAMING_SNAKE_CASE       :		Optional[int]           =		self.num_mel_bins
					else:
							__SCREAMING_SNAKE_CASE       :		Optional[Any]           =		BatchFeature({"""input_values""": speech}						)

					__SCREAMING_SNAKE_CASE       :		List[str]           =		self.pad(
					    lowerCAmelCase__							,     padding=lowerCAmelCase__							,     max_length=lowerCAmelCase__							,     truncation=lowerCAmelCase__							,     pad_to_multiple_of=lowerCAmelCase__							,     return_attention_mask=lowerCAmelCase__							,     **lowerCAmelCase__							,     )

					__SCREAMING_SNAKE_CASE       :		str           =		feature_size_hack

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

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

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

					if return_tensors is not None:
							__SCREAMING_SNAKE_CASE       :		Optional[Any]           =		padded_inputs.convert_to_tensors(lowerCAmelCase__						)

					return padded_inputs



			def UpperCamelCase__					(							self     : List[str]						):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE       :		List[str]           =		super().to_dict()

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

					return output




'''simple docstring'''




def 				lowerCAmelCase_   (	_lowerCamelCase:   int					):
		assert (
		    isinstance(_lowerCamelCase       ,      _lowerCamelCase					) and number_of_steps > 0
		), F"number_of_steps needs to be positive integer, your input {number_of_steps}"
		if number_of_steps == 1:
				return 1
		__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       :		Dict           =		1, 1
		for _ in range(number_of_steps - 1					):
				__SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       :		Tuple           =		current + previous, current
		return current


if __name__ == "__main__":
						import doctest

						doctest.testmod()