


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


     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.0_2							,					A_=None							,					A_=2							,					A_=2							,					):
       _UpperCAmelCase		:							Optional[int]							=     parent
       _UpperCAmelCase		:							List[Any]							=     batch_size
       _UpperCAmelCase		:							Tuple							=     patch_size
       _UpperCAmelCase		:							Union[str, Any]							=     max_length
       _UpperCAmelCase		:							List[str]							=     num_mel_bins
       _UpperCAmelCase		:							Tuple							=     is_training
       _UpperCAmelCase		:							List[Any]							=     use_labels
       _UpperCAmelCase		:							Optional[Any]							=     hidden_size
       _UpperCAmelCase		:							Dict							=     num_hidden_layers
       _UpperCAmelCase		:							Optional[Any]							=     num_attention_heads
       _UpperCAmelCase		:							Union[str, Any]							=     intermediate_size
       _UpperCAmelCase		:							Union[str, Any]							=     hidden_act
       _UpperCAmelCase		:							int							=     hidden_dropout_prob
       _UpperCAmelCase		:							Union[str, Any]							=     attention_probs_dropout_prob
       _UpperCAmelCase		:							List[Any]							=     type_sequence_label_size
       _UpperCAmelCase		:							Union[str, Any]							=     initializer_range
       _UpperCAmelCase		:							List[str]							=     scope
       _UpperCAmelCase		:							Dict							=     frequency_stride
       _UpperCAmelCase		:							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)
       _UpperCAmelCase		:							Dict							=     (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
       _UpperCAmelCase		:							Union[str, Any]							=     (self.max_length - self.patch_size) // self.time_stride + 1
       _UpperCAmelCase		:							Dict							=     frequency_out_dimension * time_out_dimension
       _UpperCAmelCase		:							Optional[int]							=     num_patches + 2


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

       _UpperCAmelCase		:							int							=     None
       if self.use_labels:
         _UpperCAmelCase		:							str							=     ids_tensor([self.batch_size]							,					self.type_sequence_label_size    )

       _UpperCAmelCase		:							Tuple							=     self.get_config()

       return config, input_values, labels


     def        __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=A_							,					initializer_range=self.initializer_range							,					frequency_stride=self.frequency_stride							,					time_stride=self.time_stride							,					)


     def        __snake_case(  self							,					A_							,					A_							,					A_    ):
       _UpperCAmelCase		:							Union[str, Any]							=     ASTModel(config=A_    )
       model.to(A_    )
       model.eval()
       _UpperCAmelCase		:							Optional[int]							=     model(A_    )
       self.parent.assertEqual(result.last_hidden_state.shape							,					(self.batch_size, self.seq_length, self.hidden_size)    )




     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[Any]							=     self.prepare_config_and_inputs()
       (
           (
           _UpperCAmelCase
       ),(
           _UpperCAmelCase
       ),(
           _UpperCAmelCase
       ),
       )		:							Dict							=     config_and_inputs
       _UpperCAmelCase		:							Optional[Any]							=     {"""input_values""": input_values}
       return config, inputs_dict


@require_torch
class 		_SCREAMING_SNAKE_CASE     (						A							,	A							,	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        __snake_case(  self							,					A_							,					A_							,					A_							,					A_							,					A_    ):
       if pipeline_test_casse_name == "AudioClassificationPipelineTests":
         return True

       return False


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[Any]							=     ASTModelTester(self    )
       _UpperCAmelCase		:							Union[str, Any]							=     ConfigTester(self							,					config_class=A_							,					has_text_modality=A_							,					hidden_size=37    )


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


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


     def        __snake_case(  self    ):
       _UpperCAmelCase,_UpperCAmelCase		:							Tuple							=     self.model_tester.prepare_config_and_inputs_for_common()

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


     def        __snake_case(  self    ):
       _UpperCAmelCase,_UpperCAmelCase		:							str							=     self.model_tester.prepare_config_and_inputs_for_common()

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

         _UpperCAmelCase		:							Tuple							=     ["""input_values"""]
         self.assertListEqual(arg_names[:1]							,					A_    )


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Any							=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_    )




     @slow
     def        __snake_case(  self    ):
       for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _UpperCAmelCase		:							List[str]							=     ASTModel.from_pretrained(A_    )
         self.assertIsNotNone(A_    )




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

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

  return audio, sampling_rate





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


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




     @slow
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							Union[str, Any]							=     self.default_feature_extractor
       _UpperCAmelCase		:							Optional[int]							=     ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""    ).to(A_    )

       _UpperCAmelCase		:							int							=     self.default_feature_extractor
       _UpperCAmelCase,_UpperCAmelCase		:							Union[str, Any]							=     prepare_audio()
       _UpperCAmelCase		:							Tuple							=     audio.squeeze().numpy()
       _UpperCAmelCase		:							Any							=     feature_extractor(A_							,					sampling_rate=A_							,					return_tensors="""pt"""    ).to(A_    )

       # forward pass
       with torch.no_grad():
         _UpperCAmelCase		:							Any							=     model(**A_    )

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

       _UpperCAmelCase		:							List[Any]							=     torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]    ).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_torch_available


SCREAMING_SNAKE_CASE__					:     Optional[Any]       =     {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 SCREAMING_SNAKE_CASE__					:     List[str]       =     [
     'SEW_PRETRAINED_MODEL_ARCHIVE_LIST',
     'SEWForCTC',
     'SEWForSequenceClassification',
     'SEWModel',
     'SEWPreTrainedModel',
 ]

if TYPE_CHECKING:
 from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_sew import (
      SEW_PRETRAINED_MODEL_ARCHIVE_LIST,
      SEWForCTC,
      SEWForSequenceClassification,
      SEWModel,
      SEWPreTrainedModel,
  )


else:
 import sys

 SCREAMING_SNAKE_CASE__					:     Tuple       =     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)





