"""simple docstring"""







import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np

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


__SCREAMING_SNAKE_CASE								=logging.get_logger(__name__)







class  UpperCamelCase	(    lowercase_						):
   lowercase							=						['input_features']
   def __init__(    self  ,__UpperCamelCase=80  ,__UpperCamelCase=1_6000  ,__UpperCamelCase=160  ,__UpperCamelCase=30  ,__UpperCamelCase=400  ,__UpperCamelCase=0.0  ,__UpperCamelCase=False  ,**__UpperCamelCase  ,)			->   Any:


        '''simple docstring'''


        super().__init__(
            feature_size=__UpperCamelCase  ,sampling_rate=__UpperCamelCase  ,padding_value=__UpperCamelCase  ,return_attention_mask=__UpperCamelCase  ,**__UpperCamelCase  ,)
        lowercase_			:       Dict									=			n_fft
        lowercase_			:       Optional[Any]									=			hop_length
        lowercase_			:       Optional[int]									=			chunk_length
        lowercase_			:       Optional[Any]									=			chunk_length * sampling_rate
        lowercase_			:       Tuple									=			self.n_samples // hop_length
        lowercase_			:       int									=			sampling_rate
        lowercase_			:       int									=			mel_filter_bank(
            num_frequency_bins=1 + n_fft // 2  ,num_mel_filters=__UpperCamelCase  ,min_frequency=0.0  ,max_frequency=8000.0  ,sampling_rate=__UpperCamelCase  ,norm='slaney'  ,mel_scale='slaney'  ,)
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   np.ndarray:


        '''simple docstring'''


        lowercase_			:       Union[str, Any]									=			spectrogram(
            __UpperCamelCase  ,window_function(self.n_fft  ,'hann'    )  ,frame_length=self.n_fft  ,hop_length=self.hop_length  ,power=2.0  ,mel_filters=self.mel_filters  ,log_mel='log10'  ,)
        lowercase_			:       Optional[Any]									=			log_spec[:, :-1]
        lowercase_			:       int									=			np.maximum(__UpperCamelCase  ,log_spec.max() - 8.0    )
        lowercase_			:       List[Any]									=			(log_spec + 4.0) / 4.0
        return log_spec
   @staticmethod
   # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
   def     _UpperCAmelCase     (    __UpperCamelCase  ,__UpperCamelCase  ,__UpperCamelCase = 0.0    )			->   List[np.ndarray]:


        '''simple docstring'''


        if attention_mask is not None:
             lowercase_			:       Optional[int]									=			np.array(__UpperCamelCase  ,np.intaa    )
             lowercase_			:       Optional[Any]									=			[]

             for vector, length in zip(__UpperCamelCase  ,attention_mask.sum(-1    )    ):
                  lowercase_			:       Union[str, Any]									=			(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7    )
                  if length < normed_slice.shape[0]:
                       lowercase_			:       Any									=			padding_value

                  normed_input_values.append(__UpperCamelCase    )
        else:
             lowercase_			:       Optional[int]									=			[(x - x.mean()) / np.sqrt(x.var() + 1e-7    ) for x in input_values]

        return normed_input_values
   def __call__(    self  ,__UpperCamelCase  ,__UpperCamelCase = True  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = "max_length"  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,__UpperCamelCase = None  ,**__UpperCamelCase  ,)			->   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.__class__.__name__} was trained using a'''
                      f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'''
                      f''' was sampled with {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.'    )

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

        if is_batched:
             lowercase_			:       Union[str, Any]									=			[np.asarray([speech]  ,dtype=np.floataa    ).T for speech in raw_speech]
        elif not is_batched and not isinstance(__UpperCamelCase  ,np.ndarray    ):
             lowercase_			:       Dict									=			np.asarray(__UpperCamelCase  ,dtype=np.floataa    )
        elif isinstance(__UpperCamelCase  ,np.ndarray    ) and raw_speech.dtype is np.dtype(np.floataa    ):
             lowercase_			:       Dict									=			raw_speech.astype(np.floataa    )

        # always return batch
        if not is_batched:
             lowercase_			:       List[Any]									=			[np.asarray([raw_speech]    ).T]

        lowercase_			:       str									=			BatchFeature({'input_features': raw_speech}    )

        # convert into correct format for padding

        lowercase_			:       str									=			self.pad(
            __UpperCamelCase  ,padding=__UpperCamelCase  ,max_length=max_length if max_length else self.n_samples  ,truncation=__UpperCamelCase  ,pad_to_multiple_of=__UpperCamelCase  ,return_attention_mask=return_attention_mask or do_normalize  ,)

        # zero-mean and unit-variance normalization
        if do_normalize:
             lowercase_			:       int									=			self.zero_mean_unit_var_norm(
                 padded_inputs['input_features']  ,attention_mask=padded_inputs['attention_mask']  ,padding_value=self.padding_value  ,)
             lowercase_			:       Tuple									=			np.stack(padded_inputs['input_features']  ,axis=0    )

        # make sure list is in array format
        lowercase_			:       Dict									=			padded_inputs.get('input_features'    ).transpose(2  ,0  ,1    )

        lowercase_			:       List[str]									=			[self._np_extract_fbank_features(__UpperCamelCase    ) for waveform in input_features[0]]

        if isinstance(input_features[0]  ,__UpperCamelCase    ):
             lowercase_			:       Optional[Any]									=			[np.asarray(__UpperCamelCase  ,dtype=np.floataa    ) for feature in input_features]
        else:
             lowercase_			:       str									=			input_features

        if return_attention_mask:
             # rescale from sample (48000) to feature (3000)
             lowercase_			:       str									=			padded_inputs['attention_mask'][:, :: self.hop_length]

        if return_tensors is not None:
             lowercase_			:       Union[str, Any]									=			padded_inputs.convert_to_tensors(__UpperCamelCase    )

        return padded_inputs







   def     _UpperCAmelCase     (    self    )			->   Dict[str, Any]:


        '''simple docstring'''


        lowercase_			:       Dict									=			copy.deepcopy(self.__dict__    )
        lowercase_			:       Union[str, Any]									=			self.__class__.__name__
        if "mel_filters" in output:
             del output["mel_filters"]
        return output







"""simple docstring"""







from ...configuration_utils import PretrainedConfig
from ...utils import logging


__SCREAMING_SNAKE_CASE								=logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE								={
    "google/switch-base-8": "https://huggingface.co/google/switch-base-8/blob/main/config.json",
}







class  UpperCamelCase	(    lowercase_						):
   lowercase							=						'switch_transformers'
   lowercase							=						['past_key_values']
   lowercase							=						{'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
   def __init__(    self  ,__UpperCamelCase=3_2128  ,__UpperCamelCase=768  ,__UpperCamelCase=64  ,__UpperCamelCase=2048  ,__UpperCamelCase=64  ,__UpperCamelCase=12  ,__UpperCamelCase=3  ,__UpperCamelCase=12  ,__UpperCamelCase=3  ,__UpperCamelCase=12  ,__UpperCamelCase=8  ,__UpperCamelCase=False  ,__UpperCamelCase=0.01  ,__UpperCamelCase="float32"  ,__UpperCamelCase=False  ,__UpperCamelCase=32  ,__UpperCamelCase=128  ,__UpperCamelCase=0.1  ,__UpperCamelCase=1e-6  ,__UpperCamelCase=0.001  ,__UpperCamelCase=0.001  ,__UpperCamelCase=1.0  ,__UpperCamelCase="relu"  ,__UpperCamelCase=True  ,__UpperCamelCase=False  ,__UpperCamelCase=True  ,__UpperCamelCase=0  ,__UpperCamelCase=1  ,**__UpperCamelCase  ,)			->   str:


        '''simple docstring'''


        lowercase_			:       List[str]									=			vocab_size
        lowercase_			:       Optional[Any]									=			d_model
        lowercase_			:       Dict									=			d_kv
        lowercase_			:       Dict									=			d_ff

        lowercase_			:       str									=			num_sparse_encoder_layers

        lowercase_			:       List[str]									=			num_layers
        lowercase_			:       int									=			(
            num_decoder_layers if num_decoder_layers is not None else self.num_layers
        )  # default = symmetry
        lowercase_			:       Optional[Any]									=			num_sparse_decoder_layers

        # This tells us, each how many encoder layer we'll have to set a sparse layer.
        if self.num_sparse_encoder_layers > 0:
             lowercase_			:       Tuple									=			self.num_layers // self.num_sparse_encoder_layers
        else:
             lowercase_			:       Union[str, Any]									=			self.num_layers  # HACK: this will create 0 sparse layers

        # This tells us, each how many encoder layer we'll have to set a sparse layer.
        if self.num_sparse_decoder_layers > 0:
             lowercase_			:       Union[str, Any]									=			self.num_decoder_layers // self.num_sparse_decoder_layers
        else:
             lowercase_			:       List[Any]									=			self.num_decoder_layers  # HACK: this will create 0 sparse layers

        lowercase_			:       List[Any]									=			num_heads
        lowercase_			:       Dict									=			num_experts
        lowercase_			:       List[str]									=			expert_capacity
        lowercase_			:       Optional[Any]									=			router_bias
        lowercase_			:       Optional[Any]									=			router_jitter_noise
        if router_dtype not in ["float32", "float16", "bfloat16"]:
             raise ValueError(f'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}'''    )
        lowercase_			:       Optional[Any]									=			router_dtype

        lowercase_			:       Union[str, Any]									=			router_ignore_padding_tokens
        lowercase_			:       Any									=			relative_attention_num_buckets
        lowercase_			:       List[Any]									=			relative_attention_max_distance

        lowercase_			:       str									=			dropout_rate
        lowercase_			:       Any									=			layer_norm_epsilon
        lowercase_			:       Tuple									=			initializer_factor
        lowercase_			:       str									=			feed_forward_proj
        lowercase_			:       List[Any]									=			use_cache
        lowercase_			:       str									=			add_router_probs

        lowercase_			:       Tuple									=			router_z_loss_coef
        lowercase_			:       int									=			router_aux_loss_coef

        lowercase_			:       List[str]									=			self.feed_forward_proj.split('-'    )
        lowercase_			:       List[str]									=			act_info[-1]
        lowercase_			:       Optional[Any]									=			act_info[0] == 'gated'

        if len(__UpperCamelCase    ) > 1 and act_info[0] != "gated" or len(__UpperCamelCase    ) > 2:
             raise ValueError(
                 f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''
                 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
                 '\'gated-gelu\' or \'relu\''    )

        # for backwards compatibility
        if feed_forward_proj == "gated-gelu":
             lowercase_			:       Union[str, Any]									=			'gelu_new'

        super().__init__(
            pad_token_id=__UpperCamelCase  ,eos_token_id=__UpperCamelCase  ,is_encoder_decoder=__UpperCamelCase  ,**__UpperCamelCase  ,)

