


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






			"""simple docstring"""






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

						'''simple docstring'''


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

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




			def 				snake_case__				(							self     ):

						'''simple docstring'''


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

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

						UpperCamelCase__					=       self.get_config()

						return config, input_values, labels




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




			def 				snake_case__				(							self      ,						snake_case      ,						snake_case      ,						snake_case     ):

						'''simple docstring'''


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







			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       self.prepare_config_and_inputs()
						(
						    (
						    UpperCamelCase__      
						),      (
						    UpperCamelCase__      
						),      (
						    UpperCamelCase__      
						),            
						)					=       config_and_inputs
						UpperCamelCase__					=       {"input_values": input_values}
						return config, inputs_dict







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






			"""simple docstring"""






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




			def 				snake_case__				(							self      ,						snake_case      ,						snake_case      ,						snake_case      ,						snake_case      ,						snake_case     ):

						'''simple docstring'''


						if pipeline_test_casse_name == "AudioClassificationPipelineTests":
									return True

						return False




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       ASTModelTester(self     )
						UpperCamelCase__					=       ConfigTester(self      ,						config_class=snake_case      ,						has_text_modality=snake_case      ,						hidden_size=37     )




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						self.config_tester.run_common_tests()




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

						'''simple docstring'''


						pass




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__,      UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs_for_common()

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




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__,      UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs_for_common()

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

									UpperCamelCase__					=       ["input_values"]
									self.assertListEqual(arg_names[:1]      ,						snake_case     )




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*snake_case     )







			@slow
			def 				snake_case__				(							self     ):

						'''simple docstring'''


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



def        UpperCamelCase_(				)->		Dict:
			UpperCamelCase__					=       hf_hub_download(
			    repo_id="nielsr/audio-spectogram-transformer-checkpoint"				,     filename="sample_audio.flac"				,     repo_type="dataset"  )

			UpperCamelCase__,      UpperCamelCase__					=       torchaudio.load(_A  )

			return audio, sampling_rate







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






			"""simple docstring"""






			@cached_property
			def 				snake_case__				(							self     ):

						'''simple docstring'''


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







			@slow
			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       self.default_feature_extractor
						UpperCamelCase__					=       ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"     ).to(snake_case     )

						UpperCamelCase__					=       self.default_feature_extractor
						UpperCamelCase__,      UpperCamelCase__					=       prepare_audio()
						UpperCamelCase__					=       audio.squeeze().numpy()
						UpperCamelCase__					=       feature_extractor(snake_case      ,						sampling_rate=snake_case      ,						return_tensors="pt"     ).to(snake_case     )

						# forward pass
						with torch.no_grad():
									UpperCamelCase__					=       model(**snake_case     )

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

						UpperCamelCase__					=       torch.tensor([-0.8760, -7.0042, -8.6602]     ).to(snake_case     )

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






from collections import deque
def        UpperCamelCase_(				_A   :Union[str, Any]  )->		List[Any]:
			UpperCamelCase__					=       len(_A  )
			UpperCamelCase__					=       deque()
			UpperCamelCase__					=       [False for _ in range(_A  )]
			UpperCamelCase__					=       [-1 for _ in range(_A  )]
			UpperCamelCase__					=       index_of[:]

			def strong_connect(_A   :Optional[int]				,     _A   :Optional[int]				,     _A   :List[Any]  ):
						UpperCamelCase__					=       index  # the number when this node is seen
						UpperCamelCase__					=       index  # lowest rank node reachable from here
						index += 1
						stack.append(_A  )
						UpperCamelCase__					=       True

						for w in g[v]:
									if index_of[w] == -1:
												UpperCamelCase__					=       strong_connect(_A				,     _A				,     _A  )
												UpperCamelCase__					=       (
												    lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
												)
									elif on_stack[w]:
												UpperCamelCase__					=       (
												    lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
												)

						if lowlink_of[v] == index_of[v]:
									UpperCamelCase__					=       []
									UpperCamelCase__					=       stack.pop()
									UpperCamelCase__					=       False
									component.append(_A  )
									while w != v:
												UpperCamelCase__					=       stack.pop()
												UpperCamelCase__					=       False
												component.append(_A  )
									components.append(_A  )
						return index

			UpperCamelCase__					=       []
			for v in range(_A  ):
						if index_of[v] == -1:
									strong_connect(_A				,     0				,     _A  )

			return components
def        UpperCamelCase_(				_A   :Optional[Any]				,     _A   :Any  )->		Union[str, Any]:
			UpperCamelCase__					=       [[] for _ in range(_A  )]
			for u, v in edges:
						g[u].append(_A  )
			return g


if __name__ == "__main__":
						# Test
						__UpperCamelCase    		=       7
						__UpperCamelCase    		=       [0, 0, 1, 2, 3, 3, 4, 4, 6]
						__UpperCamelCase    		=       [1, 3, 2, 0, 1, 4, 5, 6, 5]
						__UpperCamelCase    		=       [(u, v) for u, v in zip(source, target)]
						__UpperCamelCase    		=       create_graph(n_vertices, edges)

						assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)


