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







							'''simple docstring'''





							def __init__(			self				,       UpperCamelCase__				,       UpperCamelCase__=13				,       UpperCamelCase__=2				,       UpperCamelCase__=24				,       UpperCamelCase__=16				,       UpperCamelCase__=True				,       UpperCamelCase__=True				,       UpperCamelCase__=32				,       UpperCamelCase__=5				,       UpperCamelCase__=4				,       UpperCamelCase__=37				,       UpperCamelCase__="gelu"				,       UpperCamelCase__=0.1				,       UpperCamelCase__=0.1				,       UpperCamelCase__=10				,       UpperCamelCase__=0.0_2				,       UpperCamelCase__=None				,       UpperCamelCase__=2				,       UpperCamelCase__=2				,       ):
											A__  :	Dict         =							parent
											A__  :	Tuple         =							batch_size
											A__  :	int         =							patch_size
											A__  :	int         =							max_length
											A__  :	Tuple         =							num_mel_bins
											A__  :	List[Any]         =							is_training
											A__  :	List[Any]         =							use_labels
											A__  :	Any         =							hidden_size
											A__  :	Optional[int]         =							num_hidden_layers
											A__  :	List[Any]         =							num_attention_heads
											A__  :	Optional[Any]         =							intermediate_size
											A__  :	List[str]         =							hidden_act
											A__  :	Dict         =							hidden_dropout_prob
											A__  :	Optional[Any]         =							attention_probs_dropout_prob
											A__  :	Dict         =							type_sequence_label_size
											A__  :	List[Any]         =							initializer_range
											A__  :	List[str]         =							scope
											A__  :	List[Any]         =							frequency_stride
											A__  :	str         =							time_stride

											# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
											A__  :	str         =							(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__  :	Dict         =							num_patches + 2





							def   __snake_case				(			self		):
											A__  :	str         =							floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]		)

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

											A__  :	List[Any]         =							self.get_config()

											return config, input_values, labels





							def   __snake_case				(			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=UpperCamelCase__				,       initializer_range=self.initializer_range				,       frequency_stride=self.frequency_stride				,       time_stride=self.time_stride				,       )





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





							def   __snake_case				(			self		):
											A__  :	Any         =							self.prepare_config_and_inputs()
											(
											    A__							
											)  :	str         =							config_and_inputs
											A__  :	Optional[int]         =							{'''input_values''': input_values}
											return config, inputs_dict







@require_torch
class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			unittest.TestCase   ):







							'''simple docstring'''
							_lowerCAmelCase							       =				(
							    (
							        ASTModel,
							        ASTForAudioClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							_lowerCAmelCase							       =				(
							    {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
							    if is_torch_available()
							    else {}
							)
							_lowerCAmelCase							       =				False
							_lowerCAmelCase							       =				False
							_lowerCAmelCase							       =				False
							_lowerCAmelCase							       =				False





							def   __snake_case				(			self				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__				,       UpperCamelCase__		):
											if pipeline_test_casse_name == "AudioClassificationPipelineTests":
															return True

											return False





							def   __snake_case				(			self		):
											A__  :	Union[str, Any]         =							ASTModelTester(self		)
											A__  :	Dict         =							ConfigTester(self				,       config_class=UpperCamelCase__				,       has_text_modality=UpperCamelCase__				,       hidden_size=37		)





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





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





							def   __snake_case				(			self		):
											A__  :	int         =							self.model_tester.prepare_config_and_inputs_for_common()

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





							def   __snake_case				(			self		):
											A__  :	Tuple         =							self.model_tester.prepare_config_and_inputs_for_common()

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

															A__  :	List[Any]         =							['''input_values''']
															self.assertListEqual(arg_names[:1]				,       UpperCamelCase__		)





							def   __snake_case				(			self		):
											A__  :	str         =							self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*UpperCamelCase__		)





							@slow
							def   __snake_case				(			self		):
											for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															A__  :	int         =							ASTModel.from_pretrained(UpperCamelCase__		)
															self.assertIsNotNone(UpperCamelCase__		)




def 				SCREAMING_SNAKE_CASE     (      ) ->       Optional[int]:

				"""simple docstring"""







				A__  :	Tuple         =							hf_hub_download(
				    repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''							,						filename='''sample_audio.flac'''							,						repo_type='''dataset'''       )

				A__  :	List[Any]         =							torchaudio.load(__UpperCamelCase       )

				return audio, sampling_rate







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







							'''simple docstring'''





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





							@slow
							def   __snake_case				(			self		):
											A__  :	Union[str, Any]         =							self.default_feature_extractor
											A__  :	Optional[Any]         =							ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''		).to(UpperCamelCase__		)

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

											# forward pass
											with torch.no_grad():
															A__  :	Optional[Any]         =							model(**UpperCamelCase__		)

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

											A__  :	str         =							torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]		).to(UpperCamelCase__		)

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

_SCREAMING_SNAKE_CASE    :      List[str]          =			range(2, 2_0 + 1)
_SCREAMING_SNAKE_CASE    :      Optional[Any]          =			[1_0**k for k in range(ks[-1] + 1)]
_SCREAMING_SNAKE_CASE    :      dict[int, dict[int, list[list[int]]]]          =			{}

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Any							,						__UpperCamelCase :						Dict							,						__UpperCamelCase :						Any							,						__UpperCamelCase :						Optional[Any]       ) ->       int:

				"""simple docstring"""







				A__  :	Tuple         =							sum(a_i[j] for j in range(__UpperCamelCase							,						len(__UpperCamelCase       )       )       )
				A__  :	Tuple         =							sum(a_i[j] * base[j] for j in range(min(len(__UpperCamelCase       )							,						__UpperCamelCase       )       )       )

				A__       ,							A__  :	Optional[int]         =							0, 0
				A__  :	List[Any]         =							n - i

				A__  :	Any         =							memo.get(__UpperCamelCase       )

				if sub_memo is not None:
								A__  :	Optional[int]         =							sub_memo.get(__UpperCamelCase       )

								if jumps is not None and len(__UpperCamelCase       ) > 0:
												# find and make the largest jump without going over
												A__  :	List[Any]         =							-1
												for _k in range(len(__UpperCamelCase       ) - 1							,						-1							,						-1       ):
																if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
																				A__  :	List[str]         =							_k
																				break

												if max_jump >= 0:
																A__       ,							A__       ,							A__  :	List[Any]         =							jumps[max_jump]
																# since the difference between jumps is cached, add c
																A__  :	int         =							diff + c
																for j in range(min(__UpperCamelCase							,						len(__UpperCamelCase       )       )       ):
																				A__       ,							A__  :	List[str]         =							divmod(__UpperCamelCase							,						10       )
																if new_c > 0:
																				add(__UpperCamelCase							,						__UpperCamelCase							,						__UpperCamelCase       )

								else:
												A__  :	List[Any]         =							[]
				else:
								A__  :	Optional[Any]         =							{c: []}
								A__  :	int         =							sub_memo

				if dn >= max_dn or c + diff >= base[k]:
								return diff, dn

				if k > ks[0]:
								while True:
												# keep doing smaller jumps
												A__       ,							A__  :	str         =							next_term(__UpperCamelCase							,						k - 1							,						i + dn							,						__UpperCamelCase       )
												diff += _diff
												dn += terms_jumped

												if dn >= max_dn or c + diff >= base[k]:
																break
				else:
								# would be too small a jump, just compute sequential terms instead
								A__       ,							A__  :	str         =							compute(__UpperCamelCase							,						__UpperCamelCase							,						i + dn							,						__UpperCamelCase       )
								diff += _diff
								dn += terms_jumped

				A__  :	str         =							sub_memo[c]

				# keep jumps sorted by # of terms skipped
				A__  :	List[Any]         =							0
				while j < len(__UpperCamelCase       ):
								if jumps[j][1] > dn:
												break
								j += 1

				# cache the jump for this value digitsum(b) and c
				sub_memo[c].insert(__UpperCamelCase							,						(diff, dn, k)       )
				return (diff, dn)

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int							,						__UpperCamelCase :						Optional[int]							,						__UpperCamelCase :						List[str]							,						__UpperCamelCase :						int       ) ->       Any:

				"""simple docstring"""







				if i >= n:
								return 0, i
				if k > len(__UpperCamelCase       ):
								a_i.extend([0 for _ in range(k - len(__UpperCamelCase       )       )]       )

				# note: a_i -> b * 10^k + c
				# ds_b -> digitsum(b)
				# ds_c -> digitsum(c)
				A__  :	Optional[Any]         =							i
				A__       ,							A__       ,							A__  :	Dict         =							0, 0, 0
				for j in range(len(__UpperCamelCase       )       ):
								if j >= k:
												ds_b += a_i[j]
								else:
												ds_c += a_i[j]

				while i < n:
								i += 1
								A__  :	int         =							ds_c + ds_b
								diff += addend
								A__  :	List[Any]         =							0
								for j in range(__UpperCamelCase       ):
												A__  :	Optional[Any]         =							a_i[j] + addend
												A__       ,							A__  :	List[str]         =							divmod(__UpperCamelCase							,						10       )

												ds_c += a_i[j]

								if addend > 0:
												break

				if addend > 0:
								add(__UpperCamelCase							,						__UpperCamelCase							,						__UpperCamelCase       )
				return diff, i - start_i

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						Dict							,						__UpperCamelCase :						List[Any]							,						__UpperCamelCase :						int       ) ->       Tuple:

				"""simple docstring"""







				for j in range(__UpperCamelCase							,						len(__UpperCamelCase       )       ):
								A__  :	Any         =							digits[j] + addend
								if s >= 10:
												A__       ,							A__  :	Union[str, Any]         =							divmod(__UpperCamelCase							,						10       )
												A__  :	Optional[int]         =							addend // 10 + quotient
								else:
												A__  :	Any         =							s
												A__  :	Dict         =							addend // 10

								if addend == 0:
												break

				while addend > 0:
								A__       ,							A__  :	Dict         =							divmod(__UpperCamelCase							,						10       )
								digits.append(__UpperCamelCase       )

def 				SCREAMING_SNAKE_CASE     (      __UpperCamelCase :						int = 10**15       ) ->       int:

				"""simple docstring"""







				A__  :	List[Any]         =							[1]
				A__  :	Dict         =							1
				A__  :	Tuple         =							0
				while True:
								A__       ,							A__  :	List[str]         =							next_term(__UpperCamelCase							,						20							,						i + dn							,						__UpperCamelCase       )
								dn += terms_jumped
								if dn == n - i:
												break

				A__  :	List[str]         =							0
				for j in range(len(__UpperCamelCase       )       ):
								a_n += digits[j] * 10**j
				return a_n


if __name__ == "__main__":
					print(f"""{solution() = }""")