


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







					"""simple docstring"""


					def __init__(       self    : str ,       UpperCamelCase    : Any ,       UpperCamelCase    : Any=13 ,       UpperCamelCase    : Tuple=2 ,       UpperCamelCase    : Any=24 ,       UpperCamelCase    : Tuple=16 ,       UpperCamelCase    : int=True ,       UpperCamelCase    : Optional[int]=True ,       UpperCamelCase    : Union[str, Any]=32 ,       UpperCamelCase    : Union[str, Any]=5 ,       UpperCamelCase    : Optional[Any]=4 ,       UpperCamelCase    : int=37 ,       UpperCamelCase    : int="gelu" ,       UpperCamelCase    : int=0.1 ,       UpperCamelCase    : Dict=0.1 ,       UpperCamelCase    : List[Any]=10 ,       UpperCamelCase    : int=0.02 ,       UpperCamelCase    : Any=None ,       UpperCamelCase    : str=2 ,       UpperCamelCase    : int=2 ,       ):
												'''simple docstring'''






												__UpperCAmelCase   :						str      							=					parent
												__UpperCAmelCase   :						Tuple      							=					batch_size
												__UpperCAmelCase   :						List[Any]      							=					patch_size
												__UpperCAmelCase   :						Dict      							=					max_length
												__UpperCAmelCase   :						str      							=					num_mel_bins
												__UpperCAmelCase   :						Tuple      							=					is_training
												__UpperCAmelCase   :						Optional[Any]      							=					use_labels
												__UpperCAmelCase   :						List[Any]      							=					hidden_size
												__UpperCAmelCase   :						Union[str, Any]      							=					num_hidden_layers
												__UpperCAmelCase   :						Union[str, Any]      							=					num_attention_heads
												__UpperCAmelCase   :						Tuple      							=					intermediate_size
												__UpperCAmelCase   :						str      							=					hidden_act
												__UpperCAmelCase   :						str      							=					hidden_dropout_prob
												__UpperCAmelCase   :						List[Any]      							=					attention_probs_dropout_prob
												__UpperCAmelCase   :						str      							=					type_sequence_label_size
												__UpperCAmelCase   :						Dict      							=					initializer_range
												__UpperCAmelCase   :						int      							=					scope
												__UpperCAmelCase   :						Dict      							=					frequency_stride
												__UpperCAmelCase   :						Dict      							=					time_stride

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






					def lowerCamelCase__							(       self    : str  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[Any]      							=					floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]  )

												__UpperCAmelCase   :						Union[str, Any]      							=					None
												if self.use_labels:
																			__UpperCAmelCase   :						Union[str, Any]      							=					ids_tensor([self.batch_size] ,       self.type_sequence_label_size  )

												__UpperCAmelCase   :						List[str]      							=					self.get_config()

												return config, input_values, labels






					def lowerCamelCase__							(       self    : Any  ):
												'''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=lowerCAmelCase_ ,       initializer_range=self.initializer_range ,       frequency_stride=self.frequency_stride ,       time_stride=self.time_stride ,       )






					def lowerCamelCase__							(       self    : Optional[Any] ,       UpperCamelCase    : str ,       UpperCamelCase    : Union[str, Any] ,       UpperCamelCase    : List[str]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Union[str, Any]      							=					ASTModel(config=lowerCAmelCase_  )
												model.to(lowerCAmelCase_  )
												model.eval()
												__UpperCAmelCase   :						Dict      							=					model(lowerCAmelCase_  )
												self.parent.assertEqual(result.last_hidden_state.shape ,       (self.batch_size, self.seq_length, self.hidden_size)  )






					def lowerCamelCase__							(       self    : Any  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[str]      							=					self.prepare_config_and_inputs()
												(
												    __UpperCAmelCase	
												)   :						Optional[Any]      							=					config_and_inputs
												__UpperCAmelCase   :						int      							=					{"input_values": input_values}
												return config, inputs_dict






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







					"""simple docstring"""


					__a	       =							(
					    (
					        ASTModel,
					        ASTForAudioClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					__a	       =							(
					    {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
					    if is_torch_available()
					    else {}
					)
					__a	       =							False
					__a	       =							False
					__a	       =							False
					__a	       =							False






					def lowerCamelCase__							(       self    : List[str] ,       UpperCamelCase    : int ,       UpperCamelCase    : Optional[int] ,       UpperCamelCase    : Optional[int] ,       UpperCamelCase    : List[str] ,       UpperCamelCase    : str  ):
												'''simple docstring'''






												if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																			return True

												return False






					def lowerCamelCase__							(       self    : List[Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[Any]      							=					ASTModelTester(self  )
												__UpperCAmelCase   :						Union[str, Any]      							=					ConfigTester(self ,       config_class=lowerCAmelCase_ ,       has_text_modality=lowerCAmelCase_ ,       hidden_size=37  )






					def lowerCamelCase__							(       self    : List[str]  ):
												'''simple docstring'''






												self.config_tester.run_common_tests()






					@unittest.skip(reason="""AST does not use inputs_embeds"""  )
					def lowerCamelCase__							(       self    : Tuple  ):
												'''simple docstring'''






												pass






					def lowerCamelCase__							(       self    : Union[str, Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Optional[Any]      							=					self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																			__UpperCAmelCase   :						Tuple      							=					model_class(lowerCAmelCase_  )
																			self.assertIsInstance(model.get_input_embeddings() ,       (nn.Module)  )
																			__UpperCAmelCase   :						Union[str, Any]      							=					model.get_output_embeddings()
																			self.assertTrue(x is None or isinstance(lowerCAmelCase_ ,       nn.Linear  )  )






					def lowerCamelCase__							(       self    : Union[str, Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						Union[str, Any]      							=					self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																			__UpperCAmelCase   :						str      							=					model_class(lowerCAmelCase_  )
																			__UpperCAmelCase   :						Union[str, Any]      							=					inspect.signature(model.forward  )
																			# signature.parameters is an OrderedDict => so arg_names order is deterministic
																			__UpperCAmelCase   :						List[Any]      							=					[*signature.parameters.keys()]

																			__UpperCAmelCase   :						Optional[int]      							=					["input_values"]
																			self.assertListEqual(arg_names[:1] ,       lowerCAmelCase_  )






					def lowerCamelCase__							(       self    : Union[str, Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[str]      							=					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*lowerCAmelCase_  )






					@slow
					def lowerCamelCase__							(       self    : Optional[Any]  ):
												'''simple docstring'''






												for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__UpperCAmelCase   :						int      							=					ASTModel.from_pretrained(lowerCAmelCase_  )
																			self.assertIsNotNone(lowerCAmelCase_  )






def      lowerCamelCase       (     )		->       Tuple:

							'''simple docstring'''



							__UpperCAmelCase   :						List[Any]      							=					hf_hub_download(
							    repo_id="""nielsr/audio-spectogram-transformer-checkpoint"""       ,			filename="""sample_audio.flac"""       ,			repo_type="""dataset"""							)

							__UpperCAmelCase   :						Tuple      							=					torchaudio.load(A__							)

							return audio, sampling_rate





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







					"""simple docstring"""


					@cached_property
					def lowerCamelCase__							(       self    : Dict  ):
												'''simple docstring'''






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






					@slow
					def lowerCamelCase__							(       self    : Union[str, Any]  ):
												'''simple docstring'''






												__UpperCAmelCase   :						List[Any]      							=					self.default_feature_extractor
												__UpperCAmelCase   :						Dict      							=					ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""  ).to(lowerCAmelCase_  )

												__UpperCAmelCase   :						Tuple      							=					self.default_feature_extractor
												__UpperCAmelCase   :						List[str]      							=					prepare_audio()
												__UpperCAmelCase   :						Any      							=					audio.squeeze().numpy()
												__UpperCAmelCase   :						int      							=					feature_extractor(lowerCAmelCase_ ,       sampling_rate=lowerCAmelCase_ ,       return_tensors="""pt"""  ).to(lowerCAmelCase_  )

												# forward pass
												with torch.no_grad():
																			__UpperCAmelCase   :						Union[str, Any]      							=					model(**lowerCAmelCase_  )

												# verify the logits
												__UpperCAmelCase   :						Optional[Any]      							=					torch.Size((1, 527)  )
												self.assertEqual(outputs.logits.shape ,       lowerCAmelCase_  )

												__UpperCAmelCase   :						str      							=					torch.tensor([-0.8760, -7.0042, -8.6602]  ).to(lowerCAmelCase_  )

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








"""simple docstring"""
from __future__ import annotations







class 			UpperCamelCase_       :





	def __init__(      self					: Any	,	lowerCAmelCase_					: int						)						->			None:
				UpperCAmelCase_     : Any			     =					data
				UpperCAmelCase_     : Node | None			     =					None
				UpperCAmelCase_     : Node | None			     =					None





def 				snake_case      (   A__						):  # In Order traversal of the tree
			if tree:
						display(tree.left						)
						print(tree.data						)
						display(tree.right						)

def 				snake_case      (   A__						):
			return 1 + max(depth_of_tree(tree.left						)	,depth_of_tree(tree.right						)						) if tree else 0

def 				snake_case      (   A__						):
			if not tree:
						return True
			if tree.left and tree.right:
						return is_full_binary_tree(tree.left						) and is_full_binary_tree(tree.right						)
			else:
						return not tree.left and not tree.right

def 				snake_case      (   ):  # Main function for testing.
			UpperCAmelCase_     : List[str]			     =					Node(1						)
			UpperCAmelCase_     : Any			     =					Node(2						)
			UpperCAmelCase_     : Optional[Any]			     =					Node(3						)
			UpperCAmelCase_     : Union[str, Any]			     =					Node(4						)
			UpperCAmelCase_     : int			     =					Node(5						)
			UpperCAmelCase_     : Optional[int]			     =					Node(6						)
			UpperCAmelCase_     : Any			     =					Node(7						)
			UpperCAmelCase_     : List[str]			     =					Node(8						)
			UpperCAmelCase_     : List[Any]			     =					Node(9						)

			print(is_full_binary_tree(A__						)						)
			print(depth_of_tree(A__						)						)
			print("Tree is: "						)
			display(A__						)


if __name__ == "__main__":
			main()



