


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




 def __init__(		self					,  _lowerCamelCase					,  _lowerCamelCase=13					,  _lowerCamelCase=2					,  _lowerCamelCase=24					,  _lowerCamelCase=16					,  _lowerCamelCase=True					,  _lowerCamelCase=True					,  _lowerCamelCase=32					,  _lowerCamelCase=5					,  _lowerCamelCase=4					,  _lowerCamelCase=37					,  _lowerCamelCase="gelu"					,  _lowerCamelCase=0.1					,  _lowerCamelCase=0.1					,  _lowerCamelCase=10					,  _lowerCamelCase=0.02					,  _lowerCamelCase=None					,  _lowerCamelCase=2					,  _lowerCamelCase=2					,  ):
       a						:Any 							=       parent
       a						:Optional[Any] 							=       batch_size
       a						:Any 							=       patch_size
       a						:Tuple 							=       max_length
       a						:Dict 							=       num_mel_bins
       a						:str 							=       is_training
       a						:Any 							=       use_labels
       a						:str 							=       hidden_size
       a						:int 							=       num_hidden_layers
       a						:List[str] 							=       num_attention_heads
       a						:str 							=       intermediate_size
       a						:Optional[Any] 							=       hidden_act
       a						:Dict 							=       hidden_dropout_prob
       a						:Dict 							=       attention_probs_dropout_prob
       a						:int 							=       type_sequence_label_size
       a						:List[Any] 							=       initializer_range
       a						:str 							=       scope
       a						:List[str] 							=       frequency_stride
       a						:Any 							=       time_stride

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




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:List[Any] 							=       floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]    )

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

       a						:Tuple 							=       self.get_config()

       return config, input_values, labels




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       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=_lowerCamelCase					,  initializer_range=self.initializer_range					,  frequency_stride=self.frequency_stride					,  time_stride=self.time_stride					,  )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase					,  _lowerCamelCase					,  _lowerCamelCase    ):
       a						:Dict 							=       ASTModel(config=_lowerCamelCase    )
       model.to(_lowerCamelCase    )
       model.eval()
       a						:Tuple 							=       model(_lowerCamelCase    )
       self.parent.assertEqual(result.last_hidden_state.shape					,  (self.batch_size, self.seq_length, self.hidden_size)    )




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Optional[Any] 							=       self.prepare_config_and_inputs()
       (
           (
           a
       )							,				(
           a
       )							,				(
           a
       )							,				
       )						:int 							=       config_and_inputs
       a						:Dict 							=       {'''input_values''': input_values}
       return config, inputs_dict







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




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase					,  _lowerCamelCase					,  _lowerCamelCase					,  _lowerCamelCase					,  _lowerCamelCase    ):
       if pipeline_test_casse_name == "AudioClassificationPipelineTests":
             return True

       return False




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Optional[Any] 							=       ASTModelTester(self    )
       a						:Optional[Any] 							=       ConfigTester(self					,  config_class=_lowerCamelCase					,  has_text_modality=_lowerCamelCase					,  hidden_size=37    )




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       self.config_tester.run_common_tests()




 @unittest.skip(reason='''AST does not use inputs_embeds'''    )
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       pass




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a							,				a						:int 							=       self.model_tester.prepare_config_and_inputs_for_common()

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




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a							,				a						:Tuple 							=       self.model_tester.prepare_config_and_inputs_for_common()

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

             a						:Dict 							=       ['''input_values''']
             self.assertListEqual(arg_names[:1]					,  _lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Dict 							=       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_lowerCamelCase    )




 @slow
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             a						:Tuple 							=       ASTModel.from_pretrained(_lowerCamelCase    )
             self.assertIsNotNone(_lowerCamelCase    )







def 				__lowerCamelCase						( ):




      """simple docstring"""





      a						:int 							=       hf_hub_download(
          repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' ,  filename='''sample_audio.flac''' ,  repo_type='''dataset'''						)

      a							,				a						:int 							=       torchaudio.load(UpperCAmelCase_						)

      return audio, sampling_rate







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




 @cached_property
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       return (
           ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''    )
           if is_torchaudio_available()
           else None
       )




 @slow
 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:Optional[int] 							=       self.default_feature_extractor
       a						:str 							=       ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''    ).to(_lowerCamelCase    )

       a						:List[Any] 							=       self.default_feature_extractor
       a							,				a						:List[Any] 							=       prepare_audio()
       a						:List[str] 							=       audio.squeeze().numpy()
       a						:Optional[Any] 							=       feature_extractor(_lowerCamelCase					,  sampling_rate=_lowerCamelCase					,  return_tensors='''pt'''    ).to(_lowerCamelCase    )

       # forward pass
       with torch.no_grad():
             a						:List[str] 							=       model(**_lowerCamelCase    )

       # verify the logits
       a						:Optional[int] 							=       torch.Size((1, 527)    )
       self.assertEqual(outputs.logits.shape					,  _lowerCamelCase    )

       a						:Optional[Any] 							=       torch.tensor([-0.8760, -7.0042, -8.6602]    ).to(_lowerCamelCase    )

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









snake_case				:    str       				=     '''
# Transformers installation
! pip install transformers datasets
# To install from source instead of the last release, comment the command above and uncomment the following one.
# ! pip install git+https://github.com/huggingface/transformers.git
'''

snake_case				:    List[Any]       				=     [{'''type''': '''code''', '''content''': INSTALL_CONTENT}]
snake_case				:    int       				=     {
    '''{processor_class}''': '''FakeProcessorClass''',
    '''{model_class}''': '''FakeModelClass''',
    '''{object_class}''': '''FakeObjectClass''',
}





