
"""simple docstring"""





import importlib
import os
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, Optional, Union

import torch

from ..utils import BaseOutput


UpperCamelCase_					:						List[Any]				= '''scheduler_config.json'''



class __lowerCAmelCase				(					_lowercase      ):




			"""simple docstring"""







			snake_case	      =				1
			snake_case	      =				2
			snake_case	      =				3
			snake_case	      =				4
			snake_case	      =				5
			snake_case	      =				6
			snake_case	      =				7
			snake_case	      =				8
			snake_case	      =				9
			snake_case	      =				10
			snake_case	      =				11
			snake_case	      =				12
			snake_case	      =				13
			snake_case	      =				14





@dataclass
class __lowerCAmelCase				(					_lowercase      ):




			"""simple docstring"""







			snake_case	      =				42





class __lowerCAmelCase				:




			"""simple docstring"""







			snake_case	      =				SCHEDULER_CONFIG_NAME
			snake_case	      =				[]
			snake_case	      =				True




			@classmethod
			def      lowerCamelCase__     (				cls						:					str       ,   _snake_case						:					Dict[str, Any] = None       ,   _snake_case						:					Optional[str] = None       ,   _snake_case						:					Tuple=False       ,   **_snake_case						:					Optional[Any]       ,   )      -> Tuple:







								"""simple docstring"""
								A_ ,    A_ ,    A_				 =						cls.load_config(
								    pretrained_model_name_or_path=_snake_case       ,   subfolder=_snake_case       ,   return_unused_kwargs=_snake_case       ,   return_commit_hash=_snake_case       ,   **_snake_case       ,   )
								return cls.from_config(_snake_case       ,   return_unused_kwargs=_snake_case       ,   **_snake_case	)




			def      lowerCamelCase__     (				self						:					Union[str, Any]       ,   _snake_case						:					Union[str, os.PathLike]       ,   _snake_case						:					bool = False       ,   **_snake_case						:					str	)      -> Any:







								"""simple docstring"""
								self.save_config(save_directory=_snake_case       ,   push_to_hub=_snake_case       ,   **_snake_case	)




			@property
			def      lowerCamelCase__     (				self						:					Any	)      -> int:







								"""simple docstring"""
								return self._get_compatibles()






			@classmethod
			def      lowerCamelCase__     (				cls						:					Any	)      -> Dict:







								"""simple docstring"""
								A_				 =						list(set([cls.__name__] + cls._compatibles	)	)
								A_				 =						importlib.import_module(__name__.split("."	)[0]	)
								A_				 =						[
								    getattr(_snake_case       ,   _snake_case	) for c in compatible_classes_str if hasattr(_snake_case       ,   _snake_case	)
								]
								return compatible_classes






"""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						:					Union[str, Any]       ,   _snake_case						:					Optional[int]       ,   _snake_case						:					Any=13       ,   _snake_case						:					Union[str, Any]=2       ,   _snake_case						:					Optional[int]=24       ,   _snake_case						:					Optional[Any]=16       ,   _snake_case						:					List[str]=True       ,   _snake_case						:					str=True       ,   _snake_case						:					List[Any]=32       ,   _snake_case						:					str=5       ,   _snake_case						:					int=4       ,   _snake_case						:					List[str]=37       ,   _snake_case						:					int="gelu"       ,   _snake_case						:					str=0.1       ,   _snake_case						:					Optional[int]=0.1       ,   _snake_case						:					Optional[int]=10       ,   _snake_case						:					int=0.0_2       ,   _snake_case						:					int=None       ,   _snake_case						:					Optional[Any]=2       ,   _snake_case						:					int=2       ,   )      -> Dict:







								"""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      lowerCamelCase__     (				self						:					Dict	)      -> int:







								"""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      lowerCamelCase__     (				self						:					List[str]	)      -> str:







								"""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      lowerCamelCase__     (				self						:					int       ,   _snake_case						:					Dict       ,   _snake_case						:					Tuple       ,   _snake_case						:					Optional[int]	)      -> Union[str, Any]:







								"""simple docstring"""
								A_				 =						ASTModel(config=_snake_case	)
								model.to(_snake_case	)
								model.eval()
								A_				 =						model(_snake_case	)
								self.parent.assertEqual(result.last_hidden_state.shape       ,   (self.batch_size, self.seq_length, self.hidden_size)	)






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







								"""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 __lowerCAmelCase				(					_lowercase     ,				_lowercase     ,				unittest.TestCase      ):




			"""simple docstring"""







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




			def      lowerCamelCase__     (				self						:					Any       ,   _snake_case						:					Tuple       ,   _snake_case						:					str       ,   _snake_case						:					List[str]       ,   _snake_case						:					int       ,   _snake_case						:					int	)      -> str:







								"""simple docstring"""
								if pipeline_test_casse_name == "AudioClassificationPipelineTests":
													return True

								return False




			def      lowerCamelCase__     (				self						:					str	)      -> str:







								"""simple docstring"""
								A_				 =						ASTModelTester(self	)
								A_				 =						ConfigTester(self       ,   config_class=_snake_case       ,   has_text_modality=_snake_case       ,   hidden_size=37	)




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







								"""simple docstring"""
								self.config_tester.run_common_tests()




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







								"""simple docstring"""
								pass




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







								"""simple docstring"""
								A_ ,    A_				 =						self.model_tester.prepare_config_and_inputs_for_common()

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




			def      lowerCamelCase__     (				self						:					Any	)      -> Tuple:







								"""simple docstring"""
								A_ ,    A_				 =						self.model_tester.prepare_config_and_inputs_for_common()

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




			def      lowerCamelCase__     (				self						:					Tuple	)      -> Optional[int]:







								"""simple docstring"""
								A_				 =						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case	)






			@slow
			def      lowerCamelCase__     (				self						:					List[Any]	)      -> Tuple:







								"""simple docstring"""
								for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													A_				 =						ASTModel.from_pretrained(_snake_case	)
													self.assertIsNotNone(_snake_case	)





def 							A_     ():

					'''simple docstring'''





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

					A_ ,    A_				 =						torchaudio.load(__a				)

					return audio, sampling_rate




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




			"""simple docstring"""







			@cached_property
			def      lowerCamelCase__     (				self						:					List[str]	)      -> int:







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






			@slow
			def      lowerCamelCase__     (				self						:					Any	)      -> Optional[int]:







								"""simple docstring"""
								A_				 =						self.default_feature_extractor
								A_				 =						ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"	).to(_snake_case	)

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

								# forward pass
								with torch.no_grad():
													A_				 =						model(**_snake_case	)

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

								A_				 =						torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]	).to(_snake_case	)

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




