


"""simple docstring"""






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					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__=13					,				SCREAMING_SNAKE_CASE__=2					,				SCREAMING_SNAKE_CASE__=24					,				SCREAMING_SNAKE_CASE__=16					,				SCREAMING_SNAKE_CASE__=True					,				SCREAMING_SNAKE_CASE__=True					,				SCREAMING_SNAKE_CASE__=32					,				SCREAMING_SNAKE_CASE__=5					,				SCREAMING_SNAKE_CASE__=4					,				SCREAMING_SNAKE_CASE__=37					,				SCREAMING_SNAKE_CASE__="gelu"					,				SCREAMING_SNAKE_CASE__=0.1					,				SCREAMING_SNAKE_CASE__=0.1					,				SCREAMING_SNAKE_CASE__=10					,				SCREAMING_SNAKE_CASE__=0.0_2					,				SCREAMING_SNAKE_CASE__=None					,				SCREAMING_SNAKE_CASE__=2					,				SCREAMING_SNAKE_CASE__=2					,				)      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	parent
					_UpperCamelCase					:Dict					     =	batch_size
					_UpperCamelCase					:List[Any]					     =	patch_size
					_UpperCamelCase					:Tuple					     =	max_length
					_UpperCamelCase					:List[str]					     =	num_mel_bins
					_UpperCamelCase					:List[str]					     =	is_training
					_UpperCamelCase					:Tuple					     =	use_labels
					_UpperCamelCase					:List[str]					     =	hidden_size
					_UpperCamelCase					:Any					     =	num_hidden_layers
					_UpperCamelCase					:Dict					     =	num_attention_heads
					_UpperCamelCase					:Optional[int]					     =	intermediate_size
					_UpperCamelCase					:str					     =	hidden_act
					_UpperCamelCase					:str					     =	hidden_dropout_prob
					_UpperCamelCase					:str					     =	attention_probs_dropout_prob
					_UpperCamelCase					:Tuple					     =	type_sequence_label_size
					_UpperCamelCase					:List[Any]					     =	initializer_range
					_UpperCamelCase					:str					     =	scope
					_UpperCamelCase					:Dict					     =	frequency_stride
					_UpperCamelCase					:Optional[int]					     =	time_stride

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

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]   )

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

					_UpperCamelCase					:int					     =	self.get_config()

					return config, input_values, labels
		def   _UpperCamelCase( self   )      ->	List[str]:

					"""simple docstring"""



					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=SCREAMING_SNAKE_CASE__					,				initializer_range=self.initializer_range					,				frequency_stride=self.frequency_stride					,				time_stride=self.time_stride					,				)
		def   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )      ->	Optional[int]:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	ASTModel(config=SCREAMING_SNAKE_CASE__   )
					model.to(SCREAMING_SNAKE_CASE__   )
					model.eval()
					_UpperCamelCase					:Union[str, Any]					     =	model(SCREAMING_SNAKE_CASE__   )
					self.parent.assertEqual(result.last_hidden_state.shape					,				(self.batch_size, self.seq_length, self.hidden_size)   )





		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Optional[Any]					     =	self.prepare_config_and_inputs()
					(
					    (
					    _UpperCamelCase
					)     ,      (
					    _UpperCamelCase
					)     ,      (
					    _UpperCamelCase
					)     ,      
					)					:Any					     =	config_and_inputs
					_UpperCamelCase					:Union[str, Any]					     =	{'''input_values''': input_values}
					return config, inputs_dict






@require_torch
class      A(  lowerCamelCase__				,							lowerCamelCase__				,							unittest.TestCase		):

		"""simple docstring"""





		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   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )      ->	str:

					"""simple docstring"""



					if pipeline_test_casse_name == "AudioClassificationPipelineTests":
								return True

					return False
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	ASTModelTester(self   )
					_UpperCamelCase					:Dict					     =	ConfigTester(self					,				config_class=SCREAMING_SNAKE_CASE__					,				has_text_modality=SCREAMING_SNAKE_CASE__					,				hidden_size=37   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					self.config_tester.run_common_tests()
		@unittest.skip(reason='''AST does not use inputs_embeds'''   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					pass
		def   _UpperCamelCase( self   )      ->	List[str]:

					"""simple docstring"""



					_UpperCamelCase     ,      _UpperCamelCase					:Union[str, Any]					     =	self.model_tester.prepare_config_and_inputs_for_common()

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

					"""simple docstring"""



					_UpperCamelCase     ,      _UpperCamelCase					:str					     =	self.model_tester.prepare_config_and_inputs_for_common()

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

								_UpperCamelCase					:int					     =	['''input_values''']
								self.assertListEqual(arg_names[:1]					,				SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:List[Any]					     =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__   )





		@slow
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								_UpperCamelCase					:int					     =	ASTModel.from_pretrained(SCREAMING_SNAKE_CASE__   )
								self.assertIsNotNone(SCREAMING_SNAKE_CASE__   )





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

			_UpperCamelCase     ,      _UpperCamelCase					:int					     =	torchaudio.load(snake_case__		)

			return audio, sampling_rate






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

		"""simple docstring"""





		@cached_property
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					return (
					    ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''   )
					    if is_torchaudio_available()
					    else None
					)





		@slow
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	self.default_feature_extractor
					_UpperCamelCase					:Dict					     =	ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''   ).to(SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:Tuple					     =	self.default_feature_extractor
					_UpperCamelCase     ,      _UpperCamelCase					:Dict					     =	prepare_audio()
					_UpperCamelCase					:int					     =	audio.squeeze().numpy()
					_UpperCamelCase					:int					     =	feature_extractor(SCREAMING_SNAKE_CASE__					,				sampling_rate=SCREAMING_SNAKE_CASE__					,				return_tensors='''pt'''   ).to(SCREAMING_SNAKE_CASE__   )

					# forward pass
					with torch.no_grad():
								_UpperCamelCase					:List[str]					     =	model(**SCREAMING_SNAKE_CASE__   )

					# verify the logits
					_UpperCamelCase					:str					     =	torch.Size((1, 5_27)   )
					self.assertEqual(outputs.logits.shape					,				SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:int					     =	torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]   ).to(SCREAMING_SNAKE_CASE__   )

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





"""simple docstring"""






UpperCamelCase__				:Tuple			   =	frozenset(
    [
        """prompt""",
        """height""",
        """width""",
        """guidance_scale""",
        """negative_prompt""",
        """prompt_embeds""",
        """negative_prompt_embeds""",
        """cross_attention_kwargs""",
    ]
)

UpperCamelCase__				:List[str]			   =	frozenset(["""prompt""", """negative_prompt"""])

UpperCamelCase__				:Tuple			   =	frozenset([])

UpperCamelCase__				:Union[str, Any]			   =	frozenset(["""image"""])

UpperCamelCase__				:str			   =	frozenset(
    [
        """image""",
        """height""",
        """width""",
        """guidance_scale""",
    ]
)

UpperCamelCase__				:Any			   =	frozenset(["""image"""])

UpperCamelCase__				:Optional[int]			   =	frozenset(
    [
        """prompt""",
        """image""",
        """height""",
        """width""",
        """guidance_scale""",
        """negative_prompt""",
        """prompt_embeds""",
        """negative_prompt_embeds""",
    ]
)

UpperCamelCase__				:int			   =	frozenset(["""prompt""", """image""", """negative_prompt"""])

UpperCamelCase__				:Tuple			   =	frozenset(
    [
        # Text guided image variation with an image mask
        """prompt""",
        """image""",
        """mask_image""",
        """height""",
        """width""",
        """guidance_scale""",
        """negative_prompt""",
        """prompt_embeds""",
        """negative_prompt_embeds""",
    ]
)

UpperCamelCase__				:Any			   =	frozenset(["""prompt""", """image""", """mask_image""", """negative_prompt"""])

UpperCamelCase__				:Dict			   =	frozenset(
    [
        # image variation with an image mask
        """image""",
        """mask_image""",
        """height""",
        """width""",
        """guidance_scale""",
    ]
)

UpperCamelCase__				:Dict			   =	frozenset(["""image""", """mask_image"""])

UpperCamelCase__				:Tuple			   =	frozenset(
    [
        """example_image""",
        """image""",
        """mask_image""",
        """height""",
        """width""",
        """guidance_scale""",
    ]
)

UpperCamelCase__				:List[str]			   =	frozenset(["""example_image""", """image""", """mask_image"""])

UpperCamelCase__				:List[str]			   =	frozenset(["""class_labels"""])

UpperCamelCase__				:Union[str, Any]			   =	frozenset(["""class_labels"""])

UpperCamelCase__				:Any			   =	frozenset(["""batch_size"""])

UpperCamelCase__				:Optional[Any]			   =	frozenset([])

UpperCamelCase__				:Optional[Any]			   =	frozenset(["""batch_size"""])

UpperCamelCase__				:Optional[int]			   =	frozenset([])

UpperCamelCase__				:str			   =	frozenset(
    [
        """prompt""",
        """audio_length_in_s""",
        """guidance_scale""",
        """negative_prompt""",
        """prompt_embeds""",
        """negative_prompt_embeds""",
        """cross_attention_kwargs""",
    ]
)

UpperCamelCase__				:Union[str, Any]			   =	frozenset(["""prompt""", """negative_prompt"""])
UpperCamelCase__				:Tuple			   =	frozenset(["""input_tokens"""])

UpperCamelCase__				:int			   =	frozenset(["""input_tokens"""])

