



import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


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

if is_torch_available():
				import torch






def  lowerCamelCase_	(      lowerCAmelCase__	:	str			,	lowerCAmelCase__	:	List[Any]=1.0			,	lowerCAmelCase__	:	Any=None			,	lowerCAmelCase__	:	List[str]=None				)       ->							Optional[Any]:

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



class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __init__(							self      :  Any						, __UpperCamelCase      :  Tuple						, __UpperCamelCase      :  str=7						, __UpperCamelCase      :  Any=400						, __UpperCamelCase      :  int=2_000						, __UpperCamelCase      :  Optional[Any]=1						, __UpperCamelCase      :  Tuple=0.0						, __UpperCamelCase      :  Dict=16_000						, __UpperCamelCase      :  Any=True						, __UpperCamelCase      :  List[str]=True						, )		->     Union[str, Any]:
											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      						=    feature_size
											A      						=    padding_value
											A      						=    sampling_rate
											A      						=    return_attention_mask
											A      						=    do_normalize


				def __UpperCamelCase						(							self      :  List[Any]       )		->     Optional[Any]:
											return {
											    "feature_size": self.feature_size,
											    "padding_value": self.padding_value,
											    "sampling_rate": self.sampling_rate,
											    "return_attention_mask": self.return_attention_mask,
											    "do_normalize": self.do_normalize,
											}


				def __UpperCamelCase						(							self      :  Dict						, __UpperCamelCase      :  Optional[int]=False						, __UpperCamelCase      :  List[Any]=False       )		->     str:



											def _flatten(__UpperCamelCase      :  Dict       ):
																		return list(itertools.chain(*UpperCamelCase_       )       )

											if equal_length:
																		A      						=    floats_list((self.batch_size, self.max_seq_length)       )
											else:
																		# make sure that inputs increase in size
																		A      						=    [
																		    _flatten(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(UpperCamelCase_       ) for x in speech_inputs]

											return speech_inputs





@require_torch
@require_torchaudio
class        lowerCAmelCase__					(  lowercase_ ,				unittest.TestCase       ):
				A_   :     Tuple								=     ASTFeatureExtractor


				def __UpperCamelCase						(							self      :  List[str]       )		->     Union[str, Any]:
											A      						=    ASTFeatureExtractionTester(self       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     str:
											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(UpperCamelCase_       ) for speech_input in speech_inputs]

											# Test not batched input
											A      						=    feat_extract(speech_inputs[0]						, return_tensors='np'       ).input_values
											A      						=    feat_extract(np_speech_inputs[0]						, return_tensors='np'       ).input_values
											self.assertTrue(np.allclose(UpperCamelCase_						, UpperCamelCase_						, atol=1e-3       )       )

											# Test batched
											A      						=    feat_extract(UpperCamelCase_						, padding=UpperCamelCase_						, return_tensors='np'       ).input_values
											A      						=    feat_extract(UpperCamelCase_						, padding=UpperCamelCase_						, return_tensors='np'       ).input_values
											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.
											A      						=    [floats_list((1, x)       )[0] for x in (800, 800, 800)]
											A      						=    np.asarray(UpperCamelCase_       )
											A      						=    feat_extract(UpperCamelCase_						, return_tensors='np'       ).input_values
											A      						=    feat_extract(UpperCamelCase_						, return_tensors='np'       ).input_values
											for enc_seq_a, enc_seq_a in zip(UpperCamelCase_						, UpperCamelCase_       ):
																		self.assertTrue(np.allclose(UpperCamelCase_						, UpperCamelCase_						, atol=1e-3       )       )


				@require_torch
				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											import torch

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

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


				def __UpperCamelCase						(							self      :  List[str]						, __UpperCamelCase      :  Union[str, Any]       )		->     Dict:
											from datasets import load_dataset

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

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


				@require_torch
				def __UpperCamelCase						(							self      :  Dict       )		->     Optional[int]:
											A      						=    torch.tensor(
											    [-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6,
											     -1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3,
											     -1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6,
											     -0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9]       )
											# fmt: on

											A      						=    self._load_datasamples(1       )
											A      						=    ASTFeatureExtractor()
											A      						=    feature_extractor(UpperCamelCase_						, return_tensors='pt'       ).input_values
											self.assertEquals(input_values.shape						, (1, 1_024, 128)       )
											self.assertTrue(torch.allclose(input_values[0, 0, :30]						, UpperCamelCase_						, atol=1e-4       )       )







def       _SCREAMING_SNAKE_CASE    (			__lowercase :      str     )    ->   str:





    """simple docstring"""

    __A       =						""""""
    for ch in key:
        if ch == " " or ch not in key_no_dups and ch.isalpha():
            key_no_dups += ch
    return key_no_dups



def       _SCREAMING_SNAKE_CASE    (			__lowercase :      str     )    ->   dict[str, str]:





    """simple docstring"""

    __A       =						[chr(i + 6_5     ) for i in range(2_6     )]
    # Remove duplicate characters from key
    __A       =						remove_duplicates(key.upper()     )
    __A       =						len(__lowercase     )
    # First fill cipher with key characters
    __A       =						{alphabet[i]: char for i, char in enumerate(__lowercase     )}
    # Then map remaining characters in alphabet to
    # the alphabet from the beginning
    for i in range(len(__lowercase     )      ,					2_6     ):
        __A       =						alphabet[i - offset]
        # Ensure we are not mapping letters to letters previously mapped
        while char in key:
            offset -= 1
            __A       =						alphabet[i - offset]
        __A       =						char
    return cipher_alphabet



def       _SCREAMING_SNAKE_CASE    (			__lowercase :      str      ,					__lowercase :      dict[str, str]     )    ->   str:





    """simple docstring"""

    return "".join(cipher_map.get(__lowercase      ,					__lowercase     ) for ch in message.upper()     )



def       _SCREAMING_SNAKE_CASE    (			__lowercase :      str      ,					__lowercase :      dict[str, str]     )    ->   str:





    """simple docstring"""

    __A       =						{v: k for k, v in cipher_map.items()}
    return "".join(rev_cipher_map.get(__lowercase      ,					__lowercase     ) for ch in message.upper()     )



def       _SCREAMING_SNAKE_CASE    (			)    ->   None:





    """simple docstring"""

    __A       =						input("""Enter message to encode or decode: """     ).strip()
    __A       =						input("""Enter keyword: """     ).strip()
    __A       =						input("""Encipher or decipher? E/D:"""     ).strip()[0].lower()
    try:
        __A       =						{"""e""": encipher, """d""": decipher}[option]
    except KeyError:
        raise KeyError("""invalid input option"""     )
    __A       =						create_cipher_map(__lowercase     )
    print(func(__lowercase      ,					__lowercase     )     )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  main()




