



'''simple docstring'''

from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


__lowerCAmelCase		    =     logging.get_logger(__name__)

class 			__magic_name__		(					_UpperCamelCase     ):
							lowerCAmelCase :					str            =      ['input_values', 'attention_mask']







							def __init__(							self      : Optional[int]			,_UpperCAmelCase      : int=1			,_UpperCAmelCase      : Dict=16000			,_UpperCAmelCase      : str=128			,_UpperCAmelCase      : List[Any]=1024			,_UpperCAmelCase      : Optional[Any]=0.0			,_UpperCAmelCase      : Any=True			,_UpperCAmelCase      : Union[str, Any]=-4.2_67_73_93			,_UpperCAmelCase      : Any=4.5_68_99_74			,_UpperCAmelCase      : Optional[Any]=False			,**_UpperCAmelCase      : Any			,):
									super().__init__(feature_size=_UpperCAmelCase			,sampling_rate=_UpperCAmelCase			,padding_value=_UpperCAmelCase			,**_UpperCAmelCase	)
									_a  :   Tuple				 =							num_mel_bins
									_a  :   Dict				 =							max_length
									_a  :   Optional[Any]				 =							do_normalize
									_a  :   int				 =							mean
									_a  :   Optional[int]				 =							std
									_a  :   Tuple				 =							return_attention_mask







							def 							__lowercase    (							self      : Optional[Any]			,_UpperCAmelCase      : np.ndarray			,_UpperCAmelCase      : int			,):
									_a  :   List[Any]				 =							torch.from_numpy(_UpperCAmelCase	).unsqueeze(0	)
									_a  :   Tuple				 =							ta_kaldi.fbank(
									    _UpperCAmelCase			,htk_compat=_UpperCAmelCase			,sample_frequency=self.sampling_rate			,use_energy=_UpperCAmelCase			,window_type='hanning'			,num_mel_bins=self.num_mel_bins			,dither=0.0			,frame_shift=10			,)

									_a  :   int				 =							fbank.shape[0]
									_a  :   Any				 =							max_length - n_frames

									# pad or truncate, depending on difference
									if difference > 0:
											_a  :   Optional[int]				 =							torch.nn.ZeroPadad((0, 0, 0, difference)	)
											_a  :   Union[str, Any]				 =							pad_module(_UpperCAmelCase	)
									elif difference < 0:
											_a  :   List[str]				 =							fbank[0:max_length, :]

									_a  :   List[Any]				 =							fbank.numpy()

									return fbank







							def 							__lowercase    (							self      : Dict			,_UpperCAmelCase      : np.ndarray	):
									return (input_values - (self.mean)) / (self.std * 2)







							def __call__(							self      : str			,_UpperCAmelCase      : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]			,_UpperCAmelCase      : Optional[int] = None			,_UpperCAmelCase      : Optional[Union[str, TensorType]] = None			,**_UpperCAmelCase      : Tuple			,):

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

									_a  :   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}"""	)
									_a  :   str				 =							is_batched_numpy or (
									    isinstance(_UpperCAmelCase			,(list, tuple)	) and (isinstance(raw_speech[0]			,(np.ndarray, tuple, list)	))
									)

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

									# always return batch
									if not is_batched:
											_a  :   List[Any]				 =							[raw_speech]

									# extract fbank features and pad/truncate to max_length
									_a  :   List[str]				 =							[self._extract_fbank_features(_UpperCAmelCase			,max_length=self.max_length	) for waveform in raw_speech]

									# convert into BatchFeature
									_a  :   Tuple				 =							BatchFeature({'input_values': features}	)

									# make sure list is in array format
									_a  :   Tuple				 =							padded_inputs.get('input_values'	)
									if isinstance(input_values[0]			,_UpperCAmelCase	):
											_a  :   Optional[Any]				 =							[np.asarray(_UpperCAmelCase			,dtype=np.floataa	) for feature in input_values]

									# normalization
									if self.do_normalize:
											_a  :   List[str]				 =							[self.normalize(_UpperCAmelCase	) for feature in input_values]

									if return_tensors is not None:
											_a  :   Tuple				 =							padded_inputs.convert_to_tensors(_UpperCAmelCase	)

									return padded_inputs









'''simple docstring'''

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


__lowerCAmelCase		    =     {'''configuration_t5''': ['''T5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''T5Config''', '''T5OnnxConfig''']}

try:
							if not is_sentencepiece_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__lowerCAmelCase		    =     ['''T5Tokenizer''']

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__lowerCAmelCase		    =     ['''T5TokenizerFast''']

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__lowerCAmelCase		    =     [
							    '''T5_PRETRAINED_MODEL_ARCHIVE_LIST''',
							    '''T5EncoderModel''',
							    '''T5ForConditionalGeneration''',
							    '''T5Model''',
							    '''T5PreTrainedModel''',
							    '''load_tf_weights_in_t5''',
							    '''T5ForQuestionAnswering''',
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__lowerCAmelCase		    =     [
							    '''TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST''',
							    '''TFT5EncoderModel''',
							    '''TFT5ForConditionalGeneration''',
							    '''TFT5Model''',
							    '''TFT5PreTrainedModel''',
							]

try:
							if not is_flax_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__lowerCAmelCase		    =     [
							    '''FlaxT5EncoderModel''',
							    '''FlaxT5ForConditionalGeneration''',
							    '''FlaxT5Model''',
							    '''FlaxT5PreTrainedModel''',
							]


if TYPE_CHECKING:
							from .configuration_ta import T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TaConfig, TaOnnxConfig

							try:
														if not is_sentencepiece_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_ta import TaTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_ta_fast import TaTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_ta import (
														    T5_PRETRAINED_MODEL_ARCHIVE_LIST,
														    TaEncoderModel,
														    TaForConditionalGeneration,
														    TaForQuestionAnswering,
														    TaModel,
														    TaPreTrainedModel,
														    load_tf_weights_in_ta,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_tf_ta import (
														    TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST,
														    TFTaEncoderModel,
														    TFTaForConditionalGeneration,
														    TFTaModel,
														    TFTaPreTrainedModel,
														)

							try:
														if not is_flax_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_flax_ta import (
														    FlaxTaEncoderModel,
														    FlaxTaForConditionalGeneration,
														    FlaxTaModel,
														    FlaxTaPreTrainedModel,
														)


else:
							import sys

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




