






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			:		Optional[Any]   				=    random.Random()





def 	lowerCAmelCase_		(lowercase__						:       Optional[Any]     ,					lowercase__						:       List[Any]=1.0     ,					lowercase__						:       Optional[int]=None     ,					lowercase__						:       str=None       )		->    List[str]:


			'''simple docstring'''




			if rng is None:
						lowerCAmelCase__      			=						global_rng

			lowerCAmelCase__      			=						[]
			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  lowerCAmelCase_       (				unittest.TestCase					):




							def __init__(   self     :   int ,							SCREAMING_SNAKE_CASE_     :   Optional[Any] ,							SCREAMING_SNAKE_CASE_     :   List[Any]=7 ,							SCREAMING_SNAKE_CASE_     :   Optional[int]=400 ,							SCREAMING_SNAKE_CASE_     :   str=2_000 ,							SCREAMING_SNAKE_CASE_     :   Dict=10 ,							SCREAMING_SNAKE_CASE_     :   Optional[int]=160 ,							SCREAMING_SNAKE_CASE_     :   Union[str, Any]=8 ,							SCREAMING_SNAKE_CASE_     :   List[str]=0.0 ,							SCREAMING_SNAKE_CASE_     :   Union[str, Any]=4_000 ,							SCREAMING_SNAKE_CASE_     :   Optional[int]=False ,							SCREAMING_SNAKE_CASE_     :   List[str]=True ,							):
										lowerCAmelCase__      			=						parent
										lowerCAmelCase__      			=						batch_size
										lowerCAmelCase__      			=						min_seq_length
										lowerCAmelCase__      			=						max_seq_length
										lowerCAmelCase__      			=						(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
										lowerCAmelCase__      			=						padding_value
										lowerCAmelCase__      			=						sampling_rate
										lowerCAmelCase__      			=						return_attention_mask
										lowerCAmelCase__      			=						do_normalize
										lowerCAmelCase__      			=						feature_size
										lowerCAmelCase__      			=						chunk_length
										lowerCAmelCase__      			=						hop_length




							def 						__snake_case					(   self     :   List[str]	):
										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     :   Dict ,							SCREAMING_SNAKE_CASE_     :   str=False ,							SCREAMING_SNAKE_CASE_     :   str=False	):
										def _flatten(SCREAMING_SNAKE_CASE_     :   Optional[Any]	):
													return list(itertools.chain(*__a	)	)

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



@require_torch
@require_torchaudio
class  lowerCAmelCase_       (				__lowercase     ,    unittest.TestCase					):
							UpperCamelCase_		:List[str]		      =    WhisperFeatureExtractor if is_speech_available() else None




							def 						__snake_case					(   self     :   Optional[Any]	):
										lowerCAmelCase__      			=						WhisperFeatureExtractionTester(self	)




							def 						__snake_case					(   self     :   List[Any]	):
										lowerCAmelCase__      			=						self.feature_extraction_class(**self.feat_extract_dict	)

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

										lowerCAmelCase__      			=						feat_extract_first.to_dict()
										lowerCAmelCase__      			=						feat_extract_second.to_dict()
										lowerCAmelCase__      			=						feat_extract_first.mel_filters
										lowerCAmelCase__      			=						feat_extract_second.mel_filters
										self.assertTrue(np.allclose(__a ,							__a	)	)
										self.assertEqual(__a ,							__a	)




							def 						__snake_case					(   self     :   Optional[Any]	):
										lowerCAmelCase__      			=						self.feature_extraction_class(**self.feat_extract_dict	)

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

										lowerCAmelCase__      			=						feat_extract_first.to_dict()
										lowerCAmelCase__      			=						feat_extract_second.to_dict()
										lowerCAmelCase__      			=						feat_extract_first.mel_filters
										lowerCAmelCase__      			=						feat_extract_second.mel_filters
										self.assertTrue(np.allclose(__a ,							__a	)	)
										self.assertEqual(__a ,							__a	)




							def 						__snake_case					(   self     :   List[Any]	):
										# Tests that all call wrap to encode_plus and batch_encode_plus
										lowerCAmelCase__      			=						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
										# create three inputs of length 800, 1000, and 1200
										lowerCAmelCase__      			=						[floats_list((1, x)	)[0] for x in range(800 ,							1_400 ,							200	)]
										lowerCAmelCase__      			=						[np.asarray(__a	) for speech_input in speech_inputs]

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

										# Test batched
										lowerCAmelCase__      			=						feature_extractor(__a ,							return_tensors='''np'''	).input_features
										lowerCAmelCase__      			=						feature_extractor(__a ,							return_tensors='''np'''	).input_features
										for enc_seq_a, enc_seq_a in zip(__a ,							__a	):
													self.assertTrue(np.allclose(__a ,							__a ,							atol=1e-3	)	)

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

										# Test truncation required
										lowerCAmelCase__      			=						[floats_list((1, x)	)[0] for x in range(200 ,							(feature_extractor.n_samples + 500) ,							200	)]
										lowerCAmelCase__      			=						[np.asarray(__a	) for speech_input in speech_inputs]

										lowerCAmelCase__      			=						[x[: feature_extractor.n_samples] for x in speech_inputs]
										lowerCAmelCase__      			=						[np.asarray(__a	) for speech_input in speech_inputs_truncated]

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




							def 						__snake_case					(   self     :   Union[str, Any]	):
										import torch

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

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




							def 						__snake_case					(   self     :   List[Any] ,							SCREAMING_SNAKE_CASE_     :   Union[str, Any]	):
										lowerCAmelCase__      			=						load_dataset('''hf-internal-testing/librispeech_asr_dummy''' ,							'''clean''' ,							split='''validation'''	)
										# automatic decoding with librispeech
										lowerCAmelCase__      			=						ds.sort('''id'''	).select(range(__a	)	)[:num_samples]["""audio"""]

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




							def 						__snake_case					(   self     :   Optional[int]	):
										# fmt: off
										lowerCAmelCase__      			=						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

										lowerCAmelCase__      			=						self._load_datasamples(1	)
										lowerCAmelCase__      			=						WhisperFeatureExtractor()
										lowerCAmelCase__      			=						feature_extractor(__a ,							return_tensors='''pt'''	).input_features
										self.assertEqual(input_features.shape ,							(1, 80, 3_000)	)
										self.assertTrue(torch.allclose(input_features[0, 0, :30] ,							__a ,							atol=1e-4	)	)




							def 						__snake_case					(   self     :   Optional[int]	):
										lowerCAmelCase__      			=						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
										lowerCAmelCase__      			=						self._load_datasamples(1	)[0]
										lowerCAmelCase__      			=						((audio - audio.min()) / (audio.max() - audio.min())) * 65_535  # Rescale to [0, 65535] to show issue
										lowerCAmelCase__      			=						feat_extract.zero_mean_unit_var_norm([audio] ,							attention_mask=__a	)[0]

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













# Imports
import numpy as np
class  lowerCAmelCase_       :




							def __init__(   self     :   Any ,							SCREAMING_SNAKE_CASE_     :   Dict=None ,							SCREAMING_SNAKE_CASE_     :   Optional[Any]=None ,							SCREAMING_SNAKE_CASE_     :   List[str]=None ,							SCREAMING_SNAKE_CASE_     :   Dict=None ,							SCREAMING_SNAKE_CASE_     :   int=None	):
											self.set_matricies(red=SCREAMING_SNAKE_CASE_ ,							green=SCREAMING_SNAKE_CASE_ ,							blue=SCREAMING_SNAKE_CASE_ ,							red_edge=SCREAMING_SNAKE_CASE_ ,							nir=SCREAMING_SNAKE_CASE_	)




							def 						__snake_case					(   self     :   str ,							SCREAMING_SNAKE_CASE_     :   Union[str, Any]=None ,							SCREAMING_SNAKE_CASE_     :   Optional[int]=None ,							SCREAMING_SNAKE_CASE_     :   Optional[Any]=None ,							SCREAMING_SNAKE_CASE_     :   Optional[Any]=None ,							SCREAMING_SNAKE_CASE_     :   Dict=None	):
											if red is not None:
															lowerCAmelCase__      			=						red
											if green is not None:
															lowerCAmelCase__      			=						green
											if blue is not None:
															lowerCAmelCase__      			=						blue
											if red_edge is not None:
															lowerCAmelCase__      			=						red_edge
											if nir is not None:
															lowerCAmelCase__      			=						nir
											return True




							def 						__snake_case					(   self     :   Union[str, Any] ,							SCREAMING_SNAKE_CASE_     :   Any="" ,							SCREAMING_SNAKE_CASE_     :   str=None ,							SCREAMING_SNAKE_CASE_     :   Optional[Any]=None ,							SCREAMING_SNAKE_CASE_     :   List[str]=None ,							SCREAMING_SNAKE_CASE_     :   Optional[Any]=None ,							SCREAMING_SNAKE_CASE_     :   Optional[Any]=None	):
											self.set_matricies(red=SCREAMING_SNAKE_CASE_ ,							green=SCREAMING_SNAKE_CASE_ ,							blue=SCREAMING_SNAKE_CASE_ ,							red_edge=SCREAMING_SNAKE_CASE_ ,							nir=SCREAMING_SNAKE_CASE_	)
											lowerCAmelCase__      			=						{
											    '''ARVI2''': self.arvaa,
											    '''CCCI''': self.ccci,
											    '''CVI''': self.cvi,
											    '''GLI''': self.gli,
											    '''NDVI''': self.ndvi,
											    '''BNDVI''': self.bndvi,
											    '''redEdgeNDVI''': self.red_edge_ndvi,
											    '''GNDVI''': self.gndvi,
											    '''GBNDVI''': self.gbndvi,
											    '''GRNDVI''': self.grndvi,
											    '''RBNDVI''': self.rbndvi,
											    '''PNDVI''': self.pndvi,
											    '''ATSAVI''': self.atsavi,
											    '''BWDRVI''': self.bwdrvi,
											    '''CIgreen''': self.ci_green,
											    '''CIrededge''': self.ci_rededge,
											    '''CI''': self.ci,
											    '''CTVI''': self.ctvi,
											    '''GDVI''': self.gdvi,
											    '''EVI''': self.evi,
											    '''GEMI''': self.gemi,
											    '''GOSAVI''': self.gosavi,
											    '''GSAVI''': self.gsavi,
											    '''Hue''': self.hue,
											    '''IVI''': self.ivi,
											    '''IPVI''': self.ipvi,
											    '''I''': self.i,
											    '''RVI''': self.rvi,
											    '''MRVI''': self.mrvi,
											    '''MSAVI''': self.m_savi,
											    '''NormG''': self.norm_g,
											    '''NormNIR''': self.norm_nir,
											    '''NormR''': self.norm_r,
											    '''NGRDI''': self.ngrdi,
											    '''RI''': self.ri,
											    '''S''': self.s,
											    '''IF''': self._if,
											    '''DVI''': self.dvi,
											    '''TVI''': self.tvi,
											    '''NDRE''': self.ndre,
											}

											try:
															return funcs[index]()
											except KeyError:
															print('''Index not in the list!'''	)
															return False




							def 						__snake_case					(   self     :   List[str]	):
											return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red)))




							def 						__snake_case					(   self     :   Optional[int]	):
											return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / (
											    (self.nir - self.red) / (self.nir + self.red)
											)




							def 						__snake_case					(   self     :   str	):
											return self.nir * (self.red / (self.green**2))




							def 						__snake_case					(   self     :   List[str]	):
											return (2 * self.green - self.red - self.blue) / (
											    2 * self.green + self.red + self.blue
											)




							def 						__snake_case					(   self     :   List[str]	):
											return (self.nir - self.red) / (self.nir + self.red)




							def 						__snake_case					(   self     :   Optional[Any]	):
											return (self.nir - self.blue) / (self.nir + self.blue)




							def 						__snake_case					(   self     :   Optional[Any]	):
											return (self.redEdge - self.red) / (self.redEdge + self.red)




							def 						__snake_case					(   self     :   Tuple	):
											return (self.nir - self.green) / (self.nir + self.green)




							def 						__snake_case					(   self     :   List[Any]	):
											return (self.nir - (self.green + self.blue)) / (
											    self.nir + (self.green + self.blue)
											)




							def 						__snake_case					(   self     :   Optional[int]	):
											return (self.nir - (self.green + self.red)) / (
											    self.nir + (self.green + self.red)
											)




							def 						__snake_case					(   self     :   Optional[Any]	):
											return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red))




							def 						__snake_case					(   self     :   Optional[int]	):
											return (self.nir - (self.green + self.red + self.blue)) / (
											    self.nir + (self.green + self.red + self.blue)
											)




							def 						__snake_case					(   self     :   Union[str, Any] ,							SCREAMING_SNAKE_CASE_     :   List[Any]=0.08 ,							SCREAMING_SNAKE_CASE_     :   List[str]=1.22 ,							SCREAMING_SNAKE_CASE_     :   Union[str, Any]=0.03	):
											return a * (
											    (self.nir - a * self.red - b)
											    / (a * self.nir + self.red - a * b + x * (1 + a**2))
											)




							def 						__snake_case					(   self     :   Tuple	):
											return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue)




							def 						__snake_case					(   self     :   Dict	):
											return (self.nir / self.green) - 1




							def 						__snake_case					(   self     :   str	):
											return (self.nir / self.redEdge) - 1




							def 						__snake_case					(   self     :   Tuple	):
											return (self.red - self.blue) / self.red




							def 						__snake_case					(   self     :   Any	):
											lowerCAmelCase__      			=						self.ndvi()
											return ((ndvi + 0.5) / (abs(ndvi + 0.5	))) * (abs(ndvi + 0.5	) ** (1 / 2))




							def 						__snake_case					(   self     :   Dict	):
											return self.nir - self.green




							def 						__snake_case					(   self     :   List[Any]	):
											return 2.5 * (
											    (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1)
											)




							def 						__snake_case					(   self     :   Tuple	):
											lowerCAmelCase__      			=						(2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / (
											    self.nir + self.red + 0.5
											)
											return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red)




							def 						__snake_case					(   self     :   Optional[Any] ,							SCREAMING_SNAKE_CASE_     :   Dict=0.16	):
											return (self.nir - self.green) / (self.nir + self.green + y)




							def 						__snake_case					(   self     :   Optional[int] ,							SCREAMING_SNAKE_CASE_     :   Any=0.5	):
											return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n)




							def 						__snake_case					(   self     :   Any	):
											return np.arctan(
											    ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue)	)




							def 						__snake_case					(   self     :   List[str] ,							SCREAMING_SNAKE_CASE_     :   List[str]=None ,							SCREAMING_SNAKE_CASE_     :   Union[str, Any]=None	):
											return (self.nir - b) / (a * self.red)




							def 						__snake_case					(   self     :   Union[str, Any]	):
											return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1)




							def 						__snake_case					(   self     :   List[str]	):
											return (self.red + self.green + self.blue) / 30.5




							def 						__snake_case					(   self     :   Optional[int]	):
											return self.nir / self.red




							def 						__snake_case					(   self     :   Dict	):
											return (self.rvi() - 1) / (self.rvi() + 1)




							def 						__snake_case					(   self     :   Union[str, Any]	):
											return (
											    (2 * self.nir + 1)
											    - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2)
											) / 2




							def 						__snake_case					(   self     :   List[Any]	):
											return self.green / (self.nir + self.red + self.green)




							def 						__snake_case					(   self     :   List[str]	):
											return self.nir / (self.nir + self.red + self.green)




							def 						__snake_case					(   self     :   Any	):
											return self.red / (self.nir + self.red + self.green)




							def 						__snake_case					(   self     :   Union[str, Any]	):
											return (self.green - self.red) / (self.green + self.red)




							def 						__snake_case					(   self     :   Dict	):
											return (self.red - self.green) / (self.red + self.green)




							def 						__snake_case					(   self     :   Optional[int]	):
											lowerCAmelCase__      			=						np.max([np.max(self.red	), np.max(self.green	), np.max(self.blue	)]	)
											lowerCAmelCase__      			=						np.min([np.min(self.red	), np.min(self.green	), np.min(self.blue	)]	)
											return (max_value - min_value) / max_value




							def 						__snake_case					(   self     :   str	):
											return (2 * self.red - self.green - self.blue) / (self.green - self.blue)




							def 						__snake_case					(   self     :   Optional[Any]	):
											return self.nir / self.red




							def 						__snake_case					(   self     :   Union[str, Any]	):
											return (self.ndvi() + 0.5) ** (1 / 2)




							def 						__snake_case					(   self     :   List[Any]	):
											return (self.nir - self.redEdge) / (self.nir + self.redEdge)





