'''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 PaddingStrategy, TensorType, logging


_lowercase						: Any						=						logging.get_logger(__name__)





class     __magic_name__						(    _UpperCAmelCase):
			UpperCamelCase__				=       ['''input_features''', '''attention_mask''']







			def __init__(	self				:  Dict				,			lowercase_				:  Dict=80				,			lowercase_				:  Dict=16000				,			lowercase_				:  List[Any]=80				,			lowercase_				:  List[Any]=0.0				,			lowercase_				:  Any=True				,			lowercase_				:  List[str]=True				,			lowercase_				:  int=True				,			**lowercase_				:  Dict				,			):
										super().__init__(feature_size=lowercase_				,			sampling_rate=lowercase_				,			padding_value=lowercase_				,			**lowercase_    )
										lowercase_					:			Dict										=       num_mel_bins
										lowercase_					:			Any										=       do_ceptral_normalize
										lowercase_					:			Union[str, Any]										=       normalize_means
										lowercase_					:			int										=       normalize_vars
										lowercase_					:			List[Any]										=       True







			def 	SCREAMING_SNAKE_CASE_     (	self				:  List[Any]				,			lowercase_				:  np.ndarray				,			):
										lowercase_					:			Optional[Any]										=       waveform * (2**15)  # Kaldi compliance: 16-bit signed integers
										lowercase_					:			Optional[Any]										=       torch.from_numpy(lowercase_    ).unsqueeze(0    )
										lowercase_					:			Optional[Any]										=       ta_kaldi.fbank(lowercase_				,			num_mel_bins=self.num_mel_bins				,			sample_frequency=self.sampling_rate    )
										return features.numpy()







			@staticmethod
			def 	SCREAMING_SNAKE_CASE_     (	lowercase_				:  np.ndarray				,			lowercase_				:  int				,			lowercase_				:  Optional[bool] = True				,			lowercase_				:  Optional[bool] = True				,			lowercase_				:  float = 0.0				,			):
										# make sure we normalize float32 arrays
										if normalize_means:
																	lowercase_					:			Optional[Any]										=       x[:input_length].mean(axis=0    )
																	lowercase_					:			Dict										=       np.subtract(lowercase_				,			lowercase_    )
										if normalize_vars:
																	lowercase_					:			Dict										=       x[:input_length].std(axis=0    )
																	lowercase_					:			Optional[int]										=       np.divide(lowercase_				,			lowercase_    )

										if input_length < x.shape[0]:
																	lowercase_					:			List[Any]										=       padding_value

										# make sure array is in float32
										lowercase_					:			Optional[int]										=       x.astype(np.floataa    )

										return x







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]				,			lowercase_				:  List[np.ndarray]				,			lowercase_				:  Optional[np.ndarray] = None    ):
										lowercase_					:			Any										=       attention_mask.sum(-1    ) if attention_mask is not None else [x.shape[0] for x in input_features]
										return [
										    self.utterance_cmvn(lowercase_				,			lowercase_				,			self.normalize_means				,			self.normalize_vars				,			self.padding_value    )
										    for x, n in zip(lowercase_				,			lowercase_    )
										]







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

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

										lowercase_					:			Optional[Any]										=       isinstance(lowercase_				,			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}'''    )
										lowercase_					:			Dict										=       is_batched_numpy or (
										    isinstance(lowercase_				,			(list, tuple)    ) and (isinstance(raw_speech[0]				,			(np.ndarray, tuple, list)    ))
										)

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

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

										# extract fbank features
										lowercase_					:			Any										=       [self._extract_fbank_features(lowercase_    ) for waveform in raw_speech]

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

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

										# make sure list is in array format
										lowercase_					:			Optional[int]										=       padded_inputs.get("""input_features"""    )
										if isinstance(input_features[0]				,			lowercase_    ):
																	lowercase_					:			str										=       [np.asarray(lowercase_				,			dtype=np.floataa    ) for feature in input_features]

										lowercase_					:			Dict										=       padded_inputs.get("""attention_mask"""    )
										if attention_mask is not None:
																	lowercase_					:			Optional[int]										=       [np.asarray(lowercase_				,			dtype=np.intaa    ) for array in attention_mask]

										# Utterance-level cepstral mean and variance normalization
										if self.do_ceptral_normalize:
																	lowercase_					:			Optional[Any]										=       (
																	    np.array(lowercase_				,			dtype=np.intaa    )
																	    if self._get_padding_strategies(lowercase_				,			max_length=lowercase_    ) is not PaddingStrategy.DO_NOT_PAD
																	    else None
																	)
																	lowercase_					:			List[str]										=       self.normalize(
																	    padded_inputs["""input_features"""]				,			attention_mask=lowercase_    )

										if return_tensors is not None:
																	lowercase_					:			Optional[int]										=       padded_inputs.convert_to_tensors(lowercase_    )

										return padded_inputs






'''simple docstring'''




import math
import unittest




def 							lowerCamelCase	(      UpperCAmelCase__       :					int )			->      bool:
							assert isinstance(UpperCAmelCase__      ,      UpperCAmelCase__ ) and (
							    number >= 0
							), "'number' must been an int and positive"

							if 1 < number < 4:
														# 2 and 3 are primes
														return True
							elif number < 2 or number % 2 == 0 or number % 3 == 0:
														# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
														return False

							# All primes number are in format of 6k +/- 1
							for i in range(5      ,      int(math.sqrt(UpperCAmelCase__ ) + 1 )      ,      6 ):
														if number % i == 0 or number % (i + 2) == 0:
																					return False
							return True





class     __magic_name__						(    unittest.TestCase):







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Dict    ):
										self.assertTrue(is_prime(2    )    )
										self.assertTrue(is_prime(3    )    )
										self.assertTrue(is_prime(5    )    )
										self.assertTrue(is_prime(7    )    )
										self.assertTrue(is_prime(11    )    )
										self.assertTrue(is_prime(13    )    )
										self.assertTrue(is_prime(17    )    )
										self.assertTrue(is_prime(19    )    )
										self.assertTrue(is_prime(23    )    )
										self.assertTrue(is_prime(29    )    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]    ):
										with self.assertRaises(lowercase_    ):
																	is_prime(-19    )
										self.assertFalse(
										    is_prime(0    )				,			"""Zero doesn't have any positive factors, primes must have exactly two."""				,			)
										self.assertFalse(
										    is_prime(1    )				,			"""One only has 1 positive factor, primes must have exactly two."""				,			)
										self.assertFalse(is_prime(2 * 2    )    )
										self.assertFalse(is_prime(2 * 3    )    )
										self.assertFalse(is_prime(3 * 3    )    )
										self.assertFalse(is_prime(3 * 5    )    )
										self.assertFalse(is_prime(3 * 5 * 7    )    )


if __name__ == "__main__":
						unittest.main()





