



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


_UpperCamelCase  						=			logging.get_logger(__name__)

class      lowerCamelCase__     (     _A				):






	'''simple docstring'''

	A__		=	['''input_values''', '''attention_mask''']




	def __init__(  self		:  Optional[int]   ,		__A		:  str=1   ,		__A		:  List[Any]=1_6000   ,		__A		:  List[Any]=128   ,		__A		:  Optional[Any]=1024   ,		__A		:  Union[str, Any]=0.0   ,		__A		:  Optional[Any]=True   ,		__A		:  Tuple=-4.2_6_7_7_3_9_3   ,		__A		:  int=4.5_6_8_9_9_7_4   ,		__A		:  Optional[int]=False   ,		**__A		:  int   ,		)     ->			str:




								'''simple docstring'''





								super().__init__(feature_size=__A   ,		sampling_rate=__A   ,		padding_value=__A   ,		**__A					)
								lowerCAmelCase__  =   num_mel_bins
								lowerCAmelCase__  =   max_length
								lowerCAmelCase__  =   do_normalize
								lowerCAmelCase__  =   mean
								lowerCAmelCase__  =   std
								lowerCAmelCase__  =   return_attention_mask




	def      lowercase__							(  self		:  List[Any]   ,		__A		:  np.ndarray   ,		__A		:  int   ,		)     ->			np.ndarray:




								'''simple docstring'''





								lowerCAmelCase__  =   torch.from_numpy(__A					).unsqueeze(0					)
								lowerCAmelCase__  =   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   ,		)

								lowerCAmelCase__  =   fbank.shape[0]
								lowerCAmelCase__  =   max_length - n_frames

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

								lowerCAmelCase__  =   fbank.numpy()

								return fbank




	def      lowercase__							(  self		:  List[str]   ,		__A		:  np.ndarray					)     ->			np.ndarray:




								'''simple docstring'''





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




	def __call__(  self		:  List[str]   ,		__A		:  Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]   ,		__A		:  Optional[int] = None   ,		__A		:  Optional[Union[str, TensorType]] = None   ,		**__A		:  Optional[int]   ,		)     ->			BatchFeature:




								'''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."""					)

								lowerCAmelCase__  =   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}'''					)
								lowerCAmelCase__  =   is_batched_numpy or (
								    isinstance(__A   ,		(list, tuple)					) and (isinstance(raw_speech[0]   ,		(np.ndarray, tuple, list)					))
								)

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

								# always return batch
								if not is_batched:
															lowerCAmelCase__  =   [raw_speech]

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

								# convert into BatchFeature
								lowerCAmelCase__  =   BatchFeature({"""input_values""": features}					)

								# make sure list is in array format
								lowerCAmelCase__  =   padded_inputs.get("""input_values"""					)
								if isinstance(input_values[0]   ,		__A					):
															lowerCAmelCase__  =   [np.asarray(__A   ,		dtype=np.floataa					) for feature in input_values]

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

								if return_tensors is not None:
															lowerCAmelCase__  =   padded_inputs.convert_to_tensors(__A					)

								return padded_inputs










'''simple docstring'''







def 			_lowerCAmelCase(      UpperCAmelCase_      :	list					, UpperCAmelCase_      :	int					, UpperCAmelCase_      :	int					, UpperCAmelCase_      :	int						) ->							int:
							lowerCAmelCase__  =   int((lower_bound + upper_bound) // 2						)
							if array[r] == value:
														return r
							if lower_bound >= upper_bound:
														return -1
							if array[r] < value:
														return binary_search(UpperCAmelCase_					, r + 1					, UpperCAmelCase_					, UpperCAmelCase_						)
							else:
														return binary_search(UpperCAmelCase_					, UpperCAmelCase_					, r - 1					, UpperCAmelCase_						)
def 			_lowerCAmelCase(      UpperCAmelCase_      :	int					, UpperCAmelCase_      :	list						) ->							list:
							lowerCAmelCase__  =   0
							if matrix[index][0] == value:
														return [index, 0]
							while index < len(UpperCAmelCase_						) and matrix[index][0] < value:
														lowerCAmelCase__  =   binary_search(matrix[index]					, 0					, len(matrix[index]						) - 1					, UpperCAmelCase_						)
														if r != -1:
																					return [index, r]
														index += 1
							return [-1, -1]


if __name__ == "__main__":
		import doctest

		doctest.testmod()





