





from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


_UpperCAmelCase				       = logging.get_logger(__name__)



class 							_UpperCamelCase    (		lowerCAmelCase_   ):
       _UpperCamelCase :    List[Any]   			=      ['''input_values''', '''attention_mask''']

       def __init__(						self:       Optional[int]    ,      _SCREAMING_SNAKE_CASE:       str=1    ,      _SCREAMING_SNAKE_CASE:       Optional[Any]=16000    ,      _SCREAMING_SNAKE_CASE:       Optional[Any]=128    ,      _SCREAMING_SNAKE_CASE:       Union[str, Any]=1024    ,      _SCREAMING_SNAKE_CASE:       Dict=0.0    ,      _SCREAMING_SNAKE_CASE:       int=True    ,      _SCREAMING_SNAKE_CASE:       int=-4.2_67_73_93    ,      _SCREAMING_SNAKE_CASE:       List[str]=4.5_68_99_74    ,      _SCREAMING_SNAKE_CASE:       List[Any]=False    ,      **_SCREAMING_SNAKE_CASE:       Any    ,      )				->       Tuple:




              """simple docstring"""


              super().__init__(feature_size=_SCREAMING_SNAKE_CASE    ,      sampling_rate=_SCREAMING_SNAKE_CASE    ,      padding_value=_SCREAMING_SNAKE_CASE    ,      **_SCREAMING_SNAKE_CASE						)
              UpperCamelCase_      				=     num_mel_bins
              UpperCamelCase_      				=     max_length
              UpperCamelCase_      				=     do_normalize
              UpperCamelCase_      				=     mean
              UpperCamelCase_      				=     std
              UpperCamelCase_      				=     return_attention_mask

       def lowercase       (						self:       Optional[int]    ,      _SCREAMING_SNAKE_CASE:       np.ndarray    ,      _SCREAMING_SNAKE_CASE:       int    ,      )				->       np.ndarray:




              """simple docstring"""


              UpperCamelCase_      				=     torch.from_numpy(_SCREAMING_SNAKE_CASE						).unsqueeze(0						)
              UpperCamelCase_      				=     ta_kaldi.fbank(
                  _SCREAMING_SNAKE_CASE    ,      htk_compat=_SCREAMING_SNAKE_CASE    ,      sample_frequency=self.sampling_rate    ,      use_energy=_SCREAMING_SNAKE_CASE    ,      window_type="hanning"    ,      num_mel_bins=self.num_mel_bins    ,      dither=0.0    ,      frame_shift=10    ,      )

              UpperCamelCase_      				=     fbank.shape[0]
              UpperCamelCase_      				=     max_length - n_frames

              # pad or truncate, depending on difference
              if difference > 0:
                     UpperCamelCase_      				=     torch.nn.ZeroPadad((0, 0, 0, difference)						)
                     UpperCamelCase_      				=     pad_module(_SCREAMING_SNAKE_CASE						)
              elif difference < 0:
                     UpperCamelCase_      				=     fbank[0:max_length, :]

              UpperCamelCase_      				=     fbank.numpy()

              return fbank

       def lowercase       (						self:       List[Any]    ,      _SCREAMING_SNAKE_CASE:       np.ndarray						)				->       np.ndarray:




              """simple docstring"""


              return (input_values - (self.mean)) / (self.std * 2)



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




              """simple docstring"""


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

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

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

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

              # extract fbank features and pad/truncate to max_length
              UpperCamelCase_      				=     [self._extract_fbank_features(_SCREAMING_SNAKE_CASE    ,      max_length=self.max_length						) for waveform in raw_speech]

              # convert into BatchFeature
              UpperCamelCase_      				=     BatchFeature({"input_values": features}						)

              # make sure list is in array format
              UpperCamelCase_      				=     padded_inputs.get("input_values"						)
              if isinstance(input_values[0]    ,      _SCREAMING_SNAKE_CASE						):
                     UpperCamelCase_      				=     [np.asarray(_SCREAMING_SNAKE_CASE    ,      dtype=np.floataa						) for feature in input_values]

              # normalization
              if self.do_normalize:
                     UpperCamelCase_      				=     [self.normalize(_SCREAMING_SNAKE_CASE						) for feature in input_values]

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

              return padded_inputs








import warnings

from .generation import GenerationMixin



class 							_UpperCamelCase    (		lowerCAmelCase_   ):
       # warning at import time
       warnings.warn(
           '''Importing `GenerationMixin` from `src/transformers/generation_utils.py` is deprecated and will '''
           '''be removed in Transformers v5. Import as `from transformers import GenerationMixin` instead.'''     ,  lowerCAmelCase_     ,  )

