






from typing import List, Optional, Union

import numpy as np

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


lowerCamelCase__			= logging.get_logger(__name__)






class    SCREAMING_SNAKE_CASE			(							lowerCamelCase__					):
							__lowerCamelCase	:	Dict    =['input_features', 'attention_mask']





							def __init__(   self		:		Dict      ,				__lowercase		:		List[str]=80      ,				__lowercase		:		List[Any]=16000      ,				__lowercase		:		int=0.0      ,				__lowercase		:		str=10      ,				__lowercase		:		str=25      ,				__lowercase		:		int="hamming_window"      ,				__lowercase		:		int=32768.0      ,				__lowercase		:		Union[str, Any]=0.97      ,				__lowercase		:		int=1.0      ,				__lowercase		:		Optional[Any]=True      ,				__lowercase		:		Optional[int]=True      ,				__lowercase		:		List[str]=False      ,				**__lowercase		:		Tuple      ,				):

											'''simple docstring'''
											super().__init__(feature_size=__lowercase      ,				sampling_rate=__lowercase      ,				padding_value=__lowercase      ,				**__lowercase	)

											__a       =		feature_size
											__a       =		sampling_rate
											__a       =		padding_value
											__a       =		hop_length
											__a       =		win_length
											__a       =		frame_signal_scale
											__a       =		preemphasis_coeff
											__a       =		mel_floor
											__a       =		normalize_means
											__a       =		normalize_vars
											__a       =		win_function
											__a       =		return_attention_mask

											__a       =		win_length * sampling_rate // 1000
											__a       =		hop_length * sampling_rate // 1000

											__a       =		optimal_fft_length(self.sample_size	)
											__a       =		(self.n_fft // 2) + 1





							def 						UpperCamelCase_					(   self		:		Optional[int]      ,				__lowercase		:		np.array	):

											'''simple docstring'''
											if self.win_function == "hamming_window":
															__a       =		window_function(window_length=self.sample_size      ,				name=self.win_function      ,				periodic=__lowercase	)
											else:
															__a       =		window_function(window_length=self.sample_size      ,				name=self.win_function	)

											__a       =		mel_filter_bank(
											    num_frequency_bins=self.n_freqs      ,				num_mel_filters=self.feature_size      ,				min_frequency=0.0      ,				max_frequency=self.sampling_rate / 2.0      ,				sampling_rate=self.sampling_rate      ,				)

											__a       =		spectrogram(
											    one_waveform * self.frame_signal_scale      ,				window=__lowercase      ,				frame_length=self.sample_size      ,				hop_length=self.sample_stride      ,				fft_length=self.n_fft      ,				center=__lowercase      ,				preemphasis=self.preemphasis_coeff      ,				mel_filters=__lowercase      ,				mel_floor=self.mel_floor      ,				log_mel="""log"""      ,				)
											return msfc_features.T





							def 						UpperCamelCase_					(   self		:		Dict      ,				__lowercase		:		Union[str, Any]      ,				__lowercase		:		Optional[int]      ,				__lowercase		:		List[Any]	):

											'''simple docstring'''
											# make sure we normalize float32 arrays
											if self.normalize_means:
															__a       =		x[:input_length].mean(axis=0	)
															__a       =		np.subtract(__lowercase      ,				__lowercase	)
											if self.normalize_vars:
															__a       =		x[:input_length].std(axis=0	)
															__a       =		np.divide(__lowercase      ,				__lowercase	)

											if input_length < x.shape[0]:
															__a       =		padding_value

											# make sure array is in float32
											__a       =		x.astype(np.floataa	)

											return x





							def 						UpperCamelCase_					(   self		:		Optional[Any]      ,				__lowercase		:		List[np.ndarray]      ,				__lowercase		:		Optional[np.ndarray] = None	):

											'''simple docstring'''
											__a       =		attention_mask.sum(-1	) if attention_mask is not None else [x.shape[0] for x in input_features]
											return [self._normalize_one(__lowercase      ,				__lowercase      ,				self.padding_value	) for x, n in zip(__lowercase      ,				__lowercase	)]







							def __call__(   self		:		Optional[Any]      ,				__lowercase		:		Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]      ,				__lowercase		:		Union[bool, str, PaddingStrategy] = False      ,				__lowercase		:		Optional[int] = None      ,				__lowercase		:		bool = False      ,				__lowercase		:		Optional[int] = None      ,				__lowercase		:		Optional[bool] = None      ,				__lowercase		:		Optional[Union[str, TensorType]] = None      ,				__lowercase		:		Optional[int] = None      ,				**__lowercase		:		List[Any]      ,				):

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

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

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

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

											# extract fbank features
											__a       =		[self._extract_mfsc_features(__lowercase	) for one_waveform in raw_speech]

											# convert into correct format for padding
											__a       =		BatchFeature({"""input_features""": features}	)

											__a       =		self.pad(
											    __lowercase      ,				padding=__lowercase      ,				max_length=__lowercase      ,				truncation=__lowercase      ,				pad_to_multiple_of=__lowercase      ,				return_attention_mask=__lowercase      ,				**__lowercase      ,				)
											# make sure list is in array format
											__a       =		padded_inputs.get("""input_features"""	)
											if isinstance(input_features[0]      ,				__lowercase	):
															__a       =		[np.asarray(__lowercase      ,				dtype=np.floataa	) for feature in input_features]

											__a       =		padded_inputs.get("""attention_mask"""	)
											if attention_mask is not None:
															__a       =		[np.asarray(__lowercase      ,				dtype=np.intaa	) for array in attention_mask]

											if self.normalize_means or self.normalize_vars:
															__a       =		(
															    np.array(__lowercase      ,				dtype=np.intaa	)
															    if self._get_padding_strategies(__lowercase      ,				max_length=__lowercase	) is not PaddingStrategy.DO_NOT_PAD
															    and padding
															    else None
															)
															__a       =		self.normalize(
															    padded_inputs["""input_features"""]      ,				attention_mask=__lowercase	)

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

											return padded_inputs





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


lowerCamelCase__			= logging.get_logger(__name__)

lowerCamelCase__			= {
    """alibaba-damo/mgp-str-base""": """https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json""",
}






class    SCREAMING_SNAKE_CASE			(							lowerCamelCase__					):
							__lowerCamelCase	:	Dict    ='mgp-str'





							def __init__(   self		:		Optional[Any]      ,				__lowercase		:		Dict=[32, 128]      ,				__lowercase		:		Tuple=4      ,				__lowercase		:		Optional[Any]=3      ,				__lowercase		:		str=27      ,				__lowercase		:		Any=38      ,				__lowercase		:		str=50257      ,				__lowercase		:		List[str]=30522      ,				__lowercase		:		Tuple=768      ,				__lowercase		:		str=12      ,				__lowercase		:		Optional[Any]=12      ,				__lowercase		:		str=4.0      ,				__lowercase		:		Union[str, Any]=True      ,				__lowercase		:		List[Any]=False      ,				__lowercase		:		Union[str, Any]=1E-5      ,				__lowercase		:		Optional[int]=0.0      ,				__lowercase		:		Dict=0.0      ,				__lowercase		:		Union[str, Any]=0.0      ,				__lowercase		:		List[str]=False      ,				__lowercase		:		List[Any]=0.02      ,				**__lowercase		:		List[Any]      ,				):

											'''simple docstring'''
											super().__init__(**__lowercase	)

											__a       =		image_size
											__a       =		patch_size
											__a       =		num_channels
											__a       =		max_token_length
											__a       =		num_character_labels
											__a       =		num_bpe_labels
											__a       =		num_wordpiece_labels
											__a       =		hidden_size
											__a       =		num_hidden_layers
											__a       =		num_attention_heads
											__a       =		mlp_ratio
											__a       =		distilled
											__a       =		layer_norm_eps
											__a       =		drop_rate
											__a       =		qkv_bias
											__a       =		attn_drop_rate
											__a       =		drop_path_rate
											__a       =		output_aa_attentions
											__a       =		initializer_range
