

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_			      =      random.Random()


def     __SCREAMING_SNAKE_CASE   (SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__=1.0    ,						SCREAMING_SNAKE_CASE__=None    ,						SCREAMING_SNAKE_CASE__=None			):
						if rng is None:
												snake_case_  =      global_rng

						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       snake_case_  (						unittest.TestCase   ):







			'''simple docstring'''

			def __init__(	self					:							Tuple				,  _UpperCamelCase					:							Optional[int]				,  _UpperCamelCase					:							Tuple=7				,  _UpperCamelCase					:							List[Any]=4_0_0				,  _UpperCamelCase					:							Optional[Any]=2_0_0_0				,  _UpperCamelCase					:							Dict=1				,  _UpperCamelCase					:							Union[str, Any]=0.0				,  _UpperCamelCase					:							Tuple=1_6_0_0_0				,  _UpperCamelCase					:							Optional[Any]=True				,  _UpperCamelCase					:							Union[str, Any]=8_0				,  _UpperCamelCase					:							int=1_6				,  _UpperCamelCase					:							Any=6_4				,  _UpperCamelCase					:							Tuple="hann_window"				,  _UpperCamelCase					:							Dict=8_0				,  _UpperCamelCase					:							int=7_6_0_0				,  _UpperCamelCase					:							Union[str, Any]=1e-10				,  _UpperCamelCase					:							str=True				,  ) ->Optional[Any]:
									snake_case_  =      parent
									snake_case_  =      batch_size
									snake_case_  =      min_seq_length
									snake_case_  =      max_seq_length
									snake_case_  =      (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									snake_case_  =      feature_size
									snake_case_  =      padding_value
									snake_case_  =      sampling_rate
									snake_case_  =      do_normalize
									snake_case_  =      num_mel_bins
									snake_case_  =      hop_length
									snake_case_  =      win_length
									snake_case_  =      win_function
									snake_case_  =      fmin
									snake_case_  =      fmax
									snake_case_  =      mel_floor
									snake_case_  =      return_attention_mask







			def 							snake_case__(	self					:							Union[str, Any]				) ->str:
									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					:							Dict				,  _UpperCamelCase					:							str=False				,  _UpperCamelCase					:							Any=False				) ->Tuple:
									def _flatten(_UpperCamelCase					:							int				):
															return list(itertools.chain(*_UpperCamelCase				)				)

									if equal_length:
															snake_case_  =      floats_list((self.batch_size, self.max_seq_length)				)
									else:
															# make sure that inputs increase in size
															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:
															snake_case_  =      [np.asarray(_UpperCamelCase				) for x in speech_inputs]

									return speech_inputs







			def 							snake_case__(	self					:							Optional[int]				,  _UpperCamelCase					:							Optional[Any]=False				,  _UpperCamelCase					:							Optional[int]=False				) ->Union[str, Any]:
									if equal_length:
															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
															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:
															snake_case_  =      [np.asarray(_UpperCamelCase				) for x in speech_inputs]

									return speech_inputs






@require_torch
class       snake_case_  (						__A      ,			unittest.TestCase   ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE	:  Optional[int]		     =							SpeechTaFeatureExtractor







			def 							snake_case__(	self					:							List[Any]				) ->int:
									snake_case_  =      SpeechTaFeatureExtractionTester(self				)







			def 							snake_case__(	self					:							Dict				,  _UpperCamelCase					:							Optional[int]				) ->Union[str, Any]:
									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]				) ->List[str]:
									# Tests that all call wrap to encode_plus and batch_encode_plus
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
									# create three inputs of length 800, 1000, and 1200
									snake_case_  =      [floats_list((1, x)				)[0] for x in range(8_0_0				,  1_4_0_0				,  2_0_0				)]
									snake_case_  =      [np.asarray(_UpperCamelCase				) for speech_input in speech_inputs]

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

									# Test batched
									snake_case_  =      feat_extract(_UpperCamelCase				,  return_tensors='''np'''				).input_values
									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					:							List[str]				) ->Optional[Any]:
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
									snake_case_  =      [floats_list((1, x)				)[0] for x in range(8_0_0				,  1_4_0_0				,  2_0_0				)]

									snake_case_  =      ['''longest''', '''max_length''', '''do_not_pad''']
									snake_case_  =      [None, 1_6_0_0, None]
									for max_length, padding in zip(_UpperCamelCase				,  _UpperCamelCase				):
															snake_case_  =      feat_extract(_UpperCamelCase				,  padding=_UpperCamelCase				,  max_length=_UpperCamelCase				,  return_tensors='''np'''				)
															snake_case_  =      processed.input_values

															self._check_zero_mean_unit_variance(input_values[0][:8_0_0]				)
															self.assertTrue(input_values[0][8_0_0:].sum() < 1e-6				)
															self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0]				)
															self.assertTrue(input_values[0][1_0_0_0:].sum() < 1e-6				)
															self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0]				)







			def 							snake_case__(	self					:							Any				) ->Tuple:
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
									snake_case_  =      range(8_0_0				,  1_4_0_0				,  2_0_0				)
									snake_case_  =      [floats_list((1, x)				)[0] for x in lengths]

									snake_case_  =      ['''longest''', '''max_length''', '''do_not_pad''']
									snake_case_  =      [None, 1_6_0_0, None]

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

															self._check_zero_mean_unit_variance(input_values[0][:8_0_0]				)
															self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0]				)
															self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0]				)







			def 							snake_case__(	self					:							Optional[int]				) ->Any:
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
									snake_case_  =      [floats_list((1, x)				)[0] for x in range(8_0_0				,  1_4_0_0				,  2_0_0				)]
									snake_case_  =      feat_extract(
									    _UpperCamelCase				,  truncation=_UpperCamelCase				,  max_length=1_0_0_0				,  padding='''max_length'''				,  return_tensors='''np'''				)
									snake_case_  =      processed.input_values

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







			def 							snake_case__(	self					:							Union[str, Any]				) ->Any:
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
									snake_case_  =      [floats_list((1, x)				)[0] for x in range(8_0_0				,  1_4_0_0				,  2_0_0				)]
									snake_case_  =      feat_extract(
									    _UpperCamelCase				,  truncation=_UpperCamelCase				,  max_length=1_0_0_0				,  padding='''longest'''				,  return_tensors='''np'''				)
									snake_case_  =      processed.input_values

									self._check_zero_mean_unit_variance(input_values[0, :8_0_0]				)
									self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0]				)
									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_0_0_0)				)

									snake_case_  =      [floats_list((1, x)				)[0] for x in range(8_0_0				,  1_4_0_0				,  2_0_0				)]
									snake_case_  =      feat_extract(
									    _UpperCamelCase				,  truncation=_UpperCamelCase				,  max_length=2_0_0_0				,  padding='''longest'''				,  return_tensors='''np'''				)
									snake_case_  =      processed.input_values

									self._check_zero_mean_unit_variance(input_values[0, :8_0_0]				)
									self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0]				)
									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_2_0_0)				)







			def 							snake_case__(	self					:							Dict				) ->str:
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
									snake_case_  =      np.random.rand(1_0_0				).astype(np.floataa				)
									snake_case_  =      np_speech_inputs.tolist()

									for inputs in [py_speech_inputs, np_speech_inputs]:
															snake_case_  =      feature_extractor.pad([{'''input_values''': inputs}]				,  return_tensors='''np'''				)
															self.assertTrue(np_processed.input_values.dtype == np.floataa				)
															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]				) ->List[Any]:
									# Tests that all call wrap to encode_plus and batch_encode_plus
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
									# create three inputs of length 800, 1000, and 1200
									snake_case_  =      [floats_list((1, x)				)[0] for x in range(8_0_0				,  1_4_0_0				,  2_0_0				)]
									snake_case_  =      [np.asarray(_UpperCamelCase				) for speech_input in speech_inputs]

									# Test feature size
									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
									snake_case_  =      feature_extractor(speech_inputs[0]				,  return_tensors='''np'''				).input_values
									snake_case_  =      feature_extractor(np_speech_inputs[0]				,  return_tensors='''np'''				).input_values
									self.assertTrue(np.allclose(_UpperCamelCase				,  _UpperCamelCase				,  atol=1e-3				)				)

									# Test batched
									snake_case_  =      feature_extractor(_UpperCamelCase				,  return_tensors='''np'''				).input_values
									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.
									snake_case_  =      [floats_list((1, x)				)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
									snake_case_  =      np.asarray(_UpperCamelCase				)
									snake_case_  =      feature_extractor(_UpperCamelCase				,  return_tensors='''np'''				).input_values
									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					:							Any				) ->Tuple:
									snake_case_  =      self.feat_extract_tester.prepare_inputs_for_target()
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_dict				)
									snake_case_  =      feat_extract.model_input_names[0]

									snake_case_  =      BatchFeature({input_name: speech_inputs}				)

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

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

									snake_case_  =      processed_features[input_name]

									if len(batch_features_input.shape				) < 3:
															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[str]				) ->Union[str, Any]:
									snake_case_  =      self.feat_extract_tester.prepare_inputs_for_target(equal_length=_UpperCamelCase				)
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_dict				)
									snake_case_  =      feat_extract.model_input_names[0]

									snake_case_  =      BatchFeature({input_name: speech_inputs}				,  tensor_type='''pt'''				)

									snake_case_  =      processed_features[input_name]

									if len(batch_features_input.shape				) < 3:
															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[int]				) ->Dict:
									snake_case_  =      self.feature_extraction_class(**self.feat_extract_dict				)
									snake_case_  =      self.feat_extract_tester.prepare_inputs_for_target()
									snake_case_  =      feat_extract.model_input_names[0]

									snake_case_  =      BatchFeature({input_name: speech_inputs}				)

									snake_case_  =      feat_extract.num_mel_bins  # hack!

									snake_case_  =      feat_extract.pad(_UpperCamelCase				,  padding='''longest'''				,  return_tensors='''np'''				)[input_name]
									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					:							Optional[Any]				) ->str:
									snake_case_  =      self.feat_extract_dict
									snake_case_  =      True
									snake_case_  =      self.feature_extraction_class(**_UpperCamelCase				)
									snake_case_  =      self.feat_extract_tester.prepare_inputs_for_target()
									snake_case_  =      [len(_UpperCamelCase				) for x in speech_inputs]
									snake_case_  =      feat_extract.model_input_names[0]

									snake_case_  =      BatchFeature({input_name: speech_inputs}				)

									snake_case_  =      feat_extract.num_mel_bins  # hack!

									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					:							Tuple				) ->str:
									snake_case_  =      self.feat_extract_dict
									snake_case_  =      True
									snake_case_  =      self.feature_extraction_class(**_UpperCamelCase				)
									snake_case_  =      self.feat_extract_tester.prepare_inputs_for_target()
									snake_case_  =      [len(_UpperCamelCase				) for x in speech_inputs]
									snake_case_  =      feat_extract.model_input_names[0]

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

									snake_case_  =      feat_extract.num_mel_bins  # hack!

									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					:							List[Any]				,  _UpperCamelCase					:							Union[str, Any]				) ->Any:
									from datasets import load_dataset

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

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







			def 							snake_case__(	self					:							List[Any]				) ->List[Any]:
									# fmt: off
									snake_case_  =      torch.tensor(
									    [2.3804e-03, 2.0752e-03, 1.9836e-03, 2.1057e-03, 1.6174e-03,
									     3.0518e-04, 9.1553e-05, 3.3569e-04, 9.7656e-04, 1.8311e-03,
									     2.0142e-03, 2.1057e-03, 1.7395e-03, 4.5776e-04, -3.9673e-04,
									     4.5776e-04, 1.0071e-03, 9.1553e-05, 4.8828e-04, 1.1597e-03,
									     7.3242e-04, 9.4604e-04, 1.8005e-03, 1.8311e-03, 8.8501e-04,
									     4.2725e-04, 4.8828e-04, 7.3242e-04, 1.0986e-03, 2.1057e-03]				)
									# fmt: on

									snake_case_  =      self._load_datasamples(1				)
									snake_case_  =      SpeechTaFeatureExtractor()
									snake_case_  =      feature_extractor(_UpperCamelCase				,  return_tensors='''pt'''				).input_values
									self.assertEquals(input_values.shape				,  (1, 9_3_6_8_0)				)
									self.assertTrue(torch.allclose(input_values[0, :3_0]				,  _UpperCamelCase				,  atol=1e-6				)				)







			def 							snake_case__(	self					:							Optional[int]				) ->List[str]:
									# fmt: off
									snake_case_  =      torch.tensor(
									    [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777,
									     -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386,
									     -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571,
									     -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998]				)
									# fmt: on

									snake_case_  =      self._load_datasamples(1				)
									snake_case_  =      SpeechTaFeatureExtractor()
									snake_case_  =      feature_extractor(audio_target=_UpperCamelCase				,  return_tensors='''pt'''				).input_values
									self.assertEquals(input_values.shape				,  (1, 3_6_6, 8_0)				)
									self.assertTrue(torch.allclose(input_values[0, 0, :3_0]				,  _UpperCamelCase				,  atol=1e-4				)				)




'''simple docstring'''



from math import pow
def        UpperCAmelCase (    A	:					int       ,		A	:					int       ,		A	:					int       ,		A	:					int       ,		A	:					int       ,		):
							if current_sum == needed_sum:
														# If the sum of the powers is equal to needed_sum, then we have a solution.
														solutions_count += 1
														return current_sum, solutions_count

							SCREAMING_SNAKE_CASE       :   Tuple         =      int(pow(A       ,		A					)					)
							if current_sum + i_to_n <= needed_sum:
														# If the sum of the powers is less than needed_sum, then continue adding powers.
														current_sum += i_to_n
														SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   Dict         =      backtrack(
														    A       ,		A       ,		current_number + 1       ,		A       ,		A					)
														current_sum -= i_to_n
							if i_to_n < needed_sum:
														# If the power of i is less than needed_sum, then try with the next power.
														SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   int         =      backtrack(
														    A       ,		A       ,		current_number + 1       ,		A       ,		A					)
							return current_sum, solutions_count
def        UpperCAmelCase (    A	:					int       ,		A	:					int					):
							if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):
														raise ValueError(
														    '''Invalid input\n'''
														    '''needed_sum must be between 1 and 1000, power between 2 and 10.'''					)

							return backtrack(A       ,		A       ,		1       ,		0       ,		0					)[1]  # Return the solutions_count


if __name__ == "__main__":
							import doctest

							doctest.testmod()




