





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   UpperCamelCase_       (     UpperCamelCase__    ):
							lowerCamelCase_           =					["input_features", "attention_mask"]


							def __init__(							self    :List[Any]							,				__A    :int=80							,				__A    :Dict=1_6000							,				__A    :str=0.0							,				__A    :Dict=10							,				__A    :Optional[int]=25							,				__A    :Dict="hamming_window"							,				__A    :List[str]=3_2_7_6_8.0							,				__A    :Dict=0.9_7							,				__A    :Union[str, Any]=1.0							,				__A    :List[str]=True							,				__A    :Tuple=True							,				__A    :List[Any]=False							,				**__A    :Optional[int]							,				)   ->   List[str]:



									"""simple docstring"""



									super().__init__(feature_size=__A							,				sampling_rate=__A							,				padding_value=__A							,				**__A		)

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

									SCREAMING_SNAKE_CASE__			=      win_length * sampling_rate // 1000
									SCREAMING_SNAKE_CASE__			=      hop_length * sampling_rate // 1000

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


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



									"""simple docstring"""



									if self.win_function == "hamming_window":
											SCREAMING_SNAKE_CASE__			=      window_function(window_length=self.sample_size							,				name=self.win_function							,				periodic=__A		)
									else:
											SCREAMING_SNAKE_CASE__			=      window_function(window_length=self.sample_size							,				name=self.win_function		)

									SCREAMING_SNAKE_CASE__			=      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							,				)

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


							def      _snake_case  (							self    :Optional[int]							,				__A    :Optional[int]							,				__A    :Optional[Any]							,				__A    :Optional[Any]		)   ->   List[str]:



									"""simple docstring"""



									if self.normalize_means:
											SCREAMING_SNAKE_CASE__			=      x[:input_length].mean(axis=0		)
											SCREAMING_SNAKE_CASE__			=      np.subtract(__A							,				__A		)
									if self.normalize_vars:
											SCREAMING_SNAKE_CASE__			=      x[:input_length].std(axis=0		)
											SCREAMING_SNAKE_CASE__			=      np.divide(__A							,				__A		)

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

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

									return x


							def      _snake_case  (							self    :Tuple							,				__A    :List[np.ndarray]							,				__A    :Optional[np.ndarray] = None		)   ->   List[np.ndarray]:



									"""simple docstring"""



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


							def __call__(							self    :Optional[int]							,				__A    :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]							,				__A    :Union[bool, str, PaddingStrategy] = False							,				__A    :Optional[int] = None							,				__A    :bool = False							,				__A    :Optional[int] = None							,				__A    :Optional[bool] = None							,				__A    :Optional[Union[str, TensorType]] = None							,				__A    :Optional[int] = None							,				**__A    :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} 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."""		)

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

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

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

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

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

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

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

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

									if return_tensors is not None:
											SCREAMING_SNAKE_CASE__			=      padded_inputs.convert_to_tensors(__A		)

									return padded_inputs






# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_lowerCamelCase   				=			{
    'configuration_xmod': [
        'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'XmodConfig',
        'XmodOnnxConfig',
    ],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	_lowerCamelCase   				=			[
	    'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST',
	    'XmodForCausalLM',
	    'XmodForMaskedLM',
	    'XmodForMultipleChoice',
	    'XmodForQuestionAnswering',
	    'XmodForSequenceClassification',
	    'XmodForTokenClassification',
	    'XmodModel',
	    'XmodPreTrainedModel',
	]

if TYPE_CHECKING:
	from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_xmod import (
		    XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
		    XmodForCausalLM,
		    XmodForMaskedLM,
		    XmodForMultipleChoice,
		    XmodForQuestionAnswering,
		    XmodForSequenceClassification,
		    XmodForTokenClassification,
		    XmodModel,
		    XmodPreTrainedModel,
		)

else:
	import sys

	_lowerCamelCase   				=			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)