




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

import numpy as np
import torch

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_		:					Optional[Any]          =  logging.get_logger(__name__)




class 		__A   (      UpperCamelCase__      ):
						UpperCamelCase      =       ["""input_features""", """is_longer"""]

						def __init__(		self :Dict     ,			__snake_case :Union[str, Any]=64     ,			__snake_case :Optional[Any]=4_80_00     ,			__snake_case :Union[str, Any]=4_80     ,			__snake_case :int=10     ,			__snake_case :Union[str, Any]=10_24     ,			__snake_case :Optional[Any]=0.0     ,			__snake_case :Union[str, Any]=False     ,			__snake_case :float = 0     ,			__snake_case :float = 1_40_00     ,			__snake_case :int = None     ,			__snake_case :str = "fusion"     ,			__snake_case :str = "repeatpad"     ,			**__snake_case :List[str]     ,			):
										'''simple docstring'''

										super().__init__(
										    feature_size=__snake_case     ,			sampling_rate=__snake_case     ,			padding_value=__snake_case     ,			return_attention_mask=__snake_case     ,			**__snake_case     ,			)
										__magic_name__						:						Tuple										=top_db
										__magic_name__						:						List[str]										=truncation
										__magic_name__						:						Tuple										=padding
										__magic_name__						:						List[str]										=fft_window_size
										__magic_name__						:						Dict										=(fft_window_size >> 1) + 1
										__magic_name__						:						Any										=hop_length
										__magic_name__						:						Optional[Any]										=max_length_s
										__magic_name__						:						List[Any]										=max_length_s * sampling_rate
										__magic_name__						:						Dict										=sampling_rate
										__magic_name__						:						int										=frequency_min
										__magic_name__						:						int										=frequency_max
										__magic_name__						:						Dict										=mel_filter_bank(
										    num_frequency_bins=self.nb_frequency_bins     ,			num_mel_filters=__snake_case     ,			min_frequency=__snake_case     ,			max_frequency=__snake_case     ,			sampling_rate=__snake_case     ,			norm=__snake_case     ,			mel_scale="""htk"""     ,			)
										__magic_name__						:						List[Any]										=mel_filter_bank(
										    num_frequency_bins=self.nb_frequency_bins     ,			num_mel_filters=__snake_case     ,			min_frequency=__snake_case     ,			max_frequency=__snake_case     ,			sampling_rate=__snake_case     ,			norm="""slaney"""     ,			mel_scale="""slaney"""     ,			)

						def      A__    (		self :int			):
										'''simple docstring'''

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

						def      A__    (		self :Union[str, Any]     ,			__snake_case :np.array     ,			__snake_case :Optional[np.array] = None			):
										'''simple docstring'''

										__magic_name__						:						Union[str, Any]										=spectrogram(
										    __snake_case     ,			window_function(self.fft_window_size     ,			"""hann"""			)     ,			frame_length=self.fft_window_size     ,			hop_length=self.hop_length     ,			power=2.0     ,			mel_filters=__snake_case     ,			log_mel="""dB"""     ,			)
										return log_mel_spectrogram.T

						def      A__    (		self :str     ,			__snake_case :int     ,			__snake_case :Optional[Any]     ,			__snake_case :List[Any]			):
										'''simple docstring'''

										__magic_name__						:						str										=np.array_split(list(range(0     ,			total_frames - chunk_frames + 1			)			)     ,			3			)
										if len(ranges[1]			) == 0:
														# if the audio is too short, we just use the first chunk
														__magic_name__						:						int										=[0]
										if len(ranges[2]			) == 0:
														# if the audio is too short, we just use the first chunk
														__magic_name__						:						Dict										=[0]
										# randomly choose index for each part
										__magic_name__						:						Tuple										=np.random.choice(ranges[0]			)
										__magic_name__						:						int										=np.random.choice(ranges[1]			)
										__magic_name__						:						Optional[int]										=np.random.choice(ranges[2]			)

										__magic_name__						:						int										=mel[idx_front : idx_front + chunk_frames, :]
										__magic_name__						:						List[Any]										=mel[idx_middle : idx_middle + chunk_frames, :]
										__magic_name__						:						List[str]										=mel[idx_back : idx_back + chunk_frames, :]

										__magic_name__						:						Dict										=torch.tensor(mel[None, None, :]			)
										__magic_name__						:						List[str]										=torch.nn.functional.interpolate(
										    __snake_case     ,			size=[chunk_frames, 64]     ,			mode="""bilinear"""     ,			align_corners=__snake_case			)
										__magic_name__						:						Dict										=mel_shrink[0][0].numpy()
										__magic_name__						:						Optional[Any]										=np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back]     ,			axis=0			)
										return mel_fusion

						def      A__    (		self :str     ,			__snake_case :np.array     ,			__snake_case :Any     ,			__snake_case :Union[str, Any]     ,			__snake_case :Tuple			):
										'''simple docstring'''

										if waveform.shape[0] > max_length:
														if truncation == "rand_trunc":
																		__magic_name__						:						Dict										=True
																		# random crop to max_length (for compatibility) -> this should be handled by self.pad
																		__magic_name__						:						Any										=len(__snake_case			) - max_length
																		__magic_name__						:						Any										=np.random.randint(0     ,			overflow + 1			)
																		__magic_name__						:						Union[str, Any]										=waveform[idx : idx + max_length]
																		__magic_name__						:						Any										=self._np_extract_fbank_features(__snake_case     ,			self.mel_filters_slaney			)[None, :]
														elif truncation == "fusion":
																		__magic_name__						:						Any										=self._np_extract_fbank_features(__snake_case     ,			self.mel_filters			)
																		__magic_name__						:						Dict										=max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
																		__magic_name__						:						Union[str, Any]										=mel.shape[0]
																		if chunk_frames == total_frames:
																						# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
																						# In this case, we just use the whole audio.
																						__magic_name__						:						List[Any]										=np.stack([mel, mel, mel, mel]     ,			axis=0			)
																						__magic_name__						:						int										=False
																		else:
																						__magic_name__						:						Any										=self._random_mel_fusion(__snake_case     ,			__snake_case     ,			__snake_case			)
																						__magic_name__						:						List[str]										=True
														else:
																		raise NotImplementedError(f"data_truncating {truncation} not implemented"			)

										else:
														__magic_name__						:						Dict										=False
														# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
														if waveform.shape[0] < max_length:
																		if padding == "repeat":
																						__magic_name__						:						List[Any]										=int(max_length / len(__snake_case			)			)
																						__magic_name__						:						List[str]										=np.stack(np.tile(__snake_case     ,			n_repeat + 1			)			)[:max_length]
																		if padding == "repeatpad":
																						__magic_name__						:						str										=int(max_length / len(__snake_case			)			)
																						__magic_name__						:						List[str]										=np.stack(np.tile(__snake_case     ,			__snake_case			)			)
																		__magic_name__						:						Optional[Any]										=np.pad(__snake_case     ,			(0, max_length - waveform.shape[0])     ,			mode="""constant"""     ,			constant_values=0			)

														if truncation == "fusion":
																		__magic_name__						:						Any										=self._np_extract_fbank_features(__snake_case     ,			self.mel_filters			)
																		__magic_name__						:						Tuple										=np.stack([input_mel, input_mel, input_mel, input_mel]     ,			axis=0			)
														else:
																		__magic_name__						:						Optional[Any]										=self._np_extract_fbank_features(__snake_case     ,			self.mel_filters_slaney			)[None, :]

										return input_mel, longer


						def __call__(		self :Optional[Any]     ,			__snake_case :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]     ,			__snake_case :str = None     ,			__snake_case :Optional[str] = None     ,			__snake_case :Optional[int] = None     ,			__snake_case :Optional[int] = None     ,			__snake_case :Optional[Union[str, TensorType]] = None     ,			**__snake_case :List[Any]     ,			):
										'''simple docstring'''

										__magic_name__						:						Any										=truncation if truncation is not None else self.truncation
										__magic_name__						:						str										=padding if padding else self.padding

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

										__magic_name__						:						Tuple										=isinstance(__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}"			)
										__magic_name__						:						List[Any]										=is_batched_numpy or (
										    isinstance(__snake_case     ,			(list, tuple)			) and (isinstance(raw_speech[0]     ,			(np.ndarray, tuple, list)			))
										)

										if is_batched:
														__magic_name__						:						Optional[Any]										=[np.asarray(__snake_case     ,			dtype=np.floataa			) for speech in raw_speech]
										elif not is_batched and not isinstance(__snake_case     ,			np.ndarray			):
														__magic_name__						:						Optional[int]										=np.asarray(__snake_case     ,			dtype=np.floataa			)
										elif isinstance(__snake_case     ,			np.ndarray			) and raw_speech.dtype is np.dtype(np.floataa			):
														__magic_name__						:						Any										=raw_speech.astype(np.floataa			)

										# always return batch
										if not is_batched:
														__magic_name__						:						Tuple										=[np.asarray(__snake_case			)]

										# convert to mel spectrogram, truncate and pad if needed.
										__magic_name__						:						List[Any]										=[
										    self._get_input_mel(__snake_case     ,			max_length if max_length else self.nb_max_samples     ,			__snake_case     ,			__snake_case			)
										    for waveform in raw_speech
										]

										__magic_name__						:						Optional[int]										=[]
										__magic_name__						:						str										=[]
										for mel, longer in padded_inputs:
														input_mel.append(__snake_case			)
														is_longer.append(__snake_case			)

										if truncation == "fusion" and sum(__snake_case			) == 0:
														# if no audio is longer than 10s, then randomly select one audio to be longer
														__magic_name__						:						List[Any]										=np.random.randint(0     ,			len(__snake_case			)			)
														__magic_name__						:						List[str]										=True

										if isinstance(input_mel[0]     ,			__snake_case			):
														__magic_name__						:						Dict										=[np.asarray(__snake_case     ,			dtype=np.floataa			) for feature in input_mel]

										# is_longer is a list of bool
										__magic_name__						:						Tuple										=[[longer] for longer in is_longer]

										__magic_name__						:						Tuple										={"""input_features""": input_mel, """is_longer""": is_longer}
										__magic_name__						:						str										=BatchFeature(__snake_case			)

										if return_tensors is not None:
														__magic_name__						:						Union[str, Any]										=input_features.convert_to_tensors(__snake_case			)

										return input_features








'''simple docstring'''





import warnings
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												=						{
    '''nvidia/segformer-b0-finetuned-ade-512-512''': (
        '''https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'''
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}




class 				UpperCAmelCase			(			_snake_case						):
 UpperCAmelCase				=					"segformer"


 def __init__(      self							:	Dict			,       __lowerCamelCase							:	Dict=3			,       __lowerCamelCase							:	List[str]=4			,       __lowerCamelCase							:	List[Any]=[2, 2, 2, 2]			,       __lowerCamelCase							:	List[str]=[8, 4, 2, 1]			,       __lowerCamelCase							:	Optional[Any]=[3_2, 6_4, 1_6_0, 2_5_6]			,       __lowerCamelCase							:	Tuple=[7, 3, 3, 3]			,       __lowerCamelCase							:	Tuple=[4, 2, 2, 2]			,       __lowerCamelCase							:	Any=[1, 2, 5, 8]			,       __lowerCamelCase							:	Optional[Any]=[4, 4, 4, 4]			,       __lowerCamelCase							:	Union[str, Any]="gelu"			,       __lowerCamelCase							:	Dict=0.0			,       __lowerCamelCase							:	Union[str, Any]=0.0			,       __lowerCamelCase							:	Tuple=0.1			,       __lowerCamelCase							:	Optional[Any]=0.02			,       __lowerCamelCase							:	Optional[int]=0.1			,       __lowerCamelCase							:	str=1e-6			,       __lowerCamelCase							:	List[Any]=2_5_6			,       __lowerCamelCase							:	int=2_5_5			,       **__lowerCamelCase							:	str			,       ):
    super().__init__(**__lowerCamelCase )

    if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
       warnings.warn(
           '''Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'''
           ''' removed, as the behaviour will default to that of reshape_last_stage = True.'''			,       __lowerCamelCase			,       )

    UpperCAmelCase__	:Dict      =      num_channels
    UpperCAmelCase__	:List[Any]      =      num_encoder_blocks
    UpperCAmelCase__	:List[str]      =      depths
    UpperCAmelCase__	:str      =      sr_ratios
    UpperCAmelCase__	:Optional[Any]      =      hidden_sizes
    UpperCAmelCase__	:List[str]      =      patch_sizes
    UpperCAmelCase__	:List[str]      =      strides
    UpperCAmelCase__	:List[str]      =      mlp_ratios
    UpperCAmelCase__	:Dict      =      num_attention_heads
    UpperCAmelCase__	:Tuple      =      hidden_act
    UpperCAmelCase__	:List[str]      =      hidden_dropout_prob
    UpperCAmelCase__	:List[Any]      =      attention_probs_dropout_prob
    UpperCAmelCase__	:int      =      classifier_dropout_prob
    UpperCAmelCase__	:str      =      initializer_range
    UpperCAmelCase__	:List[str]      =      drop_path_rate
    UpperCAmelCase__	:Dict      =      layer_norm_eps
    UpperCAmelCase__	:List[str]      =      decoder_hidden_size
    UpperCAmelCase__	:Optional[int]      =      kwargs.get('''reshape_last_stage'''			,       __lowerCamelCase )
    UpperCAmelCase__	:str      =      semantic_loss_ignore_index




class 				UpperCAmelCase			(			_snake_case						):
 UpperCAmelCase				=					version.parse("1.11"						)


 @property
 def        __SCREAMING_SNAKE_CASE					(      self							:	Optional[Any] ):
    return OrderedDict(
        [
            ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
        ] )


 @property
 def        __SCREAMING_SNAKE_CASE					(      self							:	Optional[int] ):
    return 1e-4





 @property
 def        __SCREAMING_SNAKE_CASE					(      self							:	List[str] ):
    return 1_2



