import itertools
import random
import unittest

import numpy as np

from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
							import torch


_lowerCamelCase					:   str							=		random.Random()





def 	__lowerCamelCase							(UpperCAmelCase__     :							List[Any]      , UpperCAmelCase__     :							Optional[int]=1.0      , UpperCAmelCase__     :							Any=None      , UpperCAmelCase__     :							Dict=None  ):
					if rng is None:
										SCREAMING_SNAKE_CASE    			=       global_rng

					SCREAMING_SNAKE_CASE    			=       []
					for batch_idx in range(shape[0]  ):
										values.append([]  )
										for _ in range(shape[1]  ):
															values[-1].append(rng.random() * scale  )

					return values


@require_torch
class 						lowercase    (     unittest.TestCase     ):




							def __init__(						self   :					List[str]	,							_UpperCamelCase   :					List[str]	,							_UpperCamelCase   :					List[Any]=7	,							_UpperCamelCase   :					Dict=400	,							_UpperCamelCase   :					Tuple=2_000	,							_UpperCamelCase   :					Any=1	,							_UpperCamelCase   :					Union[str, Any]=0.0	,							_UpperCamelCase   :					List[Any]=16_000	,							_UpperCamelCase   :					Dict=True	,							_UpperCamelCase   :					Any=80	,							_UpperCamelCase   :					str=16	,							_UpperCamelCase   :					Tuple=64	,							_UpperCamelCase   :					Optional[Any]="hann_window"	,							_UpperCamelCase   :					Dict=80	,							_UpperCamelCase   :					List[str]=7_600	,							_UpperCamelCase   :					Union[str, Any]=1e-10	,							_UpperCamelCase   :					Optional[Any]=True	,							)					->				Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       parent
												SCREAMING_SNAKE_CASE    			=       batch_size
												SCREAMING_SNAKE_CASE    			=       min_seq_length
												SCREAMING_SNAKE_CASE    			=       max_seq_length
												SCREAMING_SNAKE_CASE    			=       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
												SCREAMING_SNAKE_CASE    			=       feature_size
												SCREAMING_SNAKE_CASE    			=       padding_value
												SCREAMING_SNAKE_CASE    			=       sampling_rate
												SCREAMING_SNAKE_CASE    			=       do_normalize
												SCREAMING_SNAKE_CASE    			=       num_mel_bins
												SCREAMING_SNAKE_CASE    			=       hop_length
												SCREAMING_SNAKE_CASE    			=       win_length
												SCREAMING_SNAKE_CASE    			=       win_function
												SCREAMING_SNAKE_CASE    			=       fmin
												SCREAMING_SNAKE_CASE    			=       fmax
												SCREAMING_SNAKE_CASE    			=       mel_floor
												SCREAMING_SNAKE_CASE    			=       return_attention_mask




							def 	__snake_case(						self   :					Dict      )					->				Union[str, Any]:



												'''simple docstring'''

												return {
												    "feature_size": self.feature_size,
												    "padding_value": self.padding_value,
												    "sampling_rate": self.sampling_rate,
												    "do_normalize": self.do_normalize,
												    "num_mel_bins": self.num_mel_bins,
												    "hop_length": self.hop_length,
												    "win_length": self.win_length,
												    "win_function": self.win_function,
												    "fmin": self.fmin,
												    "fmax": self.fmax,
												    "mel_floor": self.mel_floor,
												    "return_attention_mask": self.return_attention_mask,
												}




							def 	__snake_case(						self   :					List[Any]	,							_UpperCamelCase   :					List[Any]=False	,							_UpperCamelCase   :					List[Any]=False      )					->				Optional[int]:



												'''simple docstring'''

												def _flatten(_UpperCamelCase   :					List[Any]      ):
																	return list(itertools.chain(*_UpperCamelCase      )      )

												if equal_length:
																	SCREAMING_SNAKE_CASE    			=       floats_list((self.batch_size, self.max_seq_length)      )
												else:
																	# make sure that inputs increase in size
																	SCREAMING_SNAKE_CASE    			=       [
																	    _flatten(floats_list((x, self.feature_size)      )      )
																	    for x in range(self.min_seq_length	,							self.max_seq_length	,							self.seq_length_diff      )
																	]

												if numpify:
																	SCREAMING_SNAKE_CASE    			=       [np.asarray(_UpperCamelCase      ) for x in speech_inputs]

												return speech_inputs





							def 	__snake_case(						self   :					int	,							_UpperCamelCase   :					Any=False	,							_UpperCamelCase   :					Dict=False      )					->				List[Any]:



												'''simple docstring'''

												if equal_length:
																	SCREAMING_SNAKE_CASE    			=       [floats_list((self.max_seq_length, self.num_mel_bins)      ) for _ in range(self.batch_size      )]
												else:
																	# make sure that inputs increase in size
																	SCREAMING_SNAKE_CASE    			=       [
																	    floats_list((x, self.num_mel_bins)      )
																	    for x in range(self.min_seq_length	,							self.max_seq_length	,							self.seq_length_diff      )
																	]

												if numpify:
																	SCREAMING_SNAKE_CASE    			=       [np.asarray(_UpperCamelCase      ) for x in speech_inputs]

												return speech_inputs



@require_torch
class 						lowercase    (     a				,       unittest.TestCase     ):
							lowercase__						:       List[Any]								=							SpeechTaFeatureExtractor




							def 	__snake_case(						self   :					str      )					->				str:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       SpeechTaFeatureExtractionTester(self      )




							def 	__snake_case(						self   :					Any	,							_UpperCamelCase   :					List[Any]      )					->				List[str]:



												'''simple docstring'''

												self.assertTrue(np.all(np.mean(_UpperCamelCase	,							axis=0      ) < 1e-3      )      )
												self.assertTrue(np.all(np.abs(np.var(_UpperCamelCase	,							axis=0      ) - 1      ) < 1e-3      )      )




							def 	__snake_case(						self   :					List[str]      )					->				int:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
												# create three inputs of length 800, 1000, and 1200
												SCREAMING_SNAKE_CASE    			=       [floats_list((1, x)      )[0] for x in range(800	,							1_400	,							200      )]
												SCREAMING_SNAKE_CASE    			=       [np.asarray(_UpperCamelCase      ) for speech_input in speech_inputs]

												# Test not batched input
												SCREAMING_SNAKE_CASE    			=       feat_extract(speech_inputs[0]	,							return_tensors="np"      ).input_values
												SCREAMING_SNAKE_CASE    			=       feat_extract(np_speech_inputs[0]	,							return_tensors="np"      ).input_values
												self.assertTrue(np.allclose(_UpperCamelCase	,							_UpperCamelCase	,							atol=1e-3      )      )

												# Test batched
												SCREAMING_SNAKE_CASE    			=       feat_extract(_UpperCamelCase	,							return_tensors="np"      ).input_values
												SCREAMING_SNAKE_CASE    			=       feat_extract(_UpperCamelCase	,							return_tensors="np"      ).input_values
												for enc_seq_a, enc_seq_a in zip(_UpperCamelCase	,							_UpperCamelCase      ):
																	self.assertTrue(np.allclose(_UpperCamelCase	,							_UpperCamelCase	,							atol=1e-3      )      )




							def 	__snake_case(						self   :					Any      )					->				Dict:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
												SCREAMING_SNAKE_CASE    			=       [floats_list((1, x)      )[0] for x in range(800	,							1_400	,							200      )]

												SCREAMING_SNAKE_CASE    			=       ["longest", "max_length", "do_not_pad"]
												SCREAMING_SNAKE_CASE    			=       [None, 1_600, None]
												for max_length, padding in zip(_UpperCamelCase	,							_UpperCamelCase      ):
																	SCREAMING_SNAKE_CASE    			=       feat_extract(_UpperCamelCase	,							padding=_UpperCamelCase	,							max_length=_UpperCamelCase	,							return_tensors="np"      )
																	SCREAMING_SNAKE_CASE    			=       processed.input_values

																	self._check_zero_mean_unit_variance(input_values[0][:800]      )
																	self.assertTrue(input_values[0][800:].sum() < 1e-6      )
																	self._check_zero_mean_unit_variance(input_values[1][:1_000]      )
																	self.assertTrue(input_values[0][1_000:].sum() < 1e-6      )
																	self._check_zero_mean_unit_variance(input_values[2][:1_200]      )




							def 	__snake_case(						self   :					Dict      )					->				Dict:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
												SCREAMING_SNAKE_CASE    			=       range(800	,							1_400	,							200      )
												SCREAMING_SNAKE_CASE    			=       [floats_list((1, x)      )[0] for x in lengths]

												SCREAMING_SNAKE_CASE    			=       ["longest", "max_length", "do_not_pad"]
												SCREAMING_SNAKE_CASE    			=       [None, 1_600, None]

												for max_length, padding in zip(_UpperCamelCase	,							_UpperCamelCase      ):
																	SCREAMING_SNAKE_CASE    			=       feat_extract(_UpperCamelCase	,							max_length=_UpperCamelCase	,							padding=_UpperCamelCase      )
																	SCREAMING_SNAKE_CASE    			=       processed.input_values

																	self._check_zero_mean_unit_variance(input_values[0][:800]      )
																	self._check_zero_mean_unit_variance(input_values[1][:1_000]      )
																	self._check_zero_mean_unit_variance(input_values[2][:1_200]      )




							def 	__snake_case(						self   :					List[Any]      )					->				List[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
												SCREAMING_SNAKE_CASE    			=       [floats_list((1, x)      )[0] for x in range(800	,							1_400	,							200      )]
												SCREAMING_SNAKE_CASE    			=       feat_extract(
												    _UpperCamelCase	,							truncation=_UpperCamelCase	,							max_length=1_000	,							padding="max_length"	,							return_tensors="np"      )
												SCREAMING_SNAKE_CASE    			=       processed.input_values

												self._check_zero_mean_unit_variance(input_values[0, :800]      )
												self._check_zero_mean_unit_variance(input_values[1]      )
												self._check_zero_mean_unit_variance(input_values[2]      )




							def 	__snake_case(						self   :					Dict      )					->				Dict:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
												SCREAMING_SNAKE_CASE    			=       [floats_list((1, x)      )[0] for x in range(800	,							1_400	,							200      )]
												SCREAMING_SNAKE_CASE    			=       feat_extract(
												    _UpperCamelCase	,							truncation=_UpperCamelCase	,							max_length=1_000	,							padding="longest"	,							return_tensors="np"      )
												SCREAMING_SNAKE_CASE    			=       processed.input_values

												self._check_zero_mean_unit_variance(input_values[0, :800]      )
												self._check_zero_mean_unit_variance(input_values[1, :1_000]      )
												self._check_zero_mean_unit_variance(input_values[2]      )

												# make sure that if max_length < longest -> then pad to max_length
												self.assertTrue(input_values.shape == (3, 1_000)      )

												SCREAMING_SNAKE_CASE    			=       [floats_list((1, x)      )[0] for x in range(800	,							1_400	,							200      )]
												SCREAMING_SNAKE_CASE    			=       feat_extract(
												    _UpperCamelCase	,							truncation=_UpperCamelCase	,							max_length=2_000	,							padding="longest"	,							return_tensors="np"      )
												SCREAMING_SNAKE_CASE    			=       processed.input_values

												self._check_zero_mean_unit_variance(input_values[0, :800]      )
												self._check_zero_mean_unit_variance(input_values[1, :1_000]      )
												self._check_zero_mean_unit_variance(input_values[2]      )

												# make sure that if max_length > longest -> then pad to longest
												self.assertTrue(input_values.shape == (3, 1_200)      )




							def 	__snake_case(						self   :					Any      )					->				List[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
												SCREAMING_SNAKE_CASE    			=       np.random.rand(100      ).astype(np.floataa      )
												SCREAMING_SNAKE_CASE    			=       np_speech_inputs.tolist()

												for inputs in [py_speech_inputs, np_speech_inputs]:
																	SCREAMING_SNAKE_CASE    			=       feature_extractor.pad([{"input_values": inputs}]	,							return_tensors="np"      )
																	self.assertTrue(np_processed.input_values.dtype == np.floataa      )
																	SCREAMING_SNAKE_CASE    			=       feature_extractor.pad([{"input_values": inputs}]	,							return_tensors="pt"      )
																	self.assertTrue(pt_processed.input_values.dtype == torch.floataa      )




							def 	__snake_case(						self   :					List[Any]      )					->				Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
												# create three inputs of length 800, 1000, and 1200
												SCREAMING_SNAKE_CASE    			=       [floats_list((1, x)      )[0] for x in range(800	,							1_400	,							200      )]
												SCREAMING_SNAKE_CASE    			=       [np.asarray(_UpperCamelCase      ) for speech_input in speech_inputs]

												# Test feature size
												SCREAMING_SNAKE_CASE    			=       feature_extractor(audio_target=_UpperCamelCase	,							padding=_UpperCamelCase	,							return_tensors="np"      ).input_values
												self.assertTrue(input_values.ndim == 3      )
												self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins      )

												# Test not batched input
												SCREAMING_SNAKE_CASE    			=       feature_extractor(speech_inputs[0]	,							return_tensors="np"      ).input_values
												SCREAMING_SNAKE_CASE    			=       feature_extractor(np_speech_inputs[0]	,							return_tensors="np"      ).input_values
												self.assertTrue(np.allclose(_UpperCamelCase	,							_UpperCamelCase	,							atol=1e-3      )      )

												# Test batched
												SCREAMING_SNAKE_CASE    			=       feature_extractor(_UpperCamelCase	,							return_tensors="np"      ).input_values
												SCREAMING_SNAKE_CASE    			=       feature_extractor(_UpperCamelCase	,							return_tensors="np"      ).input_values
												for enc_seq_a, enc_seq_a in zip(_UpperCamelCase	,							_UpperCamelCase      ):
																	self.assertTrue(np.allclose(_UpperCamelCase	,							_UpperCamelCase	,							atol=1e-3      )      )

												# Test 2-D numpy arrays are batched.
												SCREAMING_SNAKE_CASE    			=       [floats_list((1, x)      )[0] for x in (800, 800, 800)]
												SCREAMING_SNAKE_CASE    			=       np.asarray(_UpperCamelCase      )
												SCREAMING_SNAKE_CASE    			=       feature_extractor(_UpperCamelCase	,							return_tensors="np"      ).input_values
												SCREAMING_SNAKE_CASE    			=       feature_extractor(_UpperCamelCase	,							return_tensors="np"      ).input_values
												for enc_seq_a, enc_seq_a in zip(_UpperCamelCase	,							_UpperCamelCase      ):
																	self.assertTrue(np.allclose(_UpperCamelCase	,							_UpperCamelCase	,							atol=1e-3      )      )




							def 	__snake_case(						self   :					Optional[int]      )					->				str:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feat_extract_tester.prepare_inputs_for_target()
												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_dict      )
												SCREAMING_SNAKE_CASE    			=       feat_extract.model_input_names[0]

												SCREAMING_SNAKE_CASE    			=       BatchFeature({input_name: speech_inputs}      )

												self.assertTrue(all(len(_UpperCamelCase      ) == len(_UpperCamelCase      ) for x, y in zip(_UpperCamelCase	,							processed_features[input_name]      )      )      )

												SCREAMING_SNAKE_CASE    			=       self.feat_extract_tester.prepare_inputs_for_target(equal_length=_UpperCamelCase      )
												SCREAMING_SNAKE_CASE    			=       BatchFeature({input_name: speech_inputs}	,							tensor_type="np"      )

												SCREAMING_SNAKE_CASE    			=       processed_features[input_name]

												if len(batch_features_input.shape      ) < 3:
																	SCREAMING_SNAKE_CASE    			=       batch_features_input[:, :, None]

												self.assertTrue(
												    batch_features_input.shape
												    == (self.feat_extract_tester.batch_size, len(speech_inputs[0]      ), self.feat_extract_tester.num_mel_bins)      )




							@require_torch
							def 	__snake_case(						self   :					List[Any]      )					->				Union[str, Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feat_extract_tester.prepare_inputs_for_target(equal_length=_UpperCamelCase      )
												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_dict      )
												SCREAMING_SNAKE_CASE    			=       feat_extract.model_input_names[0]

												SCREAMING_SNAKE_CASE    			=       BatchFeature({input_name: speech_inputs}	,							tensor_type="pt"      )

												SCREAMING_SNAKE_CASE    			=       processed_features[input_name]

												if len(batch_features_input.shape      ) < 3:
																	SCREAMING_SNAKE_CASE    			=       batch_features_input[:, :, None]

												self.assertTrue(
												    batch_features_input.shape
												    == (self.feat_extract_tester.batch_size, len(speech_inputs[0]      ), self.feat_extract_tester.num_mel_bins)      )




							@require_torch
							def 	__snake_case(						self   :					Optional[Any]      )					->				Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**self.feat_extract_dict      )
												SCREAMING_SNAKE_CASE    			=       self.feat_extract_tester.prepare_inputs_for_target()
												SCREAMING_SNAKE_CASE    			=       feat_extract.model_input_names[0]

												SCREAMING_SNAKE_CASE    			=       BatchFeature({input_name: speech_inputs}      )

												SCREAMING_SNAKE_CASE    			=       feat_extract.num_mel_bins  # hack!

												SCREAMING_SNAKE_CASE    			=       feat_extract.pad(_UpperCamelCase	,							padding="longest"	,							return_tensors="np"      )[input_name]
												SCREAMING_SNAKE_CASE    			=       feat_extract.pad(_UpperCamelCase	,							padding="longest"	,							return_tensors="pt"      )[input_name]

												self.assertTrue(abs(input_np.astype(np.floataa      ).sum() - input_pt.numpy().astype(np.floataa      ).sum()      ) < 1e-2      )




							def 	__snake_case(						self   :					str      )					->				Optional[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feat_extract_dict
												SCREAMING_SNAKE_CASE    			=       True
												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**_UpperCamelCase      )
												SCREAMING_SNAKE_CASE    			=       self.feat_extract_tester.prepare_inputs_for_target()
												SCREAMING_SNAKE_CASE    			=       [len(_UpperCamelCase      ) for x in speech_inputs]
												SCREAMING_SNAKE_CASE    			=       feat_extract.model_input_names[0]

												SCREAMING_SNAKE_CASE    			=       BatchFeature({input_name: speech_inputs}      )

												SCREAMING_SNAKE_CASE    			=       feat_extract.num_mel_bins  # hack!

												SCREAMING_SNAKE_CASE    			=       feat_extract.pad(_UpperCamelCase	,							padding="longest"	,							return_tensors="np"      )
												self.assertIn("attention_mask"	,							_UpperCamelCase      )
												self.assertListEqual(list(processed.attention_mask.shape      )	,							list(processed[input_name].shape[:2]      )      )
												self.assertListEqual(processed.attention_mask.sum(-1      ).tolist()	,							_UpperCamelCase      )




							def 	__snake_case(						self   :					int      )					->				List[str]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.feat_extract_dict
												SCREAMING_SNAKE_CASE    			=       True
												SCREAMING_SNAKE_CASE    			=       self.feature_extraction_class(**_UpperCamelCase      )
												SCREAMING_SNAKE_CASE    			=       self.feat_extract_tester.prepare_inputs_for_target()
												SCREAMING_SNAKE_CASE    			=       [len(_UpperCamelCase      ) for x in speech_inputs]
												SCREAMING_SNAKE_CASE    			=       feat_extract.model_input_names[0]

												SCREAMING_SNAKE_CASE    			=       BatchFeature({input_name: speech_inputs}      )
												SCREAMING_SNAKE_CASE    			=       min(_UpperCamelCase      )

												SCREAMING_SNAKE_CASE    			=       feat_extract.num_mel_bins  # hack!

												SCREAMING_SNAKE_CASE    			=       feat_extract.pad(
												    _UpperCamelCase	,							padding="max_length"	,							max_length=_UpperCamelCase	,							truncation=_UpperCamelCase	,							return_tensors="np"      )
												self.assertIn("attention_mask"	,							_UpperCamelCase      )
												self.assertListEqual(
												    list(processed_pad.attention_mask.shape      )	,							[processed_pad[input_name].shape[0], max_length]      )
												self.assertListEqual(
												    processed_pad.attention_mask[:, :max_length].sum(-1      ).tolist()	,							[max_length for x in speech_inputs]      )




							def 	__snake_case(						self   :					Dict	,							_UpperCamelCase   :					Union[str, Any]      )					->				str:



												'''simple docstring'''

												from datasets import load_dataset

												SCREAMING_SNAKE_CASE    			=       load_dataset("hf-internal-testing/librispeech_asr_dummy"	,							"clean"	,							split="validation"      )
												# automatic decoding with librispeech
												SCREAMING_SNAKE_CASE    			=       ds.sort("id"      ).select(range(_UpperCamelCase      )      )[:num_samples]["audio"]

												return [x["array"] for x in speech_samples]




							def 	__snake_case(						self   :					str      )					->				Union[str, Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       torch.tensor(
												    [2.3_804e-03, 2.0_752e-03, 1.9_836e-03, 2.1_057e-03, 1.6_174e-03,
												     3.0_518e-04, 9.1_553e-05, 3.3_569e-04, 9.7_656e-04, 1.8_311e-03,
												     2.0_142e-03, 2.1_057e-03, 1.7_395e-03, 4.5_776e-04, -3.9_673e-04,
												     4.5_776e-04, 1.0_071e-03, 9.1_553e-05, 4.8_828e-04, 1.1_597e-03,
												     7.3_242e-04, 9.4_604e-04, 1.8_005e-03, 1.8_311e-03, 8.8_501e-04,
												     4.2_725e-04, 4.8_828e-04, 7.3_242e-04, 1.0_986e-03, 2.1_057e-03]      )
												# fmt: on

												SCREAMING_SNAKE_CASE    			=       self._load_datasamples(1      )
												SCREAMING_SNAKE_CASE    			=       SpeechTaFeatureExtractor()
												SCREAMING_SNAKE_CASE    			=       feature_extractor(_UpperCamelCase	,							return_tensors="pt"      ).input_values
												self.assertEquals(input_values.shape	,							(1, 93_680)      )
												self.assertTrue(torch.allclose(input_values[0, :30]	,							_UpperCamelCase	,							atol=1e-6      )      )





							def 	__snake_case(						self   :					Union[str, Any]      )					->				Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       torch.tensor(
												    [-2.6_8_7_0, -3.0_1_0_4, -3.1_3_5_6, -3.5_3_5_2, -3.0_0_4_4, -3.0_3_5_3, -3.4_7_1_9, -3.6_7_7_7,
												     -3.1_5_2_0, -2.9_4_3_5, -2.6_5_5_3, -2.8_7_9_5, -2.9_9_4_4, -2.5_9_2_1, -3.0_2_7_9, -3.0_3_8_6,
												     -3.0_8_6_4, -3.1_2_9_1, -3.2_3_5_3, -2.7_4_4_4, -2.6_8_3_1, -2.7_2_8_7, -3.1_7_6_1, -3.1_5_7_1,
												     -3.2_7_2_6, -3.0_5_8_2, -3.1_0_0_7, -3.4_5_3_3, -3.4_6_9_5, -3.0_9_9_8]      )
												# fmt: on

												SCREAMING_SNAKE_CASE    			=       self._load_datasamples(1      )
												SCREAMING_SNAKE_CASE    			=       SpeechTaFeatureExtractor()
												SCREAMING_SNAKE_CASE    			=       feature_extractor(audio_target=_UpperCamelCase	,							return_tensors="pt"      ).input_values
												self.assertEquals(input_values.shape	,							(1, 366, 80)      )
												self.assertTrue(torch.allclose(input_values[0, 0, :30]	,							_UpperCamelCase	,							atol=1e-4      )      )





from typing import Dict, List, Optional, Union

import numpy as np

from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy


_lowerCamelCase					:   Optional[Any]							=		logging.get_logger(__name__)


class 						lowercase    (     a     ):




							def __init__(						self   :					str	,							_UpperCamelCase   :					int	,							_UpperCamelCase   :					int	,							_UpperCamelCase   :					float	,							**_UpperCamelCase   :					str      )					->				Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       feature_size
												SCREAMING_SNAKE_CASE    			=       sampling_rate
												SCREAMING_SNAKE_CASE    			=       padding_value

												SCREAMING_SNAKE_CASE    			=       kwargs.pop("padding_side"	,							"right"      )
												SCREAMING_SNAKE_CASE    			=       kwargs.pop("return_attention_mask"	,							_UpperCamelCase      )

												super().__init__(**_UpperCamelCase      )




							def 	__snake_case(						self   :					List[Any]	,							_UpperCamelCase   :					Union[
							        BatchFeature,
							        List[BatchFeature],
							        Dict[str, BatchFeature],
							        Dict[str, List[BatchFeature]],
							        List[Dict[str, BatchFeature]],
							    ]	,							_UpperCamelCase   :					Union[bool, str, PaddingStrategy] = True	,							_UpperCamelCase   :					Optional[int] = None	,							_UpperCamelCase   :					bool = False	,							_UpperCamelCase   :					Optional[int] = None	,							_UpperCamelCase   :					Optional[bool] = None	,							_UpperCamelCase   :					Optional[Union[str, TensorType]] = None	,							)					->				BatchFeature:



												'''simple docstring'''

												if isinstance(_UpperCamelCase	,							(list, tuple)      ) and isinstance(processed_features[0]	,							(dict, BatchFeature)      ):
																	SCREAMING_SNAKE_CASE    			=       {
																	    key: [example[key] for example in processed_features] for key in processed_features[0].keys()
																	}

												# The model's main input name, usually `input_values`, has be passed for padding
												if self.model_input_names[0] not in processed_features:
																	raise ValueError(
																	    "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`"
																	    F" to this method that includes {self.model_input_names[0]}, but you provided"
																	    F" {list(processed_features.keys()      )}"      )

												SCREAMING_SNAKE_CASE    			=       processed_features[self.model_input_names[0]]
												SCREAMING_SNAKE_CASE    			=       (
												    return_attention_mask if return_attention_mask is not None else self.return_attention_mask
												)

												if len(_UpperCamelCase      ) == 0:
																	if return_attention_mask:
																						SCREAMING_SNAKE_CASE    			=       []
																	return processed_features

												# If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
												# and rebuild them afterwards if no return_tensors is specified
												# Note that we lose the specific device the tensor may be on for PyTorch

												SCREAMING_SNAKE_CASE    			=       required_input[0]
												if isinstance(_UpperCamelCase	,							(list, tuple)      ):
																	# first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
																	SCREAMING_SNAKE_CASE    			=       0
																	while len(required_input[index]      ) == 0:
																						index += 1
																	if index < len(_UpperCamelCase      ):
																						SCREAMING_SNAKE_CASE    			=       required_input[index][0]

												if return_tensors is None:
																	if is_tf_tensor(_UpperCamelCase      ):
																						SCREAMING_SNAKE_CASE    			=       "tf"
																	elif is_torch_tensor(_UpperCamelCase      ):
																						SCREAMING_SNAKE_CASE    			=       "pt"
																	elif isinstance(_UpperCamelCase	,							(int, float, list, tuple, np.ndarray)      ):
																						SCREAMING_SNAKE_CASE    			=       "np"
																	else:
																						raise ValueError(
																						    F"type of {first_element} unknown: {type(_UpperCamelCase      )}. "
																						    "Should be one of a python, numpy, pytorch or tensorflow object."      )

												for key, value in processed_features.items():
																	if isinstance(value[0]	,							(int, float)      ):
																						SCREAMING_SNAKE_CASE    			=       to_numpy(_UpperCamelCase      )
																	else:
																						SCREAMING_SNAKE_CASE    			=       [to_numpy(_UpperCamelCase      ) for v in value]

        # Convert padding_strategy in PaddingStrategy
												SCREAMING_SNAKE_CASE    			=       self._get_padding_strategies(padding=_UpperCamelCase	,							max_length=_UpperCamelCase      )

												SCREAMING_SNAKE_CASE    			=       processed_features[self.model_input_names[0]]

												SCREAMING_SNAKE_CASE    			=       len(_UpperCamelCase      )
												if not all(len(_UpperCamelCase      ) == batch_size for v in processed_features.values()      ):
																	raise ValueError("Some items in the output dictionary have a different batch size than others."      )

												SCREAMING_SNAKE_CASE    			=       []
												for i in range(_UpperCamelCase      ):
																	SCREAMING_SNAKE_CASE    			=       {k: v[i] for k, v in processed_features.items()}
																	# truncation
																	SCREAMING_SNAKE_CASE    			=       self._truncate(
																	    _UpperCamelCase	,							max_length=_UpperCamelCase	,							pad_to_multiple_of=_UpperCamelCase	,							truncation=_UpperCamelCase	,							)
																	truncated_inputs.append(_UpperCamelCase      )

												if padding_strategy == PaddingStrategy.LONGEST:
																	# make sure that `max_length` cannot be longer than the longest truncated length
																	SCREAMING_SNAKE_CASE    			=       max(len(input_slice[self.model_input_names[0]]      ) for input_slice in truncated_inputs      )
																	SCREAMING_SNAKE_CASE    			=       PaddingStrategy.MAX_LENGTH

												SCREAMING_SNAKE_CASE    			=       {}
												for i in range(_UpperCamelCase      ):
																	# padding
																	SCREAMING_SNAKE_CASE    			=       self._pad(
																	    truncated_inputs[i]	,							max_length=_UpperCamelCase	,							padding_strategy=_UpperCamelCase	,							pad_to_multiple_of=_UpperCamelCase	,							return_attention_mask=_UpperCamelCase	,							)

																	for key, value in outputs.items():
																						if key not in batch_outputs:
																											SCREAMING_SNAKE_CASE    			=       []
																						if value.dtype is np.dtype(np.floataa      ):
																											SCREAMING_SNAKE_CASE    			=       value.astype(np.floataa      )
																						batch_outputs[key].append(_UpperCamelCase      )

												return BatchFeature(_UpperCamelCase	,							tensor_type=_UpperCamelCase      )




							def 	__snake_case(						self   :					Union[str, Any]	,							_UpperCamelCase   :					Union[Dict[str, np.ndarray], BatchFeature]	,							_UpperCamelCase   :					Optional[int] = None	,							_UpperCamelCase   :					PaddingStrategy = PaddingStrategy.DO_NOT_PAD	,							_UpperCamelCase   :					Optional[int] = None	,							_UpperCamelCase   :					Optional[bool] = None	,							)					->				dict:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       processed_features[self.model_input_names[0]]

												if padding_strategy == PaddingStrategy.LONGEST:
																	SCREAMING_SNAKE_CASE    			=       len(_UpperCamelCase      )

												if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
																	SCREAMING_SNAKE_CASE    			=       ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

												SCREAMING_SNAKE_CASE    			=       padding_strategy != PaddingStrategy.DO_NOT_PAD and len(_UpperCamelCase      ) < max_length

												if return_attention_mask and "attention_mask" not in processed_features:
																	SCREAMING_SNAKE_CASE    			=       np.ones(len(_UpperCamelCase      )	,							dtype=np.intaa      )

												if needs_to_be_padded:
																	SCREAMING_SNAKE_CASE    			=       max_length - len(_UpperCamelCase      )
																	if self.padding_side == "right":
																						if return_attention_mask:
																											SCREAMING_SNAKE_CASE    			=       np.pad(
																											    processed_features["attention_mask"]	,							(0, difference)      )
																						SCREAMING_SNAKE_CASE    			=       ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
																						SCREAMING_SNAKE_CASE    			=       np.pad(
																						    _UpperCamelCase	,							_UpperCamelCase	,							"constant"	,							constant_values=self.padding_value      )
																	elif self.padding_side == "left":
																						if return_attention_mask:
																											SCREAMING_SNAKE_CASE    			=       np.pad(
																											    processed_features["attention_mask"]	,							(difference, 0)      )
																						SCREAMING_SNAKE_CASE    			=       ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
																						SCREAMING_SNAKE_CASE    			=       np.pad(
																						    _UpperCamelCase	,							_UpperCamelCase	,							"constant"	,							constant_values=self.padding_value      )
																	else:
																						raise ValueError("Invalid padding strategy:" + str(self.padding_side      )      )

												return processed_features




							def 	__snake_case(						self   :					Dict	,							_UpperCamelCase   :					Union[Dict[str, np.ndarray], BatchFeature]	,							_UpperCamelCase   :					Optional[int] = None	,							_UpperCamelCase   :					Optional[int] = None	,							_UpperCamelCase   :					Optional[bool] = None	,							)					->				Optional[int]:



												'''simple docstring'''

												if not truncation:
																	return processed_features
												elif truncation and max_length is None:
																	raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined."      )

												SCREAMING_SNAKE_CASE    			=       processed_features[self.model_input_names[0]]

												# find `max_length` that fits `pad_to_multiple_of`
												if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
																	SCREAMING_SNAKE_CASE    			=       ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

												SCREAMING_SNAKE_CASE    			=       len(_UpperCamelCase      ) > max_length

												if needs_to_be_truncated:
																	SCREAMING_SNAKE_CASE    			=       processed_features[self.model_input_names[0]][:max_length]
																	if "attention_mask" in processed_features:
																						SCREAMING_SNAKE_CASE    			=       processed_features["attention_mask"][:max_length]

												return processed_features





							def 	__snake_case(						self   :					Optional[Any]	,							_UpperCamelCase   :					int=False	,							_UpperCamelCase   :					Tuple=None      )					->				Tuple:



												'''simple docstring'''

												if padding is not False:
																	if padding is True:
																						SCREAMING_SNAKE_CASE    			=       PaddingStrategy.LONGEST  # Default to pad to the longest sequence in the batch
																	elif not isinstance(_UpperCamelCase	,							_UpperCamelCase      ):
																						SCREAMING_SNAKE_CASE    			=       PaddingStrategy(_UpperCamelCase      )
																	elif isinstance(_UpperCamelCase	,							_UpperCamelCase      ):
																						SCREAMING_SNAKE_CASE    			=       padding
												else:
																	SCREAMING_SNAKE_CASE    			=       PaddingStrategy.DO_NOT_PAD

												# Set max length if needed
												if max_length is None:
																	if padding_strategy == PaddingStrategy.MAX_LENGTH:
																						raise ValueError(
																						    F"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined"      )

        # Test if we have a padding value
												if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
																	raise ValueError(
																	    "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use"
																	    " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`."      )

												return padding_strategy




