


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       :




      """simple docstring"""







      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							:     str	=		parent
             _lowerCamelCase							:     List[str]	=		batch_size
             _lowerCamelCase							:     int	=		patch_size
             _lowerCamelCase							:     Optional[int]	=		max_length
             _lowerCamelCase							:     Optional[Any]	=		num_mel_bins
             _lowerCamelCase							:     Optional[int]	=		is_training
             _lowerCamelCase							:     Optional[Any]	=		use_labels
             _lowerCamelCase							:     Optional[int]	=		hidden_size
             _lowerCamelCase							:     Union[str, Any]	=		num_hidden_layers
             _lowerCamelCase							:     Optional[int]	=		num_attention_heads
             _lowerCamelCase							:     int	=		intermediate_size
             _lowerCamelCase							:     List[str]	=		hidden_act
             _lowerCamelCase							:     Dict	=		hidden_dropout_prob
             _lowerCamelCase							:     Optional[Any]	=		attention_probs_dropout_prob
             _lowerCamelCase							:     List[Any]	=		type_sequence_label_size
             _lowerCamelCase							:     str	=		initializer_range
             _lowerCamelCase							:     Dict	=		scope
             _lowerCamelCase							:     Optional[int]	=		frequency_stride
             _lowerCamelCase							:     Union[str, Any]	=		time_stride

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


      def 				__snake_case			(		self):



             """simple docstring"""





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

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

             _lowerCamelCase							:     Dict	=		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=lowerCAmelCase_      ,							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							:     Optional[Any]	=		ASTModel(config=lowerCAmelCase_)
             model.to(lowerCAmelCase_)
             model.eval()
             _lowerCamelCase							:     List[Any]	=		model(lowerCAmelCase_)
             self.parent.assertEqual(result.last_hidden_state.shape      ,							(self.batch_size, self.seq_length, self.hidden_size))



      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Union[str, Any]	=		self.prepare_config_and_inputs()
             (
                 (
                 _lowerCamelCase						
             ),  (
                 _lowerCamelCase						
             ),  (
                 _lowerCamelCase						
             ),  						
             )							:     str	=		config_and_inputs
             _lowerCamelCase							:     Union[str, Any]	=		{'''input_values''': input_values}
             return config, inputs_dict







@require_torch
class 			__A       (      __lowerCAmelCase ,__lowerCAmelCase ,unittest.TestCase  ):




      """simple docstring"""







      UpperCAmelCase__						=      (
          (
              ASTModel,
              ASTForAudioClassification,
          )
          if is_torch_available()
          else ()
      )
      UpperCAmelCase__						=      (
          {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
          if is_torch_available()
          else {}
      )
      UpperCAmelCase__						=      False
      UpperCAmelCase__						=      False
      UpperCAmelCase__						=      False
      UpperCAmelCase__						=      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							:     int	=		ConfigTester(self      ,							config_class=lowerCAmelCase_      ,							has_text_modality=lowerCAmelCase_      ,							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							:     int	=		self.model_tester.prepare_config_and_inputs_for_common()

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


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase,  _lowerCamelCase							:     Union[str, Any]	=		self.model_tester.prepare_config_and_inputs_for_common()

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

                    _lowerCamelCase							:     Any	=		['''input_values''']
                    self.assertListEqual(arg_names[:1]      ,							lowerCAmelCase_)


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     int	=		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowerCAmelCase_)



      @slow
      def 				__snake_case			(		self):



             """simple docstring"""





             for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _lowerCamelCase							:     Any	=		ASTModel.from_pretrained(lowerCAmelCase_)
                    self.assertIsNotNone(lowerCAmelCase_)




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

       _lowerCamelCase,  _lowerCamelCase							:     Dict	=		torchaudio.load(snake_case__      )

       return audio, sampling_rate







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




      """simple docstring"""







      @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							:     Optional[Any]	=		self.default_feature_extractor
             _lowerCamelCase							:     Tuple	=		ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''').to(lowerCAmelCase_)

             _lowerCamelCase							:     Optional[int]	=		self.default_feature_extractor
             _lowerCamelCase,  _lowerCamelCase							:     Tuple	=		prepare_audio()
             _lowerCamelCase							:     Optional[int]	=		audio.squeeze().numpy()
             _lowerCamelCase							:     Optional[Any]	=		feature_extractor(lowerCAmelCase_      ,							sampling_rate=lowerCAmelCase_      ,							return_tensors='''pt''').to(lowerCAmelCase_)

             # forward pass
             with torch.no_grad():
                    _lowerCamelCase							:     Any	=		model(**lowerCAmelCase_)

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

             _lowerCamelCase							:     Dict	=		torch.tensor([-0.8760, -7.0042, -8.6602]).to(lowerCAmelCase_)

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








import warnings

from .generation import TFGenerationMixin







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      warnings.warn(
          """Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will """
          """be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead.""" ,lowerCamelCase__ ,)

