




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







								'''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						:str				):







								'''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						:Optional[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=__magic_name__		,      initializer_range=self.initializer_range		,      frequency_stride=self.frequency_stride		,      time_stride=self.time_stride		,      )
							def       lowerCamelCase__							(						self						:Tuple		,      __magic_name__						:Tuple		,      __magic_name__						:Optional[int]		,      __magic_name__						:Tuple				):







								'''simple docstring'''







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





							def       lowerCamelCase__							(						self						:List[Any]				):







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







								'''simple docstring'''







								if pipeline_test_casse_name == "AudioClassificationPipelineTests":
									return True

								return False
							def       lowerCamelCase__							(						self						:Tuple				):







								'''simple docstring'''







								a										=							ASTModelTester(self				)
								a										=							ConfigTester(self		,      config_class=__magic_name__		,      has_text_modality=__magic_name__		,      hidden_size=37				)
							def       lowerCamelCase__							(						self						:List[Any]				):







								'''simple docstring'''







								self.config_tester.run_common_tests()
							@unittest.skip(reason="""AST does not use inputs_embeds"""				)
							def       lowerCamelCase__							(						self						:List[Any]				):







								'''simple docstring'''







								pass
							def       lowerCamelCase__							(						self						:Optional[int]				):







								'''simple docstring'''







								a				, a										=							self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									a										=							model_class(__magic_name__				)
									self.assertIsInstance(model.get_input_embeddings()		,      (nn.Module)				)
									a										=							model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(__magic_name__		,      nn.Linear				)				)
							def       lowerCamelCase__							(						self						:List[Any]				):







								'''simple docstring'''







								a				, a										=							self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									a										=							model_class(__magic_name__				)
									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]		,      __magic_name__				)
							def       lowerCamelCase__							(						self						:str				):







								'''simple docstring'''







								a										=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__magic_name__				)





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







								'''simple docstring'''







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







def 		__A		(	)      ->       Union[str, Any]:
	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 ):
							@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						:int				):







								'''simple docstring'''







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

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

								# forward pass
								with torch.no_grad():
									a										=							model(**__magic_name__				)

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

								a										=							torch.tensor([-0.8760, -7.0042, -8.6602]				).to(__magic_name__				)

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







def 		__A		(	__lowerCamelCase							,			__lowerCamelCase    )      ->       str:
	if not isinstance(__lowerCamelCase							,			__lowerCamelCase    ):
		raise ValueError("""iterations must be defined as integers"""    )
	if not isinstance(__lowerCamelCase							,			__lowerCamelCase    ) or not number >= 1:
		raise ValueError(
		    """starting number must be
                         and integer and be more than 0"""    )
	if not iterations >= 1:
		raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz"""    )

	a										=							""""""
	while number <= iterations:
		if number % 3 == 0:
			out += "Fizz"
		if number % 5 == 0:
			out += "Buzz"
		if 0 not in (number % 3, number % 5):
			out += str(__lowerCamelCase    )

		# print(out)
		number += 1
		out += " "
	return out


if __name__ == "__main__":
		import doctest

		doctest.testmod()

