





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


					def __init__(					self	:  Any       ,     __snake_case	:  Tuple       ,     __snake_case	:  str=13       ,     __snake_case	:  Tuple=2       ,     __snake_case	:  int=24       ,     __snake_case	:  List[Any]=16       ,     __snake_case	:  str=True       ,     __snake_case	:  Dict=True       ,     __snake_case	:  Union[str, Any]=32       ,     __snake_case	:  int=5       ,     __snake_case	:  Tuple=4       ,     __snake_case	:  Optional[int]=37       ,     __snake_case	:  Union[str, Any]="gelu"       ,     __snake_case	:  Optional[Any]=0.1       ,     __snake_case	:  Union[str, Any]=0.1       ,     __snake_case	:  Tuple=10       ,     __snake_case	:  Optional[Any]=0.02       ,     __snake_case	:  int=None       ,     __snake_case	:  str=2       ,     __snake_case	:  Optional[int]=2       ,     ):





											'''simple docstring'''





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

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


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											_snake_case:   Any  					=		floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]       )

											_snake_case:   Dict  					=		None
											if self.use_labels:
																	_snake_case:   Optional[Any]  					=		ids_tensor([self.batch_size]       ,     self.type_sequence_label_size       )

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

											return config, input_values, labels


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''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    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ,     __snake_case	:  str       ,     __snake_case	:  Optional[Any]       ,     __snake_case	:  str       ):





											'''simple docstring'''





											_snake_case:   int  					=		ASTModel(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Union[str, Any]  					=		model(__snake_case       )
											self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)       )




					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		self.prepare_config_and_inputs()
											(
											    (
											    _snake_case
											)					,						(
											    _snake_case
											)					,						(
											    _snake_case
											)					,						
											):   List[str]  					=		config_and_inputs
											_snake_case:   List[str]  					=		{'input_values': input_values}
											return config, inputs_dict







@require_torch
class 			lowerCamelCase					(						__UpperCAmelCase     ,							__UpperCAmelCase     ,							unittest.TestCase  ):
					_SCREAMING_SNAKE_CASE							   =    (
					    (
					        ASTModel,
					        ASTForAudioClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					_SCREAMING_SNAKE_CASE							   =    (
					    {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
					    if is_torch_available()
					    else {}
					)
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Tuple       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  List[Any]       ,     __snake_case	:  List[str]       ):





											'''simple docstring'''





											if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																	return True

											return False


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		ASTModelTester(self       )
											_snake_case:   int  					=		ConfigTester(self       ,     config_class=__snake_case       ,     has_text_modality=__snake_case       ,     hidden_size=37       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											self.config_tester.run_common_tests()


					@unittest.skip(reason='AST does not use inputs_embeds'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											pass


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	_snake_case:   Optional[Any]  					=		model_class(__snake_case       )
																	self.assertIsInstance(model.get_input_embeddings()       ,     (nn.Module)       )
																	_snake_case:   str  					=		model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(__snake_case       ,     nn.Linear       )       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   Dict  					=		self.model_tester.prepare_config_and_inputs_for_common()

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

																	_snake_case:   Optional[int]  					=		['input_values']
																	self.assertListEqual(arg_names[:1]       ,     __snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case:   int  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__snake_case       )




					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_snake_case:   Any  					=		ASTModel.from_pretrained(__snake_case       )
																	self.assertIsNotNone(__snake_case       )





def       lowercase_      (		)   ->Optional[int]:
						_snake_case:   Tuple  					=		hf_hub_download(
						    repo_id='nielsr/audio-spectogram-transformer-checkpoint'				,  filename='sample_audio.flac'				,  repo_type='dataset'						)

						_snake_case					,						_snake_case:   int  					=		torchaudio.load(lowercase__						)

						return audio, sampling_rate







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


					@cached_property
					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''simple docstring'''





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




					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case:   str  					=		self.default_feature_extractor
											_snake_case:   int  					=		ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'       ).to(__snake_case       )

											_snake_case:   Any  					=		self.default_feature_extractor
											_snake_case					,						_snake_case:   str  					=		prepare_audio()
											_snake_case:   Tuple  					=		audio.squeeze().numpy()
											_snake_case:   Dict  					=		feature_extractor(__snake_case       ,     sampling_rate=__snake_case       ,     return_tensors='pt'       ).to(__snake_case       )

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

											# verify the logits
											_snake_case:   Union[str, Any]  					=		torch.Size((1, 5_27)       )
											self.assertEqual(outputs.logits.shape       ,     __snake_case       )

											_snake_case:   Union[str, Any]  					=		torch.tensor([-0.8_760, -7.0_042, -8.6_602]       ).to(__snake_case       )

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












'''simple docstring'''






def       lowercase_      (		lowercase__ = 1				,  lowercase__ = 1000						)   ->int:
						_snake_case:   int  					=		1
						_snake_case:   Union[str, Any]  					=		0

						for divide_by_number in range(lowercase__				,  digit + 1						):
												_snake_case:   list[int]  					=		[]
												_snake_case:   int  					=		numerator
												for _ in range(1				,  digit + 1						):
																		if now_divide in has_been_divided:
																								if longest_list_length < len(lowercase__						):
																														_snake_case:   Union[str, Any]  					=		len(lowercase__						)
																														_snake_case:   Tuple  					=		divide_by_number
																		else:
																								has_been_divided.append(lowercase__						)
																								_snake_case:   Union[str, Any]  					=		now_divide * 10 % divide_by_number

						return the_digit


# Tests
if __name__ == "__main__":
		import doctest

		doctest.testmod()





