'''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 					UpperCAmelCase			:




    '''simple docstring'''







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






    def    _UpperCamelCase     (							self			)				->			int:
         SCREAMING_SNAKE_CASE       :      int     						=							floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]			)

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

         SCREAMING_SNAKE_CASE       :      int     						=							self.get_config()

         return config, input_values, labels






    def    _UpperCamelCase     (							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=_UpperCamelCase     ,				initializer_range=self.initializer_range     ,				frequency_stride=self.frequency_stride     ,				time_stride=self.time_stride     ,				)






    def    _UpperCamelCase     (							self     ,				lowercase__     ,				lowercase__     ,				lowercase__			)				->			Optional[Any]:
         SCREAMING_SNAKE_CASE       :      int     						=							ASTModel(config=_UpperCamelCase			)
         model.to(_UpperCamelCase			)
         model.eval()
         SCREAMING_SNAKE_CASE       :      str     						=							model(_UpperCamelCase			)
         self.parent.assertEqual(result.last_hidden_state.shape     ,				(self.batch_size, self.seq_length, self.hidden_size)			)






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






@require_torch
class 					UpperCAmelCase			(							_SCREAMING_SNAKE_CASE ,     _SCREAMING_SNAKE_CASE ,     unittest.TestCase			):




    '''simple docstring'''







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






    def    _UpperCamelCase     (							self     ,				lowercase__     ,				lowercase__     ,				lowercase__     ,				lowercase__     ,				lowercase__			)				->			Union[str, Any]:
         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
              return True

         return False






    def    _UpperCamelCase     (							self			)				->			List[str]:
         SCREAMING_SNAKE_CASE       :      Optional[Any]     						=							ASTModelTester(self			)
         SCREAMING_SNAKE_CASE       :      Union[str, Any]     						=							ConfigTester(self     ,				config_class=_UpperCamelCase     ,				has_text_modality=_UpperCamelCase     ,				hidden_size=37			)






    def    _UpperCamelCase     (							self			)				->			int:
         self.config_tester.run_common_tests()






    @unittest.skip(reason='AST does not use inputs_embeds'			)
    def    _UpperCamelCase     (							self			)				->			List[Any]:
         pass






    def    _UpperCamelCase     (							self			)				->			str:
         SCREAMING_SNAKE_CASE						, SCREAMING_SNAKE_CASE       :      List[Any]     						=							self.model_tester.prepare_config_and_inputs_for_common()

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






    def    _UpperCamelCase     (							self			)				->			List[str]:
         SCREAMING_SNAKE_CASE						, SCREAMING_SNAKE_CASE       :      Union[str, Any]     						=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE       :      List[str]     						=							model_class(_UpperCamelCase			)
              SCREAMING_SNAKE_CASE       :      Optional[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[str]     						=							['input_values']
              self.assertListEqual(arg_names[:1]     ,				_UpperCamelCase			)






    def    _UpperCamelCase     (							self			)				->			Optional[Any]:
         SCREAMING_SNAKE_CASE       :      str     						=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_UpperCamelCase			)






    @slow
    def    _UpperCamelCase     (							self			)				->			Tuple:
         for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE       :      Dict     						=							ASTModel.from_pretrained(_UpperCamelCase			)
              self.assertIsNotNone(_UpperCamelCase			)






def      __lowerCAmelCase    (							)   ->						Union[str, Any]:





     '''simple docstring'''





     SCREAMING_SNAKE_CASE       :      List[str]     						=							hf_hub_download(
         repo_id='nielsr/audio-spectogram-transformer-checkpoint'							,   filename='sample_audio.flac'							,   repo_type='dataset'		)

     SCREAMING_SNAKE_CASE						, SCREAMING_SNAKE_CASE       :      Union[str, Any]     						=							torchaudio.load(__UpperCamelCase		)

     return audio, sampling_rate






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




    '''simple docstring'''







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






    @slow
    def    _UpperCamelCase     (							self			)				->			Any:
         SCREAMING_SNAKE_CASE       :      List[Any]     						=							self.default_feature_extractor
         SCREAMING_SNAKE_CASE       :      List[str]     						=							ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'			).to(_UpperCamelCase			)

         SCREAMING_SNAKE_CASE       :      int     						=							self.default_feature_extractor
         SCREAMING_SNAKE_CASE						, SCREAMING_SNAKE_CASE       :      List[str]     						=							prepare_audio()
         SCREAMING_SNAKE_CASE       :      int     						=							audio.squeeze().numpy()
         SCREAMING_SNAKE_CASE       :      int     						=							feature_extractor(_UpperCamelCase     ,				sampling_rate=_UpperCamelCase     ,				return_tensors='pt'			).to(_UpperCamelCase			)

         # forward pass
         with torch.no_grad():
              SCREAMING_SNAKE_CASE       :      Any     						=							model(**_UpperCamelCase			)

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

         SCREAMING_SNAKE_CASE       :      Optional[Any]     						=							torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]			).to(_UpperCamelCase			)

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







'''simple docstring'''
from __future__ import annotations

def 					lowerCamelCase_ ( __UpperCamelCase					:       dict							,    __UpperCamelCase					:       str		)					->	set[str]:







     """simple docstring"""
     _A		,				_A				=							set(__UpperCamelCase		), [start]

     while stack:
          _A				=							stack.pop()
          explored.add(__UpperCamelCase		)
          # Differences from BFS:
          # 1) pop last element instead of first one
          # 2) add adjacent elements to stack without exploring them
          for adj in reversed(graph[v]		):
               if adj not in explored:
                    stack.append(__UpperCamelCase		)
     return explored


lowerCAmelCase						=					{
    """A""": ["""B""", """C""", """D"""],
    """B""": ["""A""", """D""", """E"""],
    """C""": ["""A""", """F"""],
    """D""": ["""B""", """D"""],
    """E""": ["""B""", """F"""],
    """F""": ["""C""", """E""", """G"""],
    """G""": ["""F"""],
}

if __name__ == "__main__":
    import doctest

    doctest.testmod()
    print(depth_first_search(G, """A"""))





