



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							:



		def __init__(     self     :Any   ,__lowercase     :Dict   ,__lowercase     :int=1_3   ,__lowercase     :List[Any]=2   ,__lowercase     :Tuple=2_4   ,__lowercase     :Optional[int]=1_6   ,__lowercase     :Optional[int]=True   ,__lowercase     :Any=True   ,__lowercase     :str=3_2   ,__lowercase     :List[Any]=5   ,__lowercase     :Any=4   ,__lowercase     :List[str]=3_7   ,__lowercase     :Any="gelu"   ,__lowercase     :Union[str, Any]=0.1   ,__lowercase     :str=0.1   ,__lowercase     :str=1_0   ,__lowercase     :List[Any]=0.02   ,__lowercase     :Optional[int]=None   ,__lowercase     :Optional[Any]=2   ,__lowercase     :List[Any]=2   ,):
						snake_case__	:      Dict     		=	parent
						snake_case__	:      Dict     		=	batch_size
						snake_case__	:      Tuple     		=	patch_size
						snake_case__	:      Optional[int]     		=	max_length
						snake_case__	:      Optional[int]     		=	num_mel_bins
						snake_case__	:      Dict     		=	is_training
						snake_case__	:      Optional[int]     		=	use_labels
						snake_case__	:      Union[str, Any]     		=	hidden_size
						snake_case__	:      Union[str, Any]     		=	num_hidden_layers
						snake_case__	:      Tuple     		=	num_attention_heads
						snake_case__	:      Any     		=	intermediate_size
						snake_case__	:      Optional[Any]     		=	hidden_act
						snake_case__	:      Tuple     		=	hidden_dropout_prob
						snake_case__	:      Tuple     		=	attention_probs_dropout_prob
						snake_case__	:      List[str]     		=	type_sequence_label_size
						snake_case__	:      Union[str, Any]     		=	initializer_range
						snake_case__	:      Union[str, Any]     		=	scope
						snake_case__	:      Optional[int]     		=	frequency_stride
						snake_case__	:      str     		=	time_stride

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



		def 	__lowerCamelCase			(     self     :Any  ):
						snake_case__	:      Any     		=	floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]  )

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

						snake_case__	:      Tuple     		=	self.get_config()

						return config, input_values, labels



		def 	__lowerCamelCase			(     self     :Any  ):
						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=__lowercase   ,initializer_range=self.initializer_range   ,frequency_stride=self.frequency_stride   ,time_stride=self.time_stride   ,)



		def 	__lowerCamelCase			(     self     :Dict   ,__lowercase     :int   ,__lowercase     :int   ,__lowercase     :List[Any]  ):
						snake_case__	:      List[str]     		=	ASTModel(config=__lowercase  )
						model.to(__lowercase  )
						model.eval()
						snake_case__	:      int     		=	model(__lowercase  )
						self.parent.assertEqual(result.last_hidden_state.shape   ,(self.batch_size, self.seq_length, self.hidden_size)  )






		def 	__lowerCamelCase			(     self     :Optional[int]  ):
						snake_case__	:      Dict     		=	self.prepare_config_and_inputs()
						(
						    (
						    snake_case__
						)		, (
						    snake_case__
						)		, (
						    snake_case__
						)		, 
						)	:      List[Any]     		=	config_and_inputs
						snake_case__	:      List[Any]     		=	{'''input_values''': input_values}
						return config, inputs_dict


@require_torch
class       a							(			__lowerCamelCase  ,							__lowerCamelCase  ,							unittest.TestCase				):
		__lowerCAmelCase	:    Dict											=					(
		    (
		        ASTModel,
		        ASTForAudioClassification,
		    )
		    if is_torch_available()
		    else ()
		)
		__lowerCAmelCase	:    Union[str, Any]											=					(
		    {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
		    if is_torch_available()
		    else {}
		)
		__lowerCAmelCase	:    List[Any]											=					False
		__lowerCAmelCase	:    Tuple											=					False
		__lowerCAmelCase	:    Union[str, Any]											=					False
		__lowerCAmelCase	:    Optional[Any]											=					False



		def 	__lowerCamelCase			(     self     :Optional[int]   ,__lowercase     :Dict   ,__lowercase     :Optional[Any]   ,__lowercase     :List[str]   ,__lowercase     :Dict   ,__lowercase     :int  ):
						if pipeline_test_casse_name == "AudioClassificationPipelineTests":
										return True

						return False



		def 	__lowerCamelCase			(     self     :List[Any]  ):
						snake_case__	:      Any     		=	ASTModelTester(self  )
						snake_case__	:      int     		=	ConfigTester(self   ,config_class=__lowercase   ,has_text_modality=__lowercase   ,hidden_size=3_7  )



		def 	__lowerCamelCase			(     self     :Dict  ):
						self.config_tester.run_common_tests()



		@unittest.skip(reason='''AST does not use inputs_embeds'''  )
		def 	__lowerCamelCase			(     self     :List[Any]  ):
						pass



		def 	__lowerCamelCase			(     self     :List[str]  ):
						snake_case__		, snake_case__	:      List[Any]     		=	self.model_tester.prepare_config_and_inputs_for_common()

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



		def 	__lowerCamelCase			(     self     :Optional[Any]  ):
						snake_case__		, snake_case__	:      Union[str, Any]     		=	self.model_tester.prepare_config_and_inputs_for_common()

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

										snake_case__	:      Dict     		=	['''input_values''']
										self.assertListEqual(arg_names[:1]   ,__lowercase  )



		def 	__lowerCamelCase			(     self     :Dict  ):
						snake_case__	:      int     		=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowercase  )






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



def 			_lowerCAmelCase       (					)   ->					Any:


				"""simple docstring"""

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

				snake_case__		, snake_case__	:      Union[str, Any]     		=	torchaudio.load(__lowerCAmelCase      )

				return audio, sampling_rate





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



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






		@slow
		def 	__lowerCamelCase			(     self     :Optional[int]  ):
						snake_case__	:      int     		=	self.default_feature_extractor
						snake_case__	:      Tuple     		=	ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''  ).to(__lowercase  )

						snake_case__	:      Dict     		=	self.default_feature_extractor
						snake_case__		, snake_case__	:      int     		=	prepare_audio()
						snake_case__	:      List[str]     		=	audio.squeeze().numpy()
						snake_case__	:      int     		=	feature_extractor(__lowercase   ,sampling_rate=__lowercase   ,return_tensors='''pt'''  ).to(__lowercase  )

						# forward pass
						with torch.no_grad():
										snake_case__	:      Dict     		=	model(**__lowercase  )

						# verify the logits
						snake_case__	:      Dict     		=	torch.Size((1, 5_2_7)  )
						self.assertEqual(outputs.logits.shape   ,__lowercase  )

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

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






# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import sys
import warnings
from os.path import abspath, dirname, join


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
A__								=						abspath(join(dirname(dirname(dirname(__file__))), '''src'''))
sys.path.insert(1, git_repo_path)


# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)



def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					str:


				"""simple docstring"""

				from transformers.testing_utils import pytest_addoption_shared

				pytest_addoption_shared(__lowerCAmelCase      )





def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					List[Any]:


				"""simple docstring"""

				from transformers.testing_utils import pytest_terminal_summary_main

				snake_case__	:      Dict     		=	terminalreporter.config.getoption('''--make-reports'''      )
				if make_reports:
								pytest_terminal_summary_main(__lowerCAmelCase  ,  id=__lowerCAmelCase      )

