

import warnings
from typing import Any, Dict, 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 ...utils import PaddingStrategy, TensorType, logging


__snake_case				:      int   		=			logging.get_logger(__name__)



class        A__(a_							):
						"""simple docstring"""






						_A    :				Dict       					=			['''input_values''', '''attention_mask''']





						def __init__(    self  ,      _lowercase = 1  ,      _lowercase = 16_000  ,      _lowercase = 0.0  ,      _lowercase = False  ,      _lowercase = 80  ,      _lowercase = 16  ,      _lowercase = 64  ,      _lowercase = "hann_window"  ,      _lowercase = 1.0  ,      _lowercase = 80  ,      _lowercase = 7_600  ,      _lowercase = 1e-10  ,      _lowercase = 2  ,      _lowercase = True  ,      **_lowercase  ,      )     -> List[Any]:
									super().__init__(feature_size=_lowercase  ,      sampling_rate=_lowercase  ,      padding_value=_lowercase  ,      **_lowercase    )
									a_						:						Optional[Any] 							= do_normalize
									a_						:						Tuple 							= return_attention_mask

									a_						:						Dict 							= num_mel_bins
									a_						:						Union[str, Any] 							= hop_length
									a_						:						Optional[Any] 							= win_length
									a_						:						List[Any] 							= win_function
									a_						:						Dict 							= frame_signal_scale
									a_						:						List[str] 							= fmin
									a_						:						Any 							= fmax
									a_						:						Tuple 							= mel_floor
									a_						:						Union[str, Any] 							= reduction_factor

									a_						:						List[Any] 							= win_length * sampling_rate // 1_000
									a_						:						Any 							= hop_length * sampling_rate // 1_000
									a_						:						List[str] 							= optimal_fft_length(self.sample_size    )
									a_						:						Dict 							= (self.n_fft // 2) + 1

									a_						:						int 							= window_function(window_length=self.sample_size  ,      name=self.win_function  ,      periodic=_lowercase    )

									a_						:						Any 							= mel_filter_bank(
									    num_frequency_bins=self.n_freqs  ,      num_mel_filters=self.num_mel_bins  ,      min_frequency=self.fmin  ,      max_frequency=self.fmax  ,      sampling_rate=self.sampling_rate  ,      norm="""slaney"""  ,      mel_scale="""slaney"""  ,      )

									if frame_signal_scale != 1.0:
												warnings.warn(
												    """The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers"""  ,      _lowercase  ,      )
									if reduction_factor != 2.0:
												warnings.warn(
												    """The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"""  ,      _lowercase  ,      )





						@staticmethod
						# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
						def 			UpperCamelCase__					(    _lowercase  ,      _lowercase  ,      _lowercase = 0.0    )     -> List[np.ndarray]:
									if attention_mask is not None:
												a_						:						str 							= np.array(_lowercase  ,      np.intaa    )
												a_						:						Optional[Any] 							= []

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

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

									return normed_input_values





						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      )     -> np.ndarray:
									a_						:						int 							= spectrogram(
									    _lowercase  ,      window=self.window  ,      frame_length=self.sample_size  ,      hop_length=self.sample_stride  ,      fft_length=self.n_fft  ,      mel_filters=self.mel_filters  ,      mel_floor=self.mel_floor  ,      log_mel="""log10"""  ,      )
									return log_mel_spec.T





						def __call__(    self  ,      _lowercase = None  ,      _lowercase = None  ,      _lowercase = False  ,      _lowercase = None  ,      _lowercase = False  ,      _lowercase = None  ,      _lowercase = None  ,      _lowercase = None  ,      _lowercase = None  ,      **_lowercase  ,      )     -> BatchFeature:
									if audio is None and audio_target is None:
												raise ValueError("""You must provide either `audio` or `audio_target` values."""    )

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

									if audio is not None:
												a_						:						Dict 							= self._process_audio(
												    _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      **_lowercase  ,      )
									else:
												a_						:						int 							= None

									if audio_target is not None:
												a_						:						Optional[int] 							= self._process_audio(
												    _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      **_lowercase  ,      )

												if inputs is None:
															return inputs_target
												else:
															a_						:						Optional[Any] 							= inputs_target["""input_values"""]
															a_						:						Union[str, Any] 							= inputs_target.get("""attention_mask"""    )
															if decoder_attention_mask is not None:
																		a_						:						List[Any] 							= decoder_attention_mask

									return inputs





						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      _lowercase = False  ,      _lowercase = False  ,      _lowercase = None  ,      _lowercase = False  ,      _lowercase = None  ,      _lowercase = None  ,      _lowercase = None  ,      **_lowercase  ,      )     -> BatchFeature:
									a_						:						int 							= isinstance(_lowercase  ,      np.ndarray    ) and len(speech.shape    ) > 1
									if is_batched_numpy and len(speech.shape    ) > 2:
												raise ValueError(F'''Only mono-channel audio is supported for input to {self}'''    )
									a_						:						Optional[int] 							= is_batched_numpy or (
									    isinstance(_lowercase  ,      (list, tuple)    ) and (isinstance(speech[0]  ,      (np.ndarray, tuple, list)    ))
									)

									if is_batched:
												a_						:						str 							= [np.asarray(_lowercase  ,      dtype=np.floataa    ) for speech in speech]
									elif not is_batched and not isinstance(_lowercase  ,      np.ndarray    ):
												a_						:						Tuple 							= np.asarray(_lowercase  ,      dtype=np.floataa    )
									elif isinstance(_lowercase  ,      np.ndarray    ) and speech.dtype is np.dtype(np.floataa    ):
												a_						:						Tuple 							= speech.astype(np.floataa    )

									# always return batch
									if not is_batched:
												a_						:						int 							= [speech]

									# needed to make pad() work on spectrogram inputs
									a_						:						Optional[int] 							= self.feature_size

									# convert into correct format for padding
									if is_target:
												a_						:						Any 							= [self._extract_mel_features(_lowercase    ) for waveform in speech]
												a_						:						List[Any] 							= BatchFeature({"""input_values""": features}    )
												a_						:						List[Any] 							= self.num_mel_bins
									else:
												a_						:						List[Any] 							= BatchFeature({"""input_values""": speech}    )

									a_						:						Any 							= self.pad(
									    _lowercase  ,      padding=_lowercase  ,      max_length=_lowercase  ,      truncation=_lowercase  ,      pad_to_multiple_of=_lowercase  ,      return_attention_mask=_lowercase  ,      **_lowercase  ,      )

									a_						:						List[Any] 							= feature_size_hack

									# convert input values to correct format
									a_						:						Union[str, Any] 							= padded_inputs["""input_values"""]
									if not isinstance(input_values[0]  ,      np.ndarray    ):
												a_						:						str 							= [np.asarray(_lowercase  ,      dtype=np.floataa    ) for array in input_values]
									elif (
									    not isinstance(_lowercase  ,      np.ndarray    )
									    and isinstance(input_values[0]  ,      np.ndarray    )
									    and input_values[0].dtype is np.dtype(np.floataa    )
									):
												a_						:						Optional[int] 							= [array.astype(np.floataa    ) for array in input_values]
									elif isinstance(_lowercase  ,      np.ndarray    ) and input_values.dtype is np.dtype(np.floataa    ):
												a_						:						Tuple 							= input_values.astype(np.floataa    )

									# convert attention_mask to correct format
									a_						:						Optional[Any] 							= padded_inputs.get("""attention_mask"""    )
									if attention_mask is not None:
												a_						:						List[str] 							= [np.asarray(_lowercase  ,      dtype=np.intaa    ) for array in attention_mask]

									# zero-mean and unit-variance normalization
									if not is_target and self.do_normalize:
												a_						:						Tuple 							= (
												    attention_mask
												    if self._get_padding_strategies(_lowercase  ,      max_length=_lowercase    ) is not PaddingStrategy.DO_NOT_PAD
												    else None
												)
												a_						:						Dict 							= self.zero_mean_unit_var_norm(
												    padded_inputs["""input_values"""]  ,      attention_mask=_lowercase  ,      padding_value=self.padding_value    )

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

									return padded_inputs





						def 			UpperCamelCase__					(    self    )     -> Dict[str, Any]:
									a_						:						Tuple 							= super().to_dict()

									# Don't serialize these as they are derived from the other properties.
									a_						:						List[Any] 							= ["""window""", """mel_filters""", """sample_size""", """sample_stride""", """n_fft""", """n_freqs"""]
									for name in names:
												if name in output:
															del output[name]

									return output





import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)


__snake_case				:      Union[str, Any]   		=			logging.get_logger(__name__)

__snake_case				:      Tuple   		=			OrderedDict(
    [
        ("""audio-spectrogram-transformer""", """ASTFeatureExtractor"""),
        ("""beit""", """BeitFeatureExtractor"""),
        ("""chinese_clip""", """ChineseCLIPFeatureExtractor"""),
        ("""clap""", """ClapFeatureExtractor"""),
        ("""clip""", """CLIPFeatureExtractor"""),
        ("""clipseg""", """ViTFeatureExtractor"""),
        ("""conditional_detr""", """ConditionalDetrFeatureExtractor"""),
        ("""convnext""", """ConvNextFeatureExtractor"""),
        ("""cvt""", """ConvNextFeatureExtractor"""),
        ("""data2vec-audio""", """Wav2Vec2FeatureExtractor"""),
        ("""data2vec-vision""", """BeitFeatureExtractor"""),
        ("""deformable_detr""", """DeformableDetrFeatureExtractor"""),
        ("""deit""", """DeiTFeatureExtractor"""),
        ("""detr""", """DetrFeatureExtractor"""),
        ("""dinat""", """ViTFeatureExtractor"""),
        ("""donut-swin""", """DonutFeatureExtractor"""),
        ("""dpt""", """DPTFeatureExtractor"""),
        ("""encodec""", """EncodecFeatureExtractor"""),
        ("""flava""", """FlavaFeatureExtractor"""),
        ("""glpn""", """GLPNFeatureExtractor"""),
        ("""groupvit""", """CLIPFeatureExtractor"""),
        ("""hubert""", """Wav2Vec2FeatureExtractor"""),
        ("""imagegpt""", """ImageGPTFeatureExtractor"""),
        ("""layoutlmv2""", """LayoutLMv2FeatureExtractor"""),
        ("""layoutlmv3""", """LayoutLMv3FeatureExtractor"""),
        ("""levit""", """LevitFeatureExtractor"""),
        ("""maskformer""", """MaskFormerFeatureExtractor"""),
        ("""mctct""", """MCTCTFeatureExtractor"""),
        ("""mobilenet_v1""", """MobileNetV1FeatureExtractor"""),
        ("""mobilenet_v2""", """MobileNetV2FeatureExtractor"""),
        ("""mobilevit""", """MobileViTFeatureExtractor"""),
        ("""nat""", """ViTFeatureExtractor"""),
        ("""owlvit""", """OwlViTFeatureExtractor"""),
        ("""perceiver""", """PerceiverFeatureExtractor"""),
        ("""poolformer""", """PoolFormerFeatureExtractor"""),
        ("""regnet""", """ConvNextFeatureExtractor"""),
        ("""resnet""", """ConvNextFeatureExtractor"""),
        ("""segformer""", """SegformerFeatureExtractor"""),
        ("""sew""", """Wav2Vec2FeatureExtractor"""),
        ("""sew-d""", """Wav2Vec2FeatureExtractor"""),
        ("""speech_to_text""", """Speech2TextFeatureExtractor"""),
        ("""speecht5""", """SpeechT5FeatureExtractor"""),
        ("""swiftformer""", """ViTFeatureExtractor"""),
        ("""swin""", """ViTFeatureExtractor"""),
        ("""swinv2""", """ViTFeatureExtractor"""),
        ("""table-transformer""", """DetrFeatureExtractor"""),
        ("""timesformer""", """VideoMAEFeatureExtractor"""),
        ("""tvlt""", """TvltFeatureExtractor"""),
        ("""unispeech""", """Wav2Vec2FeatureExtractor"""),
        ("""unispeech-sat""", """Wav2Vec2FeatureExtractor"""),
        ("""van""", """ConvNextFeatureExtractor"""),
        ("""videomae""", """VideoMAEFeatureExtractor"""),
        ("""vilt""", """ViltFeatureExtractor"""),
        ("""vit""", """ViTFeatureExtractor"""),
        ("""vit_mae""", """ViTFeatureExtractor"""),
        ("""vit_msn""", """ViTFeatureExtractor"""),
        ("""wav2vec2""", """Wav2Vec2FeatureExtractor"""),
        ("""wav2vec2-conformer""", """Wav2Vec2FeatureExtractor"""),
        ("""wavlm""", """Wav2Vec2FeatureExtractor"""),
        ("""whisper""", """WhisperFeatureExtractor"""),
        ("""xclip""", """CLIPFeatureExtractor"""),
        ("""yolos""", """YolosFeatureExtractor"""),
    ]
)

__snake_case				:      List[Any]   		=			_LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)


def 					_UpperCAmelCase				(						a__):

			'''simple docstring'''



			for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
						if class_name in extractors:
									a_						:						Tuple 							= model_type_to_module_name(a__)

									a_						:						Any 							= importlib.import_module(f'''.{module_name}'''  ,	"""transformers.models""")
									try:
												return getattr(a__  ,	a__)
									except AttributeError:
												continue

			for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
						if getattr(a__  ,	"""__name__"""  ,	a__) == class_name:
									return extractor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
			a_						:						Tuple 							= importlib.import_module("""transformers""")
			if hasattr(a__  ,	a__):
						return getattr(a__  ,	a__)

			return None


def 					_UpperCAmelCase				(						a__  ,	a__ = None  ,	a__ = False  ,	a__ = False  ,	a__ = None  ,	a__ = None  ,	a__ = None  ,	a__ = False  ,	**a__  ,	):

			'''simple docstring'''



			a_						:						List[str] 							= get_file_from_repo(
			    a__  ,	a__  ,	cache_dir=a__  ,	force_download=a__  ,	resume_download=a__  ,	proxies=a__  ,	use_auth_token=a__  ,	revision=a__  ,	local_files_only=a__  ,	)
			if resolved_config_file is None:
						logger.info(
						    """Could not locate the feature extractor configuration file, will try to use the model config instead.""")
						return {}

			with open(a__  ,	encoding="""utf-8""") as reader:
						return json.load(a__)



class        A__:
						"""simple docstring"""






						def __init__(    self    )     -> List[str]:
									raise EnvironmentError(
									    """AutoFeatureExtractor is designed to be instantiated """
									    """using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method."""    )





						@classmethod
						@replace_list_option_in_docstrings(_lowercase    )
						def 			UpperCamelCase__					(    cls  ,      _lowercase  ,      **_lowercase    )     -> Dict:
									a_						:						Tuple 							= kwargs.pop("""config"""  ,      _lowercase    )
									a_						:						Dict 							= kwargs.pop("""trust_remote_code"""  ,      _lowercase    )
									a_						:						Dict 							= True

									a_							,					a_						:						List[str] 							= FeatureExtractionMixin.get_feature_extractor_dict(_lowercase  ,      **_lowercase    )
									a_						:						Tuple 							= config_dict.get("""feature_extractor_type"""  ,      _lowercase    )
									a_						:						List[Any] 							= None
									if "AutoFeatureExtractor" in config_dict.get("""auto_map"""  ,      {}    ):
												a_						:						Any 							= config_dict["""auto_map"""]["""AutoFeatureExtractor"""]

									# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
									if feature_extractor_class is None and feature_extractor_auto_map is None:
												if not isinstance(_lowercase  ,      _lowercase    ):
															a_						:						List[str] 							= AutoConfig.from_pretrained(_lowercase  ,      **_lowercase    )
												# It could be in `config.feature_extractor_type``
												a_						:						List[Any] 							= getattr(_lowercase  ,      """feature_extractor_type"""  ,      _lowercase    )
												if hasattr(_lowercase  ,      """auto_map"""    ) and "AutoFeatureExtractor" in config.auto_map:
															a_						:						List[str] 							= config.auto_map["""AutoFeatureExtractor"""]

									if feature_extractor_class is not None:
												a_						:						int 							= feature_extractor_class_from_name(_lowercase    )

									a_						:						Dict 							= feature_extractor_auto_map is not None
									a_						:						Union[str, Any] 							= feature_extractor_class is not None or type(_lowercase    ) in FEATURE_EXTRACTOR_MAPPING
									a_						:						Optional[Any] 							= resolve_trust_remote_code(
									    _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase    )

									if has_remote_code and trust_remote_code:
												a_						:						int 							= get_class_from_dynamic_module(
												    _lowercase  ,      _lowercase  ,      **_lowercase    )
												a_						:						Tuple 							= kwargs.pop("""code_revision"""  ,      _lowercase    )
												if os.path.isdir(_lowercase    ):
															feature_extractor_class.register_for_auto_class()
												return feature_extractor_class.from_dict(_lowercase  ,      **_lowercase    )
									elif feature_extractor_class is not None:
												return feature_extractor_class.from_dict(_lowercase  ,      **_lowercase    )
									# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
									elif type(_lowercase    ) in FEATURE_EXTRACTOR_MAPPING:
												a_						:						List[str] 							= FEATURE_EXTRACTOR_MAPPING[type(_lowercase    )]
												return feature_extractor_class.from_dict(_lowercase  ,      **_lowercase    )

									raise ValueError(
									    F'''Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a '''
									    F'''`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following '''
									    F'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys()    )}'''    )





						@staticmethod
						def 			UpperCamelCase__					(    _lowercase  ,      _lowercase    )     -> List[Any]:
									FEATURE_EXTRACTOR_MAPPING.register(_lowercase  ,      _lowercase    )


