




'''simple docstring'''



from math import ceil
from typing import List, Optional, Union

import numpy as np

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


UpperCAmelCase_							:	Tuple	     =		logging.get_logger(__name__)





class      lowerCAmelCase (			__lowerCAmelCase):
       __lowercase	:   Any										=      ['''audio_values''', '''audio_mask''']


       def __init__( self     ,	__SCREAMING_SNAKE_CASE=2048     ,	__SCREAMING_SNAKE_CASE=1     ,	__SCREAMING_SNAKE_CASE=[16, 16]     ,	__SCREAMING_SNAKE_CASE=128     ,	__SCREAMING_SNAKE_CASE=4_4100     ,	__SCREAMING_SNAKE_CASE=86     ,	__SCREAMING_SNAKE_CASE=2048     ,	__SCREAMING_SNAKE_CASE=0.0     ,	**__SCREAMING_SNAKE_CASE     ,	)   ->	Optional[int]:



            '''simple docstring'''




            super().__init__(
                feature_size=__SCREAMING_SNAKE_CASE     ,	sampling_rate=__SCREAMING_SNAKE_CASE     ,	padding_value=__SCREAMING_SNAKE_CASE     ,	**__SCREAMING_SNAKE_CASE     ,	)

            __snake_case            =	spectrogram_length
            __snake_case            =	num_channels
            __snake_case            =	patch_size
            __snake_case            =	feature_size // self.patch_size[1]
            __snake_case            =	n_fft
            __snake_case            =	sampling_rate // hop_length_to_sampling_rate
            __snake_case            =	sampling_rate
            __snake_case            =	padding_value
            __snake_case            =	mel_filter_bank(
                num_frequency_bins=1 + n_fft // 2     ,	num_mel_filters=__SCREAMING_SNAKE_CASE     ,	min_frequency=0.0     ,	max_frequency=22_050.0     ,	sampling_rate=__SCREAMING_SNAKE_CASE     ,	norm='''slaney'''     ,	mel_scale='''slaney'''     ,	).T


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE	)   ->	np.ndarray:



            '''simple docstring'''




            __snake_case            =	spectrogram(
                __SCREAMING_SNAKE_CASE     ,	window_function(self.n_fft     ,	'''hann'''	)     ,	frame_length=self.n_fft     ,	hop_length=self.hop_length     ,	power=2.0     ,	mel_filters=self.mel_filters.T     ,	log_mel='''dB'''     ,	db_range=80.0     ,	)
            __snake_case            =	log_spec[:, :-1]
            __snake_case            =	log_spec - 20.0
            __snake_case            =	np.clip(log_spec / 40.0     ,	-2.0     ,	0.0	) + 1.0
            return log_spec




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



            '''simple docstring'''




            if sampling_rate is not None:
                 if sampling_rate != self.sampling_rate:
                      raise ValueError(
                          '''This feature extractor is set to support sampling rate'''
                          F''' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled'''
                          F''' with {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.'''	)

            __snake_case            =	isinstance(__SCREAMING_SNAKE_CASE     ,	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}'''	)
            __snake_case            =	is_batched_numpy or (
                isinstance(__SCREAMING_SNAKE_CASE     ,	(list, tuple)	) and (isinstance(raw_speech[0]     ,	(np.ndarray, tuple, list)	))
            )
            if is_batched:
                 __snake_case            =	[np.asarray([speech]     ,	dtype=np.floataa	).T for speech in raw_speech]
            elif not is_batched and not isinstance(__SCREAMING_SNAKE_CASE     ,	np.ndarray	):
                 __snake_case            =	np.asarray(__SCREAMING_SNAKE_CASE     ,	dtype=np.floataa	)
            elif isinstance(__SCREAMING_SNAKE_CASE     ,	np.ndarray	) and raw_speech.dtype is np.dtype(np.floataa	):
                 __snake_case            =	raw_speech.astype(np.floataa	)
            # always return batch
            if not is_batched:
                 __snake_case            =	[np.asarray([raw_speech]	).T]

            # Convert audio signals to log mel spectrograms, truncate by time axis
            __snake_case            =	[
                self._np_extract_fbank_features(waveform.squeeze()	).T[: self.spectrogram_length] for waveform in raw_speech
            ]
            if isinstance(audio_features[0]     ,	__SCREAMING_SNAKE_CASE	):
                 __snake_case            =	[np.asarray(__SCREAMING_SNAKE_CASE     ,	dtype=np.floataa	) for feature in audio_features]

            # Create audio attention mask
            __snake_case            =	max(
                [ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len for feature in audio_features]	)  # The maximum number of audio patches in a batch
            if return_attention_mask:
                 __snake_case            =	[
                     (ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len) * [1]
                     + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len) * [0]
                     for feature in audio_features
                 ]
                 __snake_case            =	np.array(__SCREAMING_SNAKE_CASE	).astype(np.floataa	)

            # convert into correct format for padding
            __snake_case            =	max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
            __snake_case            =	np.ones([len(__SCREAMING_SNAKE_CASE	), 1, max_time_len, self.feature_size]	).astype(np.floataa	)
            __snake_case            =	padded_audio_features * self.padding_value
            for i in range(len(__SCREAMING_SNAKE_CASE	)	):
                 __snake_case            =	audio_features[i]
                 __snake_case            =	feature

            # return as BatchFeature
            if return_attention_mask:
                 __snake_case            =	{'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask}
            else:
                 __snake_case            =	{'''audio_values''': padded_audio_features}

            __snake_case            =	BatchFeature(data=__SCREAMING_SNAKE_CASE     ,	tensor_type=__SCREAMING_SNAKE_CASE	)
            return encoded_inputs












'''simple docstring'''



def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> int:




     '''simple docstring'''





     __snake_case            =	abs(_lowerCamelCase						)
     __snake_case            =	0
     while n > 0:
          res += n % 10
          n //= 10
     return res







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> int:




     '''simple docstring'''





     __snake_case            =	abs(_lowerCamelCase						)
     return n if n < 10 else n % 10 + sum_of_digits(n // 10						)







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> int:




     '''simple docstring'''





     return sum(int(_lowerCamelCase						) for c in str(abs(_lowerCamelCase						)						)						)







def       _UpperCamelCase			()-> None:




     '''simple docstring'''





     from collections.abc import Callable
     from timeit import timeit

     def benchmark_a_function(_lowerCamelCase				:  Callable ,						_lowerCamelCase				:  int						) -> None:
          __snake_case            =	f'''{func.__name__}({value})'''
          __snake_case            =	timeit(f'''__main__.{call}''' ,						setup='''import __main__'''						)
          print(f'''{call:56} = {func(_lowerCamelCase						)} -- {timing:.4f} seconds'''						)

     for value in (26_21_44, 11_25_89_99_06_84_26_24, 1_26_76_50_60_02_28_22_94_01_49_67_03_20_53_76):
          for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
               benchmark_a_function(_lowerCamelCase ,						_lowerCamelCase						)
          print()


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     benchmark()






