


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


   '''simple docstring'''







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

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

        lowercase_       :Any     =       None
        if self.use_labels:
             lowercase_       :Tuple     =       ids_tensor([self.batch_size]   ,							self.type_sequence_label_size		)

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

        return config, input_values, labels
   def 		UpperCamelCase  (     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 		UpperCamelCase  (     self   ,							UpperCamelCase_   ,							UpperCamelCase_   ,							UpperCamelCase_		):
        lowercase_       :Optional[int]     =       ASTModel(config=__a		)
        model.to(__a		)
        model.eval()
        lowercase_       :Any     =       model(__a		)
        self.parent.assertEqual(result.last_hidden_state.shape   ,							(self.batch_size, self.seq_length, self.hidden_size)		)




   def 		UpperCamelCase  (     self		):
        lowercase_       :int     =       self.prepare_config_and_inputs()
        (
            (
            lowercase_						
        )    ,      (
            lowercase_						
        )    ,      (
            lowercase_						
        )    ,      						
        )       :Optional[Any]     =       config_and_inputs
        lowercase_       :int     =       {'''input_values''': input_values}
        return config, inputs_dict






@require_torch
class      UpperCamelCase					(		lowercase__						,      lowercase__						,      unittest.TestCase     ):


   '''simple docstring'''







   lowercase					:	Optional[int]									=(
       (
           ASTModel,
           ASTForAudioClassification,
       )
       if is_torch_available()
       else ()
   )
   lowercase					:	Any									=(
       {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
       if is_torch_available()
       else {}
   )
   lowercase					:	List[Any]									=False
   lowercase					:	List[Any]									=False
   lowercase					:	Dict									=False
   lowercase					:	int									=False
   def 		UpperCamelCase  (     self   ,							UpperCamelCase_   ,							UpperCamelCase_   ,							UpperCamelCase_   ,							UpperCamelCase_   ,							UpperCamelCase_		):
        if pipeline_test_casse_name == "AudioClassificationPipelineTests":
             return True

        return False
   def 		UpperCamelCase  (     self		):
        lowercase_       :Union[str, Any]     =       ASTModelTester(self		)
        lowercase_       :List[Any]     =       ConfigTester(self   ,							config_class=__a   ,							has_text_modality=__a   ,							hidden_size=37		)
   def 		UpperCamelCase  (     self		):
        self.config_tester.run_common_tests()
   @unittest.skip(reason='''AST does not use inputs_embeds'''		)
   def 		UpperCamelCase  (     self		):
        pass
   def 		UpperCamelCase  (     self		):
        lowercase_    ,      lowercase_       :str     =       self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             lowercase_       :Optional[int]     =       model_class(__a		)
             self.assertIsInstance(model.get_input_embeddings()   ,							(nn.Module)		)
             lowercase_       :Optional[int]     =       model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(__a   ,							nn.Linear		)		)
   def 		UpperCamelCase  (     self		):
        lowercase_    ,      lowercase_       :Tuple     =       self.model_tester.prepare_config_and_inputs_for_common()

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

             lowercase_       :Any     =       ['''input_values''']
             self.assertListEqual(arg_names[:1]   ,							__a		)
   def 		UpperCamelCase  (     self		):
        lowercase_       :Tuple     =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__a		)




   @slow
   def 		UpperCamelCase  (     self		):
        for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowercase_       :Tuple     =       ASTModel.from_pretrained(__a		)
             self.assertIsNotNone(__a		)




def     UpperCamelCase    (      )					->							List[str]:
     '''simple docstring'''





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

     lowercase_    ,      lowercase_       :Optional[Any]     =       torchaudio.load(__snake_case		)

     return audio, sampling_rate






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


   '''simple docstring'''







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




   @slow
   def 		UpperCamelCase  (     self		):
        lowercase_       :Union[str, Any]     =       self.default_feature_extractor
        lowercase_       :str     =       ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''		).to(__a		)

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

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

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

        lowercase_       :Optional[int]     =       torch.tensor([-0.8760, -7.0042, -8.6602]		).to(__a		)

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





def     UpperCamelCase    (      _a		)					->							int:
     '''simple docstring'''





     assert isinstance(_a       ,		_a		), f"The input value of [n={number}] is not an integer"

     if number == 1:
          return 2
     elif number < 1:
          lowercase_       :str     =       f"The input value of [n={number}] has to be > 0"
          raise ValueError(_a		)
     else:
          lowercase_       :List[str]     =       sylvester(number - 1		)
          lowercase_       :Union[str, Any]     =       num - 1
          lowercase_       :List[str]     =       num
          return lower * upper + 1


if __name__ == "__main__":
   print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")

