
"""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     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE=1_3     ,				__SCREAMING_SNAKE_CASE=2     ,				__SCREAMING_SNAKE_CASE=2_4     ,				__SCREAMING_SNAKE_CASE=1_6     ,				__SCREAMING_SNAKE_CASE=True     ,				__SCREAMING_SNAKE_CASE=True     ,				__SCREAMING_SNAKE_CASE=3_2     ,				__SCREAMING_SNAKE_CASE=5     ,				__SCREAMING_SNAKE_CASE=4     ,				__SCREAMING_SNAKE_CASE=3_7     ,				__SCREAMING_SNAKE_CASE="gelu"     ,				__SCREAMING_SNAKE_CASE=0.1     ,				__SCREAMING_SNAKE_CASE=0.1     ,				__SCREAMING_SNAKE_CASE=1_0     ,				__SCREAMING_SNAKE_CASE=0.02     ,				__SCREAMING_SNAKE_CASE=None     ,				__SCREAMING_SNAKE_CASE=2     ,				__SCREAMING_SNAKE_CASE=2     ,				)		->     List[Any]:







         """simple docstring"""



         a__		=			parent
         a__		=			batch_size
         a__		=			patch_size
         a__		=			max_length
         a__		=			num_mel_bins
         a__		=			is_training
         a__		=			use_labels
         a__		=			hidden_size
         a__		=			num_hidden_layers
         a__		=			num_attention_heads
         a__		=			intermediate_size
         a__		=			hidden_act
         a__		=			hidden_dropout_prob
         a__		=			attention_probs_dropout_prob
         a__		=			type_sequence_label_size
         a__		=			initializer_range
         a__		=			scope
         a__		=			frequency_stride
         a__		=			time_stride

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



     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



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

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

         a__		=			self.get_config()

         return config, input_values, labels



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



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   )		->     str:







         """simple docstring"""



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




     def 			lowercase__  (							self   )		->     Tuple:







         """simple docstring"""



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







@require_torch
class     lowercase(_lowercase    ,						_lowercase    ,						unittest.TestCase       ):
     __snake_case:	str						=     (
         (
             ASTModel,
             ASTForAudioClassification,
         )
         if is_torch_available()
         else ()
     )
     __snake_case:	Optional[int]						=     (
         {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
         if is_torch_available()
         else {}
     )
     __snake_case:	str						=     False
     __snake_case:	Union[str, Any]						=     False
     __snake_case:	List[Any]						=     False
     __snake_case:	str						=     False



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   )		->     Any:







         """simple docstring"""



         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
             return True

         return False



     def 			lowercase__  (							self   )		->     int:







         """simple docstring"""



         a__		=			ASTModelTester(self   )
         a__		=			ConfigTester(self     ,				config_class=__SCREAMING_SNAKE_CASE     ,				has_text_modality=__SCREAMING_SNAKE_CASE     ,				hidden_size=3_7   )



     def 			lowercase__  (							self   )		->     List[str]:







         """simple docstring"""



         self.config_tester.run_common_tests()



     @unittest.skip(reason='AST does not use inputs_embeds'   )
     def 			lowercase__  (							self   )		->     Tuple:







         """simple docstring"""



         pass



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







         """simple docstring"""



         a__	,     a__		=			self.model_tester.prepare_config_and_inputs_for_common()

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



     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



         a__	,     a__		=			self.model_tester.prepare_config_and_inputs_for_common()

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

             a__		=			['input_values']
             self.assertListEqual(arg_names[:1]     ,				__SCREAMING_SNAKE_CASE   )



     def 			lowercase__  (							self   )		->     str:







         """simple docstring"""



         a__		=			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE   )




     @slow
     def 			lowercase__  (							self   )		->     List[str]:







         """simple docstring"""



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




def     __magic_name__		(					)     ->						Optional[Any]:
    a__		=			hf_hub_download(
        repo_id='nielsr/audio-spectogram-transformer-checkpoint'							,		filename='sample_audio.flac'							,		repo_type='dataset'     )

    a__	,     a__		=			torchaudio.load(UpperCamelCase     )

    return audio, sampling_rate







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



     @cached_property
     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



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




     @slow
     def 			lowercase__  (							self   )		->     int:







         """simple docstring"""



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

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

         # forward pass
         with torch.no_grad():
             a__		=			model(**__SCREAMING_SNAKE_CASE   )

         # verify the logits
         a__		=			torch.Size((1, 5_2_7)   )
         self.assertEqual(outputs.logits.shape     ,				__SCREAMING_SNAKE_CASE   )

         a__		=			torch.tensor([-0.87_60, -7.00_42, -8.66_02]   ).to(__SCREAMING_SNAKE_CASE   )

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




"""simple docstring"""




from __future__ import annotations

a		:       str     						=       {
    'A': ['B', 'C', 'E'],
    'B': ['A', 'D', 'E'],
    'C': ['A', 'F', 'G'],
    'D': ['B'],
    'E': ['A', 'B', 'D'],
    'F': ['C'],
    'G': ['C'],
}







class     lowercase:



     def __init__(							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   )		->     None:







         """simple docstring"""



         a__		=			graph
         # mapping node to its parent in resulting breadth first tree
         a__		=			{}
         a__		=			source_vertex



     def 			lowercase__  (							self   )		->     None:







         """simple docstring"""



         a__		=			{self.source_vertex}
         a__		=			None
         a__		=			[self.source_vertex]  # first in first out queue

         while queue:
             a__		=			queue.pop(0   )
             for adjacent_vertex in self.graph[vertex]:
                 if adjacent_vertex not in visited:
                     visited.add(__SCREAMING_SNAKE_CASE   )
                     a__		=			vertex
                     queue.append(__SCREAMING_SNAKE_CASE   )




     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE   )		->     str:







         """simple docstring"""



         if target_vertex == self.source_vertex:
             return self.source_vertex

         a__		=			self.parent.get(__SCREAMING_SNAKE_CASE   )
         if target_vertex_parent is None:
             a__		=			(
                 f'No path from vertex: {self.source_vertex} to vertex: {target_vertex}'
             )
             raise ValueError(__SCREAMING_SNAKE_CASE   )

         return self.shortest_path(__SCREAMING_SNAKE_CASE   ) + f'->{target_vertex}'


if __name__ == "__main__":
    a		:       Optional[Any]     						=       Graph(graph, 'G')
    g.breath_first_search()
    print(g.shortest_path('D'))
    print(g.shortest_path('G'))
    print(g.shortest_path('Foo'))


