


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 ,   lowerCamelCase_ ,   lowerCamelCase_=13 ,   lowerCamelCase_=2 ,   lowerCamelCase_=24 ,   lowerCamelCase_=16 ,   lowerCamelCase_=True ,   lowerCamelCase_=True ,   lowerCamelCase_=32 ,   lowerCamelCase_=5 ,   lowerCamelCase_=4 ,   lowerCamelCase_=37 ,   lowerCamelCase_="gelu" ,   lowerCamelCase_=0.1 ,   lowerCamelCase_=0.1 ,   lowerCamelCase_=10 ,   lowerCamelCase_=0.02 ,   lowerCamelCase_=None ,   lowerCamelCase_=2 ,   lowerCamelCase_=2 ,   )	->							int:
														lowerCAmelCase__	       =     parent
														lowerCAmelCase__	       =     batch_size
														lowerCAmelCase__	       =     patch_size
														lowerCAmelCase__	       =     max_length
														lowerCAmelCase__	       =     num_mel_bins
														lowerCAmelCase__	       =     is_training
														lowerCAmelCase__	       =     use_labels
														lowerCAmelCase__	       =     hidden_size
														lowerCAmelCase__	       =     num_hidden_layers
														lowerCAmelCase__	       =     num_attention_heads
														lowerCAmelCase__	       =     intermediate_size
														lowerCAmelCase__	       =     hidden_act
														lowerCAmelCase__	       =     hidden_dropout_prob
														lowerCAmelCase__	       =     attention_probs_dropout_prob
														lowerCAmelCase__	       =     type_sequence_label_size
														lowerCAmelCase__	       =     initializer_range
														lowerCAmelCase__	       =     scope
														lowerCAmelCase__	       =     frequency_stride
														lowerCAmelCase__	       =     time_stride

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







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							List[str]:
														lowerCAmelCase__	       =     floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]       )

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

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







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ ,   lowerCamelCase_ ,   lowerCamelCase_       )	->							Union[str, Any]:
														lowerCAmelCase__	       =     ASTModel(config=__snake_case       )
														model.to(__snake_case       )
														model.eval()
														lowerCAmelCase__	       =     model(__snake_case       )
														self.parent.assertEqual(result.last_hidden_state.shape ,   (self.batch_size, self.seq_length, self.hidden_size)       )







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Tuple:
														lowerCAmelCase__	       =     self.prepare_config_and_inputs()
														(
														    lowerCAmelCase__     
														)	       =     config_and_inputs
														lowerCAmelCase__	       =     {'input_values': input_values}
														return config, inputs_dict




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





							'''simple docstring'''






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







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ ,   lowerCamelCase_ ,   lowerCamelCase_ ,   lowerCamelCase_ ,   lowerCamelCase_       )	->							List[str]:
														if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																					return True

														return False







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							List[Any]:
														lowerCAmelCase__	       =     ASTModelTester(self       )
														lowerCAmelCase__	       =     ConfigTester(self ,   config_class=__snake_case ,   has_text_modality=__snake_case ,   hidden_size=37       )







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Any:
														self.config_tester.run_common_tests()







							@unittest.skip(reason='''AST does not use inputs_embeds'''       )
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							str:
														pass







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Tuple:
														lowerCAmelCase__	       =     self.model_tester.prepare_config_and_inputs_for_common()

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







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							int:
														lowerCAmelCase__	       =     self.model_tester.prepare_config_and_inputs_for_common()

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

																					lowerCAmelCase__	       =     ['input_values']
																					self.assertListEqual(arg_names[:1] ,   __snake_case       )







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							List[str]:
														lowerCAmelCase__	       =     self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*__snake_case       )







							@slow
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Tuple:
														for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCAmelCase__	       =     ASTModel.from_pretrained(__snake_case       )
																					self.assertIsNotNone(__snake_case       )


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

							lowerCAmelCase__	       =     torchaudio.load(_A	)

							return audio, sampling_rate






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





							'''simple docstring'''






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







							@slow
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							int:
														lowerCAmelCase__	       =     self.default_feature_extractor
														lowerCAmelCase__	       =     ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''       ).to(__snake_case       )

														lowerCAmelCase__	       =     self.default_feature_extractor
														lowerCAmelCase__	       =     prepare_audio()
														lowerCAmelCase__	       =     audio.squeeze().numpy()
														lowerCAmelCase__	       =     feature_extractor(__snake_case ,   sampling_rate=__snake_case ,   return_tensors='''pt'''       ).to(__snake_case       )

														# forward pass
														with torch.no_grad():
																					lowerCAmelCase__	       =     model(**__snake_case       )

														# verify the logits
														lowerCAmelCase__	       =     torch.Size((1, 5_27)       )
														self.assertEqual(outputs.logits.shape ,   __snake_case       )

														lowerCAmelCase__	       =     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'''






import numpy as np

import datasets


__UpperCAmelCase       =							'''
Compute the Mahalanobis Distance

Mahalonobis distance is the distance between a point and a distribution.
And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.
It was introduced by Prof. P. C. Mahalanobis in 1936
and has been used in various statistical applications ever since
[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]
'''

__UpperCAmelCase       =							'''\
@article{de2000mahalanobis,
  title={The mahalanobis distance},
  author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},
  journal={Chemometrics and intelligent laboratory systems},
  volume={50},
  number={1},
  pages={1--18},
  year={2000},
  publisher={Elsevier}
}
'''

__UpperCAmelCase       =							'''
Args:
    X: List of datapoints to be compared with the `reference_distribution`.
    reference_distribution: List of datapoints from the reference distribution we want to compare to.
Returns:
    mahalanobis: The Mahalonobis distance for each datapoint in `X`.
Examples:

    >>> mahalanobis_metric = datasets.load_metric("mahalanobis")
    >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])
    >>> print(results)
    {\'mahalanobis\': array([0.5])}
'''




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,    _KWARGS_DESCRIPTION  )
class 		a__    (							datasets.Metric  ):





							'''simple docstring'''






							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Any:
														return datasets.MetricInfo(
														    description=_DESCRIPTION ,   citation=_CITATION ,   inputs_description=_KWARGS_DESCRIPTION ,   features=datasets.Features(
														        {
														            '''X''': datasets.Sequence(datasets.Value('''float''' ,   id='''sequence'''       ) ,   id='''X'''       ),
														        }       ) ,   )







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ ,   lowerCamelCase_       )	->							str:
														# convert to numpy arrays
														lowerCAmelCase__	       =     np.array(lowerCamelCase_       )
														lowerCAmelCase__	       =     np.array(lowerCamelCase_       )

														# Assert that arrays are 2D
														if len(X.shape       ) != 2:
																					raise ValueError('''Expected `X` to be a 2D vector'''       )
														if len(reference_distribution.shape       ) != 2:
																					raise ValueError('''Expected `reference_distribution` to be a 2D vector'''       )
														if reference_distribution.shape[0] < 2:
																					raise ValueError(
																					    '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension'''       )

														# Get mahalanobis distance for each prediction
														lowerCAmelCase__	       =     X - np.mean(lowerCamelCase_       )
														lowerCAmelCase__	       =     np.cov(reference_distribution.T       )
														try:
																					lowerCAmelCase__	       =     np.linalg.inv(lowerCamelCase_       )
														except np.linalg.LinAlgError:
																					lowerCAmelCase__	       =     np.linalg.pinv(lowerCamelCase_       )
														lowerCAmelCase__	       =     np.dot(lowerCamelCase_ ,   lowerCamelCase_       )
														lowerCAmelCase__	       =     np.dot(lowerCamelCase_ ,   X_minus_mu.T       ).diagonal()

														return {"mahalanobis": mahal_dist}