



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 						UpperCAmelCase_					:







							def __init__(     self,    __a,    __a=13,    __a=2,    __a=24,    __a=16,    __a=True,    __a=True,    __a=32,    __a=5,    __a=4,    __a=37,    __a="gelu",    __a=0.1,    __a=0.1,    __a=10,    __a=0.02,    __a=None,    __a=2,    __a=2,    ):

														'''simple docstring'''

														_lowerCAmelCase  :							List[str]				     =					parent
														_lowerCAmelCase  :							Any				     =					batch_size
														_lowerCAmelCase  :							Optional[Any]				     =					patch_size
														_lowerCAmelCase  :							int				     =					max_length
														_lowerCAmelCase  :							str				     =					num_mel_bins
														_lowerCAmelCase  :							Union[str, Any]				     =					is_training
														_lowerCAmelCase  :							List[str]				     =					use_labels
														_lowerCAmelCase  :							Optional[Any]				     =					hidden_size
														_lowerCAmelCase  :							int				     =					num_hidden_layers
														_lowerCAmelCase  :							Any				     =					num_attention_heads
														_lowerCAmelCase  :							List[Any]				     =					intermediate_size
														_lowerCAmelCase  :							str				     =					hidden_act
														_lowerCAmelCase  :							List[str]				     =					hidden_dropout_prob
														_lowerCAmelCase  :							Tuple				     =					attention_probs_dropout_prob
														_lowerCAmelCase  :							Optional[int]				     =					type_sequence_label_size
														_lowerCAmelCase  :							Optional[Any]				     =					initializer_range
														_lowerCAmelCase  :							List[Any]				     =					scope
														_lowerCAmelCase  :							Any				     =					frequency_stride
														_lowerCAmelCase  :							Optional[Any]				     =					time_stride

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







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Tuple				     =					floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])

														_lowerCAmelCase  :							Dict				     =					None
														if self.use_labels:
																					_lowerCAmelCase  :							List[Any]				     =					ids_tensor([self.batch_size],    self.type_sequence_label_size)

														_lowerCAmelCase  :							Any				     =					self.get_config()

														return config, input_values, labels







							def      snake_case__   (     self):

														'''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=__a,    initializer_range=self.initializer_range,    frequency_stride=self.frequency_stride,    time_stride=self.time_stride,    )







							def      snake_case__   (     self,    __a,    __a,    __a):

														'''simple docstring'''

														_lowerCAmelCase  :							List[Any]				     =					ASTModel(config=__a)
														model.to(__a)
														model.eval()
														_lowerCAmelCase  :							Union[str, Any]				     =					model(__a)
														self.parent.assertEqual(result.last_hidden_state.shape,    (self.batch_size, self.seq_length, self.hidden_size))







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Tuple				     =					self.prepare_config_and_inputs()
														(
														    (
														    _lowerCAmelCase
														)     ,					(
														    _lowerCAmelCase
														)     ,					(
														    _lowerCAmelCase
														)     ,					
														)  :							List[Any]				     =					config_and_inputs
														_lowerCAmelCase  :							Union[str, Any]				     =					{"input_values": input_values}
														return config, inputs_dict



@require_torch
class 						UpperCAmelCase_					( a     ,      a     ,      unittest.TestCase):
							lowerCamelCase__         =	(
							    (
							        ASTModel,
							        ASTForAudioClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							lowerCamelCase__         =	(
							    {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
							    if is_torch_available()
							    else {}
							)
							lowerCamelCase__         =	False
							lowerCamelCase__         =	False
							lowerCamelCase__         =	False
							lowerCamelCase__         =	False







							def      snake_case__   (     self,    __a,    __a,    __a,    __a,    __a):

														'''simple docstring'''

														if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																					return True

														return False







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							int				     =					ASTModelTester(self)
														_lowerCAmelCase  :							List[Any]				     =					ConfigTester(self,    config_class=__a,    has_text_modality=__a,    hidden_size=37)







							def      snake_case__   (     self):

														'''simple docstring'''

														self.config_tester.run_common_tests()







							@unittest.skip(reason="AST does not use inputs_embeds")
							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase     ,					_lowerCAmelCase  :							Dict				     =					self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					_lowerCAmelCase  :							Optional[Any]				     =					model_class(__a)
																					self.assertIsInstance(model.get_input_embeddings(),    (nn.Module))
																					_lowerCAmelCase  :							List[str]				     =					model.get_output_embeddings()
																					self.assertTrue(x is None or isinstance(__a,    nn.Linear))







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase     ,					_lowerCAmelCase  :							Any				     =					self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					_lowerCAmelCase  :							Union[str, Any]				     =					model_class(__a)
																					_lowerCAmelCase  :							Optional[int]				     =					inspect.signature(model.forward)
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					_lowerCAmelCase  :							Optional[Any]				     =					[*signature.parameters.keys()]

																					_lowerCAmelCase  :							int				     =					["input_values"]
																					self.assertListEqual(arg_names[:1],    __a)







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Any				     =					self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*__a)







							@slow
							def      snake_case__   (     self):

														'''simple docstring'''

														for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					_lowerCAmelCase  :							str				     =					ASTModel.from_pretrained(__a)
																					self.assertIsNotNone(__a)






def        A       (      ):





							'''simple docstring'''




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

							_lowerCAmelCase     ,					_lowerCAmelCase  :							Union[str, Any]				     =					torchaudio.load(_lowerCamelCase						)

							return audio, sampling_rate



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







							@cached_property
							def      snake_case__   (     self):

														'''simple docstring'''

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







							@slow
							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							List[Any]				     =					self.default_feature_extractor
														_lowerCAmelCase  :							Optional[Any]				     =					ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593").to(__a)

														_lowerCAmelCase  :							Any				     =					self.default_feature_extractor
														_lowerCAmelCase     ,					_lowerCAmelCase  :							Dict				     =					prepare_audio()
														_lowerCAmelCase  :							str				     =					audio.squeeze().numpy()
														_lowerCAmelCase  :							str				     =					feature_extractor(__a,    sampling_rate=__a,    return_tensors="pt").to(__a)

														# forward pass
														with torch.no_grad():
																					_lowerCAmelCase  :							Union[str, Any]				     =					model(**__a)

														# verify the logits
														_lowerCAmelCase  :							Dict				     =					torch.Size((1, 527))
														self.assertEqual(outputs.logits.shape,    __a)

														_lowerCAmelCase  :							List[Any]				     =					torch.tensor([-0.8_760, -7.0_042, -8.6_602]).to(__a)

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





import string






def        A       (      _lowerCamelCase						):





							'''simple docstring'''




							for key in range(len(string.ascii_uppercase						)						):
														_lowerCAmelCase  :							str				     =					""
														for symbol in message:
																					if symbol in string.ascii_uppercase:
																												_lowerCAmelCase  :							List[str]				     =					string.ascii_uppercase.find(_lowerCamelCase						)
																												_lowerCAmelCase  :							Dict				     =					num - key
																												if num < 0:
																																			_lowerCAmelCase  :							Dict				     =					num + len(string.ascii_uppercase						)
																												_lowerCAmelCase  :							Optional[Any]				     =					translated + string.ascii_uppercase[num]
																					else:
																												_lowerCAmelCase  :							int				     =					translated + symbol
														print(F"Decryption using Key #{key}: {translated}"						)






def        A       (      ):





							'''simple docstring'''




							_lowerCAmelCase  :							Tuple				     =					input("Encrypted message: "						)
							_lowerCAmelCase  :							Dict				     =					message.upper()
							decrypt(_lowerCamelCase						)


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						main()
