



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    :
						'''simple docstring'''


						def __init__(  self    :				int       ,	snake_case    :				Any       ,	snake_case    :				Union[str, Any]=13       ,	snake_case    :				str=2       ,	snake_case    :				str=24       ,	snake_case    :				int=16       ,	snake_case    :				List[str]=True       ,	snake_case    :				Union[str, Any]=True       ,	snake_case    :				str=32       ,	snake_case    :				Tuple=5       ,	snake_case    :				Optional[Any]=4       ,	snake_case    :				Dict=37       ,	snake_case    :				Any="gelu"       ,	snake_case    :				Optional[int]=0.1       ,	snake_case    :				Tuple=0.1       ,	snake_case    :				Optional[Any]=10       ,	snake_case    :				int=0.02       ,	snake_case    :				List[str]=None       ,	snake_case    :				Optional[int]=2       ,	snake_case    :				str=2       ,	):



											'''simple docstring'''


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

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







						def       lowerCamelCase_				(  self    :				List[str]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     List[Any]						=				floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]	)

											SCREAMING_SNAKE_CASE							:     Dict						=				None
											if self.use_labels:
																SCREAMING_SNAKE_CASE							:     List[Any]						=				ids_tensor([self.batch_size]       ,	self.type_sequence_label_size	)

											SCREAMING_SNAKE_CASE							:     Tuple						=				self.get_config()

											return config, input_values, labels







						def       lowerCamelCase_				(  self    :				Dict	):



											'''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=snake_case       ,	initializer_range=self.initializer_range       ,	frequency_stride=self.frequency_stride       ,	time_stride=self.time_stride       ,	)







						def       lowerCamelCase_				(  self    :				Union[str, Any]       ,	snake_case    :				Union[str, Any]       ,	snake_case    :				str       ,	snake_case    :				Union[str, Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				ASTModel(config=snake_case	)
											model.to(snake_case	)
											model.eval()
											SCREAMING_SNAKE_CASE							:     List[Any]						=				model(snake_case	)
											self.parent.assertEqual(result.last_hidden_state.shape       ,	(self.batch_size, self.seq_length, self.hidden_size)	)







						def       lowerCamelCase_				(  self    :				List[Any]	):



											'''simple docstring'''


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


@require_torch
class 						lowercase    (							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_      ,    unittest.TestCase):
						'''simple docstring'''


						UpperCAmelCase			:		Dict		=		(
						    (
						        ASTModel,
						        ASTForAudioClassification,
						    )
						    if is_torch_available()
						    else ()
						)
						UpperCAmelCase			:		List[str]		=		(
						    {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
						    if is_torch_available()
						    else {}
						)
						UpperCAmelCase			:		str		=		False
						UpperCAmelCase			:		Union[str, Any]		=		False
						UpperCAmelCase			:		Optional[int]		=		False
						UpperCAmelCase			:		str		=		False







						def       lowerCamelCase_				(  self    :				Dict       ,	snake_case    :				Union[str, Any]       ,	snake_case    :				Any       ,	snake_case    :				str       ,	snake_case    :				int       ,	snake_case    :				Optional[Any]	):



											'''simple docstring'''


											if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																return True

											return False







						def       lowerCamelCase_				(  self    :				Optional[Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     int						=				ASTModelTester(self	)
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				ConfigTester(self       ,	config_class=snake_case       ,	has_text_modality=snake_case       ,	hidden_size=37	)







						def       lowerCamelCase_				(  self    :				Optional[int]	):



											'''simple docstring'''


											self.config_tester.run_common_tests()







						@unittest.skip(reason='AST does not use inputs_embeds'	)
						def       lowerCamelCase_				(  self    :				Union[str, Any]	):



											'''simple docstring'''


											pass







						def       lowerCamelCase_				(  self    :				str	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE					,  SCREAMING_SNAKE_CASE							:     Optional[Any]						=				self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																SCREAMING_SNAKE_CASE							:     Dict						=				model_class(snake_case	)
																self.assertIsInstance(model.get_input_embeddings()       ,	(nn.Module)	)
																SCREAMING_SNAKE_CASE							:     Tuple						=				model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(snake_case       ,	nn.Linear	)	)







						def       lowerCamelCase_				(  self    :				Optional[Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE					,  SCREAMING_SNAKE_CASE							:     List[str]						=				self.model_tester.prepare_config_and_inputs_for_common()

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

																SCREAMING_SNAKE_CASE							:     List[Any]						=				['input_values']
																self.assertListEqual(arg_names[:1]       ,	snake_case	)







						def       lowerCamelCase_				(  self    :				str	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Optional[int]						=				self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*snake_case	)







						@slow
						def       lowerCamelCase_				(  self    :				Dict	):



											'''simple docstring'''


											for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																SCREAMING_SNAKE_CASE							:     str						=				ASTModel.from_pretrained(snake_case	)
																self.assertIsNotNone(snake_case	)


def        __a			(   )     ->     Dict:
					SCREAMING_SNAKE_CASE							:     Any						=				hf_hub_download(
					    repo_id='nielsr/audio-spectogram-transformer-checkpoint'      ,	filename='sample_audio.flac'      ,	repo_type='dataset'   )

					SCREAMING_SNAKE_CASE					,  SCREAMING_SNAKE_CASE							:     int						=				torchaudio.load(__lowerCAmelCase   )

					return audio, sampling_rate



@require_torch
@require_torchaudio
class 						lowercase    (							unittest.TestCase):
						'''simple docstring'''


						@cached_property
						def       lowerCamelCase_				(  self    :				Tuple	):



											'''simple docstring'''


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







						@slow
						def       lowerCamelCase_				(  self    :				Tuple	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     str						=				self.default_feature_extractor
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'	).to(snake_case	)

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

											# forward pass
											with torch.no_grad():
																SCREAMING_SNAKE_CASE							:     Optional[Any]						=				model(**snake_case	)

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

											SCREAMING_SNAKE_CASE							:     List[Any]						=				torch.tensor([-0.8760, -7.0042, -8.6602]	).to(snake_case	)

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




def        __a			(   __lowerCAmelCase   )     ->     list[list[float]]:
					SCREAMING_SNAKE_CASE							:     list[list[float]]						=				[]
					for data in source_data:
										for i, el in enumerate(__lowerCAmelCase   ):
															if len(__lowerCAmelCase   ) < i + 1:
																				data_lists.append([]   )
															data_lists[i].append(float(__lowerCAmelCase   )   )
					return data_lists

def        __a			(   __lowerCAmelCase      ,	__lowerCAmelCase   )     ->     list[list[float]]:
					SCREAMING_SNAKE_CASE							:     list[list[float]]						=				[]
					for dlist, weight in zip(__lowerCAmelCase      ,	__lowerCAmelCase   ):
										SCREAMING_SNAKE_CASE							:     str						=				min(__lowerCAmelCase   )
										SCREAMING_SNAKE_CASE							:     int						=				max(__lowerCAmelCase   )

										SCREAMING_SNAKE_CASE							:     list[float]						=				[]
										# for weight 0 score is 1 - actual score
										if weight == 0:
															for item in dlist:
																				try:
																									score.append(1 - ((item - mind) / (maxd - mind))   )
																				except ZeroDivisionError:
																									score.append(1   )

										elif weight == 1:
															for item in dlist:
																				try:
																									score.append((item - mind) / (maxd - mind)   )
																				except ZeroDivisionError:
																									score.append(0   )

        # weight not 0 or 1
										else:
															SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				F'''Invalid weight of {weight:f} provided'''
															raise ValueError(__lowerCAmelCase   )

										score_lists.append(__lowerCAmelCase   )

					return score_lists

def        __a			(   __lowerCAmelCase   )     ->     list[float]:
					SCREAMING_SNAKE_CASE							:     list[float]						=				[0 for i in range(len(score_lists[0]   )   )]

					for slist in score_lists:
										for j, ele in enumerate(__lowerCAmelCase   ):
															SCREAMING_SNAKE_CASE							:     str						=				final_scores[j] + ele

					return final_scores



def        __a			(   __lowerCAmelCase      ,	__lowerCAmelCase   )     ->     list[list[float]]:
					SCREAMING_SNAKE_CASE							:     Tuple						=				get_data(__lowerCAmelCase   )
					SCREAMING_SNAKE_CASE							:     List[str]						=				calculate_each_score(__lowerCAmelCase      ,	__lowerCAmelCase   )
					SCREAMING_SNAKE_CASE							:     str						=				generate_final_scores(__lowerCAmelCase   )

					# append scores to source data
					for i, ele in enumerate(__lowerCAmelCase   ):
										source_data[i].append(__lowerCAmelCase   )

					return source_data