






"""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        lowercase__      :


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


			def      UpperCAmelCase__						(				self					:  Union[str, Any] ):
										lowerCamelCase_	:							List[Any]									=floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] )

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

										lowerCamelCase_	:							Optional[int]									=self.get_config()

										return config, input_values, labels


			def      UpperCAmelCase__						(				self					:  List[str] ):
										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=snake_case__       ,	initializer_range=self.initializer_range       ,	frequency_stride=self.frequency_stride       ,	time_stride=self.time_stride       ,	)


			def      UpperCAmelCase__						(				self					:  Optional[Any]       ,	snake_case__					:  Optional[Any]       ,	snake_case__					:  Optional[Any]       ,	snake_case__					:  Optional[Any] ):
										lowerCamelCase_	:							Tuple									=ASTModel(config=snake_case__ )
										model.to(snake_case__ )
										model.eval()
										lowerCamelCase_	:							Optional[int]									=model(snake_case__ )
										self.parent.assertEqual(result.last_hidden_state.shape       ,	(self.batch_size, self.seq_length, self.hidden_size) )


			def      UpperCAmelCase__						(				self					:  Tuple ):
										lowerCamelCase_	:							Optional[int]									=self.prepare_config_and_inputs()
										(
										    (
										    lowerCamelCase_
										)							,						(
										    lowerCamelCase_
										)							,						(
										    lowerCamelCase_
										)							,						
										)	:							List[Any]									=config_and_inputs
										lowerCamelCase_	:							Tuple									={"input_values": input_values}
										return config, inputs_dict







@require_torch
class        lowercase__      (							snake_case__,       snake_case__,       unittest.TestCase       ):
			_UpperCAmelCase		:str             =			(
			    (
			        ASTModel,
			        ASTForAudioClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			_UpperCAmelCase		:Union[str, Any]             =			(
			    {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
			    if is_torch_available()
			    else {}
			)
			_UpperCAmelCase		:Any             =			False
			_UpperCAmelCase		:Dict             =			False
			_UpperCAmelCase		:Any             =			False
			_UpperCAmelCase		:Union[str, Any]             =			False


			def      UpperCAmelCase__						(				self					:  Optional[Any]       ,	snake_case__					:  List[Any]       ,	snake_case__					:  List[str]       ,	snake_case__					:  str       ,	snake_case__					:  List[str]       ,	snake_case__					:  List[Any] ):
										if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																	return True

										return False


			def      UpperCAmelCase__						(				self					:  List[str] ):
										lowerCamelCase_	:							Optional[int]									=ASTModelTester(self )
										lowerCamelCase_	:							Tuple									=ConfigTester(self       ,	config_class=snake_case__       ,	has_text_modality=snake_case__       ,	hidden_size=37 )


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


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


			def      UpperCAmelCase__						(				self					:  Optional[int] ):
										lowerCamelCase_							,						lowerCamelCase_	:							Optional[Any]									=self.model_tester.prepare_config_and_inputs_for_common()

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


			def      UpperCAmelCase__						(				self					:  Any ):
										lowerCamelCase_							,						lowerCamelCase_	:							Optional[Any]									=self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowerCamelCase_	:							Dict									=["input_values"]
																	self.assertListEqual(arg_names[:1]       ,	snake_case__ )


			def      UpperCAmelCase__						(				self					:  List[str] ):
										lowerCamelCase_	:							str									=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*snake_case__ )


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


def 			_snake_case    (					)    ->     Optional[Any]:
							lowerCamelCase_	:							List[str]									=hf_hub_download(
							    repo_id="nielsr/audio-spectogram-transformer-checkpoint"    ,						filename="sample_audio.flac"    ,						repo_type="dataset"  )

							lowerCamelCase_							,						lowerCamelCase_	:							List[Any]									=torchaudio.load(lowerCamelCase__  )

							return audio, sampling_rate







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


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


			@slow
			def      UpperCAmelCase__						(				self					:  Dict ):
										lowerCamelCase_	:							Union[str, Any]									=self.default_feature_extractor
										lowerCamelCase_	:							Any									=ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(snake_case__ )

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

										# forward pass
										with torch.no_grad():
																	lowerCamelCase_	:							Optional[int]									=model(**snake_case__ )

										# verify the logits
										lowerCamelCase_	:							List[Any]									=torch.Size((1, 527) )
										self.assertEqual(outputs.logits.shape       ,	snake_case__ )

										lowerCamelCase_	:							Optional[Any]									=torch.tensor([-0.8_760, -7.0_042, -8.6_602] ).to(snake_case__ )

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











"""simple docstring"""



def 			_snake_case    (					lowerCamelCase__     :   int  )    ->     int:

							if not isinstance(lowerCamelCase__    ,						lowerCamelCase__  ):
														raise TypeError("only integers accepted as input"  )
							else:
														lowerCamelCase_	:							str									=str(abs(lowerCamelCase__  )  )
														lowerCamelCase_	:							Tuple									=[list(lowerCamelCase__  ) for char in range(len(lowerCamelCase__  )  )]
														for index in range(len(lowerCamelCase__  )  ):
																					num_transpositions[index].pop(lowerCamelCase__  )
														return max(
														    int("".join(list(lowerCamelCase__  )  )  ) for transposition in num_transpositions  )


if __name__ == "__main__":
						__import__('doctest').testmod()



