


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




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

										"""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 					a__(		self      :			Union[str, Any]				)->					Dict:

										"""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 					a__(		self      :			List[str]				)->					Union[str, 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 					a__(		self      :			int				,   lowerCAmelCase      :			List[str]				,   lowerCAmelCase      :			Optional[Any]				,   lowerCAmelCase      :			str				)->					Any:

										"""simple docstring"""




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





				def 					a__(		self      :			List[str]				)->					int:

										"""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 	UpperCamelCase__(       lowerCAmelCase						,    lowerCAmelCase						,    unittest.TestCase	):
				__magic_name__    :				Union[str, Any]  		=	(
				    (
				        ASTModel,
				        ASTForAudioClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				__magic_name__    :				Union[str, Any]  		=	(
				    {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
				    if is_torch_available()
				    else {}
				)
				__magic_name__    :				str  		=	False
				__magic_name__    :				Optional[Any]  		=	False
				__magic_name__    :				int  		=	False
				__magic_name__    :				Tuple  		=	False




				def 					a__(		self      :			Optional[int]				,   lowerCAmelCase      :			Tuple				,   lowerCAmelCase      :			Dict				,   lowerCAmelCase      :			Tuple				,   lowerCAmelCase      :			Dict				,   lowerCAmelCase      :			Dict				)->					Optional[int]:

										"""simple docstring"""




										if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																return True

										return False




				def 					a__(		self      :			Dict				)->					Dict:

										"""simple docstring"""




										UpperCAmelCase					    =     ASTModelTester(self				)
										UpperCAmelCase					    =     ConfigTester(self				,   config_class=_lowerCAmelCase				,   has_text_modality=_lowerCAmelCase				,   hidden_size=37				)




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

										"""simple docstring"""




										self.config_tester.run_common_tests()




				@unittest.skip(reason='''AST does not use inputs_embeds'''				)
				def 					a__(		self      :			Optional[Any]				)->					Union[str, Any]:

										"""simple docstring"""




										pass




				def 					a__(		self      :			Dict				)->					List[Any]:

										"""simple docstring"""




										UpperCAmelCase    ,    UpperCAmelCase					    =     self.model_tester.prepare_config_and_inputs_for_common()

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




				def 					a__(		self      :			int				)->					Any:

										"""simple docstring"""




										UpperCAmelCase    ,    UpperCAmelCase					    =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																UpperCAmelCase					    =     model_class(_lowerCAmelCase				)
																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]				,   _lowerCAmelCase				)




				def 					a__(		self      :			Dict				)->					Tuple:

										"""simple docstring"""




										UpperCAmelCase					    =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_lowerCAmelCase				)





				@slow
				def 					a__(		self      :			Optional[Any]				)->					Tuple:

										"""simple docstring"""




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







def 				lowerCamelCase__				(	):




						'''simple docstring'''






						UpperCAmelCase					    =     hf_hub_download(
						    repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''				,       filename='''sample_audio.flac'''				,       repo_type='''dataset'''					)

						UpperCAmelCase    ,    UpperCAmelCase					    =     torchaudio.load(_lowerCAmelCase					)

						return audio, sampling_rate






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




				@cached_property
				def 					a__(		self      :			Tuple				)->					List[str]:

										"""simple docstring"""




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





				@slow
				def 					a__(		self      :			List[Any]				)->					Dict:

										"""simple docstring"""




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

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

										# forward pass
										with torch.no_grad():
																UpperCAmelCase					    =     model(**_lowerCAmelCase				)

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

										UpperCAmelCase					    =     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

from collections import namedtuple
from dataclasses import dataclass






@dataclass
class 	UpperCamelCase__:
				__magic_name__    :				int
				__magic_name__    :				TreeNode | None  		=	None
				__magic_name__    :				TreeNode | None  		=	None







_lowercase      :      Tuple            =					namedtuple("""CoinsDistribResult""", """moves excess""")


def 				lowerCamelCase__				(	A       :      TreeNode | None					):




						'''simple docstring'''






						if root is None:
												return 0

						# Validation
						def count_nodes(A       :      TreeNode | None					) -> int:
												if node is None:
																		return 0

												return count_nodes(node.left					) + count_nodes(node.right					) + 1

						def count_coins(A       :      TreeNode | None					) -> int:
												if node is None:
																		return 0

												return count_coins(node.left					) + count_coins(node.right					) + node.data

						if count_nodes(A					) != count_coins(A					):
												raise ValueError('''The nodes number should be same as the number of coins'''					)

						# Main calculation
						def get_distrib(A       :      TreeNode | None					) -> CoinsDistribResult:

												if node is None:
																		return CoinsDistribResult(0				,       1					)

												UpperCAmelCase    ,    UpperCAmelCase					    =     get_distrib(node.left					)
												UpperCAmelCase    ,    UpperCAmelCase					    =     get_distrib(node.right					)

												UpperCAmelCase					    =     1 - left_distrib_excess
												UpperCAmelCase					    =     1 - right_distrib_excess

												UpperCAmelCase					    =     (
												    left_distrib_moves
												    + right_distrib_moves
												    + abs(A					)
												    + abs(A					)
												)
												UpperCAmelCase					    =     node.data - coins_to_left - coins_to_right

												return CoinsDistribResult(A				,       A					)

						return get_distrib(A					)[0]


if __name__ == "__main__":
	import doctest

	doctest.testmod()





