


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			:  Optional[int]				,				lowerCamelCase__			:  List[str]				,				lowerCamelCase__			:  str=13				,				lowerCamelCase__			:  Optional[Any]=2				,				lowerCamelCase__			:  Any=24				,				lowerCamelCase__			:  Optional[Any]=16				,				lowerCamelCase__			:  int=True				,				lowerCamelCase__			:  List[str]=True				,				lowerCamelCase__			:  List[Any]=32				,				lowerCamelCase__			:  List[str]=5				,				lowerCamelCase__			:  Dict=4				,				lowerCamelCase__			:  Optional[Any]=37				,				lowerCamelCase__			:  Any="gelu"				,				lowerCamelCase__			:  Union[str, Any]=0.1				,				lowerCamelCase__			:  Optional[int]=0.1				,				lowerCamelCase__			:  str=10				,				lowerCamelCase__			:  Optional[Any]=0.02				,				lowerCamelCase__			:  str=None				,				lowerCamelCase__			:  List[str]=2				,				lowerCamelCase__			:  Optional[Any]=2				,				):
        a__	:  str     =   parent
        a__	:  Any     =   batch_size
        a__	:  Dict     =   patch_size
        a__	:  List[Any]     =   max_length
        a__	:  str     =   num_mel_bins
        a__	:  Optional[Any]     =   is_training
        a__	:  Optional[int]     =   use_labels
        a__	:  List[Any]     =   hidden_size
        a__	:  str     =   num_hidden_layers
        a__	:  Any     =   num_attention_heads
        a__	:  Union[str, Any]     =   intermediate_size
        a__	:  List[str]     =   hidden_act
        a__	:  str     =   hidden_dropout_prob
        a__	:  Tuple     =   attention_probs_dropout_prob
        a__	:  List[Any]     =   type_sequence_label_size
        a__	:  Any     =   initializer_range
        a__	:  str     =   scope
        a__	:  List[str]     =   frequency_stride
        a__	:  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)
        a__	:  List[Any]     =   (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
        a__	:  List[str]     =   (self.max_length - self.patch_size) // self.time_stride + 1
        a__	:  Tuple     =   frequency_out_dimension * time_out_dimension
        a__	:  List[str]     =   num_patches + 2

  def    _UpperCamelCase( self			:  List[str]       ):
        a__	:  Any     =   floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]       )

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

        a__	:  List[str]     =   self.get_config()

        return config, input_values, labels

  def    _UpperCamelCase( 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=lowerCamelCase__				,				initializer_range=self.initializer_range				,				frequency_stride=self.frequency_stride				,				time_stride=self.time_stride				,				)

  def    _UpperCamelCase( self			:  Union[str, Any]				,				lowerCamelCase__			:  Tuple				,				lowerCamelCase__			:  int				,				lowerCamelCase__			:  Optional[int]       ):
        a__	:  List[Any]     =   ASTModel(config=lowerCamelCase__       )
        model.to(lowerCamelCase__       )
        model.eval()
        a__	:  Dict     =   model(lowerCamelCase__       )
        self.parent.assertEqual(result.last_hidden_state.shape				,				(self.batch_size, self.seq_length, self.hidden_size)       )

  def    _UpperCamelCase( self			:  str       ):
        a__	:  Dict     =   self.prepare_config_and_inputs()
        (
            (
            a__
        ),	(
            a__
        ),	(
            a__
        ),	
        )	:  Optional[int]     =   config_and_inputs
        a__	:  List[Any]     =   {"input_values": input_values}
        return config, inputs_dict




@require_torch
class A__     ( A__				,		A__				,		unittest.TestCase  ):



  """simple docstring"""



  _lowercase									=		(
      (
          ASTModel,
          ASTForAudioClassification,
      )
      if is_torch_available()
      else ()
  )
  _lowercase									=		(
      {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
      if is_torch_available()
      else {}
  )
  _lowercase									=		False
  _lowercase									=		False
  _lowercase									=		False
  _lowercase									=		False

  def    _UpperCamelCase( self			:  Union[str, Any]				,				lowerCamelCase__			:  int				,				lowerCamelCase__			:  Any				,				lowerCamelCase__			:  Any				,				lowerCamelCase__			:  Any				,				lowerCamelCase__			:  Dict       ):
        if pipeline_test_casse_name == "AudioClassificationPipelineTests":
              return True

        return False

  def    _UpperCamelCase( self			:  str       ):
        a__	:  str     =   ASTModelTester(self       )
        a__	:  Any     =   ConfigTester(self				,				config_class=lowerCamelCase__				,				has_text_modality=lowerCamelCase__				,				hidden_size=37       )

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

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

  def    _UpperCamelCase( self			:  Optional[int]       ):
        a__,	a__	:  str     =   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__	:  Union[str, Any]     =   model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(lowerCamelCase__				,				nn.Linear       )       )

  def    _UpperCamelCase( self			:  Tuple       ):
        a__,	a__	:  List[Any]     =   self.model_tester.prepare_config_and_inputs_for_common()

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

              a__	:  Optional[Any]     =   ["input_values"]
              self.assertListEqual(arg_names[:1]				,				lowerCamelCase__       )

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        a__	:  Dict     =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase__       )

  @slow
  def    _UpperCamelCase( self			:  int       ):
        for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              a__	:  Union[str, Any]     =   ASTModel.from_pretrained(lowerCamelCase__       )
              self.assertIsNotNone(lowerCamelCase__       )




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

      a__,	a__	:  List[str]     =   torchaudio.load(__a      )

      return audio, sampling_rate



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



  """simple docstring"""



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

  @slow
  def    _UpperCamelCase( self			:  Optional[int]       ):
        a__	:  int     =   self.default_feature_extractor
        a__	:  Optional[Any]     =   ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"       ).to(lowerCamelCase__       )

        a__	:  Any     =   self.default_feature_extractor
        a__,	a__	:  Dict     =   prepare_audio()
        a__	:  str     =   audio.squeeze().numpy()
        a__	:  Any     =   feature_extractor(lowerCamelCase__				,				sampling_rate=lowerCamelCase__				,				return_tensors="pt"       ).to(lowerCamelCase__       )

        # forward pass
        with torch.no_grad():
              a__	:  Any     =   model(**lowerCamelCase__       )

        # verify the logits
        a__	:  Union[str, Any]     =   torch.Size((1, 527)       )
        self.assertEqual(outputs.logits.shape				,				lowerCamelCase__       )

        a__	:  List[str]     =   torch.tensor([-0.8760, -7.0042, -8.6602]       ).to(lowerCamelCase__       )

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




import baseaa


def 							__lowerCAmelCase     (							_UpperCamelCase		:	str						)		->				bytes:
 '''simple docstring'''


 return baseaa.aaaencode(string.encode('utf-8'						)						)


def 							__lowerCAmelCase     (							_UpperCamelCase		:	bytes						)		->				str:
 '''simple docstring'''


 return baseaa.aaadecode(_UpperCamelCase						).decode('utf-8'						)


if __name__ == "__main__":
      import doctest

      doctest.testmod()

