
"""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_       :    Optional[Any]						      =			random.Random()
def 				A_  (__a					, __a=1.0					, __a=None					, __a=None					):

					'''simple docstring'''





					if rng is None:
										A_								=    global_rng

					A_								=    []
					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   ):




			"""simple docstring"""







			def __init__(					self    :       List[str]							, _snake_case    :       Tuple							, _snake_case    :       Dict=7							, _snake_case    :       List[Any]=400							, _snake_case    :       Dict=2_000							, _snake_case    :       Optional[Any]=10							, _snake_case    :       List[Any]=160							, _snake_case    :       List[Any]=8							, _snake_case    :       Tuple=0.0							, _snake_case    :       Union[str, Any]=4_000							, _snake_case    :       Union[str, Any]=False							, _snake_case    :       Dict=True							, )   ->			Union[str, Any]:







								"""simple docstring"""
								A_								=    parent
								A_								=    batch_size
								A_								=    min_seq_length
								A_								=    max_seq_length
								A_								=    (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
								A_								=    padding_value
								A_								=    sampling_rate
								A_								=    return_attention_mask
								A_								=    do_normalize
								A_								=    feature_size
								A_								=    chunk_length
								A_								=    hop_length




			def   lowerCamelCase__  (					self    :       str						)   ->			str:







								"""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   lowerCamelCase__  (					self    :       Optional[Any]							, _snake_case    :       str=False							, _snake_case    :       int=False						)   ->			Optional[int]:







								"""simple docstring"""
								def _flatten(_snake_case    :       Dict						):
													return list(itertools.chain(*_snake_case						)						)

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





@require_torch
@require_torchaudio
class __lowerCAmelCase					(       _lowercase  ,					unittest.TestCase   ):




			"""simple docstring"""







			snake_case						   =					WhisperFeatureExtractor if is_speech_available() else None




			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			Dict:







								"""simple docstring"""
								A_								=    WhisperFeatureExtractionTester(self						)




			def   lowerCamelCase__  (					self    :       List[str]						)   ->			List[Any]:







								"""simple docstring"""
								A_								=    self.feature_extraction_class(**self.feat_extract_dict						)

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

								A_								=    feat_extract_first.to_dict()
								A_								=    feat_extract_second.to_dict()
								A_								=    feat_extract_first.mel_filters
								A_								=    feat_extract_second.mel_filters
								self.assertTrue(np.allclose(_snake_case							, _snake_case						)						)
								self.assertEqual(_snake_case							, _snake_case						)




			def   lowerCamelCase__  (					self    :       int						)   ->			Optional[int]:







								"""simple docstring"""
								A_								=    self.feature_extraction_class(**self.feat_extract_dict						)

								with tempfile.TemporaryDirectory() as tmpdirname:
													A_								=    os.path.join(_snake_case							, "feat_extract.json"						)
													feat_extract_first.to_json_file(_snake_case						)
													A_								=    self.feature_extraction_class.from_json_file(_snake_case						)

								A_								=    feat_extract_first.to_dict()
								A_								=    feat_extract_second.to_dict()
								A_								=    feat_extract_first.mel_filters
								A_								=    feat_extract_second.mel_filters
								self.assertTrue(np.allclose(_snake_case							, _snake_case						)						)
								self.assertEqual(_snake_case							, _snake_case						)




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







								"""simple docstring"""
								# Tests that all call wrap to encode_plus and batch_encode_plus
								A_								=    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
								# create three inputs of length 800, 1000, and 1200
								A_								=    [floats_list((1, x)						)[0] for x in range(800							, 1_400							, 200						)]
								A_								=    [np.asarray(_snake_case						) for speech_input in speech_inputs]

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

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

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

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

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

								A_								=    feature_extractor(_snake_case							, return_tensors="np"						).input_features
								A_								=    feature_extractor(_snake_case							, return_tensors="np"						).input_features
								for enc_seq_a, enc_seq_a in zip(_snake_case							, _snake_case						):
													self.assertTrue(np.allclose(_snake_case							, _snake_case							, atol=1e-3						)						)




			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			Dict:







								"""simple docstring"""
								import torch

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

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




			def   lowerCamelCase__  (					self    :       Optional[int]							, _snake_case    :       Optional[Any]						)   ->			Optional[int]:







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

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




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







								"""simple docstring"""
								# fmt: off
								A_								=    torch.tensor(
								    [
								        0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
								        0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
								        0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
								        -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
								    ]						)
								# fmt: on

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






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







								"""simple docstring"""
								A_								=    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
								A_								=    self._load_datasamples(1						)[0]
								A_								=    ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535  # Rescale to [0, 65535] to show issue
								A_								=    feat_extract.zero_mean_unit_var_norm([audio]							, attention_mask=_snake_case						)[0]

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








'''simple docstring'''
from __future__ import annotations

from typing import Any







def       a_				(	UpperCamelCase_ ):
							create_state_space_tree(UpperCamelCase_						,  []						,  0 )







def       a_				(	UpperCamelCase_						,  UpperCamelCase_						,  UpperCamelCase_ ):

							if index == len(UpperCamelCase_ ):
														print(UpperCamelCase_ )
														return

							create_state_space_tree(UpperCamelCase_						,  UpperCamelCase_						,  index + 1 )
							current_subsequence.append(sequence[index] )
							create_state_space_tree(UpperCamelCase_						,  UpperCamelCase_						,  index + 1 )
							current_subsequence.pop()


if __name__ == "__main__":
							__SCREAMING_SNAKE_CASE					:				list[Any]									=		[3, 1, 2, 4]
							generate_all_subsequences(seq)

							seq.clear()
							seq.extend(['''A''', '''B''', '''C'''])
							generate_all_subsequences(seq)





