




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






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






       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         lowercase    :int      	=						floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]				)

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

         lowercase    :Optional[Any]      	=						self.get_config()

         return config, input_values, labels






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






       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):
         lowercase    :Optional[Any]      	=						self.prepare_config_and_inputs()
         (
             (
             lowercase    
         )	,    (
             lowercase    
         )	,    (
             lowercase    
         )	,        
         )    :Any      	=						config_and_inputs
         lowercase    :List[Any]      	=						{"input_values": input_values}
         return config, inputs_dict







@require_torch
class    __lowerCAmelCase       (							__UpperCAmelCase      , __UpperCAmelCase      , unittest.TestCase):
       _a 					=						(
           (
               ASTModel,
               ASTForAudioClassification,
           )
           if is_torch_available()
           else ()
       )
       _a 					=						(
           {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
           if is_torch_available()
           else {}
       )
       _a 					=						False
       _a 					=						False
       _a 					=						False
       _a 					=						False






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]       ,					_lowerCAmelCase:					List[str]       ,					_lowerCAmelCase:					int       ,					_lowerCAmelCase:					List[str]       ,					_lowerCAmelCase:					Optional[Any]       ,					_lowerCAmelCase:					Optional[int]				):







         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
           return True

         return False






       def 					SCREAMING_SNAKE_CASE    (   self:					Dict				):
         lowercase    :Optional[int]      	=						ASTModelTester(self				)
         lowercase    :Any      	=						ConfigTester(self       ,					config_class=lowerCAmelCase_       ,					has_text_modality=lowerCAmelCase_       ,					hidden_size=37				)






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         self.config_tester.run_common_tests()






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






       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]				):
         lowercase	,    lowercase    :List[Any]      	=						self.model_tester.prepare_config_and_inputs_for_common()

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






       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, Any]				):
         lowercase	,    lowercase    :List[str]      	=						self.model_tester.prepare_config_and_inputs_for_common()

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

           lowercase    :Optional[int]      	=						["input_values"]
           self.assertListEqual(arg_names[:1]       ,					lowerCAmelCase_				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         lowercase    :List[str]      	=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCAmelCase_				)






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]				):







         for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase    :List[str]      	=						ASTModel.from_pretrained(lowerCAmelCase_				)
           self.assertIsNotNone(lowerCAmelCase_				)







def       UpperCAmelCase__  (     ):
  lowercase    :Dict      	=						hf_hub_download(
      repo_id="nielsr/audio-spectogram-transformer-checkpoint",			filename="sample_audio.flac",			repo_type="dataset"   )

  lowercase	,    lowercase    :Optional[int]      	=						torchaudio.load(__lowerCAmelCase   )

  return audio, sampling_rate







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






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






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         lowercase    :Tuple      	=						self.default_feature_extractor
         lowercase    :Optional[Any]      	=						ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"				).to(lowerCAmelCase_				)

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

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

         # verify the logits
         lowercase    :Optional[Any]      	=						torch.Size((1, 5_27)				)
         self.assertEqual(outputs.logits.shape       ,					lowerCAmelCase_				)

         lowercase    :Dict      	=						torch.tensor([-0.87_60, -7.00_42, -8.66_02]				).to(lowerCAmelCase_				)

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










def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  if discount_rate < 0:
    raise ValueError("Discount rate cannot be negative"   )
  if not cash_flows:
    raise ValueError("Cash flows list cannot be empty"   )
  lowercase    :Dict      	=						sum(
      cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase   )   )
  return round(lowerCamelCase,			ndigits=2   )


if __name__ == "__main__":
     import doctest

     doctest.testmod()



