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


lowercase__						       =      logging.get_logger(__name__)






class 	snake_case__       (      __SCREAMING_SNAKE_CASE					):







		"""simple docstring"""

		lowerCamelCase     							=						["""input_features"""]



		def __init__(      self				:			List[str]  ,	UpperCamelCase__				:			Tuple=80  ,	UpperCamelCase__				:			Optional[Any]=1_6000  ,	UpperCamelCase__				:			int=160  ,	UpperCamelCase__				:			Tuple=30  ,	UpperCamelCase__				:			Any=400  ,	UpperCamelCase__				:			Optional[int]=0.0  ,	UpperCamelCase__				:			List[str]=False  ,	**UpperCamelCase__				:			List[Any]  ,	)						->			Any:






				"""simple docstring"""







				super().__init__(
				    feature_size=UpperCamelCase__  ,	sampling_rate=UpperCamelCase__  ,	padding_value=UpperCamelCase__  ,	return_attention_mask=UpperCamelCase__  ,	**UpperCamelCase__  ,	)
				snake_case  :       int     			=						n_fft
				snake_case  :       Any     			=						hop_length
				snake_case  :       int     			=						chunk_length
				snake_case  :       Tuple     			=						chunk_length * sampling_rate
				snake_case  :       List[str]     			=						self.n_samples // hop_length
				snake_case  :       List[Any]     			=						sampling_rate
				snake_case  :       Optional[Any]     			=						mel_filter_bank(
				    num_frequency_bins=1 + n_fft // 2  ,	num_mel_filters=UpperCamelCase__  ,	min_frequency=0.0  ,	max_frequency=8_000.0  ,	sampling_rate=UpperCamelCase__  ,	norm='''slaney'''  ,	mel_scale='''slaney'''  ,	)



		def       lowerCAmelCase				(      self				:			Optional[int]  ,	UpperCamelCase__				:			np.array      )						->			np.ndarray:






				"""simple docstring"""







				snake_case  :       int     			=						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'''  ,	)
				snake_case  :       str     			=						log_spec[:, :-1]
				snake_case  :       Tuple     			=						np.maximum(UpperCamelCase__  ,	log_spec.max() - 8.0      )
				snake_case  :       Optional[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       lowerCAmelCase				(      UpperCamelCase__				:			List[np.ndarray]  ,	UpperCamelCase__				:			List[np.ndarray]  ,	UpperCamelCase__				:			float = 0.0      )						->			List[np.ndarray]:






				"""simple docstring"""







				if attention_mask is not None:
						snake_case  :       int     			=						np.array(UpperCamelCase__  ,	np.intaa      )
						snake_case  :       Dict     			=						[]

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

								normed_input_values.append(UpperCamelCase__      )
				else:
						snake_case  :       Dict     			=						[(x - x.mean()) / np.sqrt(x.var() + 1e-7      ) for x in input_values]

				return normed_input_values



		def __call__(      self				:			int  ,	UpperCamelCase__				:			Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]  ,	UpperCamelCase__				:			bool = True  ,	UpperCamelCase__				:			Optional[int] = None  ,	UpperCamelCase__				:			Optional[Union[str, TensorType]] = None  ,	UpperCamelCase__				:			Optional[bool] = None  ,	UpperCamelCase__				:			Optional[str] = "max_length"  ,	UpperCamelCase__				:			Optional[int] = None  ,	UpperCamelCase__				:			Optional[int] = None  ,	UpperCamelCase__				:			Optional[bool] = None  ,	**UpperCamelCase__				:			Optional[Any]  ,	)						->			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.'''      )

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

				if is_batched:
						snake_case  :       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      ):
						snake_case  :       str     			=						np.asarray(UpperCamelCase__  ,	dtype=np.floataa      )
				elif isinstance(UpperCamelCase__  ,	np.ndarray      ) and raw_speech.dtype is np.dtype(np.floataa      ):
						snake_case  :       int     			=						raw_speech.astype(np.floataa      )

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

				snake_case  :       List[Any]     			=						BatchFeature({'''input_features''': raw_speech}      )

				# convert into correct format for padding

				snake_case  :       Optional[int]     			=						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:
						snake_case  :       int     			=						self.zero_mean_unit_var_norm(
						    padded_inputs['''input_features''']  ,	attention_mask=padded_inputs['''attention_mask''']  ,	padding_value=self.padding_value  ,	)
						snake_case  :       List[str]     			=						np.stack(padded_inputs['''input_features''']  ,	axis=0      )

				# make sure list is in array format
				snake_case  :       List[str]     			=						padded_inputs.get('''input_features'''      ).transpose(2  ,	0  ,	1      )

				snake_case  :       Union[str, Any]     			=						[self._np_extract_fbank_features(UpperCamelCase__      ) for waveform in input_features[0]]

				if isinstance(input_features[0]  ,	UpperCamelCase__      ):
						snake_case  :       Optional[int]     			=						[np.asarray(UpperCamelCase__  ,	dtype=np.floataa      ) for feature in input_features]
				else:
						snake_case  :       Tuple     			=						input_features

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

				if return_tensors is not None:
						snake_case  :       Tuple     			=						padded_inputs.convert_to_tensors(UpperCamelCase__      )

				return padded_inputs



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






				"""simple docstring"""







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




'''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
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


lowercase__						       =      logging.get_logger(__name__)

lowercase__						       =      {
    "microsoft/swin-tiny-patch4-window7-224": (
        "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json"
    ),
    # See all Swin models at https://huggingface.co/models?filter=swin
}






class 	snake_case__       (      __SCREAMING_SNAKE_CASE    ,					__SCREAMING_SNAKE_CASE					):







		"""simple docstring"""

		lowerCamelCase     							=						"""swin"""

		lowerCamelCase     							=						{
		    """num_attention_heads""": """num_heads""",
		    """num_hidden_layers""": """num_layers""",
		}



		def __init__(      self				:			Tuple  ,	UpperCamelCase__				:			int=224  ,	UpperCamelCase__				:			Optional[int]=4  ,	UpperCamelCase__				:			str=3  ,	UpperCamelCase__				:			str=96  ,	UpperCamelCase__				:			List[Any]=[2, 2, 6, 2]  ,	UpperCamelCase__				:			Optional[Any]=[3, 6, 12, 24]  ,	UpperCamelCase__				:			Optional[Any]=7  ,	UpperCamelCase__				:			Tuple=4.0  ,	UpperCamelCase__				:			Tuple=True  ,	UpperCamelCase__				:			str=0.0  ,	UpperCamelCase__				:			Optional[Any]=0.0  ,	UpperCamelCase__				:			List[str]=0.1  ,	UpperCamelCase__				:			Optional[Any]="gelu"  ,	UpperCamelCase__				:			Optional[Any]=False  ,	UpperCamelCase__				:			Tuple=0.02  ,	UpperCamelCase__				:			List[Any]=1e-5  ,	UpperCamelCase__				:			Any=32  ,	UpperCamelCase__				:			List[str]=None  ,	UpperCamelCase__				:			int=None  ,	**UpperCamelCase__				:			Optional[Any]  ,	)						->			Optional[int]:






				"""simple docstring"""







				super().__init__(**UpperCamelCase__      )

				snake_case  :       Any     			=						image_size
				snake_case  :       Optional[int]     			=						patch_size
				snake_case  :       List[Any]     			=						num_channels
				snake_case  :       Union[str, Any]     			=						embed_dim
				snake_case  :       str     			=						depths
				snake_case  :       str     			=						len(UpperCamelCase__      )
				snake_case  :       List[Any]     			=						num_heads
				snake_case  :       List[Any]     			=						window_size
				snake_case  :       Optional[int]     			=						mlp_ratio
				snake_case  :       Union[str, Any]     			=						qkv_bias
				snake_case  :       Optional[int]     			=						hidden_dropout_prob
				snake_case  :       Optional[int]     			=						attention_probs_dropout_prob
				snake_case  :       Optional[int]     			=						drop_path_rate
				snake_case  :       List[Any]     			=						hidden_act
				snake_case  :       int     			=						use_absolute_embeddings
				snake_case  :       str     			=						layer_norm_eps
				snake_case  :       Optional[Any]     			=						initializer_range
				snake_case  :       Any     			=						encoder_stride
				# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
				# this indicates the channel dimension after the last stage of the model
				snake_case  :       str     			=						int(embed_dim * 2 ** (len(UpperCamelCase__      ) - 1)      )
				snake_case  :       int     			=						['''stem'''] + [f'stage{idx}' for idx in range(1  ,	len(UpperCamelCase__      ) + 1      )]
				snake_case			,snake_case  :       List[Any]     			=						get_aligned_output_features_output_indices(
				    out_features=UpperCamelCase__  ,	out_indices=UpperCamelCase__  ,	stage_names=self.stage_names      )







class 	snake_case__       (      __SCREAMING_SNAKE_CASE					):







		"""simple docstring"""

		lowerCamelCase     							=						version.parse("""1.11"""					)



		@property
		def       lowerCAmelCase				(      self				:			List[Any]      )						->			Mapping[str, Mapping[int, str]]:






				"""simple docstring"""







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



		@property
		def       lowerCAmelCase				(      self				:			List[Any]      )						->			float:






				"""simple docstring"""







				return 1e-4


