





"""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 		__snake_case (		SCREAMING_SNAKE_CASE__					):





 """simple docstring"""


 _lowerCamelCase				=					["""audio_values""", """audio_mask"""]

 def __init__(   self ,						__lowerCamelCase=2048 ,						__lowerCamelCase=1 ,						__lowerCamelCase=[16, 16] ,						__lowerCamelCase=128 ,						__lowerCamelCase=4_4100 ,						__lowerCamelCase=86 ,						__lowerCamelCase=2048 ,						__lowerCamelCase=0.0 ,						**__lowerCamelCase ,						):



     '''simple docstring'''




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

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

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     __A   :						str									=					spectrogram(
         __lowerCamelCase ,						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 ,						)
     __A   :						Optional[int]									=					log_spec[:, :-1]
     __A   :						Union[str, Any]									=					log_spec - 2_0.0
     __A   :						List[str]									=					np.clip(log_spec / 4_0.0 ,						-2.0 ,						0.0  ) + 1.0
     return log_spec







 def __call__(   self ,						__lowerCamelCase ,						__lowerCamelCase = None ,						__lowerCamelCase = True ,						__lowerCamelCase = None ,						__lowerCamelCase = False ,						__lowerCamelCase = False ,						**__lowerCamelCase ,						):



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

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

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

     # Create audio attention mask
     __A   :						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:
         __A   :						List[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
         ]
         __A   :						Dict									=					np.array(__lowerCamelCase  ).astype(np.floataa  )

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

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

     __A   :						Optional[int]									=					BatchFeature(data=__lowerCamelCase ,						tensor_type=__lowerCamelCase  )
     return encoded_inputs











"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


a_			=      {
    """configuration_bloom""": ["""BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BloomConfig""", """BloomOnnxConfig"""],
}
try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a_			=      ["""BloomTokenizerFast"""]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a_			=      [
           """BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST""",
           """BloomForCausalLM""",
           """BloomModel""",
           """BloomPreTrainedModel""",
           """BloomForSequenceClassification""",
           """BloomForTokenClassification""",
           """BloomForQuestionAnswering""",
       ]

if TYPE_CHECKING:
       from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_bloom_fast import BloomTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_bloom import (
                  BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST,
                  BloomForCausalLM,
                  BloomForQuestionAnswering,
                  BloomForSequenceClassification,
                  BloomForTokenClassification,
                  BloomModel,
                  BloomPreTrainedModel,
              )

else:
       import sys

       a_			=      _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




