





from typing import List, Optional, Union

import numpy as np

from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


_a				:	Optional[Any]           =       logging.get_logger(__name__)




class 							UpperCamelCase_							(       _a		):







 """simple docstring"""

 A			 =       ["input_features", "attention_mask"]


 def __init__(   self  ,				UpperCAmelCase=8_0  ,				UpperCAmelCase=1_6_0_0_0  ,				UpperCAmelCase=0.0  ,				UpperCAmelCase=1_0  ,				UpperCAmelCase=2_5  ,				UpperCAmelCase="hamming_window"  ,				UpperCAmelCase=3_2_7_6_8.0  ,				UpperCAmelCase=0.97  ,				UpperCAmelCase=1.0  ,				UpperCAmelCase=True  ,				UpperCAmelCase=True  ,				UpperCAmelCase=False  ,				**UpperCAmelCase  ,				):
       super().__init__(feature_size=__lowerCamelCase  ,				sampling_rate=__lowerCamelCase  ,				padding_value=__lowerCamelCase  ,				**__lowerCamelCase							)

       __lowerCamelCase				   =       feature_size
       __lowerCamelCase				   =       sampling_rate
       __lowerCamelCase				   =       padding_value
       __lowerCamelCase				   =       hop_length
       __lowerCamelCase				   =       win_length
       __lowerCamelCase				   =       frame_signal_scale
       __lowerCamelCase				   =       preemphasis_coeff
       __lowerCamelCase				   =       mel_floor
       __lowerCamelCase				   =       normalize_means
       __lowerCamelCase				   =       normalize_vars
       __lowerCamelCase				   =       win_function
       __lowerCamelCase				   =       return_attention_mask

       __lowerCamelCase				   =       win_length * sampling_rate // 1_0_0_0
       __lowerCamelCase				   =       hop_length * sampling_rate // 1_0_0_0

       __lowerCamelCase				   =       optimal_fft_length(self.sample_size							)
       __lowerCamelCase				   =       (self.n_fft // 2) + 1


 def 		lowerCamelCase_ (   self  ,				UpperCAmelCase							):
       if self.win_function == "hamming_window":
             __lowerCamelCase				   =       window_function(window_length=self.sample_size  ,				name=self.win_function  ,				periodic=__lowerCamelCase							)
       else:
             __lowerCamelCase				   =       window_function(window_length=self.sample_size  ,				name=self.win_function							)

       __lowerCamelCase				   =       mel_filter_bank(
           num_frequency_bins=self.n_freqs  ,				num_mel_filters=self.feature_size  ,				min_frequency=0.0  ,				max_frequency=self.sampling_rate / 2.0  ,				sampling_rate=self.sampling_rate  ,				)

       __lowerCamelCase				   =       spectrogram(
           one_waveform * self.frame_signal_scale  ,				window=__lowerCamelCase  ,				frame_length=self.sample_size  ,				hop_length=self.sample_stride  ,				fft_length=self.n_fft  ,				center=__lowerCamelCase  ,				preemphasis=self.preemphasis_coeff  ,				mel_filters=__lowerCamelCase  ,				mel_floor=self.mel_floor  ,				log_mel="""log"""  ,				)
       return msfc_features.T


 def 		lowerCamelCase_ (   self  ,				UpperCAmelCase  ,				UpperCAmelCase  ,				UpperCAmelCase							):
       # make sure we normalize float32 arrays
       if self.normalize_means:
             __lowerCamelCase				   =       x[:input_length].mean(axis=0							)
             __lowerCamelCase				   =       np.subtract(__lowerCamelCase  ,				__lowerCamelCase							)
       if self.normalize_vars:
             __lowerCamelCase				   =       x[:input_length].std(axis=0							)
             __lowerCamelCase				   =       np.divide(__lowerCamelCase  ,				__lowerCamelCase							)

       if input_length < x.shape[0]:
             __lowerCamelCase				   =       padding_value

       # make sure array is in float32
       __lowerCamelCase				   =       x.astype(np.floataa							)

       return x


 def 		lowerCamelCase_ (   self  ,				UpperCAmelCase  ,				UpperCAmelCase = None							):
       __lowerCamelCase				   =       attention_mask.sum(-1							) if attention_mask is not None else [x.shape[0] for x in input_features]
       return [self._normalize_one(__lowerCamelCase  ,				__lowerCamelCase  ,				self.padding_value							) for x, n in zip(__lowerCamelCase  ,				__lowerCamelCase							)]



 def __call__(   self  ,				UpperCAmelCase  ,				UpperCAmelCase = False  ,				UpperCAmelCase = None  ,				UpperCAmelCase = False  ,				UpperCAmelCase = None  ,				UpperCAmelCase = None  ,				UpperCAmelCase = None  ,				UpperCAmelCase = None  ,				**UpperCAmelCase  ,				):

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

       if is_batched:
             __lowerCamelCase				   =       [np.asarray(__lowerCamelCase  ,				dtype=np.floataa							) for speech in raw_speech]
       elif not is_batched and not isinstance(__lowerCamelCase  ,				np.ndarray							):
             __lowerCamelCase				   =       np.asarray(__lowerCamelCase  ,				dtype=np.floataa							)
       elif isinstance(__lowerCamelCase  ,				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
       __lowerCamelCase				   =       [self._extract_mfsc_features(__lowerCamelCase							) for one_waveform in raw_speech]

       # convert into correct format for padding
       __lowerCamelCase				   =       BatchFeature({"""input_features""": features}							)

       __lowerCamelCase				   =       self.pad(
           __lowerCamelCase  ,				padding=__lowerCamelCase  ,				max_length=__lowerCamelCase  ,				truncation=__lowerCamelCase  ,				pad_to_multiple_of=__lowerCamelCase  ,				return_attention_mask=__lowerCamelCase  ,				**__lowerCamelCase  ,				)
       # make sure list is in array format
       __lowerCamelCase				   =       padded_inputs.get("""input_features"""							)
       if isinstance(input_features[0]  ,				__lowerCamelCase							):
             __lowerCamelCase				   =       [np.asarray(__lowerCamelCase  ,				dtype=np.floataa							) for feature in input_features]

       __lowerCamelCase				   =       padded_inputs.get("""attention_mask"""							)
       if attention_mask is not None:
             __lowerCamelCase				   =       [np.asarray(__lowerCamelCase  ,				dtype=np.intaa							) for array in attention_mask]

       if self.normalize_means or self.normalize_vars:
             __lowerCamelCase				   =       (
                 np.array(__lowerCamelCase  ,				dtype=np.intaa							)
                 if self._get_padding_strategies(__lowerCamelCase  ,				max_length=__lowerCamelCase							) is not PaddingStrategy.DO_NOT_PAD
                 and padding
                 else None
             )
             __lowerCamelCase				   =       self.normalize(
                 padded_inputs["""input_features"""]  ,				attention_mask=__lowerCamelCase							)

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

       return padded_inputs












from typing import TYPE_CHECKING

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


__magic_name__  :  List[str]					=       {
    """configuration_m2m_100""": ["""M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP""", """M2M100Config""", """M2M100OnnxConfig"""],
    """tokenization_m2m_100""": ["""M2M100Tokenizer"""],
}


try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __magic_name__  :  Union[str, Any]					=       [
          """M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """M2M100ForConditionalGeneration""",
          """M2M100Model""",
          """M2M100PreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig
      from .tokenization_mam_aaa import MaMaaaTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_mam_aaa import (
                M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST,
                MaMaaaForConditionalGeneration,
                MaMaaaModel,
                MaMaaaPreTrainedModel,
            )


else:
      import sys

      __magic_name__  :  List[str]					=       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

