from math import ceil
from typing import List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging


__UpperCamelCase	: str    		=  logging.get_logger(__name__)





class       lowercase__		(     UpperCamelCase_):
						UpperCamelCase_  =	["""audio_values""", """audio_mask"""]


						def __init__( self			:       Optional[Any]					,	UpperCamelCase__			:       List[str]=2048					,	UpperCamelCase__			:       List[Any]=1					,	UpperCamelCase__			:       str=[16, 16]					,	UpperCamelCase__			:       List[str]=128					,	UpperCamelCase__			:       Union[str, Any]=4_4100					,	UpperCamelCase__			:       Optional[int]=86					,	UpperCamelCase__			:       Dict=2048					,	UpperCamelCase__			:       Any=0.0					,	**UpperCamelCase__			:       List[Any]					,	):





												'''simple docstring'''





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

												SCREAMING_SNAKE_CASE							:					str           =							spectrogram_length
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							num_channels
												SCREAMING_SNAKE_CASE							:					List[Any]           =							patch_size
												SCREAMING_SNAKE_CASE							:					str           =							feature_size // self.patch_size[1]
												SCREAMING_SNAKE_CASE							:					Any           =							n_fft
												SCREAMING_SNAKE_CASE							:					List[str]           =							sampling_rate // hop_length_to_sampling_rate
												SCREAMING_SNAKE_CASE							:					List[str]           =							sampling_rate
												SCREAMING_SNAKE_CASE							:					Dict           =							padding_value
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							mel_filter_bank(
												    num_frequency_bins=1 + n_fft // 2					,	num_mel_filters=UpperCamelCase__					,	min_frequency=0.0					,	max_frequency=2_2050.0					,	sampling_rate=UpperCamelCase__					,	norm='''slaney'''					,	mel_scale='''slaney'''					,	).T


						def  __A ( self			:       str					,	UpperCamelCase__			:       np.array		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							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.T					,	log_mel='''dB'''					,	db_range=80.0					,	)
												SCREAMING_SNAKE_CASE							:					Any           =							log_spec[:, :-1]
												SCREAMING_SNAKE_CASE							:					List[Any]           =							log_spec - 20.0
												SCREAMING_SNAKE_CASE							:					int           =							np.clip(log_spec / 40.0					,	-2.0					,	0.0		) + 1.0
												return log_spec



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





												'''simple docstring'''





												if sampling_rate is not None:
																		if sampling_rate != self.sampling_rate:
																								raise ValueError(
																								    '''This feature extractor is set to support sampling rate'''
																								    f""" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"""
																								    f""" 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.'''		)

												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							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}"""		)
												SCREAMING_SNAKE_CASE							:					List[str]           =							is_batched_numpy or (
												    isinstance(UpperCamelCase__					,	(list, tuple)		) and (isinstance(raw_speech[0]					,	(np.ndarray, tuple, list)		))
												)
												if is_batched:
																		SCREAMING_SNAKE_CASE							:					List[Any]           =							[np.asarray([speech]					,	dtype=np.floataa		).T for speech in raw_speech]
												elif not is_batched and not isinstance(UpperCamelCase__					,	np.ndarray		):
																		SCREAMING_SNAKE_CASE							:					Any           =							np.asarray(UpperCamelCase__					,	dtype=np.floataa		)
												elif isinstance(UpperCamelCase__					,	np.ndarray		) and raw_speech.dtype is np.dtype(np.floataa		):
																		SCREAMING_SNAKE_CASE							:					Any           =							raw_speech.astype(np.floataa		)
												# always return batch
												if not is_batched:
																		SCREAMING_SNAKE_CASE							:					Dict           =							[np.asarray([raw_speech]		).T]

												# Convert audio signals to log mel spectrograms, truncate by time axis
												SCREAMING_SNAKE_CASE							:					List[str]           =							[
												    self._np_extract_fbank_features(waveform.squeeze()		).T[: self.spectrogram_length] for waveform in raw_speech
												]
												if isinstance(audio_features[0]					,	UpperCamelCase__		):
																		SCREAMING_SNAKE_CASE							:					Tuple           =							[np.asarray(UpperCamelCase__					,	dtype=np.floataa		) for feature in audio_features]

												# Create audio attention mask
												SCREAMING_SNAKE_CASE							:					Tuple           =							max(
												    [ceil(feature.shape[0] / self.patch_size[0]		) * self.freq_len for feature in audio_features]		)  # The maximum number of audio patches in a batch
												if return_attention_mask:
																		SCREAMING_SNAKE_CASE							:					int           =							[
																		    (ceil(feature.shape[0] / self.patch_size[0]		) * self.freq_len) * [1]
																		    + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]		) * self.freq_len) * [0]
																		    for feature in audio_features
																		]
																		SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							np.array(UpperCamelCase__		).astype(np.floataa		)

												# convert into correct format for padding
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
												SCREAMING_SNAKE_CASE							:					List[str]           =							np.ones([len(UpperCamelCase__		), 1, max_time_len, self.feature_size]		).astype(np.floataa		)
												SCREAMING_SNAKE_CASE							:					Any           =							padded_audio_features * self.padding_value
												for i in range(len(UpperCamelCase__		)		):
																		SCREAMING_SNAKE_CASE							:					Optional[Any]           =							audio_features[i]
																		SCREAMING_SNAKE_CASE							:					Optional[int]           =							feature

												# return as BatchFeature
												if return_attention_mask:
																		SCREAMING_SNAKE_CASE							:					Optional[Any]           =							{'''audio_values''': padded_audio_features, '''audio_mask''': audio_mask}
												else:
																		SCREAMING_SNAKE_CASE							:					Dict           =							{'''audio_values''': padded_audio_features}

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							BatchFeature(data=UpperCamelCase__					,	tensor_type=UpperCamelCase__		)
												return encoded_inputs






# Copyright 2021 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.

import argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


__UpperCamelCase	: Dict    		=  [
    'EAGER',
    'AOT_EAGER',
    'INDUCTOR',
    'NVFUSER',
    'AOT_NVFUSER',
    'AOT_CUDAGRAPHS',
    'OFI',
    'FX2TRT',
    'ONNXRT',
    'IPEX',
]
def    A			(					_lowercase	,						_lowercase=None	,						_lowercase=None	,						_lowercase=None		):
						SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							True
						while ask_again:
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							input(_lowercase		)
												try:
																		if default is not None and len(_lowercase		) == 0:
																								return default
																		return convert_value(_lowercase		) if convert_value is not None else result
												except Exception:
																		if error_message is not None:
																								print(_lowercase		)
def    A			(					_lowercase	,						_lowercase=[]	,						_lowercase=None	,						_lowercase=0		):
						SCREAMING_SNAKE_CASE							:					Dict           =							BulletMenu(_lowercase	,						_lowercase		)
						SCREAMING_SNAKE_CASE							:					str           =							menu.run(default_choice=_lowercase		)
						return convert_value(_lowercase		) if convert_value is not None else result
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Dict           =							int(_lowercase		)
						return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value]		)
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Any           =							int(_lowercase		)
						return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value]		)
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							int(_lowercase		)
						return DynamoBackend(DYNAMO_BACKENDS[value]		).value
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							int(_lowercase		)
						return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value]		)
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Dict           =							int(_lowercase		)
						return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value]		)
def    A			(					_lowercase		):
						return {"yes": True, "no": False}[value.lower()]





class       lowercase__		(     argparse.RawDescriptionHelpFormatter):


						def  __A ( self			:       List[str]					,	UpperCamelCase__			:       List[str]					,	UpperCamelCase__			:       Dict					,	UpperCamelCase__			:       Dict					,	UpperCamelCase__			:       Dict		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					str           =							super()._format_usage(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							usage.replace('''<command> [<args>] '''					,	''''''		)
												return usage





