





'''simple docstring'''

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


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






class   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							["""input_features""", """attention_mask"""]
 def __init__(							self :Optional[int]		,			lowercase_ :Optional[int]=80		,			lowercase_ :str=1_60_00		,			lowercase_ :Optional[int]=0.0		,			lowercase_ :List[str]=10		,			lowercase_ :List[Any]=25		,			lowercase_ :int="hamming_window"		,			lowercase_ :Optional[Any]=3_2_7_6_8.0		,			lowercase_ :Any=0.9_7		,			lowercase_ :Dict=1.0		,			lowercase_ :Dict=True		,			lowercase_ :Any=True		,			lowercase_ :Optional[Any]=False		,			**lowercase_ :Union[str, Any]		,			)->				Optional[Any]:
     super().__init__(feature_size=lowercase_		,			sampling_rate=lowercase_		,			padding_value=lowercase_		,			**lowercase_				)

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

     A__							=     win_length * sampling_rate // 10_00
     A__							=     hop_length * sampling_rate // 10_00

     A__							=     optimal_fft_length(self.sample_size				)
     A__							=     (self.n_fft // 2) + 1
 def 	UpperCAmelCase_				(							self :List[str]		,			lowercase_ :np.array				)->				np.ndarray:
     if self.win_function == "hamming_window":
         A__							=     window_function(window_length=self.sample_size		,			name=self.win_function		,			periodic=lowercase_				)
     else:
         A__							=     window_function(window_length=self.sample_size		,			name=self.win_function				)

     A__							=     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		,			)

     A__							=     spectrogram(
         one_waveform * self.frame_signal_scale		,			window=lowercase_		,			frame_length=self.sample_size		,			hop_length=self.sample_stride		,			fft_length=self.n_fft		,			center=lowercase_		,			preemphasis=self.preemphasis_coeff		,			mel_filters=lowercase_		,			mel_floor=self.mel_floor		,			log_mel="log"		,			)
     return msfc_features.T
 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :str		,			lowercase_ :int		,			lowercase_ :List[Any]				)->				Dict:
     # make sure we normalize float32 arrays
     if self.normalize_means:
         A__							=     x[:input_length].mean(axis=0				)
         A__							=     np.subtract(lowercase_		,			lowercase_				)
     if self.normalize_vars:
         A__							=     x[:input_length].std(axis=0				)
         A__							=     np.divide(lowercase_		,			lowercase_				)

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

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

     return x
 def 	UpperCAmelCase_				(							self :Optional[int]		,			lowercase_ :List[np.ndarray]		,			lowercase_ :Optional[np.ndarray] = None				)->				List[np.ndarray]:
     A__							=     attention_mask.sum(-1				) if attention_mask is not None else [x.shape[0] for x in input_features]
     return [self._normalize_one(lowercase_		,			lowercase_		,			self.padding_value				) for x, n in zip(lowercase_		,			lowercase_				)]



 def __call__(							self :str		,			lowercase_ :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]		,			lowercase_ :Union[bool, str, PaddingStrategy] = False		,			lowercase_ :Optional[int] = None		,			lowercase_ :bool = False		,			lowercase_ :Optional[int] = None		,			lowercase_ :Optional[bool] = None		,			lowercase_ :Optional[Union[str, TensorType]] = None		,			lowercase_ :Optional[int] = None		,			**lowercase_ :str		,			)->				BatchFeature:

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

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

     if is_batched:
         A__							=     [np.asarray(lowercase_		,			dtype=np.floataa				) for speech in raw_speech]
     elif not is_batched and not isinstance(lowercase_		,			np.ndarray				):
         A__							=     np.asarray(lowercase_		,			dtype=np.floataa				)
     elif isinstance(lowercase_		,			np.ndarray				) and raw_speech.dtype is np.dtype(np.floataa				):
         A__							=     raw_speech.astype(np.floataa				)

     # always return batch
     if not is_batched:
         A__							=     [raw_speech]

     # extract fbank features
     A__							=     [self._extract_mfsc_features(lowercase_				) for one_waveform in raw_speech]

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

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

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

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

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

     return padded_inputs










'''simple docstring'''

# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


__lowerCAmelCase				:      Union[str, Any]						      ={"configuration_mra": ["MRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MraConfig"]}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __lowerCAmelCase				:      int						      =[
      "MRA_PRETRAINED_MODEL_ARCHIVE_LIST",
      "MraForMaskedLM",
      "MraForMultipleChoice",
      "MraForQuestionAnswering",
      "MraForSequenceClassification",
      "MraForTokenClassification",
      "MraLayer",
      "MraModel",
      "MraPreTrainedModel",
  ]


if TYPE_CHECKING:
  from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_mra import (
        MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
        MraForMaskedLM,
        MraForMultipleChoice,
        MraForQuestionAnswering,
        MraForSequenceClassification,
        MraForTokenClassification,
        MraLayer,
        MraModel,
        MraPreTrainedModel,
    )
else:
  import sys

  __lowerCAmelCase				:      Dict						      =_LazyModule(__name__, globals()["__file__"], _import_structure)



