



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


UpperCamelCase__ =						logging.get_logger(__name__)
class 			_lowerCAmelCase   ( _UpperCAmelCase			):






			"""simple docstring"""





			lowercase__      :  Any      =			["""input_features"""]





			def __init__(				self	:       Optional[int]			,     lowercase	:       List[Any]=80			,     lowercase	:       List[str]=16_000			,     lowercase	:       Optional[Any]=160			,     lowercase	:       Optional[int]=30			,     lowercase	:       Optional[Any]=400			,     lowercase	:       Optional[Any]=0.0			,     lowercase	:       List[str]=False			,     **lowercase	:       int			,     )						->					Any:
									"""simple docstring"""







									super().__init__(
									    feature_size=lowercase			,     sampling_rate=lowercase			,     padding_value=lowercase			,     return_attention_mask=lowercase			,     **lowercase			,     )
									__lowercase					=				n_fft
									__lowercase					=				hop_length
									__lowercase					=				chunk_length
									__lowercase					=				chunk_length * sampling_rate
									__lowercase					=				self.n_samples // hop_length
									__lowercase					=				sampling_rate
									__lowercase					=				mel_filter_bank(
									    num_frequency_bins=1 + n_fft // 2			,     num_mel_filters=lowercase			,     min_frequency=0.0			,     max_frequency=8000.0			,     sampling_rate=lowercase			,     norm="""slaney"""			,     mel_scale="""slaney"""			,     )





			def 		snake_case__			(				self	:       Dict			,     lowercase	:       np.array   )						->					np.ndarray:
									"""simple docstring"""







									__lowercase					=				spectrogram(
									    lowercase			,     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					=				log_spec[:, :-1]
									__lowercase					=				np.maximum(lowercase			,     log_spec.max() - 8.0   )
									__lowercase					=				(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 		snake_case__			(				lowercase	:       List[np.ndarray]			,     lowercase	:       List[np.ndarray]			,     lowercase	:       float = 0.0   )						->					List[np.ndarray]:
									"""simple docstring"""







									if attention_mask is not None:
															__lowercase					=				np.array(lowercase			,     np.intaa   )
															__lowercase					=				[]

															for vector, length in zip(lowercase			,     attention_mask.sum(-1   )   ):
																					__lowercase					=				(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7   )
																					if length < normed_slice.shape[0]:
																											__lowercase					=				padding_value

																					normed_input_values.append(lowercase   )
									else:
															__lowercase					=				[(x - x.mean()) / np.sqrt(x.var() + 1E-7   ) for x in input_values]

									return normed_input_values





			def __call__(				self	:       Any			,     lowercase	:       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]			,     lowercase	:       bool = True			,     lowercase	:       Optional[int] = None			,     lowercase	:       Optional[Union[str, TensorType]] = None			,     lowercase	:       Optional[bool] = None			,     lowercase	:       Optional[str] = "max_length"			,     lowercase	:       Optional[int] = None			,     lowercase	:       Optional[int] = None			,     lowercase	:       Optional[bool] = None			,     **lowercase	:       List[str]			,     )						->					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					=				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}"   )
									__lowercase					=				is_batched_numpy or (
									    isinstance(lowercase			,     (list, tuple)   ) and (isinstance(raw_speech[0]			,     (np.ndarray, tuple, list)   ))
									)

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

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

									__lowercase					=				BatchFeature({"""input_features""": raw_speech}   )

									# convert into correct format for padding

									__lowercase					=				self.pad(
									    lowercase			,     padding=lowercase			,     max_length=max_length if max_length else self.n_samples			,     truncation=lowercase			,     pad_to_multiple_of=lowercase			,     return_attention_mask=return_attention_mask or do_normalize			,     )

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

									# make sure list is in array format
									__lowercase					=				padded_inputs.get("""input_features"""   ).transpose(2			,     0			,     1   )

									__lowercase					=				[self._np_extract_fbank_features(lowercase   ) for waveform in input_features[0]]

									if isinstance(input_features[0]			,     lowercase   ):
															__lowercase					=				[np.asarray(lowercase			,     dtype=np.floataa   ) for feature in input_features]
									else:
															__lowercase					=				input_features

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

									if return_tensors is not None:
															__lowercase					=				padded_inputs.convert_to_tensors(lowercase   )

									return padded_inputs







			def 		snake_case__			(				self	:       List[Any]   )						->					Dict[str, Any]:
									"""simple docstring"""







									__lowercase					=				copy.deepcopy(self.__dict__   )
									__lowercase					=				self.__class__.__name__
									if "mel_filters" in output:
															del output["mel_filters"]
									return output










import functools
import operator

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


UpperCamelCase__ =						logging.get_logger(__name__)

UpperCamelCase__ =						{
    "asapp/sew-tiny-100k": "https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json",
    # See all SEW models at https://huggingface.co/models?filter=sew
}
class 			_lowerCAmelCase   ( _UpperCAmelCase			):






			"""simple docstring"""





			lowercase__      :  Union[str, Any]      =			"""sew"""





			def __init__(				self	:       List[Any]			,     lowercase	:       int=32			,     lowercase	:       List[str]=768			,     lowercase	:       Dict=12			,     lowercase	:       str=12			,     lowercase	:       str=3_072			,     lowercase	:       Optional[int]=2			,     lowercase	:       List[str]="gelu"			,     lowercase	:       List[str]=0.1			,     lowercase	:       Tuple=0.1			,     lowercase	:       Dict=0.1			,     lowercase	:       Any=0.0			,     lowercase	:       Dict=0.1			,     lowercase	:       Optional[int]=0.1			,     lowercase	:       List[str]=0.02			,     lowercase	:       Dict=1E-5			,     lowercase	:       Tuple="group"			,     lowercase	:       int="gelu"			,     lowercase	:       Any=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)			,     lowercase	:       Optional[int]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)			,     lowercase	:       Any=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)			,     lowercase	:       List[str]=False			,     lowercase	:       Tuple=128			,     lowercase	:       int=16			,     lowercase	:       Union[str, Any]=True			,     lowercase	:       List[str]=0.05			,     lowercase	:       Optional[int]=10			,     lowercase	:       Any=2			,     lowercase	:       Optional[Any]=0.0			,     lowercase	:       Optional[Any]=10			,     lowercase	:       int=0			,     lowercase	:       Optional[int]="mean"			,     lowercase	:       List[Any]=False			,     lowercase	:       str=False			,     lowercase	:       int=256			,     lowercase	:       str=0			,     lowercase	:       List[Any]=1			,     lowercase	:       List[Any]=2			,     **lowercase	:       List[Any]			,     )						->					Optional[Any]:
									"""simple docstring"""







									super().__init__(**lowercase			,     pad_token_id=lowercase			,     bos_token_id=lowercase			,     eos_token_id=lowercase   )
									__lowercase					=				hidden_size
									__lowercase					=				feat_extract_norm
									__lowercase					=				feat_extract_activation
									__lowercase					=				list(lowercase   )
									__lowercase					=				list(lowercase   )
									__lowercase					=				list(lowercase   )
									__lowercase					=				conv_bias
									__lowercase					=				num_conv_pos_embeddings
									__lowercase					=				num_conv_pos_embedding_groups
									__lowercase					=				len(self.conv_dim   )
									__lowercase					=				num_hidden_layers
									__lowercase					=				intermediate_size
									__lowercase					=				squeeze_factor
									__lowercase					=				hidden_act
									__lowercase					=				num_attention_heads
									__lowercase					=				hidden_dropout
									__lowercase					=				attention_dropout
									__lowercase					=				activation_dropout
									__lowercase					=				feat_proj_dropout
									__lowercase					=				final_dropout
									__lowercase					=				layerdrop
									__lowercase					=				layer_norm_eps
									__lowercase					=				initializer_range
									__lowercase					=				vocab_size

									if (
									    (len(self.conv_stride   ) != self.num_feat_extract_layers)
									    or (len(self.conv_kernel   ) != self.num_feat_extract_layers)
									    or (len(self.conv_dim   ) != self.num_feat_extract_layers)
									):
															raise ValueError(
															    """Configuration for convolutional layers is incorrect."""
															    """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
															    F"but is `len(config.conv_dim) = {len(self.conv_dim   )}`, `len(config.conv_stride)"
															    F"= {len(self.conv_stride   )}`, `len(config.conv_kernel) = {len(self.conv_kernel   )}`."   )

									# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
									__lowercase					=				apply_spec_augment
									__lowercase					=				mask_time_prob
									__lowercase					=				mask_time_length
									__lowercase					=				mask_time_min_masks
									__lowercase					=				mask_feature_prob
									__lowercase					=				mask_feature_length
									__lowercase					=				mask_feature_min_masks

									# ctc loss
									__lowercase					=				ctc_loss_reduction
									__lowercase					=				ctc_zero_infinity

									# sequence classification
									__lowercase					=				use_weighted_layer_sum
									__lowercase					=				classifier_proj_size







			@property
			def 		snake_case__			(				self	:       Dict   )						->					str:
									"""simple docstring"""







									return functools.reduce(operator.mul			,     self.conv_stride			,     1   )





