


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







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

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







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

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

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

           return config, input_values, labels







     def 							lowercase__       (						self :						Union[str, Any]      ):
           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=_lowercase   ,   initializer_range=self.initializer_range   ,   frequency_stride=self.frequency_stride   ,   time_stride=self.time_stride   ,   )







     def 							lowercase__       (						self :						Tuple   ,   _lowercase :						str   ,   _lowercase :						int   ,   _lowercase :						Tuple      ):
           SCREAMING_SNAKE_CASE__       :  Union[str, Any]						     =		ASTModel(config=_lowercase      )
           model.to(_lowercase      )
           model.eval()
           SCREAMING_SNAKE_CASE__       :  List[str]						     =		model(_lowercase      )
           self.parent.assertEqual(result.last_hidden_state.shape   ,   (self.batch_size, self.seq_length, self.hidden_size)      )







     def 							lowercase__       (						self :						int      ):
           SCREAMING_SNAKE_CASE__       :  str						     =		self.prepare_config_and_inputs()
           (
               (
               SCREAMING_SNAKE_CASE__
           )     ,       (
               SCREAMING_SNAKE_CASE__
           )     ,       (
               SCREAMING_SNAKE_CASE__
           )     ,       
           )       :  int						     =		config_and_inputs
           SCREAMING_SNAKE_CASE__       :  Dict						     =		{'''input_values''': input_values}
           return config, inputs_dict




@require_torch
class 							lowercase  (						_UpperCAmelCase    ,       _UpperCAmelCase    ,       unittest.TestCase			):
     lowerCamelCase			:			Optional[int]      = (
         (
             ASTModel,
             ASTForAudioClassification,
         )
         if is_torch_available()
         else ()
     )
     lowerCamelCase			:			Tuple      = (
         {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
         if is_torch_available()
         else {}
     )
     lowerCamelCase			:			str      = False
     lowerCamelCase			:			Union[str, Any]      = False
     lowerCamelCase			:			int      = False
     lowerCamelCase			:			List[str]      = False







     def 							lowercase__       (						self :						int   ,   _lowercase :						Dict   ,   _lowercase :						Optional[int]   ,   _lowercase :						int   ,   _lowercase :						Dict   ,   _lowercase :						int      ):
           if pipeline_test_casse_name == "AudioClassificationPipelineTests":
                 return True

           return False







     def 							lowercase__       (						self :						Any      ):
           SCREAMING_SNAKE_CASE__       :  int						     =		ASTModelTester(self      )
           SCREAMING_SNAKE_CASE__       :  Union[str, Any]						     =		ConfigTester(self   ,   config_class=_lowercase   ,   has_text_modality=_lowercase   ,   hidden_size=37      )







     def 							lowercase__       (						self :						Any      ):
           self.config_tester.run_common_tests()







     @unittest.skip(reason='''AST does not use inputs_embeds'''      )
     def 							lowercase__       (						self :						List[Any]      ):
           pass







     def 							lowercase__       (						self :						List[str]      ):
           SCREAMING_SNAKE_CASE__     ,       SCREAMING_SNAKE_CASE__       :  Optional[Any]						     =		self.model_tester.prepare_config_and_inputs_for_common()

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







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

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

                 SCREAMING_SNAKE_CASE__       :  Optional[int]						     =		['''input_values''']
                 self.assertListEqual(arg_names[:1]   ,   _lowercase      )







     def 							lowercase__       (						self :						List[str]      ):
           SCREAMING_SNAKE_CASE__       :  int						     =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_lowercase      )







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




def    a   (							)	-> Optional[int]:




      '''simple docstring'''

      SCREAMING_SNAKE_CASE__       :  List[Any]						     =		hf_hub_download(
          repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''      ,    filename='''sample_audio.flac'''      ,    repo_type='''dataset'''							)

      SCREAMING_SNAKE_CASE__     ,       SCREAMING_SNAKE_CASE__       :  List[Any]						     =		torchaudio.load(A__							)

      return audio, sampling_rate





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







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







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

           SCREAMING_SNAKE_CASE__       :  Optional[int]						     =		self.default_feature_extractor
           SCREAMING_SNAKE_CASE__     ,       SCREAMING_SNAKE_CASE__       :  Union[str, Any]						     =		prepare_audio()
           SCREAMING_SNAKE_CASE__       :  Union[str, Any]						     =		audio.squeeze().numpy()
           SCREAMING_SNAKE_CASE__       :  int						     =		feature_extractor(_lowercase   ,   sampling_rate=_lowercase   ,   return_tensors='''pt'''      ).to(_lowercase      )

           # forward pass
           with torch.no_grad():
                 SCREAMING_SNAKE_CASE__       :  Dict						     =		model(**_lowercase      )

           # verify the logits
           SCREAMING_SNAKE_CASE__       :  Optional[int]						     =		torch.Size((1, 5_27)      )
           self.assertEqual(outputs.logits.shape   ,   _lowercase      )

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

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









def 	__a     (      A__			:  float			,  A__			:  float       ):
    if mass < 0:
        raise ValueError("The mass of a body cannot be negative"       )
    return 0.5 * mass * abs(A__       ) * abs(A__       )


if __name__ == "__main__":
    import doctest

    doctest.testmod(verbose=True)