





"""simple docstring"""




import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
		from transformers import WhisperFeatureExtractor

if is_torch_available():
		import torch

UpperCamelCase_									=random.Random()





def 	a_    (							_lowercase	,						_lowercase=1.0	,						_lowercase=None	,						_lowercase=None       ):
						if rng is None:
												_UpperCamelCase      : Optional[int]         =   global_rng

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

						return values




@require_torch
@require_torchaudio
class 			_a						(				unittest.TestCase    ):






				def __init__(			self		:   str,			lowerCAmelCase__		:   Union[str, Any],			lowerCAmelCase__		:   Optional[int]=7,			lowerCAmelCase__		:   List[str]=4_0_0,			lowerCAmelCase__		:   Tuple=2_0_0_0,			lowerCAmelCase__		:   Optional[int]=1_0,			lowerCAmelCase__		:   int=1_6_0,			lowerCAmelCase__		:   Union[str, Any]=8,			lowerCAmelCase__		:   Tuple=0.0,			lowerCAmelCase__		:   Tuple=4_0_0_0,			lowerCAmelCase__		:   List[Any]=False,			lowerCAmelCase__		:   Any=True,			)     ->				Any:




										'''simple docstring'''



										_UpperCamelCase      : Union[str, Any]         =   parent
										_UpperCamelCase      : Optional[Any]         =   batch_size
										_UpperCamelCase      : Any         =   min_seq_length
										_UpperCamelCase      : Optional[Any]         =   max_seq_length
										_UpperCamelCase      : int         =   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
										_UpperCamelCase      : List[Any]         =   padding_value
										_UpperCamelCase      : Optional[Any]         =   sampling_rate
										_UpperCamelCase      : str         =   return_attention_mask
										_UpperCamelCase      : Dict         =   do_normalize
										_UpperCamelCase      : Union[str, Any]         =   feature_size
										_UpperCamelCase      : Optional[Any]         =   chunk_length
										_UpperCamelCase      : List[Any]         =   hop_length






				def     snake_case     (			self		:   Dict							)     ->				Tuple:




										'''simple docstring'''



										return {
										    "feature_size": self.feature_size,
										    "hop_length": self.hop_length,
										    "chunk_length": self.chunk_length,
										    "padding_value": self.padding_value,
										    "sampling_rate": self.sampling_rate,
										    "return_attention_mask": self.return_attention_mask,
										    "do_normalize": self.do_normalize,
										}






				def     snake_case     (			self		:   Union[str, Any],			lowerCAmelCase__		:   Dict=False,			lowerCAmelCase__		:   Tuple=False							)     ->				Tuple:




										'''simple docstring'''



										def _flatten(lowerCAmelCase__		:   int							):
																return list(itertools.chain(*lowerCAmelCase__							)							)

										if equal_length:
																_UpperCamelCase      : Tuple         =   [floats_list((self.max_seq_length, self.feature_size)							) for _ in range(self.batch_size							)]
										else:
																# make sure that inputs increase in size
																_UpperCamelCase      : List[str]         =   [
																    floats_list((x, self.feature_size)							)
																    for x in range(self.min_seq_length,			self.max_seq_length,			self.seq_length_diff							)
																]
										if numpify:
																_UpperCamelCase      : Tuple         =   [np.asarray(lowerCAmelCase__							) for x in speech_inputs]
										return speech_inputs




@require_torch
@require_torchaudio
class 			_a						(				_lowerCAmelCase     ,    unittest.TestCase    ):
				UpperCamelCase								=   WhisperFeatureExtractor if is_speech_available() else None






				def     snake_case     (			self		:   Tuple							)     ->				List[str]:




										'''simple docstring'''



										_UpperCamelCase      : Optional[int]         =   WhisperFeatureExtractionTester(self							)






				def     snake_case     (			self		:   Dict							)     ->				Tuple:




										'''simple docstring'''



										_UpperCamelCase      : Optional[Any]         =   self.feature_extraction_class(**self.feat_extract_dict							)

										with tempfile.TemporaryDirectory() as tmpdirname:
																_UpperCamelCase      : Tuple         =   feat_extract_first.save_pretrained(lowerCAmelCase__							)[0]
																check_json_file_has_correct_format(lowerCAmelCase__							)
																_UpperCamelCase      : Tuple         =   self.feature_extraction_class.from_pretrained(lowerCAmelCase__							)

										_UpperCamelCase      : int         =   feat_extract_first.to_dict()
										_UpperCamelCase      : int         =   feat_extract_second.to_dict()
										_UpperCamelCase      : int         =   feat_extract_first.mel_filters
										_UpperCamelCase      : Tuple         =   feat_extract_second.mel_filters
										self.assertTrue(np.allclose(lowerCAmelCase__,			lowerCAmelCase__							)							)
										self.assertEqual(lowerCAmelCase__,			lowerCAmelCase__							)






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




										'''simple docstring'''



										_UpperCamelCase      : List[str]         =   self.feature_extraction_class(**self.feat_extract_dict							)

										with tempfile.TemporaryDirectory() as tmpdirname:
																_UpperCamelCase      : int         =   os.path.join(lowerCAmelCase__,			'''feat_extract.json'''							)
																feat_extract_first.to_json_file(lowerCAmelCase__							)
																_UpperCamelCase      : Any         =   self.feature_extraction_class.from_json_file(lowerCAmelCase__							)

										_UpperCamelCase      : List[str]         =   feat_extract_first.to_dict()
										_UpperCamelCase      : Any         =   feat_extract_second.to_dict()
										_UpperCamelCase      : Tuple         =   feat_extract_first.mel_filters
										_UpperCamelCase      : Union[str, Any]         =   feat_extract_second.mel_filters
										self.assertTrue(np.allclose(lowerCAmelCase__,			lowerCAmelCase__							)							)
										self.assertEqual(lowerCAmelCase__,			lowerCAmelCase__							)






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




										'''simple docstring'''



										_UpperCamelCase      : str         =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
										# create three inputs of length 800, 1000, and 1200
										_UpperCamelCase      : int         =   [floats_list((1, x)							)[0] for x in range(8_0_0,			1_4_0_0,			2_0_0							)]
										_UpperCamelCase      : Any         =   [np.asarray(lowerCAmelCase__							) for speech_input in speech_inputs]

										# Test feature size
										_UpperCamelCase      : List[Any]         =   feature_extractor(lowerCAmelCase__,			padding='''max_length''',			return_tensors='''np'''							).input_features
										self.assertTrue(input_features.ndim == 3							)
										self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames							)
										self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size							)

										# Test not batched input
										_UpperCamelCase      : int         =   feature_extractor(speech_inputs[0],			return_tensors='''np'''							).input_features
										_UpperCamelCase      : Any         =   feature_extractor(np_speech_inputs[0],			return_tensors='''np'''							).input_features
										self.assertTrue(np.allclose(lowerCAmelCase__,			lowerCAmelCase__,			atol=1e-3							)							)

										# Test batched
										_UpperCamelCase      : List[str]         =   feature_extractor(lowerCAmelCase__,			return_tensors='''np'''							).input_features
										_UpperCamelCase      : List[Any]         =   feature_extractor(lowerCAmelCase__,			return_tensors='''np'''							).input_features
										for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__,			lowerCAmelCase__							):
																self.assertTrue(np.allclose(lowerCAmelCase__,			lowerCAmelCase__,			atol=1e-3							)							)

										# Test 2-D numpy arrays are batched.
										_UpperCamelCase      : str         =   [floats_list((1, x)							)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
										_UpperCamelCase      : Tuple         =   np.asarray(lowerCAmelCase__							)
										_UpperCamelCase      : Optional[Any]         =   feature_extractor(lowerCAmelCase__,			return_tensors='''np'''							).input_features
										_UpperCamelCase      : List[Any]         =   feature_extractor(lowerCAmelCase__,			return_tensors='''np'''							).input_features
										for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__,			lowerCAmelCase__							):
																self.assertTrue(np.allclose(lowerCAmelCase__,			lowerCAmelCase__,			atol=1e-3							)							)

										# Test truncation required
										_UpperCamelCase      : str         =   [floats_list((1, x)							)[0] for x in range(2_0_0,			(feature_extractor.n_samples + 5_0_0),			2_0_0							)]
										_UpperCamelCase      : int         =   [np.asarray(lowerCAmelCase__							) for speech_input in speech_inputs]

										_UpperCamelCase      : List[Any]         =   [x[: feature_extractor.n_samples] for x in speech_inputs]
										_UpperCamelCase      : str         =   [np.asarray(lowerCAmelCase__							) for speech_input in speech_inputs_truncated]

										_UpperCamelCase      : str         =   feature_extractor(lowerCAmelCase__,			return_tensors='''np'''							).input_features
										_UpperCamelCase      : int         =   feature_extractor(lowerCAmelCase__,			return_tensors='''np'''							).input_features
										for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__,			lowerCAmelCase__							):
																self.assertTrue(np.allclose(lowerCAmelCase__,			lowerCAmelCase__,			atol=1e-3							)							)






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




										'''simple docstring'''



										import torch

										_UpperCamelCase      : Union[str, Any]         =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
										_UpperCamelCase      : Any         =   np.random.rand(1_0_0,			3_2							).astype(np.floataa							)
										_UpperCamelCase      : Optional[Any]         =   np_speech_inputs.tolist()

										for inputs in [py_speech_inputs, np_speech_inputs]:
																_UpperCamelCase      : Optional[int]         =   feature_extractor.pad([{'''input_features''': inputs}],			return_tensors='''np'''							)
																self.assertTrue(np_processed.input_features.dtype == np.floataa							)
																_UpperCamelCase      : Union[str, Any]         =   feature_extractor.pad([{'''input_features''': inputs}],			return_tensors='''pt'''							)
																self.assertTrue(pt_processed.input_features.dtype == torch.floataa							)






				def     snake_case     (			self		:   Any,			lowerCAmelCase__		:   int							)     ->				Union[str, Any]:




										'''simple docstring'''



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

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






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




										'''simple docstring'''



										_UpperCamelCase      : Optional[int]         =   torch.tensor(
										    [
										        0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951,
										        0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678,
										        0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554,
										        -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854
										    ]							)
										# fmt: on

										_UpperCamelCase      : List[Any]         =   self._load_datasamples(1							)
										_UpperCamelCase      : Dict         =   WhisperFeatureExtractor()
										_UpperCamelCase      : Any         =   feature_extractor(lowerCAmelCase__,			return_tensors='''pt'''							).input_features
										self.assertEqual(input_features.shape,			(1, 8_0, 3_0_0_0)							)
										self.assertTrue(torch.allclose(input_features[0, 0, :3_0],			lowerCAmelCase__,			atol=1e-4							)							)






				def     snake_case     (			self		:   Tuple							)     ->				Optional[int]:




										'''simple docstring'''



										_UpperCamelCase      : Union[str, Any]         =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()							)
										_UpperCamelCase      : Union[str, Any]         =   self._load_datasamples(1							)[0]
										_UpperCamelCase      : Dict         =   ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5  # Rescale to [0, 65535] to show issue
										_UpperCamelCase      : str         =   feat_extract.zero_mean_unit_var_norm([audio],			attention_mask=lowerCAmelCase__							)[0]

										self.assertTrue(np.all(np.mean(lowerCAmelCase__							) < 1e-3							)							)
										self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase__							) - 1							) < 1e-3							)							)










"""simple docstring"""




def 	a_    (							_lowercase = 100       ):
						_UpperCamelCase      : List[Any]         =   0
						_UpperCamelCase      : Optional[Any]         =   0
						for i in range(1	,						n + 1       ):
												sum_of_squares += i**2
												sum_of_ints += i
						return sum_of_ints**2 - sum_of_squares


if __name__ == "__main__":
						print(F"{solution() = }")



