


"""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							, _a							, _a=13							, _a=2							, _a=24							, _a=16							, _a=True							, _a=True							, _a=32							, _a=5							, _a=4							, _a=37							, _a="gelu"							, _a=0.1							, _a=0.1							, _a=10							, _a=0.02							, _a=None							, _a=2							, _a=2							, ):
				__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 			__UpperCAmelCase       (  self      ):
				__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 			__UpperCAmelCase       (  self      ):
				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=_a							, initializer_range=self.initializer_range							, frequency_stride=self.frequency_stride							, time_stride=self.time_stride							, )

		def 			__UpperCAmelCase       (  self							, _a							, _a							, _a      ):
				__a           =			ASTModel(config=_a      )
				model.to(_a      )
				model.eval()
				__a           =			model(_a      )
				self.parent.assertEqual(result.last_hidden_state.shape							, (self.batch_size, self.seq_length, self.hidden_size)      )





		def 			__UpperCAmelCase       (  self      ):
				__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					(   __SCREAMING_SNAKE_CASE     ,			__SCREAMING_SNAKE_CASE     ,			unittest.TestCase       ):


		'''simple docstring'''



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

		def 			__UpperCAmelCase       (  self							, _a							, _a							, _a							, _a							, _a      ):
				if pipeline_test_casse_name == "AudioClassificationPipelineTests":
						return True

				return False

		def 			__UpperCAmelCase       (  self      ):
				__a           =			ASTModelTester(self      )
				__a           =			ConfigTester(self							, config_class=_a							, has_text_modality=_a							, hidden_size=37      )

		def 			__UpperCAmelCase       (  self      ):
				self.config_tester.run_common_tests()

		@unittest.skip(reason='''AST does not use inputs_embeds'''      )
		def 			__UpperCAmelCase       (  self      ):
				pass

		def 			__UpperCAmelCase       (  self      ):
				__a      ,     __a           =			self.model_tester.prepare_config_and_inputs_for_common()

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

		def 			__UpperCAmelCase       (  self      ):
				__a      ,     __a           =			self.model_tester.prepare_config_and_inputs_for_common()

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

		def 			__UpperCAmelCase       (  self      ):
				__a           =			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_a      )





		@slow
		def 			__UpperCAmelCase       (  self      ):
				for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						__a           =			ASTModel.from_pretrained(_a      )
						self.assertIsNotNone(_a      )







def        lowercase							(		) ->      int:
		__a           =			hf_hub_download(
		    repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''    ,					filename='''sample_audio.flac'''    ,					repo_type='''dataset'''			)

		__a      ,     __a           =			torchaudio.load(lowerCAmelCase__			)

		return audio, sampling_rate




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


		'''simple docstring'''



		@cached_property
		def 			__UpperCAmelCase       (  self      ):
				return (
				    ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''      )
				    if is_torchaudio_available()
				    else None
				)





		@slow
		def 			__UpperCAmelCase       (  self      ):
				__a           =			self.default_feature_extractor
				__a           =			ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''      ).to(_a      )

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

				# forward pass
				with torch.no_grad():
						__a           =			model(**_a      )

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

				__a           =			torch.tensor([-0.8760, -7.0042, -8.6602]      ).to(_a      )

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














"""simple docstring"""


class 					snake_case		:


   '''simple docstring'''

   def __init__(	self :     List[str],       _lowerCamelCase :     list[int]  ):

     '''simple docstring'''
     __A									= len(_lowerCamelCase  )
     __A									= [0] * len_array

     if len_array > 0:
       __A									= array[0]

     for i in range(1,       _lowerCamelCase  ):
       __A									= self.prefix_sum[i - 1] + array[i]


   def 				_SCREAMING_SNAKE_CASE				(	self :     List[Any],       _lowerCamelCase :     int,       _lowerCamelCase :     int  ):

     '''simple docstring'''
     if start == 0:
       return self.prefix_sum[end]

     return self.prefix_sum[end] - self.prefix_sum[start - 1]






   def 				_SCREAMING_SNAKE_CASE				(	self :     List[str],       _lowerCamelCase :     int  ):

     '''simple docstring'''
     __A									= {0}
     for sum_item in self.prefix_sum:
       if sum_item - target_sum in sums:
         return True

       sums.add(_lowerCamelCase  )

     return False


if __name__ == "__main__":
       import doctest

       doctest.testmod()




