
"""simple docstring"""

import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_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_torch_available():
      import torch

if is_datasets_available():
      from datasets import load_dataset

UpperCamelCase			:       str									=				random.Random()






def 							A		(       snake_case   :Optional[Any]       ,      snake_case   :str=1.0       ,      snake_case   :List[Any]=None       ,      snake_case   :Optional[Any]=None	)   ->			Optional[int]:
 if rng is None:
  __UpperCamelCase       						= global_rng

 __UpperCamelCase       						= []
 for batch_idx in range(shape[0]	):
  values.append([]	)
  for _ in range(shape[1]	):
   values[-1].append(rng.random() * scale	)

 return values

class __lowerCAmelCase	(   unittest.TestCase    ):





     def __init__(			self			,  __UpperCAmelCase			,  __UpperCAmelCase=7			,  __UpperCAmelCase=400			,  __UpperCAmelCase=2000			,  __UpperCAmelCase=2048			,  __UpperCAmelCase=128			,  __UpperCAmelCase=1			,  __UpperCAmelCase=512			,  __UpperCAmelCase=30			,  __UpperCAmelCase=4_4100			,  ):

      '''simple docstring'''




      __UpperCamelCase       						= parent
      __UpperCamelCase       						= batch_size
      __UpperCamelCase       						= min_seq_length
      __UpperCamelCase       						= max_seq_length
      __UpperCamelCase       						= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
      __UpperCamelCase       						= spectrogram_length
      __UpperCamelCase       						= feature_size
      __UpperCamelCase       						= num_audio_channels
      __UpperCamelCase       						= hop_length
      __UpperCamelCase       						= chunk_length
      __UpperCamelCase       						= sampling_rate





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      return {
          "spectrogram_length": self.spectrogram_length,
          "feature_size": self.feature_size,
          "num_audio_channels": self.num_audio_channels,
          "hop_length": self.hop_length,
          "chunk_length": self.chunk_length,
          "sampling_rate": self.sampling_rate,
      }







     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase=False			,  __UpperCAmelCase=False   ):

      '''simple docstring'''




      def _flatten(__UpperCAmelCase   ):
       return list(itertools.chain(*__UpperCAmelCase   )   )

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


@require_torch
@require_torchaudio
class __lowerCAmelCase	(   __SCREAMING_SNAKE_CASE    ,						unittest.TestCase    ):
     lowercase		     =		TvltFeatureExtractor





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= TvltFeatureExtractionTester(self   )





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.feature_extraction_class(**self.feat_extract_dict   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'spectrogram_length'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'feature_size'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'num_audio_channels'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'hop_length'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'chunk_length'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'sampling_rate'   )   )





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.feature_extraction_class(**self.feat_extract_dict   )

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

      __UpperCamelCase       						= feat_extract_first.to_dict()
      __UpperCamelCase       						= feat_extract_second.to_dict()
      __UpperCamelCase       						= dict_first.pop('mel_filters'   )
      __UpperCamelCase       						= dict_second.pop('mel_filters'   )
      self.assertTrue(np.allclose(__UpperCAmelCase			,  __UpperCAmelCase   )   )
      self.assertEqual(__UpperCAmelCase			,  __UpperCAmelCase   )





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.feature_extraction_class(**self.feat_extract_dict   )

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

      __UpperCamelCase       						= feat_extract_first.to_dict()
      __UpperCamelCase       						= feat_extract_second.to_dict()
      __UpperCamelCase       						= dict_first.pop('mel_filters'   )
      __UpperCamelCase       						= dict_second.pop('mel_filters'   )
      self.assertTrue(np.allclose(__UpperCAmelCase			,  __UpperCAmelCase   )   )
      self.assertEqual(__UpperCAmelCase			,  __UpperCAmelCase   )





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.feature_extraction_class(**self.feat_extract_dict   )

      # create three inputs of length 800, 1000, and 1200
      __UpperCamelCase       						= [floats_list((1, x)   )[0] for x in range(800			,  1400			,  200   )]
      __UpperCamelCase       						= [np.asarray(__UpperCAmelCase   ) for speech_input in speech_inputs]

      # Test not batched input
      __UpperCamelCase       						= feature_extractor(np_speech_inputs[0]			,  return_tensors='np'			,  sampling_rate=4_4100   ).audio_values

      self.assertTrue(encoded_audios.ndim == 4   )
      self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size   )
      self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length   )
      self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels   )

      # Test batched
      __UpperCamelCase       						= feature_extractor(__UpperCAmelCase			,  return_tensors='np'			,  sampling_rate=4_4100   ).audio_values

      self.assertTrue(encoded_audios.ndim == 4   )
      self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size   )
      self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length   )
      self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels   )

      # Test audio masking
      __UpperCamelCase       						= feature_extractor(
          __UpperCAmelCase			,  return_tensors='np'			,  sampling_rate=4_4100			,  mask_audio=__UpperCAmelCase   ).audio_values

      self.assertTrue(encoded_audios.ndim == 4   )
      self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size   )
      self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length   )
      self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels   )

      # Test 2-D numpy arrays are batched.
      __UpperCamelCase       						= [floats_list((1, x)   )[0] for x in (800, 800, 800)]
      __UpperCamelCase       						= np.asarray(__UpperCAmelCase   )
      __UpperCamelCase       						= feature_extractor(__UpperCAmelCase			,  return_tensors='np'			,  sampling_rate=4_4100   ).audio_values
      self.assertTrue(encoded_audios.ndim == 4   )
      self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size   )
      self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length   )
      self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




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

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







     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self._load_datasamples(1   )
      __UpperCamelCase       						= TvltFeatureExtractor()
      __UpperCamelCase       						= feature_extractor(__UpperCAmelCase			,  return_tensors='pt'   ).audio_values

      self.assertEquals(audio_values.shape			,  (1, 1, 192, 128)   )

      __UpperCamelCase       						= torch.tensor([[-0.3_0_3_2, -0.2_7_0_8], [-0.4_4_3_4, -0.4_0_0_7]]   )
      self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]			,  __UpperCAmelCase			,  atol=1E-4   )   )





"""simple docstring"""

import string

import numpy






def 							A		(       snake_case   :int       ,      snake_case   :int	)   ->			int:
 return b if a == 0 else greatest_common_divisor(b % a       ,      snake_case	)

class __lowerCAmelCase	:
     lowercase		     =		string.ascii_uppercase + string.digits
     # This cipher takes alphanumerics into account
     # i.e. a total of 36 characters

     # take x and return x % len(key_string)
     lowercase		     =		numpy.vectorize(lambda __SCREAMING_SNAKE_CASE    : x % 36    )

     lowercase		     =		numpy.vectorize(__SCREAMING_SNAKE_CASE    )





     def __init__(			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.modulus(__UpperCAmelCase   )  # mod36 calc's on the encrypt key
      self.check_determinant()  # validate the determinant of the encryption key
      __UpperCamelCase       						= encrypt_key.shape[0]





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self.key_string.index(__UpperCAmelCase   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self.key_string[round(__UpperCAmelCase   )]





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= round(numpy.linalg.det(self.encrypt_key   )   )

      if det < 0:
       __UpperCamelCase       						= det % len(self.key_string   )

      __UpperCamelCase       						= len(self.key_string   )
      if greatest_common_divisor(__UpperCAmelCase			,  len(self.key_string   )   ) != 1:
       __UpperCamelCase       						= (
           F'determinant modular {req_l} of encryption key({det}) '
           F'is not co prime w.r.t {req_l}.\nTry another key.'
       )
       raise ValueError(__UpperCAmelCase   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= [char for char in text.upper() if char in self.key_string]

      __UpperCamelCase       						= chars[-1]
      while len(__UpperCAmelCase   ) % self.break_key != 0:
       chars.append(__UpperCAmelCase   )

      return "".join(__UpperCAmelCase   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.process_text(text.upper()   )
      __UpperCamelCase       						= ''

      for i in range(0			,  len(__UpperCAmelCase   ) - self.break_key + 1			,  self.break_key   ):
       __UpperCamelCase       						= text[i : i + self.break_key]
       __UpperCamelCase       						= [self.replace_letters(__UpperCAmelCase   ) for char in batch]
       __UpperCamelCase       						= numpy.array([vec]   ).T
       __UpperCamelCase       						= self.modulus(self.encrypt_key.dot(__UpperCAmelCase   )   ).T.tolist()[
           0
       ]
       __UpperCamelCase       						= ''.join(
           self.replace_digits(__UpperCAmelCase   ) for num in batch_encrypted   )
       encrypted += encrypted_batch

      return encrypted





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= round(numpy.linalg.det(self.encrypt_key   )   )

      if det < 0:
       __UpperCamelCase       						= det % len(self.key_string   )
      __UpperCamelCase       						= None
      for i in range(len(self.key_string   )   ):
       if (det * i) % len(self.key_string   ) == 1:
        __UpperCamelCase       						= i
        break

      __UpperCamelCase       						= (
          det_inv
          * numpy.linalg.det(self.encrypt_key   )
          * numpy.linalg.inv(self.encrypt_key   )
      )

      return self.to_int(self.modulus(__UpperCAmelCase   )   )







     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.make_decrypt_key()
      __UpperCamelCase       						= self.process_text(text.upper()   )
      __UpperCamelCase       						= ''

      for i in range(0			,  len(__UpperCAmelCase   ) - self.break_key + 1			,  self.break_key   ):
       __UpperCamelCase       						= text[i : i + self.break_key]
       __UpperCamelCase       						= [self.replace_letters(__UpperCAmelCase   ) for char in batch]
       __UpperCamelCase       						= numpy.array([vec]   ).T
       __UpperCamelCase       						= self.modulus(decrypt_key.dot(__UpperCAmelCase   )   ).T.tolist()[0]
       __UpperCamelCase       						= ''.join(
           self.replace_digits(__UpperCAmelCase   ) for num in batch_decrypted   )
       decrypted += decrypted_batch

      return decrypted






def 							A		(       )   ->			None:
 __UpperCamelCase       						= int(input('Enter the order of the encryption key: '	)	)
 __UpperCamelCase       						= []

 print('Enter each row of the encryption key with space separated integers'	)
 for _ in range(snake_case	):
  __UpperCamelCase       						= [int(snake_case	) for x in input().split()]
  hill_matrix.append(snake_case	)

 __UpperCamelCase       						= HillCipher(numpy.array(snake_case	)	)

 print('Would you like to encrypt or decrypt some text? (1 or 2)'	)
 __UpperCamelCase       						= input('\n1. Encrypt\n2. Decrypt\n'	)
 if option == "1":
  __UpperCamelCase       						= input('What text would you like to encrypt?: '	)
  print('Your encrypted text is:'	)
  print(hc.encrypt(snake_case	)	)
 elif option == "2":
  __UpperCamelCase       						= input('What text would you like to decrypt?: '	)
  print('Your decrypted text is:'	)
  print(hc.decrypt(snake_case	)	)


if __name__ == "__main__":
      import doctest

      doctest.testmod()

      main()



