




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


A_      			=       logging.get_logger(__name__)






class       lowercase(  __a				):







 '''simple docstring'''





 lowercase__				      =      ["audio_values", "audio_mask"]


 def __init__(       self:	Dict,   a_:	Tuple=2_048,   a_:	str=1,   a_:	Any=[16, 16],   a_:	str=128,   a_:	int=44_100,   a_:	Optional[Any]=86,   a_:	int=2_048,   a_:	Optional[Any]=0.0,   **a_:	Union[str, Any],   ):




   '''simple docstring'''



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

   _snake_case							:	Optional[int]			=						spectrogram_length
   _snake_case							:	Dict			=						num_channels
   _snake_case							:	int			=						patch_size
   _snake_case							:	Any			=						feature_size // self.patch_size[1]
   _snake_case							:	List[Any]			=						n_fft
   _snake_case							:	List[str]			=						sampling_rate // hop_length_to_sampling_rate
   _snake_case							:	int			=						sampling_rate
   _snake_case							:	Dict			=						padding_value
   _snake_case							:	Optional[int]			=						mel_filter_bank(
       num_frequency_bins=1 + n_fft // 2,   num_mel_filters=a_,   min_frequency=0.0,   max_frequency=22_050.0,   sampling_rate=a_,   norm="""slaney""",   mel_scale="""slaney""",   ).T


 def 				UpperCamelCase_     (       self:	Optional[int],   a_:	np.array	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						spectrogram(
       a_,   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							:	Dict			=						log_spec[:, :-1]
   _snake_case							:	Union[str, Any]			=						log_spec - 20.0
   _snake_case							:	int			=						np.clip(log_spec / 40.0,   -2.0,   0.0	) + 1.0
   return log_spec


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




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

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

   # Create audio attention mask
   _snake_case							:	Any			=						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							:	Any			=						[
         (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							:	Optional[int]			=						np.array(a_	).astype(np.floataa	)

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

   # return as BatchFeature
   if return_attention_mask:
     _snake_case							:	Dict			=						{"""audio_values""": padded_audio_features, """audio_mask""": audio_mask}
   else:
     _snake_case							:	Optional[Any]			=						{"""audio_values""": padded_audio_features}

   _snake_case							:	int			=						BatchFeature(data=a_,   tensor_type=a_	)
   return encoded_inputs








"""simple docstring"""


def       UpperCAmelCase__ (snake_case__							:      int					):
  """simple docstring"""

  if not isinstance(snake_case__	,     snake_case__					) or number < 0:
    raise ValueError("""Input must be a non-negative integer"""					)

  _snake_case							:	Dict			=						0
  while number:
    # This way we arrive at next set bit (next 1) instead of looping
    # through each bit and checking for 1s hence the
    # loop won't run 32 times it will only run the number of `1` times
    number &= number - 1
    count += 1
  return count


if __name__ == "__main__":
     import doctest

     doctest.testmod()


