





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 					__snake_case	:


    '''simple docstring'''







    def __init__(       self   ,				A_   ,				A_=13   ,				A_=2   ,				A_=24   ,				A_=16   ,				A_=True   ,				A_=True   ,				A_=32   ,				A_=5   ,				A_=4   ,				A_=37   ,				A_="gelu"   ,				A_=0.1   ,				A_=0.1   ,				A_=10   ,				A_=0.02   ,				A_=None   ,				A_=2   ,				A_=2   ,				):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			parent
        SCREAMING_SNAKE_CASE__											=			batch_size
        SCREAMING_SNAKE_CASE__											=			patch_size
        SCREAMING_SNAKE_CASE__											=			max_length
        SCREAMING_SNAKE_CASE__											=			num_mel_bins
        SCREAMING_SNAKE_CASE__											=			is_training
        SCREAMING_SNAKE_CASE__											=			use_labels
        SCREAMING_SNAKE_CASE__											=			hidden_size
        SCREAMING_SNAKE_CASE__											=			num_hidden_layers
        SCREAMING_SNAKE_CASE__											=			num_attention_heads
        SCREAMING_SNAKE_CASE__											=			intermediate_size
        SCREAMING_SNAKE_CASE__											=			hidden_act
        SCREAMING_SNAKE_CASE__											=			hidden_dropout_prob
        SCREAMING_SNAKE_CASE__											=			attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE__											=			type_sequence_label_size
        SCREAMING_SNAKE_CASE__											=			initializer_range
        SCREAMING_SNAKE_CASE__											=			scope
        SCREAMING_SNAKE_CASE__											=			frequency_stride
        SCREAMING_SNAKE_CASE__											=			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__											=			(self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
        SCREAMING_SNAKE_CASE__											=			(self.max_length - self.patch_size) // self.time_stride + 1
        SCREAMING_SNAKE_CASE__											=			frequency_out_dimension * time_out_dimension
        SCREAMING_SNAKE_CASE__											=			num_patches + 2



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]     )

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

        SCREAMING_SNAKE_CASE__											=			self.get_config()

        return config, input_values, labels



    def  lowercase_					(       self     ):





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



    def  lowercase_					(       self   ,				A_   ,				A_   ,				A_     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			ASTModel(config=A_     )
        model.to(A_     )
        model.eval()
        SCREAMING_SNAKE_CASE__											=			model(A_     )
        self.parent.assertEqual(result.last_hidden_state.shape   ,				(self.batch_size, self.seq_length, self.hidden_size)     )




    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.prepare_config_and_inputs()
        (
            (
            SCREAMING_SNAKE_CASE__
        )				,		(
            SCREAMING_SNAKE_CASE__
        )				,		(
            SCREAMING_SNAKE_CASE__
        )				,		
        )											=			config_and_inputs
        SCREAMING_SNAKE_CASE__											=			{'''input_values''': input_values}
        return config, inputs_dict





@require_torch
class 					__snake_case	(  __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     unittest.TestCase    ):


    '''simple docstring'''







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



    def  lowercase_					(       self   ,				A_   ,				A_   ,				A_   ,				A_   ,				A_     ):





        '''simple docstring'''

        if pipeline_test_casse_name == "AudioClassificationPipelineTests":
            return True

        return False



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			ASTModelTester(self     )
        SCREAMING_SNAKE_CASE__											=			ConfigTester(self   ,				config_class=A_   ,				has_text_modality=A_   ,				hidden_size=37     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        self.config_tester.run_common_tests()



    @unittest.skip(reason='''AST does not use inputs_embeds'''     )
    def  lowercase_					(       self     ):





        '''simple docstring'''

        pass



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()

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



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()

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

            SCREAMING_SNAKE_CASE__											=			['''input_values''']
            self.assertListEqual(arg_names[:1]   ,				A_     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A_     )




    @slow
    def  lowercase_					(       self     ):





        '''simple docstring'''

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





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

    SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			torchaudio.load(lowerCAmelCase_	)

    return audio, sampling_rate



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


    '''simple docstring'''







    @cached_property
    def  lowercase_					(       self     ):





        '''simple docstring'''

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




    @slow
    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.default_feature_extractor
        SCREAMING_SNAKE_CASE__											=			ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''     ).to(A_     )

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

        # forward pass
        with torch.no_grad():
            SCREAMING_SNAKE_CASE__											=			model(**A_     )

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

        SCREAMING_SNAKE_CASE__											=			torch.tensor([-0.8760, -7.0042, -8.6602]     ).to(A_     )

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







'''simple docstring'''






from collections import defaultdict

from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst






def   __A    (				):
		lowerCAmelCase						,		lowerCAmelCase  :     List[Any]       						= 9, 1_4  # noqa: F841
		lowerCAmelCase  :     int       						= [
		    [0, 1, 4],
		    [0, 7, 8],
		    [1, 2, 8],
		    [7, 8, 7],
		    [7, 6, 1],
		    [2, 8, 2],
		    [8, 6, 6],
		    [2, 3, 7],
		    [2, 5, 4],
		    [6, 5, 2],
		    [3, 5, 1_4],
		    [3, 4, 9],
		    [5, 4, 1_0],
		    [1, 7, 1_1],
		]

		lowerCAmelCase  :     Optional[Any]       						= defaultdict(a_						)
		for nodea, nodea, cost in edges:
				adjancency[nodea].append([nodea, cost]						)
				adjancency[nodea].append([nodea, cost]						)

		lowerCAmelCase  :     int       						= mst(a_						)

		lowerCAmelCase  :     Tuple       						= [
		    [7, 6, 1],
		    [2, 8, 2],
		    [6, 5, 2],
		    [0, 1, 4],
		    [2, 5, 4],
		    [2, 3, 7],
		    [0, 7, 8],
		    [3, 4, 9],
		]

		for answer in expected:
				lowerCAmelCase  :     List[str]       						= tuple(answer[:2]						)
				lowerCAmelCase  :     int       						= tuple(edge[::-1]						)
				assert edge in result or reverse in result



