'''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

lowerCAmelCase			:							List[str]     =random.Random()







def 						A__  (					__A   , __A=1.0   , __A=None   , __A=None	):







    '''simple docstring'''
    if rng is None:
        _lowerCamelCase     :		str 						=						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		):





      '''simple docstring'''






      def __init__(					self     :				Tuple    ,  _UpperCamelCase     :				Optional[int]    ,  _UpperCamelCase     :				str=7    ,  _UpperCamelCase     :				Dict=400    ,  _UpperCamelCase     :				str=2000    ,  _UpperCamelCase     :				str=10    ,  _UpperCamelCase     :				Any=160    ,  _UpperCamelCase     :				List[Any]=8    ,  _UpperCamelCase     :				List[str]=0.0    ,  _UpperCamelCase     :				List[Any]=4000    ,  _UpperCamelCase     :				Optional[Any]=False    ,  _UpperCamelCase     :				Dict=True    ,  )				->List[Any]:


          """simple docstring"""


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



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


          """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 	_SCREAMING_SNAKE_CASE    (					self     :				Dict    ,  _UpperCamelCase     :				Dict=False    ,  _UpperCamelCase     :				int=False)				->Union[str, Any]:


          """simple docstring"""


          def _flatten(_UpperCamelCase     :				Optional[Any]):
              return list(itertools.chain(*_UpperCamelCase))

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





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





      '''simple docstring'''






      _snake_case    		=       WhisperFeatureExtractor if is_speech_available() else None



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict)				->List[str]:


          """simple docstring"""


          _lowerCamelCase     :		int 						=						WhisperFeatureExtractionTester(self)



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


          """simple docstring"""


          _lowerCamelCase     :		int 						=						self.feature_extraction_class(**self.feat_extract_dict)

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

          _lowerCamelCase     :		Tuple 						=						feat_extract_first.to_dict()
          _lowerCamelCase     :		Any 						=						feat_extract_second.to_dict()
          _lowerCamelCase     :		Optional[Any] 						=						feat_extract_first.mel_filters
          _lowerCamelCase     :		Optional[int] 						=						feat_extract_second.mel_filters
          self.assertTrue(np.allclose(_UpperCamelCase    ,  _UpperCamelCase))
          self.assertEqual(_UpperCamelCase    ,  _UpperCamelCase)



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


          """simple docstring"""


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

          with tempfile.TemporaryDirectory() as tmpdirname:
              _lowerCamelCase     :		Optional[Any] 						=						os.path.join(_UpperCamelCase    ,  """feat_extract.json""")
              feat_extract_first.to_json_file(_UpperCamelCase)
              _lowerCamelCase     :		List[str] 						=						self.feature_extraction_class.from_json_file(_UpperCamelCase)

          _lowerCamelCase     :		Optional[Any] 						=						feat_extract_first.to_dict()
          _lowerCamelCase     :		Dict 						=						feat_extract_second.to_dict()
          _lowerCamelCase     :		List[Any] 						=						feat_extract_first.mel_filters
          _lowerCamelCase     :		Optional[Any] 						=						feat_extract_second.mel_filters
          self.assertTrue(np.allclose(_UpperCamelCase    ,  _UpperCamelCase))
          self.assertEqual(_UpperCamelCase    ,  _UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->Tuple:


          """simple docstring"""


          _lowerCamelCase     :		Optional[int] 						=						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     :		List[Any] 						=						[np.asarray(_UpperCamelCase) for speech_input in speech_inputs]

          # Test feature size
          _lowerCamelCase     :		Tuple 						=						feature_extractor(_UpperCamelCase    ,  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     :		Tuple 						=						feature_extractor(speech_inputs[0]    ,  return_tensors="""np""").input_features
          _lowerCamelCase     :		List[Any] 						=						feature_extractor(np_speech_inputs[0]    ,  return_tensors="""np""").input_features
          self.assertTrue(np.allclose(_UpperCamelCase    ,  _UpperCamelCase    ,  atol=1E-3))

          # Test batched
          _lowerCamelCase     :		Dict 						=						feature_extractor(_UpperCamelCase    ,  return_tensors="""np""").input_features
          _lowerCamelCase     :		Optional[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     :		Tuple 						=						np.asarray(_UpperCamelCase)
          _lowerCamelCase     :		List[str] 						=						feature_extractor(_UpperCamelCase    ,  return_tensors="""np""").input_features
          _lowerCamelCase     :		List[str] 						=						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 truncation required
          _lowerCamelCase     :		Union[str, Any] 						=						[floats_list((1, x))[0] for x in range(200    ,  (feature_extractor.n_samples + 500)    ,  200)]
          _lowerCamelCase     :		Optional[int] 						=						[np.asarray(_UpperCamelCase) for speech_input in speech_inputs]

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

          _lowerCamelCase     :		Tuple 						=						feature_extractor(_UpperCamelCase    ,  return_tensors="""np""").input_features
          _lowerCamelCase     :		Dict 						=						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     :				Optional[Any])				->Tuple:


          """simple docstring"""


          import torch

          _lowerCamelCase     :		Optional[int] 						=						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
          _lowerCamelCase     :		int 						=						np.random.rand(100    ,  32).astype(np.floataa)
          _lowerCamelCase     :		Tuple 						=						np_speech_inputs.tolist()

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



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict    ,  _UpperCamelCase     :				List[Any])				->Union[str, Any]:


          """simple docstring"""


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

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



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


          """simple docstring"""


          _lowerCamelCase     :		Optional[int] 						=						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

          _lowerCamelCase     :		Union[str, Any] 						=						self._load_datasamples(1)
          _lowerCamelCase     :		Dict 						=						WhisperFeatureExtractor()
          _lowerCamelCase     :		Any 						=						feature_extractor(_UpperCamelCase    ,  return_tensors="""pt""").input_features
          self.assertEqual(input_features.shape    ,  (1, 80, 3000))
          self.assertTrue(torch.allclose(input_features[0, 0, :30]    ,  _UpperCamelCase    ,  atol=1E-4))




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


          """simple docstring"""


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

          self.assertTrue(np.all(np.mean(_UpperCamelCase) < 1E-3))
          self.assertTrue(np.all(np.abs(np.var(_UpperCamelCase) - 1) < 1E-3))





from __future__ import annotations




class 	__snake_case	:





      '''simple docstring'''






      def __init__(					self     :				Tuple    ,  _UpperCamelCase     :				int = 0)				->str:


          """simple docstring"""


          _lowerCamelCase     :		Union[str, Any] 						=						key



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Any    ,  _UpperCamelCase     :				str    ,  _UpperCamelCase     :				int)				->list[str]:


          """simple docstring"""


          assert isinstance(_UpperCamelCase    ,  _UpperCamelCase) and isinstance(_UpperCamelCase    ,  _UpperCamelCase)

          _lowerCamelCase     :		Union[str, 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     :				str    ,  _UpperCamelCase     :				str    ,  _UpperCamelCase     :				int)				->list[str]:


          """simple docstring"""


          assert isinstance(_UpperCamelCase    ,  _UpperCamelCase) and isinstance(_UpperCamelCase    ,  _UpperCamelCase)

          _lowerCamelCase     :		Optional[int] 						=						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 = 0)				->str:


          """simple docstring"""


          assert isinstance(_UpperCamelCase    ,  _UpperCamelCase) and isinstance(_UpperCamelCase    ,  _UpperCamelCase)

          _lowerCamelCase     :		int 						=						key or self.__key or 1

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

          # This will be returned
          _lowerCamelCase     :		Any 						=						""""""

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

          return ans



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


          """simple docstring"""


          assert isinstance(_UpperCamelCase    ,  _UpperCamelCase) and isinstance(_UpperCamelCase    ,  _UpperCamelCase)

          _lowerCamelCase     :		int 						=						key or self.__key or 1

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

          # This will be returned
          _lowerCamelCase     :		Optional[Any] 						=						""""""

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

          return ans



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[int]    ,  _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     :				List[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")




