
"""simple docstring"""





from __future__ import annotations
def 							A_     (__a				,   __a = None				,   __a = None				,   __a = False				,   ):

					'''simple docstring'''





					A_				 =						cipher_alphabet or [chr(__a				) for i in range(97				,   123				)]

					# If the argument is None or the user provided an empty dictionary
					if not frequencies_dict:
										# Frequencies of letters in the english language (how much they show up)
										A_				 =						{
										    "a": 0.08497,
										    "b": 0.01492,
										    "c": 0.02202,
										    "d": 0.04253,
										    "e": 0.11162,
										    "f": 0.02228,
										    "g": 0.02015,
										    "h": 0.06094,
										    "i": 0.07546,
										    "j": 0.00153,
										    "k": 0.01292,
										    "l": 0.04025,
										    "m": 0.02406,
										    "n": 0.06749,
										    "o": 0.07507,
										    "p": 0.01929,
										    "q": 0.00095,
										    "r": 0.07587,
										    "s": 0.06327,
										    "t": 0.09356,
										    "u": 0.02758,
										    "v": 0.00978,
										    "w": 0.02560,
										    "x": 0.00150,
										    "y": 0.01994,
										    "z": 0.00077,
										}
					else:
										# Custom frequencies dictionary
										A_				 =						frequencies_dict

					if not case_sensitive:
										A_				 =						ciphertext.lower()

					# Chi squared statistic values
					A_				 =						{}

					# cycle through all of the shifts
					for shift in range(len(__a				)				):
										A_				 =						""

										# decrypt the message with the shift
										for letter in ciphertext:
															try:
																				# Try to index the letter in the alphabet
																				A_				 =						(alphabet_letters.index(letter.lower()				) - shift) % len(
																				    __a				)
																				decrypted_with_shift += (
																				    alphabet_letters[new_key].upper()
																				    if case_sensitive and letter.isupper()
																				    else alphabet_letters[new_key]
																				)
															except ValueError:
																				# Append the character if it isn't in the alphabet
																				decrypted_with_shift += letter

										A_				 =						0.0

										# Loop through each letter in the decoded message with the shift
										for letter in decrypted_with_shift:
															if case_sensitive:
																				A_				 =						letter.lower()
																				if letter in frequencies:
																									# Get the amount of times the letter occurs in the message
																									A_				 =						decrypted_with_shift.lower().count(__a				)

																									# Get the excepcted amount of times the letter should appear based
																									# on letter frequencies
																									A_				 =						frequencies[letter] * occurrences

																									# Complete the chi squared statistic formula
																									A_				 =						((occurrences - expected) ** 2) / expected

																									# Add the margin of error to the total chi squared statistic
																									chi_squared_statistic += chi_letter_value
															else:
																				if letter.lower() in frequencies:
																									# Get the amount of times the letter occurs in the message
																									A_				 =						decrypted_with_shift.count(__a				)

																									# Get the excepcted amount of times the letter should appear based
																									# on letter frequencies
																									A_				 =						frequencies[letter] * occurrences

																									# Complete the chi squared statistic formula
																									A_				 =						((occurrences - expected) ** 2) / expected

																									# Add the margin of error to the total chi squared statistic
																									chi_squared_statistic += chi_letter_value

        # Add the data to the chi_squared_statistic_values dictionary
										A_				 =						(
										    chi_squared_statistic,
										    decrypted_with_shift,
										)

					# Get the most likely cipher by finding the cipher with the smallest chi squared
					# statistic
					def chi_squared_statistic_values_sorting_key(__a				) -> tuple[float, str]:
										return chi_squared_statistic_values[key]

					A_				 =						min(
					    __a				,   key=__a				,   )

					# Get all the data from the most likely cipher (key, decoded message)
					(
					    (
					    A_
					) ,    (
					    A_
					) ,    
					)				 =						chi_squared_statistic_values[most_likely_cipher]

					# Return the data on the most likely shift
					return (
					    most_likely_cipher,
					    most_likely_cipher_chi_squared_value,
					    decoded_most_likely_cipher,
					)






"""simple docstring"""





import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import ASTForAudioClassification, ASTModel
		from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
		    AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
		)


if is_torchaudio_available():
		import torchaudio

		from transformers import ASTFeatureExtractor



class __lowerCAmelCase				:




			"""simple docstring"""







			def __init__(				self						:					Union[str, Any]       ,   _snake_case						:					Optional[int]       ,   _snake_case						:					Any=13       ,   _snake_case						:					Union[str, Any]=2       ,   _snake_case						:					Optional[int]=24       ,   _snake_case						:					Optional[Any]=16       ,   _snake_case						:					List[str]=True       ,   _snake_case						:					str=True       ,   _snake_case						:					List[Any]=32       ,   _snake_case						:					str=5       ,   _snake_case						:					int=4       ,   _snake_case						:					List[str]=37       ,   _snake_case						:					int="gelu"       ,   _snake_case						:					str=0.1       ,   _snake_case						:					Optional[int]=0.1       ,   _snake_case						:					Optional[int]=10       ,   _snake_case						:					int=0.0_2       ,   _snake_case						:					int=None       ,   _snake_case						:					Optional[Any]=2       ,   _snake_case						:					int=2       ,   )      -> Dict:







								"""simple docstring"""
								A_				 =						parent
								A_				 =						batch_size
								A_				 =						patch_size
								A_				 =						max_length
								A_				 =						num_mel_bins
								A_				 =						is_training
								A_				 =						use_labels
								A_				 =						hidden_size
								A_				 =						num_hidden_layers
								A_				 =						num_attention_heads
								A_				 =						intermediate_size
								A_				 =						hidden_act
								A_				 =						hidden_dropout_prob
								A_				 =						attention_probs_dropout_prob
								A_				 =						type_sequence_label_size
								A_				 =						initializer_range
								A_				 =						scope
								A_				 =						frequency_stride
								A_				 =						time_stride

								# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
								A_				 =						(self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
								A_				 =						(self.max_length - self.patch_size) // self.time_stride + 1
								A_				 =						frequency_out_dimension * time_out_dimension
								A_				 =						num_patches + 2




			def      lowerCamelCase__     (				self						:					Dict	)      -> int:







								"""simple docstring"""
								A_				 =						floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]	)

								A_				 =						None
								if self.use_labels:
													A_				 =						ids_tensor([self.batch_size]       ,   self.type_sequence_label_size	)

								A_				 =						self.get_config()

								return config, input_values, labels




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







								"""simple docstring"""
								return ASTConfig(
								    patch_size=self.patch_size       ,   max_length=self.max_length       ,   num_mel_bins=self.num_mel_bins       ,   hidden_size=self.hidden_size       ,   num_hidden_layers=self.num_hidden_layers       ,   num_attention_heads=self.num_attention_heads       ,   intermediate_size=self.intermediate_size       ,   hidden_act=self.hidden_act       ,   hidden_dropout_prob=self.hidden_dropout_prob       ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,   is_decoder=_snake_case       ,   initializer_range=self.initializer_range       ,   frequency_stride=self.frequency_stride       ,   time_stride=self.time_stride       ,   )




			def      lowerCamelCase__     (				self						:					int       ,   _snake_case						:					Dict       ,   _snake_case						:					Tuple       ,   _snake_case						:					Optional[int]	)      -> Union[str, Any]:







								"""simple docstring"""
								A_				 =						ASTModel(config=_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						model(_snake_case	)
								self.parent.assertEqual(result.last_hidden_state.shape       ,   (self.batch_size, self.seq_length, self.hidden_size)	)






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







								"""simple docstring"""
								A_				 =						self.prepare_config_and_inputs()
								(
								    (
								    A_
								) ,    (
								    A_
								) ,    (
								    A_
								) ,    
								)				 =						config_and_inputs
								A_				 =						{"input_values": input_values}
								return config, inputs_dict





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




			"""simple docstring"""







			snake_case	      =				(
			    (
			        ASTModel,
			        ASTForAudioClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			snake_case	      =				(
			    {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
			    if is_torch_available()
			    else {}
			)
			snake_case	      =				False
			snake_case	      =				False
			snake_case	      =				False
			snake_case	      =				False




			def      lowerCamelCase__     (				self						:					Any       ,   _snake_case						:					Tuple       ,   _snake_case						:					str       ,   _snake_case						:					List[str]       ,   _snake_case						:					int       ,   _snake_case						:					int	)      -> str:







								"""simple docstring"""
								if pipeline_test_casse_name == "AudioClassificationPipelineTests":
													return True

								return False




			def      lowerCamelCase__     (				self						:					str	)      -> str:







								"""simple docstring"""
								A_				 =						ASTModelTester(self	)
								A_				 =						ConfigTester(self       ,   config_class=_snake_case       ,   has_text_modality=_snake_case       ,   hidden_size=37	)




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







								"""simple docstring"""
								self.config_tester.run_common_tests()




			@unittest.skip(reason="AST does not use inputs_embeds"	)
			def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> Dict:







								"""simple docstring"""
								pass




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







								"""simple docstring"""
								A_ ,    A_				 =						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													A_				 =						model_class(_snake_case	)
													self.assertIsInstance(model.get_input_embeddings()       ,   (nn.Module)	)
													A_				 =						model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_snake_case       ,   nn.Linear	)	)




			def      lowerCamelCase__     (				self						:					Any	)      -> Tuple:







								"""simple docstring"""
								A_ ,    A_				 =						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													A_				 =						model_class(_snake_case	)
													A_				 =						inspect.signature(model.forward	)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													A_				 =						[*signature.parameters.keys()]

													A_				 =						["input_values"]
													self.assertListEqual(arg_names[:1]       ,   _snake_case	)




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







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case	)






			@slow
			def      lowerCamelCase__     (				self						:					List[Any]	)      -> Tuple:







								"""simple docstring"""
								for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													A_				 =						ASTModel.from_pretrained(_snake_case	)
													self.assertIsNotNone(_snake_case	)





def 							A_     ():

					'''simple docstring'''





					A_				 =						hf_hub_download(
					    repo_id="nielsr/audio-spectogram-transformer-checkpoint"				,   filename="sample_audio.flac"				,   repo_type="dataset"				)

					A_ ,    A_				 =						torchaudio.load(__a				)

					return audio, sampling_rate




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




			"""simple docstring"""







			@cached_property
			def      lowerCamelCase__     (				self						:					List[str]	)      -> int:







								"""simple docstring"""
								return (
								    ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"	)
								    if is_torchaudio_available()
								    else None
								)






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







								"""simple docstring"""
								A_				 =						self.default_feature_extractor
								A_				 =						ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"	).to(_snake_case	)

								A_				 =						self.default_feature_extractor
								A_ ,    A_				 =						prepare_audio()
								A_				 =						audio.squeeze().numpy()
								A_				 =						feature_extractor(_snake_case       ,   sampling_rate=_snake_case       ,   return_tensors="pt"	).to(_snake_case	)

								# forward pass
								with torch.no_grad():
													A_				 =						model(**_snake_case	)

								# verify the logits
								A_				 =						torch.Size((1, 527)	)
								self.assertEqual(outputs.logits.shape       ,   _snake_case	)

								A_				 =						torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]	).to(_snake_case	)

								self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,   _snake_case       ,   atol=1e-4	)	)




