





"""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 PaddingStrategy, TensorType, logging


lowerCamelCase_       =		logging.get_logger(__name__)






class  _SCREAMING_SNAKE_CASE(       A  ):
       SCREAMING_SNAKE_CASE_       :				int     						=  ['''input_features''', '''attention_mask''']




       def __init__(						self		,SCREAMING_SNAKE_CASE__=80		,SCREAMING_SNAKE_CASE__=1_60_00		,SCREAMING_SNAKE_CASE__=80		,SCREAMING_SNAKE_CASE__=0.0		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=True		,**SCREAMING_SNAKE_CASE__		,)      ->				List[Any]:





             """simple docstring"""






             super().__init__(feature_size=SCREAMING_SNAKE_CASE__		,sampling_rate=SCREAMING_SNAKE_CASE__		,padding_value=SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :str		    =  num_mel_bins
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  do_ceptral_normalize
             __SCREAMING_SNAKE_CASE       :Any		    =  normalize_means
             __SCREAMING_SNAKE_CASE       :Dict		    =  normalize_vars
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  True




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,)      ->				np.ndarray:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
             __SCREAMING_SNAKE_CASE       :Any		    =  torch.from_numpy(SCREAMING_SNAKE_CASE__							).unsqueeze(0							)
             __SCREAMING_SNAKE_CASE       :Tuple		    =  ta_kaldi.fbank(SCREAMING_SNAKE_CASE__		,num_mel_bins=self.num_mel_bins		,sample_frequency=self.sampling_rate							)
             return features.numpy()




       @staticmethod
       def    _UpperCamelCase					(						SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = True		,SCREAMING_SNAKE_CASE__ = True		,SCREAMING_SNAKE_CASE__ = 0.0		,)      ->				np.ndarray:





             """simple docstring"""






             if normalize_means:
                   __SCREAMING_SNAKE_CASE       :Any		    =  x[:input_length].mean(axis=0							)
                   __SCREAMING_SNAKE_CASE       :Tuple		    =  np.subtract(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             if normalize_vars:
                   __SCREAMING_SNAKE_CASE       :str		    =  x[:input_length].std(axis=0							)
                   __SCREAMING_SNAKE_CASE       :int		    =  np.divide(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)

             if input_length < x.shape[0]:
                   __SCREAMING_SNAKE_CASE       :List[Any]		    =  padding_value

             # make sure array is in float32
             __SCREAMING_SNAKE_CASE       :Tuple		    =  x.astype(np.floataa							)

             return x




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = None							)      ->				List[np.ndarray]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :List[str]		    =  attention_mask.sum(-1							) if attention_mask is not None else [x.shape[0] for x in input_features]
             return [
                 self.utterance_cmvn(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,self.normalize_means		,self.normalize_vars		,self.padding_value							)
                 for x, n in zip(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)
             ]




       def __call__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = False		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = False		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = None		,**SCREAMING_SNAKE_CASE__		,)      ->				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.'''							)

             __SCREAMING_SNAKE_CASE       :Tuple		    =  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}'''							)
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  is_batched_numpy or (
                 isinstance(SCREAMING_SNAKE_CASE__		,(list, tuple)							) and (isinstance(raw_speech[0]		,(np.ndarray, tuple, list)							))
             )

             if is_batched:
                   __SCREAMING_SNAKE_CASE       :Tuple		    =  [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							):
                   __SCREAMING_SNAKE_CASE       :List[Any]		    =  np.asarray(SCREAMING_SNAKE_CASE__		,dtype=np.floataa							)
             elif isinstance(SCREAMING_SNAKE_CASE__		,np.ndarray							) and raw_speech.dtype is np.dtype(np.floataa							):
                   __SCREAMING_SNAKE_CASE       :Any		    =  raw_speech.astype(np.floataa							)

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

             # extract fbank features
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  [self._extract_fbank_features(SCREAMING_SNAKE_CASE__							) for waveform in raw_speech]

             # convert into correct format for padding
             __SCREAMING_SNAKE_CASE       :Dict		    =  BatchFeature({'''input_features''': features}							)

             __SCREAMING_SNAKE_CASE       :Tuple		    =  self.pad(
                 SCREAMING_SNAKE_CASE__		,padding=SCREAMING_SNAKE_CASE__		,max_length=SCREAMING_SNAKE_CASE__		,truncation=SCREAMING_SNAKE_CASE__		,pad_to_multiple_of=SCREAMING_SNAKE_CASE__		,return_attention_mask=SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__		,)

             # make sure list is in array format
             __SCREAMING_SNAKE_CASE       :List[str]		    =  padded_inputs.get('''input_features'''							)
             if isinstance(input_features[0]		,SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE       :Tuple		    =  [np.asarray(SCREAMING_SNAKE_CASE__		,dtype=np.floataa							) for feature in input_features]

             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  padded_inputs.get('''attention_mask'''							)
             if attention_mask is not None:
                   __SCREAMING_SNAKE_CASE       :str		    =  [np.asarray(SCREAMING_SNAKE_CASE__		,dtype=np.intaa							) for array in attention_mask]

             # Utterance-level cepstral mean and variance normalization
             if self.do_ceptral_normalize:
                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  (
                       np.array(SCREAMING_SNAKE_CASE__		,dtype=np.intaa							)
                       if self._get_padding_strategies(SCREAMING_SNAKE_CASE__		,max_length=SCREAMING_SNAKE_CASE__							) is not PaddingStrategy.DO_NOT_PAD
                       else None
                   )
                   __SCREAMING_SNAKE_CASE       :int		    =  self.normalize(
                       padded_inputs['''input_features''']		,attention_mask=SCREAMING_SNAKE_CASE__							)

             if return_tensors is not None:
                   __SCREAMING_SNAKE_CASE       :List[Any]		    =  padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE__							)

             return padded_inputs






"""simple docstring"""
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_       =		logging.get_logger(__name__)

lowerCamelCase_       =		{
    "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json",
    # See all LeViT models at https://huggingface.co/models?filter=levit
}






class  _SCREAMING_SNAKE_CASE(       A  ):
       SCREAMING_SNAKE_CASE_       :				List[Any]     						=  '''levit'''




       def __init__(						self		,SCREAMING_SNAKE_CASE__=2_24		,SCREAMING_SNAKE_CASE__=3		,SCREAMING_SNAKE_CASE__=3		,SCREAMING_SNAKE_CASE__=2		,SCREAMING_SNAKE_CASE__=1		,SCREAMING_SNAKE_CASE__=16		,SCREAMING_SNAKE_CASE__=[1_28, 2_56, 3_84]		,SCREAMING_SNAKE_CASE__=[4, 8, 12]		,SCREAMING_SNAKE_CASE__=[4, 4, 4]		,SCREAMING_SNAKE_CASE__=[16, 16, 16]		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__=[2, 2, 2]		,SCREAMING_SNAKE_CASE__=[2, 2, 2]		,SCREAMING_SNAKE_CASE__=0.0_2		,**SCREAMING_SNAKE_CASE__		,)      ->				Tuple:





             """simple docstring"""






             super().__init__(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  image_size
             __SCREAMING_SNAKE_CASE       :Dict		    =  num_channels
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  kernel_size
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  stride
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  padding
             __SCREAMING_SNAKE_CASE       :Tuple		    =  hidden_sizes
             __SCREAMING_SNAKE_CASE       :List[str]		    =  num_attention_heads
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  depths
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  key_dim
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  drop_path_rate
             __SCREAMING_SNAKE_CASE       :Tuple		    =  patch_size
             __SCREAMING_SNAKE_CASE       :int		    =  attention_ratio
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  mlp_ratio
             __SCREAMING_SNAKE_CASE       :str		    =  initializer_range
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  [
                 ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
                 ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
             ]






class  _SCREAMING_SNAKE_CASE(       A  ):
       SCREAMING_SNAKE_CASE_       :				int     						=  version.parse('''1.11'''  )




       @property
       def    _UpperCamelCase					(						self							)      ->				Mapping[str, Mapping[int, str]]:





             """simple docstring"""






             return OrderedDict(
                 [
                     ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                 ]							)




       @property
       def    _UpperCamelCase					(						self							)      ->				float:





             """simple docstring"""






             return 1E-4