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


a_     =  logging.get_logger(__name__)






class 				UpperCAmelCase_			(		snake_case__   ):
 UpperCAmelCase_						      =  ["""input_values""", """attention_mask"""]





 def __init__(      self	,    lowercase_=1	,    lowercase_=1_60_00	,    lowercase_=1_28	,    lowercase_=10_24	,    lowercase_=0.0	,    lowercase_=True	,    lowercase_=-4.2_677_393	,    lowercase_=4.5_689_974	,    lowercase_=False	,    **lowercase_	,    ):
     super().__init__(feature_size=lowercase_	,    sampling_rate=lowercase_	,    padding_value=lowercase_	,    **lowercase_)
     snake_case_	:      Optional[int]            =  num_mel_bins
     snake_case_	:      Optional[Any]            =  max_length
     snake_case_	:      str            =  do_normalize
     snake_case_	:      Union[str, Any]            =  mean
     snake_case_	:      Dict            =  std
     snake_case_	:      str            =  return_attention_mask





 def     snake_case__						(      self	,    lowercase_	,    lowercase_	,    ):
     snake_case_	:      int            =  torch.from_numpy(lowercase_).unsqueeze(0)
     snake_case_	:      List[str]            =  ta_kaldi.fbank(
         lowercase_	,    htk_compat=lowercase_	,    sample_frequency=self.sampling_rate	,    use_energy=lowercase_	,    window_type="hanning"	,    num_mel_bins=self.num_mel_bins	,    dither=0.0	,    frame_shift=10	,    )

     snake_case_	:      Optional[Any]            =  fbank.shape[0]
     snake_case_	:      List[Any]            =  max_length - n_frames

     # pad or truncate, depending on difference
     if difference > 0:
         snake_case_	:      Tuple            =  torch.nn.ZeroPadad((0, 0, 0, difference))
         snake_case_	:      List[Any]            =  pad_module(lowercase_)
     elif difference < 0:
         snake_case_	:      Any            =  fbank[0:max_length, :]

     snake_case_	:      Optional[int]            =  fbank.numpy()

     return fbank





 def     snake_case__						(      self	,    lowercase_):
     return (input_values - (self.mean)) / (self.std * 2)





 def __call__(      self	,    lowercase_	,    lowercase_ = None	,    lowercase_ = None	,    **lowercase_	,    ):

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

     snake_case_	:      int            =  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}')
     snake_case_	:      List[Any]            =  is_batched_numpy or (
         isinstance(lowercase_	,    (list, tuple)) and (isinstance(raw_speech[0]	,    (np.ndarray, tuple, list)))
     )

     if is_batched:
         snake_case_	:      str            =  [np.asarray(lowercase_	,    dtype=np.floataa) for speech in raw_speech]
     elif not is_batched and not isinstance(lowercase_	,    np.ndarray):
         snake_case_	:      Optional[int]            =  np.asarray(lowercase_	,    dtype=np.floataa)
     elif isinstance(lowercase_	,    np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
         snake_case_	:      List[Any]            =  raw_speech.astype(np.floataa)

     # always return batch
     if not is_batched:
         snake_case_	:      Union[str, Any]            =  [raw_speech]

     # extract fbank features and pad/truncate to max_length
     snake_case_	:      Optional[int]            =  [self._extract_fbank_features(lowercase_	,    max_length=self.max_length) for waveform in raw_speech]

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

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

     # normalization
     if self.do_normalize:
         snake_case_	:      int            =  [self.normalize(lowercase_) for feature in input_values]

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

     return padded_inputs






'''simple docstring'''
import importlib.metadata
import sys

from transformers.testing_utils import TestCasePlus
from transformers.utils.versions import require_version, require_version_core


a_     =  importlib.metadata.version("numpy")
a_     =  ".".join([str(x) for x in sys.version_info[:3]])






class 				UpperCAmelCase_			(		snake_case__   ):





 def     snake_case__						(      self):
     # lt + different version strings
     require_version_core("numpy<1000.4.5")
     require_version_core("numpy<1000.4")
     require_version_core("numpy<1000")

     # le
     require_version_core("numpy<=1000.4.5")
     require_version_core(F'numpy<={numpy_ver}')

     # eq
     require_version_core(F'numpy=={numpy_ver}')

     # ne
     require_version_core("numpy!=1000.4.5")

     # ge
     require_version_core("numpy>=1.0")
     require_version_core("numpy>=1.0.0")
     require_version_core(F'numpy>={numpy_ver}')

     # gt
     require_version_core("numpy>1.0.0")

     # mix
     require_version_core("numpy>1.0.0,<1000")

     # requirement w/o version
     require_version_core("numpy")

     # unmet requirements due to version conflict
     for req in ["numpy==1.0.0", "numpy>=1000.0.0", F'numpy<{numpy_ver}']:
         try:
             require_version_core(lowercase_)
         except ImportError as e:
             self.assertIn(F'{req} is required'	,    str(lowercase_))
             self.assertIn("but found"	,    str(lowercase_))

        # unmet requirements due to missing module
     for req in ["numpipypie>1", "numpipypie2"]:
         try:
             require_version_core(lowercase_)
         except importlib.metadata.PackageNotFoundError as e:
             self.assertIn(F'The \'{req}\' distribution was not found and is required by this application'	,    str(lowercase_))
             self.assertIn("Try: pip install transformers -U"	,    str(lowercase_))

        # bogus requirements formats:
        # 1. whole thing
     for req in ["numpy??1.0.0", "numpy1.0.0"]:
         try:
             require_version_core(lowercase_)
         except ValueError as e:
             self.assertIn("requirement needs to be in the pip package format"	,    str(lowercase_))
        # 2. only operators
     for req in ["numpy=1.0.0", "numpy == 1.00", "numpy<>1.0.0", "numpy><1.00", "numpy>>1.0.0"]:
         try:
             require_version_core(lowercase_)
         except ValueError as e:
             self.assertIn("need one of "	,    str(lowercase_))





 def     snake_case__						(      self):
     # matching requirement
     require_version("python>=3.6.0")

     # not matching requirements
     for req in ["python>9.9.9", "python<3.0.0"]:
         try:
             require_version_core(lowercase_)
         except ImportError as e:
             self.assertIn(F'{req} is required'	,    str(lowercase_))
             self.assertIn(F'but found python=={python_ver}'	,    str(lowercase_))




