




import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
	from transformers import SpeechaTextFeatureExtractor

_lowerCamelCase      :  List[Any]      						=						random.Random()




def 							_UpperCAmelCase  (UpperCamelCase_ : List[str]      ,    UpperCamelCase_ : Tuple=1.0      ,    UpperCamelCase_ : Any=None      ,    UpperCamelCase_ : List[str]=None       ):
				'''simple docstring'''
				if rng is None:
								_lowerCAmelCase    :    Union[str, Any]										=      global_rng

				_lowerCAmelCase    :    int										=      []
				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        __snake_case  (unittest.TestCase		):



				def __init__(      self      :		str		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		Optional[int]=7		,	_UpperCAmelCase      :		List[Any]=400		,	_UpperCAmelCase      :		str=2000		,	_UpperCAmelCase      :		Tuple=24		,	_UpperCAmelCase      :		List[Any]=24		,	_UpperCAmelCase      :		Dict=0.0		,	_UpperCAmelCase      :		Optional[int]=1_6000		,	_UpperCAmelCase      :		int=True		,	_UpperCAmelCase      :		Optional[int]=True		,	)  ->    int:





								'''simple docstring'''




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



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





								'''simple docstring'''




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



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[int]		,	_UpperCAmelCase      :		Tuple=False		,	_UpperCAmelCase      :		List[str]=False      )  ->    Tuple:





								'''simple docstring'''




								def _flatten(_UpperCAmelCase      :		Tuple      ):
												return list(itertools.chain(*_UpperCAmelCase      )      )

								if equal_length:
												_lowerCAmelCase    :    Optional[Any]										=      [floats_list((self.max_seq_length, self.feature_size)      ) for _ in range(self.batch_size      )]
								else:
												# make sure that inputs increase in size
												_lowerCAmelCase    :    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:
												_lowerCAmelCase    :    int										=      [np.asarray(_UpperCAmelCase      ) for x in speech_inputs]
								return speech_inputs






@require_torch
@require_torchaudio
class        __snake_case  (_a						,	unittest.TestCase		):
				lowerCAmelCase__				=     SpeechaTextFeatureExtractor if is_speech_available() else None



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





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[int]										=      SpeechaTextFeatureExtractionTester(self      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict		,	_UpperCAmelCase      :		int      )  ->    Any:





								'''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       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]      )  ->    Union[str, Any]:





								'''simple docstring'''




								_lowerCAmelCase    :    List[str]										=      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								# create three inputs of length 800, 1000, and 1200
								_lowerCAmelCase    :    Optional[int]										=      [floats_list((1, x)      )[0] for x in range(800		,	1400		,	200      )]
								_lowerCAmelCase    :    Tuple										=      [np.asarray(_UpperCAmelCase      ) for speech_input in speech_inputs]

								# Test feature size
								_lowerCAmelCase    :    List[Any]										=      feature_extractor(_UpperCAmelCase		,	padding=_UpperCAmelCase		,	return_tensors="""np"""      ).input_features
								self.assertTrue(input_features.ndim == 3      )
								self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size      )

								# Test not batched input
								_lowerCAmelCase    :    Tuple										=      feature_extractor(speech_inputs[0]		,	return_tensors="""np"""      ).input_features
								_lowerCAmelCase    :    Union[str, Any]										=      feature_extractor(np_speech_inputs[0]		,	return_tensors="""np"""      ).input_features
								self.assertTrue(np.allclose(_UpperCAmelCase		,	_UpperCAmelCase		,	atol=1E-3      )      )

								# Test batched
								_lowerCAmelCase    :    int										=      feature_extractor(_UpperCAmelCase		,	return_tensors="""np"""      ).input_features
								_lowerCAmelCase    :    Union[str, Any]										=      feature_extractor(_UpperCAmelCase		,	return_tensors="""np"""      ).input_features
								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.
								_lowerCAmelCase    :    Any										=      [floats_list((1, x)      )[0] for x in (800, 800, 800)]
								_lowerCAmelCase    :    Any										=      np.asarray(_UpperCAmelCase      )
								_lowerCAmelCase    :    Any										=      feature_extractor(_UpperCAmelCase		,	return_tensors="""np"""      ).input_features
								_lowerCAmelCase    :    int										=      feature_extractor(_UpperCAmelCase		,	return_tensors="""np"""      ).input_features
								for enc_seq_a, enc_seq_a in zip(_UpperCAmelCase		,	_UpperCAmelCase      ):
												self.assertTrue(np.allclose(_UpperCAmelCase		,	_UpperCAmelCase		,	atol=1E-3      )      )



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





								'''simple docstring'''




								_lowerCAmelCase    :    Union[str, Any]										=      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								_lowerCAmelCase    :    List[str]										=      [floats_list((1, x)      )[0] for x in range(800		,	1400		,	200      )]

								_lowerCAmelCase    :    Dict										=      ["""longest""", """max_length""", """do_not_pad"""]
								_lowerCAmelCase    :    Dict										=      [None, 16, None]
								for max_length, padding in zip(_UpperCAmelCase		,	_UpperCAmelCase      ):
												_lowerCAmelCase    :    List[Any]										=      feature_extractor(
												    _UpperCAmelCase		,	padding=_UpperCAmelCase		,	max_length=_UpperCAmelCase		,	return_attention_mask=_UpperCAmelCase      )
												_lowerCAmelCase    :    Dict										=      inputs.input_features
												_lowerCAmelCase    :    int										=      inputs.attention_mask
												_lowerCAmelCase    :    List[Any]										=      [np.sum(_UpperCAmelCase      ) for x in attention_mask]

												self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]      )
												self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]      )
												self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]      )



				def       SCREAMING_SNAKE_CASE       (      self      :		List[str]      )  ->    str:





								'''simple docstring'''




								_lowerCAmelCase    :    Tuple										=      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								_lowerCAmelCase    :    Optional[Any]										=      [floats_list((1, x)      )[0] for x in range(800		,	1400		,	200      )]

								_lowerCAmelCase    :    Dict										=      ["""longest""", """max_length""", """do_not_pad"""]
								_lowerCAmelCase    :    Tuple										=      [None, 16, None]
								for max_length, padding in zip(_UpperCAmelCase		,	_UpperCAmelCase      ):
												_lowerCAmelCase    :    Optional[int]										=      feature_extractor(
												    _UpperCAmelCase		,	max_length=_UpperCAmelCase		,	padding=_UpperCAmelCase		,	return_tensors="""np"""		,	return_attention_mask=_UpperCAmelCase      )
												_lowerCAmelCase    :    Tuple										=      inputs.input_features
												_lowerCAmelCase    :    Optional[Any]										=      inputs.attention_mask
												_lowerCAmelCase    :    Union[str, Any]										=      [np.sum(_UpperCAmelCase      ) for x in attention_mask]

												self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]      )
												self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6      )
												self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]      )
												self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6      )
												self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]      )



				def       SCREAMING_SNAKE_CASE       (      self      :		Any      )  ->    Any:





								'''simple docstring'''




								_lowerCAmelCase    :    Union[str, Any]										=      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								_lowerCAmelCase    :    List[str]										=      [floats_list((1, x)      )[0] for x in range(800		,	1400		,	200      )]
								_lowerCAmelCase    :    List[str]										=      feature_extractor(
								    _UpperCAmelCase		,	padding="""max_length"""		,	max_length=4		,	truncation=_UpperCAmelCase		,	return_tensors="""np"""		,	return_attention_mask=_UpperCAmelCase		,	)
								_lowerCAmelCase    :    List[Any]										=      inputs.input_features
								_lowerCAmelCase    :    Any										=      inputs.attention_mask
								_lowerCAmelCase    :    int										=      np.sum(attention_mask == 1		,	axis=1      )

								self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]      )
								self._check_zero_mean_unit_variance(input_features[1]      )
								self._check_zero_mean_unit_variance(input_features[2]      )



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





								'''simple docstring'''




								_lowerCAmelCase    :    List[Any]										=      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								_lowerCAmelCase    :    List[str]										=      [floats_list((1, x)      )[0] for x in range(800		,	1400		,	200      )]
								_lowerCAmelCase    :    Dict										=      feature_extractor(
								    _UpperCAmelCase		,	padding="""longest"""		,	max_length=4		,	truncation=_UpperCAmelCase		,	return_tensors="""np"""		,	return_attention_mask=_UpperCAmelCase		,	)
								_lowerCAmelCase    :    str										=      inputs.input_features
								_lowerCAmelCase    :    int										=      inputs.attention_mask
								_lowerCAmelCase    :    Optional[int]										=      np.sum(attention_mask == 1		,	axis=1      )

								self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]      )
								self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]      )
								self._check_zero_mean_unit_variance(input_features[2]      )

								# make sure that if max_length < longest -> then pad to max_length
								self.assertEqual(input_features.shape		,	(3, 4, 24)      )

								_lowerCAmelCase    :    List[Any]										=      [floats_list((1, x)      )[0] for x in range(800		,	1400		,	200      )]
								_lowerCAmelCase    :    Optional[Any]										=      feature_extractor(
								    _UpperCAmelCase		,	padding="""longest"""		,	max_length=16		,	truncation=_UpperCAmelCase		,	return_tensors="""np"""		,	return_attention_mask=_UpperCAmelCase		,	)
								_lowerCAmelCase    :    Union[str, Any]										=      inputs.input_features
								_lowerCAmelCase    :    Tuple										=      inputs.attention_mask
								_lowerCAmelCase    :    str										=      np.sum(attention_mask == 1		,	axis=1      )

								self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]      )
								self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]      )
								self._check_zero_mean_unit_variance(input_features[2]      )

								# make sure that if max_length < longest -> then pad to max_length
								self.assertEqual(input_features.shape		,	(3, 6, 24)      )



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





								'''simple docstring'''




								import torch

								_lowerCAmelCase    :    Tuple										=      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								_lowerCAmelCase    :    Union[str, Any]										=      np.random.rand(100		,	32      ).astype(np.floataa      )
								_lowerCAmelCase    :    List[str]										=      np_speech_inputs.tolist()

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



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





								'''simple docstring'''




								from datasets import load_dataset

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

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



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]      )  ->    Any:





								'''simple docstring'''




								_lowerCAmelCase    :    str										=      np.array([
								    -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241,
								    -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128,
								    -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625,
								]      )
								# fmt: on

								_lowerCAmelCase    :    Optional[int]										=      self._load_datasamples(1      )
								_lowerCAmelCase    :    Optional[int]										=      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								_lowerCAmelCase    :    Optional[Any]										=      feature_extractor(_UpperCAmelCase		,	return_tensors="""pt"""      ).input_features
								self.assertEquals(input_features.shape		,	(1, 584, 24)      )
								self.assertTrue(np.allclose(input_features[0, 0, :30]		,	_UpperCAmelCase		,	atol=1E-4      )      )







from __future__ import annotations
class        __snake_case  :



				def __init__(      self      :		Union[str, Any]		,	_UpperCAmelCase      :		int = 0      )  ->    Optional[int]:





								'''simple docstring'''




								_lowerCAmelCase    :    int										=      key



				def       SCREAMING_SNAKE_CASE       (      self      :		Dict		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		int      )  ->    list[str]:





								'''simple docstring'''




								assert isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ) and isinstance(_UpperCAmelCase		,	_UpperCAmelCase      )

								_lowerCAmelCase    :    Optional[Any]										=      key or self.__key or 1

								# make sure key is an appropriate size
								key %= 255

								return [chr(ord(_UpperCAmelCase      ) ^ key      ) for ch in content]



				def       SCREAMING_SNAKE_CASE       (      self      :		List[str]		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		int      )  ->    list[str]:





								'''simple docstring'''




								assert isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ) and isinstance(_UpperCAmelCase		,	_UpperCAmelCase      )

								_lowerCAmelCase    :    List[Any]										=      key or self.__key or 1

								# make sure key is an appropriate size
								key %= 255

								return [chr(ord(_UpperCAmelCase      ) ^ key      ) for ch in content]



				def       SCREAMING_SNAKE_CASE       (      self      :		Optional[Any]		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		int = 0      )  ->    str:





								'''simple docstring'''




								assert isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ) and isinstance(_UpperCAmelCase		,	_UpperCAmelCase      )

								_lowerCAmelCase    :    Union[str, Any]										=      key or self.__key or 1

								# make sure key can be any size
								while key > 255:
												key -= 255

								# This will be returned
								_lowerCAmelCase    :    List[str]										=      """"""

								for ch in content:
												ans += chr(ord(_UpperCAmelCase      ) ^ key      )

								return ans



				def       SCREAMING_SNAKE_CASE       (      self      :		Tuple		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		int = 0      )  ->    str:





								'''simple docstring'''




								assert isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ) and isinstance(_UpperCAmelCase		,	_UpperCAmelCase      )

								_lowerCAmelCase    :    Any										=      key or self.__key or 1

								# make sure key can be any size
								while key > 255:
												key -= 255

								# This will be returned
								_lowerCAmelCase    :    List[Any]										=      """"""

								for ch in content:
												ans += chr(ord(_UpperCAmelCase      ) ^ key      )

								return ans



				def       SCREAMING_SNAKE_CASE       (      self      :		List[str]		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		int = 0      )  ->    bool:





								'''simple docstring'''




								assert isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ) and isinstance(_UpperCAmelCase		,	_UpperCAmelCase      )

								try:
												with open(_UpperCAmelCase      ) as fin, open("""encrypt.out"""		,	"""w+"""      ) as fout:
																# actual encrypt-process
																for line in fin:
																				fout.write(self.encrypt_string(_UpperCAmelCase		,	_UpperCAmelCase      )      )

								except OSError:
												return False

								return True



				def       SCREAMING_SNAKE_CASE       (      self      :		Any		,	_UpperCAmelCase      :		str		,	_UpperCAmelCase      :		int      )  ->    bool:





								'''simple docstring'''




								assert isinstance(_UpperCAmelCase		,	_UpperCAmelCase      ) and isinstance(_UpperCAmelCase		,	_UpperCAmelCase      )

								try:
												with open(_UpperCAmelCase      ) as fin, open("""decrypt.out"""		,	"""w+"""      ) as fout:
																# actual encrypt-process
																for line in fin:
																				fout.write(self.decrypt_string(_UpperCAmelCase		,	_UpperCAmelCase      )      )

								except OSError:
												return False

								return True


# Tests
# crypt = XORCipher()
# key = 67

# # test encrypt
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))

# # test encrypt_string
# print(crypt.encrypt_string("hallo welt",key))

# # test decrypt_string
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))

# if (crypt.encrypt_file("test.txt",key)):
#       print("encrypt successful")
# else:
#       print("encrypt unsuccessful")

# if (crypt.decrypt_file("encrypt.out",key)):
#       print("decrypt successful")
# else:
#       print("decrypt unsuccessful")

