



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







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

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





			def 		snake_case__			(				self	:       Any   )						->					Optional[Any]:
									"""simple docstring"""







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

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

									__lowercase					=				self.get_config()

									return config, input_values, labels





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





			def 		snake_case__			(				self	:       Optional[int]			,     lowercase	:       Any			,     lowercase	:       List[Any]			,     lowercase	:       str   )						->					Tuple:
									"""simple docstring"""







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







			def 		snake_case__			(				self	:       Union[str, Any]   )						->					List[Any]:
									"""simple docstring"""







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





@require_torch
class 			_lowerCAmelCase   ( _UpperCAmelCase    ,					_UpperCAmelCase    ,					unittest.TestCase			):






			"""simple docstring"""





			lowercase__      :  Union[str, Any]      =			(
			    (
			        ASTModel,
			        ASTForAudioClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			lowercase__      :  str      =			(
			    {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
			    if is_torch_available()
			    else {}
			)
			lowercase__      :  List[str]      =			False
			lowercase__      :  List[Any]      =			False
			lowercase__      :  Any      =			False
			lowercase__      :  Dict      =			False





			def 		snake_case__			(				self	:       List[str]			,     lowercase	:       int			,     lowercase	:       Any			,     lowercase	:       Optional[int]			,     lowercase	:       str			,     lowercase	:       str   )						->					Union[str, Any]:
									"""simple docstring"""







									if pipeline_test_casse_name == "AudioClassificationPipelineTests":
															return True

									return False





			def 		snake_case__			(				self	:       List[Any]   )						->					str:
									"""simple docstring"""







									__lowercase					=				ASTModelTester(self   )
									__lowercase					=				ConfigTester(self			,     config_class=lowercase			,     has_text_modality=lowercase			,     hidden_size=37   )





			def 		snake_case__			(				self	:       List[str]   )						->					Optional[int]:
									"""simple docstring"""







									self.config_tester.run_common_tests()





			@unittest.skip(reason="""AST does not use inputs_embeds"""   )
			def 		snake_case__			(				self	:       Optional[int]   )						->					Union[str, Any]:
									"""simple docstring"""







									pass





			def 		snake_case__			(				self	:       Optional[int]   )						->					str:
									"""simple docstring"""







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()

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





			def 		snake_case__			(				self	:       Optional[int]   )						->					List[Any]:
									"""simple docstring"""







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()

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

															__lowercase					=				["""input_values"""]
															self.assertListEqual(arg_names[:1]			,     lowercase   )





			def 		snake_case__			(				self	:       Union[str, Any]   )						->					Dict:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowercase   )







			@slow
			def 		snake_case__			(				self	:       List[str]   )						->					str:
									"""simple docstring"""







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






def  UpperCAmelCase__    (    ) ->      int:
						__lowercase					=				hf_hub_download(
						    repo_id="""nielsr/audio-spectogram-transformer-checkpoint"""						,       filename="""sample_audio.flac"""						,       repo_type="""dataset"""   )

						__lowercase	,			__lowercase					=				torchaudio.load(lowercase__   )

						return audio, sampling_rate







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






			"""simple docstring"""





			@cached_property
			def 		snake_case__			(				self	:       Union[str, Any]   )						->					List[Any]:
									"""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	:       List[str]   )						->					int:
									"""simple docstring"""







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

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

									# forward pass
									with torch.no_grad():
															__lowercase					=				model(**lowercase   )

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

									__lowercase					=				torch.tensor([-0.8760, -7.0042, -8.6602]   ).to(lowercase   )

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










from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import Features, Value
from .base import TaskTemplate
@dataclass(frozen=_UpperCAmelCase			)
class 			_lowerCAmelCase   ( _UpperCAmelCase			):






			"""simple docstring"""





			lowercase__      :  str      =			field(default="""summarization"""    ,					metadata={"""include_in_asdict_even_if_is_default""": True}			)
			lowercase__      :  ClassVar[Features]      =			Features({"""text""": Value("""string"""			)}			)
			lowercase__      :  ClassVar[Features]      =			Features({"""summary""": Value("""string"""			)}			)
			lowercase__      :  str      =			"text"
			lowercase__      :  str      =			"summary"





			@property
			def 		snake_case__			(				self	:       List[Any]   )						->					Dict[str, str]:
									"""simple docstring"""







									return {self.text_column: "text", self.summary_column: "summary"}





