






'''simple docstring'''

from typing import 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 ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


A:      Optional[Any]  				=				logging.get_logger(__name__)






class 							__magic_name__     (	UpperCAmelCase_				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      List[Any]        =  ['input_features', 'attention_mask']
	def __init__(							self  ,      _lowercase=80  ,      _lowercase=1_6000  ,      _lowercase=0.0  ,      _lowercase=10  ,      _lowercase=25  ,      _lowercase="hamming_window"  ,      _lowercase=3_27_68.0  ,      _lowercase=0.97  ,      _lowercase=1.0  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase=False  ,      **_lowercase  ,      )						->  int:
							super().__init__(feature_size=_lowercase  ,      sampling_rate=_lowercase  ,      padding_value=_lowercase  ,      **_lowercase       )

							lowercase_      :   str        =			feature_size
							lowercase_      :   Optional[Any]        =			sampling_rate
							lowercase_      :   str        =			padding_value
							lowercase_      :   Optional[int]        =			hop_length
							lowercase_      :   Optional[int]        =			win_length
							lowercase_      :   Optional[int]        =			frame_signal_scale
							lowercase_      :   List[Any]        =			preemphasis_coeff
							lowercase_      :   str        =			mel_floor
							lowercase_      :   Tuple        =			normalize_means
							lowercase_      :   List[Any]        =			normalize_vars
							lowercase_      :   Optional[int]        =			win_function
							lowercase_      :   List[Any]        =			return_attention_mask

							lowercase_      :   Optional[int]        =			win_length * sampling_rate // 1000
							lowercase_      :   Dict        =			hop_length * sampling_rate // 1000

							lowercase_      :   Union[str, Any]        =			optimal_fft_length(self.sample_size       )
							lowercase_      :   str        =			(self.n_fft // 2) + 1
	def        lowerCamelCase__		(							self  ,      _lowercase       )						->  np.ndarray:
							if self.win_function == "hamming_window":
													lowercase_      :   Any        =			window_function(window_length=self.sample_size  ,      name=self.win_function  ,      periodic=_lowercase       )
							else:
													lowercase_      :   Optional[int]        =			window_function(window_length=self.sample_size  ,      name=self.win_function       )

							lowercase_      :   Union[str, Any]        =			mel_filter_bank(
							    num_frequency_bins=self.n_freqs  ,      num_mel_filters=self.feature_size  ,      min_frequency=0.0  ,      max_frequency=self.sampling_rate / 2.0  ,      sampling_rate=self.sampling_rate  ,      )

							lowercase_      :   List[Any]        =			spectrogram(
							    one_waveform * self.frame_signal_scale  ,      window=_lowercase  ,      frame_length=self.sample_size  ,      hop_length=self.sample_stride  ,      fft_length=self.n_fft  ,      center=_lowercase  ,      preemphasis=self.preemphasis_coeff  ,      mel_filters=_lowercase  ,      mel_floor=self.mel_floor  ,      log_mel='log'  ,      )
							return msfc_features.T
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Optional[int]:
							# make sure we normalize float32 arrays
							if self.normalize_means:
													lowercase_      :   Any        =			x[:input_length].mean(axis=0       )
													lowercase_      :   Optional[Any]        =			np.subtract(_lowercase  ,      _lowercase       )
							if self.normalize_vars:
													lowercase_      :   List[Any]        =			x[:input_length].std(axis=0       )
													lowercase_      :   List[str]        =			np.divide(_lowercase  ,      _lowercase       )

							if input_length < x.shape[0]:
													lowercase_      :   List[Any]        =			padding_value

							# make sure array is in float32
							lowercase_      :   Optional[Any]        =			x.astype(np.floataa       )

							return x
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase = None       )						->  List[np.ndarray]:
							lowercase_      :   List[str]        =			attention_mask.sum(-1       ) if attention_mask is not None else [x.shape[0] for x in input_features]
							return [self._normalize_one(_lowercase  ,      _lowercase  ,      self.padding_value       ) for x, n in zip(_lowercase  ,      _lowercase       )]







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

							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 `raw_speech` 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.'       )

							lowercase_      :   Optional[Any]        =			isinstance(_lowercase  ,      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}"       )
							lowercase_      :   Optional[Any]        =			is_batched_numpy or (
							    isinstance(_lowercase  ,      (list, tuple)       ) and (isinstance(raw_speech[0]  ,      (np.ndarray, tuple, list)       ))
							)

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

							# always return batch
							if not is_batched:
													lowercase_      :   List[Any]        =			[raw_speech]

							# extract fbank features
							lowercase_      :   str        =			[self._extract_mfsc_features(_lowercase       ) for one_waveform in raw_speech]

							# convert into correct format for padding
							lowercase_      :   Any        =			BatchFeature({'input_features': features}       )

							lowercase_      :   Any        =			self.pad(
							    _lowercase  ,      padding=_lowercase  ,      max_length=_lowercase  ,      truncation=_lowercase  ,      pad_to_multiple_of=_lowercase  ,      return_attention_mask=_lowercase  ,      **_lowercase  ,      )
							# make sure list is in array format
							lowercase_      :   str        =			padded_inputs.get('input_features'       )
							if isinstance(input_features[0]  ,      _lowercase       ):
													lowercase_      :   Optional[Any]        =			[np.asarray(_lowercase  ,      dtype=np.floataa       ) for feature in input_features]

							lowercase_      :   str        =			padded_inputs.get('attention_mask'       )
							if attention_mask is not None:
													lowercase_      :   Dict        =			[np.asarray(_lowercase  ,      dtype=np.intaa       ) for array in attention_mask]

							if self.normalize_means or self.normalize_vars:
													lowercase_      :   Optional[int]        =			(
													    np.array(_lowercase  ,      dtype=np.intaa       )
													    if self._get_padding_strategies(_lowercase  ,      max_length=_lowercase       ) is not PaddingStrategy.DO_NOT_PAD
													    and padding
													    else None
													)
													lowercase_      :   Any        =			self.normalize(
													    padded_inputs['input_features']  ,      attention_mask=_lowercase       )

							if return_tensors is not None:
													lowercase_      :   Optional[int]        =			padded_inputs.convert_to_tensors(_lowercase       )

							return padded_inputs








'''simple docstring'''

from ..utils import DummyObject, requires_backends






class 							__magic_name__     (	metaclass=UpperCAmelCase_				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      str        =  ['transformers', 'torch', 'note_seq']
	def __init__(							self  ,      *_lowercase  ,      **_lowercase       )						->  Dict:
							requires_backends(self  ,      ['transformers', 'torch', 'note_seq']       )
	@classmethod
	def        lowerCamelCase__		(							cls  ,      *_lowercase  ,      **_lowercase       )						->  List[str]:
							requires_backends(cls  ,      ['transformers', 'torch', 'note_seq']       )







	@classmethod
	def        lowerCamelCase__		(							cls  ,      *_lowercase  ,      **_lowercase       )						->  Dict:
							requires_backends(cls  ,      ['transformers', 'torch', 'note_seq']       )
