


'''simple docstring'''



from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


__lowercase			:		Optional[int] =			logging.get_logger(__name__)





class 							__UpperCamelCase       (	lowerCAmelCase_      ):
	A_			    =					["input_values", "attention_mask"]




	def __init__(     self		,       __a=1		,       __a=1_6000		,       __a=128		,       __a=1024		,       __a=0.0		,       __a=True		,       __a=-4.2677393		,       __a=4.5689974		,       __a=False		,       **__a		,       ):

						'''simple docstring'''





						super().__init__(feature_size=__a		,       sampling_rate=__a		,       padding_value=__a		,       **__a							)
						__a    : List[str]      					=						num_mel_bins
						__a    : Dict      					=						max_length
						__a    : Tuple      					=						do_normalize
						__a    : Optional[Any]      					=						mean
						__a    : Any      					=						std
						__a    : Optional[int]      					=						return_attention_mask




	def    __UpperCAmelCase							(     self		,       __a		,       __a		,       ):

						'''simple docstring'''





						__a    : Optional[int]      					=						torch.from_numpy(__a							).unsqueeze(0							)
						__a    : List[str]      					=						ta_kaldi.fbank(
						    __a		,       htk_compat=__a		,       sample_frequency=self.sampling_rate		,       use_energy=__a		,       window_type='hanning'		,       num_mel_bins=self.num_mel_bins		,       dither=0.0		,       frame_shift=10		,       )

						__a    : List[str]      					=						fbank.shape[0]
						__a    : Union[str, Any]      					=						max_length - n_frames

						# pad or truncate, depending on difference
						if difference > 0:
											__a    : List[Any]      					=						torch.nn.ZeroPadad((0, 0, 0, difference)							)
											__a    : Optional[Any]      					=						pad_module(__a							)
						elif difference < 0:
											__a    : Optional[Any]      					=						fbank[0:max_length, :]

						__a    : Tuple      					=						fbank.numpy()

						return fbank




	def    __UpperCAmelCase							(     self		,       __a							):

						'''simple docstring'''





						return (input_values - (self.mean)) / (self.std * 2)





	def __call__(     self		,       __a		,       __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} 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.'							)

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

						if is_batched:
											__a    : Union[str, Any]      					=						[np.asarray(__a		,       dtype=np.floataa							) for speech in raw_speech]
						elif not is_batched and not isinstance(__a		,       np.ndarray							):
											__a    : Optional[int]      					=						np.asarray(__a		,       dtype=np.floataa							)
						elif isinstance(__a		,       np.ndarray							) and raw_speech.dtype is np.dtype(np.floataa							):
											__a    : str      					=						raw_speech.astype(np.floataa							)

						# always return batch
						if not is_batched:
											__a    : List[str]      					=						[raw_speech]

						# extract fbank features and pad/truncate to max_length
						__a    : Tuple      					=						[self._extract_fbank_features(__a		,       max_length=self.max_length							) for waveform in raw_speech]

						# convert into BatchFeature
						__a    : Tuple      					=						BatchFeature({'input_values': features}							)

						# make sure list is in array format
						__a    : Optional[Any]      					=						padded_inputs.get('input_values'							)
						if isinstance(input_values[0]		,       __a							):
											__a    : Union[str, Any]      					=						[np.asarray(__a		,       dtype=np.floataa							) for feature in input_values]

						# normalization
						if self.do_normalize:
											__a    : int      					=						[self.normalize(__a							) for feature in input_values]

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

						return padded_inputs







'''simple docstring'''



def 						lowerCamelCase							(_SCREAMING_SNAKE_CASE   :     set		,   _SCREAMING_SNAKE_CASE   :     set     ):
					assert isinstance(_SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE     ), F"""The input value of [set_a={set_a}] is not a set"""
					assert isinstance(_SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE     ), F"""The input value of [set_b={set_b}] is not a set"""

					return {a + b for a in set_a for b in set_b}


if __name__ == "__main__":
	from doctest import testmod

	testmod()



