





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







		def __init__(    self ,						__snake_case ,						__snake_case=1_3 ,						__snake_case=2 ,						__snake_case=2_4 ,						__snake_case=1_6 ,						__snake_case=True ,						__snake_case=True ,						__snake_case=3_2 ,						__snake_case=5 ,						__snake_case=4 ,						__snake_case=3_7 ,						__snake_case="gelu" ,						__snake_case=0.1 ,						__snake_case=0.1 ,						__snake_case=1_0 ,						__snake_case=0.02 ,						__snake_case=None ,						__snake_case=2 ,						__snake_case=2 ,						)      ->      Any:


							'''simple docstring'''

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

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







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


							'''simple docstring'''

							_snake_case       :					List[Any]				       =   floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]				)

							_snake_case       :					Tuple				       =   None
							if self.use_labels:
												_snake_case       :					Dict				       =   ids_tensor([self.batch_size] ,						self.type_sequence_label_size				)

							_snake_case       :					Optional[Any]				       =   self.get_config()

							return config, input_values, labels







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


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







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      Optional[Any]:


							'''simple docstring'''

							_snake_case       :					Dict				       =   ASTModel(config=UpperCAmelCase_				)
							model.to(UpperCAmelCase_				)
							model.eval()
							_snake_case       :					List[str]				       =   model(UpperCAmelCase_				)
							self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.hidden_size)				)







		def        lowercase       (    self				)      ->      List[Any]:


							'''simple docstring'''

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






@require_torch
class        _a(    __UpperCAmelCase	,   __UpperCAmelCase	,   unittest.TestCase    ):
		lowerCamelCase__     :List[str]   				=		(
		    (
		        ASTModel,
		        ASTForAudioClassification,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCamelCase__     :Dict   				=		(
		    {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
		    if is_torch_available()
		    else {}
		)
		lowerCamelCase__     :str   				=		False
		lowerCamelCase__     :Union[str, Any]   				=		False
		lowerCamelCase__     :Optional[int]   				=		False
		lowerCamelCase__     :Any   				=		False







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      List[str]:


							'''simple docstring'''

							if pipeline_test_casse_name == "AudioClassificationPipelineTests":
												return True

							return False







		def        lowercase       (    self				)      ->      Any:


							'''simple docstring'''

							_snake_case       :					Union[str, Any]				       =   ASTModelTester(self				)
							_snake_case       :					List[str]				       =   ConfigTester(self ,						config_class=UpperCAmelCase_ ,						has_text_modality=UpperCAmelCase_ ,						hidden_size=3_7				)







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


							'''simple docstring'''

							self.config_tester.run_common_tests()







		@unittest.skip(reason="AST does not use inputs_embeds"				)
		def        lowercase       (    self				)      ->      Tuple:


							'''simple docstring'''

							pass







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


							'''simple docstring'''

							_snake_case       , _snake_case       :					List[str]				       =   self.model_tester.prepare_config_and_inputs_for_common()

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







		def        lowercase       (    self				)      ->      List[Any]:


							'''simple docstring'''

							_snake_case       , _snake_case       :					List[Any]				       =   self.model_tester.prepare_config_and_inputs_for_common()

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

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







		def        lowercase       (    self				)      ->      Any:


							'''simple docstring'''

							_snake_case       :					str				       =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase_				)







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


							'''simple docstring'''

							for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_snake_case       :					Optional[int]				       =   ASTModel.from_pretrained(UpperCAmelCase_				)
												self.assertIsNotNone(UpperCAmelCase_				)







def    A				(							):
					_snake_case       :					Optional[int]				       =   hf_hub_download(
					    repo_id="nielsr/audio-spectogram-transformer-checkpoint"  ,  filename="sample_audio.flac"  ,  repo_type="dataset"				)

					_snake_case       , _snake_case       :					Optional[int]				       =   torchaudio.load(_snake_case				)

					return audio, sampling_rate






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







		@cached_property
		def        lowercase       (    self				)      ->      Any:


							'''simple docstring'''

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







		@slow
		def        lowercase       (    self				)      ->      Tuple:


							'''simple docstring'''

							_snake_case       :					Dict				       =   self.default_feature_extractor
							_snake_case       :					Optional[Any]				       =   ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"				).to(UpperCAmelCase_				)

							_snake_case       :					Tuple				       =   self.default_feature_extractor
							_snake_case       , _snake_case       :					List[str]				       =   prepare_audio()
							_snake_case       :					int				       =   audio.squeeze().numpy()
							_snake_case       :					List[str]				       =   feature_extractor(UpperCAmelCase_ ,						sampling_rate=UpperCAmelCase_ ,						return_tensors="pt"				).to(UpperCAmelCase_				)

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

							# verify the logits
							_snake_case       :					Any				       =   torch.Size((1, 5_2_7)				)
							self.assertEqual(outputs.logits.shape ,						UpperCAmelCase_				)

							_snake_case       :					Optional[Any]				       =   torch.tensor([-0.87_60, -7.00_42, -8.66_02]				).to(UpperCAmelCase_				)

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






import numpy as np

__lowerCAmelCase :Dict     =    [
    ['a', 'b', 'c', 'd', 'e'],
    ['f', 'g', 'h', 'i', 'k'],
    ['l', 'm', 'n', 'o', 'p'],
    ['q', 'r', 's', 't', 'u'],
    ['v', 'w', 'x', 'y', 'z'],
]






class        _a:







		def __init__(    self				)      ->      None:


							'''simple docstring'''

							_snake_case       :					Optional[Any]				       =   np.array(__snake_case				)







		def        lowercase       (    self ,						__snake_case				)      ->      np.ndarray:


							'''simple docstring'''

							_snake_case       , _snake_case       :					List[Any]				       =   np.where(letter == self.SQUARE				)
							_snake_case       :					Any				       =   np.concatenate([indexa + 1, indexa + 1]				)
							return indexes







		def        lowercase       (    self ,						__snake_case ,						__snake_case				)      ->      str:


							'''simple docstring'''

							_snake_case       :					int				       =   self.SQUARE[indexa - 1, indexa - 1]
							return letter







		def        lowercase       (    self ,						__snake_case				)      ->      str:


							'''simple docstring'''

							_snake_case       :					Optional[Any]				       =   message.lower()
							_snake_case       :					List[Any]				       =   message.replace(" " ,						""				)
							_snake_case       :					Any				       =   message.replace("j" ,						"i"				)

							_snake_case       :					Tuple				       =   np.empty((2, len(__snake_case				))				)
							for letter_index in range(len(__snake_case				)				):
												_snake_case       :					Dict				       =   self.letter_to_numbers(message[letter_index]				)

												_snake_case       :					Tuple				       =   numbers[0]
												_snake_case       :					List[Any]				       =   numbers[1]

							_snake_case       :					Any				       =   first_step.reshape(2 * len(__snake_case				)				)
							_snake_case       :					Optional[Any]				       =   ""
							for numbers_index in range(len(__snake_case				)				):
												_snake_case       :					Optional[int]				       =   int(second_step[numbers_index * 2]				)
												_snake_case       :					List[str]				       =   int(second_step[(numbers_index * 2) + 1]				)
												_snake_case       :					Any				       =   self.numbers_to_letter(__snake_case ,						__snake_case				)
												_snake_case       :					Any				       =   encoded_message + letter

							return encoded_message







		def        lowercase       (    self ,						__snake_case				)      ->      str:


							'''simple docstring'''

							_snake_case       :					Union[str, Any]				       =   message.lower()
							message.replace(" " ,						""				)
							_snake_case       :					Tuple				       =   np.empty(2 * len(__snake_case				)				)
							for letter_index in range(len(__snake_case				)				):
												_snake_case       :					Union[str, Any]				       =   self.letter_to_numbers(message[letter_index]				)
												_snake_case       :					Tuple				       =   numbers[0]
												_snake_case       :					Any				       =   numbers[1]

							_snake_case       :					Optional[Any]				       =   first_step.reshape((2, len(__snake_case				))				)
							_snake_case       :					Union[str, Any]				       =   ""
							for numbers_index in range(len(__snake_case				)				):
												_snake_case       :					Dict				       =   int(second_step[0, numbers_index]				)
												_snake_case       :					Optional[Any]				       =   int(second_step[1, numbers_index]				)
												_snake_case       :					Union[str, Any]				       =   self.numbers_to_letter(__snake_case ,						__snake_case				)
												_snake_case       :					str				       =   decoded_message + letter

							return decoded_message