

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





									'''simple docstring'''
									A__					:       Tuple     =parent
									A__					:       Tuple     =batch_size
									A__					:       List[str]     =patch_size
									A__					:       Dict     =max_length
									A__					:       int     =num_mel_bins
									A__					:       Optional[Any]     =is_training
									A__					:       Dict     =use_labels
									A__					:       Dict     =hidden_size
									A__					:       List[str]     =num_hidden_layers
									A__					:       Optional[int]     =num_attention_heads
									A__					:       Tuple     =intermediate_size
									A__					:       Dict     =hidden_act
									A__					:       Any     =hidden_dropout_prob
									A__					:       int     =attention_probs_dropout_prob
									A__					:       int     =type_sequence_label_size
									A__					:       Dict     =initializer_range
									A__					:       str     =scope
									A__					:       Optional[Any]     =frequency_stride
									A__					:       Any     =time_stride

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


			def lowercase__						(				self	:						int			)      ->		int:





									'''simple docstring'''
									A__					:       Optional[Any]     =floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]			)

									A__					:       List[str]     =None
									if self.use_labels:
															A__					:       List[Any]     =ids_tensor([self.batch_size]		,      self.type_sequence_label_size			)

									A__					:       Optional[int]     =self.get_config()

									return config, input_values, labels


			def lowercase__						(				self	:						str			)      ->		Dict:





									'''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 lowercase__						(				self	:						Any		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						str			)      ->		List[Any]:





									'''simple docstring'''
									A__					:       List[str]     =ASTModel(config=lowerCAmelCase_			)
									model.to(lowerCAmelCase_			)
									model.eval()
									A__					:       List[str]     =model(lowerCAmelCase_			)
									self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size)			)



			def lowercase__						(				self	:						List[str]			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Any     =self.prepare_config_and_inputs()
									(
									    (
									    A__
									)   ,						(
									    A__
									)   ,						(
									    A__
									)   ,						
									)					:       List[Any]     =config_and_inputs
									A__					:       int     ={"""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 lowercase__						(				self	:						Union[str, Any]		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Union[str, Any]			)      ->		Union[str, Any]:





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

									return False


			def lowercase__						(				self	:						List[str]			)      ->		Dict:





									'''simple docstring'''
									A__					:       Union[str, Any]     =ASTModelTester(self			)
									A__					:       Any     =ConfigTester(self		,      config_class=lowerCAmelCase_		,      has_text_modality=lowerCAmelCase_		,      hidden_size=37			)


			def lowercase__						(				self	:						Any			)      ->		Optional[int]:





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


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





									'''simple docstring'''
									pass


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





									'''simple docstring'''
									A__   ,						A__					:       int     =self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															A__					:       List[str]     =model_class(lowerCAmelCase_			)
															self.assertIsInstance(model.get_input_embeddings()		,      (nn.Module)			)
															A__					:       List[str]     =model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowerCAmelCase_		,      nn.Linear			)			)


			def lowercase__						(				self	:						Optional[Any]			)      ->		Any:





									'''simple docstring'''
									A__   ,						A__					:       Optional[Any]     =self.model_tester.prepare_config_and_inputs_for_common()

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

															A__					:       Tuple     =["""input_values"""]
															self.assertListEqual(arg_names[:1]		,      lowerCAmelCase_			)


			def lowercase__						(				self	:						Any			)      ->		str:





									'''simple docstring'''
									A__					:       Any     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCAmelCase_			)



			@slow
			def lowercase__						(				self	:						List[str]			)      ->		Optional[Any]:





									'''simple docstring'''
									for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															A__					:       Tuple     =ASTModel.from_pretrained(lowerCAmelCase_			)
															self.assertIsNotNone(lowerCAmelCase_			)


def 						__lowerCamelCase	(       )	->							Union[str, Any]:






						"""simple docstring"""





						A__					:       List[Any]     =hf_hub_download(
						    repo_id="""nielsr/audio-spectogram-transformer-checkpoint""",		filename="""sample_audio.flac""",		repo_type="""dataset"""	)

						A__   ,						A__					:       List[str]     =torchaudio.load(__snake_case	)

						return audio, sampling_rate



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



			'''simple docstring'''






			@cached_property
			def lowercase__						(				self	:						Union[str, Any]			)      ->		int:





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



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





									'''simple docstring'''
									A__					:       Union[str, Any]     =self.default_feature_extractor
									A__					:       str     =ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""			).to(lowerCAmelCase_			)

									A__					:       str     =self.default_feature_extractor
									A__   ,						A__					:       int     =prepare_audio()
									A__					:       Optional[int]     =audio.squeeze().numpy()
									A__					:       Any     =feature_extractor(lowerCAmelCase_		,      sampling_rate=lowerCAmelCase_		,      return_tensors="""pt"""			).to(lowerCAmelCase_			)

									# forward pass
									with torch.no_grad():
															A__					:       Any     =model(**lowerCAmelCase_			)

									# verify the logits
									A__					:       Optional[int]     =torch.Size((1, 5_27)			)
									self.assertEqual(outputs.logits.shape		,      lowerCAmelCase_			)

									A__					:       Tuple     =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 maths.is_square_free import is_square_free
from maths.prime_factors import prime_factors
def 						__lowerCamelCase	(       __snake_case					:		int	)	->							int:






						"""simple docstring"""





						A__					:       List[Any]     =prime_factors(__snake_case	)
						if is_square_free(__snake_case	):
												return -1 if len(__snake_case	) % 2 else 1
						return 0


if __name__ == "__main__":
		import doctest

		doctest.testmod()

