



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


_lowerCAmelCase      						=	logging.get_logger(__name__)






class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  __lowercase							:      List[str]				=      ['''audio_values''', '''audio_mask''']




  def __init__(    self  ,__UpperCAmelCase=2048  ,__UpperCAmelCase=1  ,__UpperCAmelCase=[16, 16]  ,__UpperCAmelCase=128  ,__UpperCAmelCase=4_4100  ,__UpperCAmelCase=86  ,__UpperCAmelCase=2048  ,__UpperCAmelCase=0.0  ,**__UpperCAmelCase  ,)    ->		Dict:
      super().__init__(
          feature_size=__UpperCAmelCase  ,sampling_rate=__UpperCAmelCase  ,padding_value=__UpperCAmelCase  ,**__UpperCAmelCase  ,)

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




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		np.ndarray:
      lowerCAmelCase__ :  str							      =					spectrogram(
          __UpperCAmelCase  ,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=8_0.0  ,)
      lowerCAmelCase__ :  List[Any]							      =					log_spec[:, :-1]
      lowerCAmelCase__ :  Any							      =					log_spec - 2_0.0
      lowerCAmelCase__ :  Dict							      =					np.clip(log_spec / 4_0.0  ,-2.0  ,0.0      ) + 1.0
      return log_spec






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

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

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

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

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

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

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

      lowerCAmelCase__ :  Optional[int]							      =					BatchFeature(data=__UpperCAmelCase  ,tensor_type=__UpperCAmelCase      )
      return encoded_inputs







'''simple docstring'''





from maths.prime_factors import prime_factors
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    if not isinstance(UpperCamelCase							,    UpperCamelCase			):
        lowerCAmelCase__ :  int							      =					f"""Input value of [number={number}] must be an integer"""
        raise TypeError(UpperCamelCase			)
    if number < 1:
        raise ValueError("""Input must be a positive integer"""			)
    return -1 if len(prime_factors(UpperCamelCase			)			) % 2 else 1


if __name__ == "__main__":
 import doctest

 doctest.testmod()


