'''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 			__A :



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

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



    def    _lowercase		(self       :       List[str]					):
         UpperCAmelCase_			       =  floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]					)

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

         UpperCAmelCase_			       =  self.get_config()

         return config, input_values, labels



    def    _lowercase		(self       :       Optional[int]					):
         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    _lowercase		(self       :       str  ,     __a       :       Any  ,     __a       :       str  ,     __a       :       str					):
         UpperCAmelCase_			       =  ASTModel(config=__a					)
         model.to(__a					)
         model.eval()
         UpperCAmelCase_			       =  model(__a					)
         self.parent.assertEqual(result.last_hidden_state.shape  ,     (self.batch_size, self.seq_length, self.hidden_size)					)






    def    _lowercase		(self       :       Dict					):
         UpperCAmelCase_			       =  self.prepare_config_and_inputs()
         (
             (
             UpperCAmelCase_
         )       ,					(
             UpperCAmelCase_
         )       ,					(
             UpperCAmelCase_
         )       ,					
         )			       =  config_and_inputs
         UpperCAmelCase_			       =  {"input_values": input_values}
         return config, inputs_dict




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



    def    _lowercase		(self       :       Optional[Any]  ,     __a       :       str  ,     __a       :       List[Any]  ,     __a       :       Optional[Any]  ,     __a       :       str  ,     __a       :       str					):
         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
              return True

         return False



    def    _lowercase		(self       :       Optional[Any]					):
         UpperCAmelCase_			       =  ASTModelTester(self					)
         UpperCAmelCase_			       =  ConfigTester(self  ,     config_class=__a  ,     has_text_modality=__a  ,     hidden_size=37					)



    def    _lowercase		(self       :       List[str]					):
         self.config_tester.run_common_tests()



    @unittest.skip(reason="AST does not use inputs_embeds"					)
    def    _lowercase		(self       :       List[str]					):
         pass



    def    _lowercase		(self       :       Optional[Any]					):
         UpperCAmelCase_       ,					UpperCAmelCase_			       =  self.model_tester.prepare_config_and_inputs_for_common()

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



    def    _lowercase		(self       :       Dict					):
         UpperCAmelCase_       ,					UpperCAmelCase_			       =  self.model_tester.prepare_config_and_inputs_for_common()

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

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



    def    _lowercase		(self       :       Union[str, Any]					):
         UpperCAmelCase_			       =  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__a					)






    @slow
    def    _lowercase		(self       :       List[str]					):
         for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase_			       =  ASTModel.from_pretrained(__a					)
              self.assertIsNotNone(__a					)





def       lowerCAmelCase_							(   )       -> Optional[int]:


     '''simple docstring'''




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

     UpperCAmelCase_       ,					UpperCAmelCase_			       =  torchaudio.load(snake_case_     )

     return audio, sampling_rate






@require_torch
@require_torchaudio
class 			__A (					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]					):
         UpperCAmelCase_			       =  self.default_feature_extractor
         UpperCAmelCase_			       =  ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"					).to(__a					)

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

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

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

         UpperCAmelCase_			       =  torch.tensor([-0.87_60, -7.00_42, -8.66_02]					).to(__a					)

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










from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


__magic_name__  :  List[str]					=       {
    """configuration_m2m_100""": ["""M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP""", """M2M100Config""", """M2M100OnnxConfig"""],
    """tokenization_m2m_100""": ["""M2M100Tokenizer"""],
}


try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __magic_name__  :  Union[str, Any]					=       [
          """M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """M2M100ForConditionalGeneration""",
          """M2M100Model""",
          """M2M100PreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig
      from .tokenization_mam_aaa import MaMaaaTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_mam_aaa import (
                M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST,
                MaMaaaForConditionalGeneration,
                MaMaaaModel,
                MaMaaaPreTrainedModel,
            )


else:
      import sys

      __magic_name__  :  List[str]					=       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

