




"""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  ,      lowercase  ,      lowercase=13  ,      lowercase=2  ,      lowercase=24  ,      lowercase=16  ,      lowercase=True  ,      lowercase=True  ,      lowercase=32  ,      lowercase=5  ,      lowercase=4  ,      lowercase=37  ,      lowercase="gelu"  ,      lowercase=0.1  ,      lowercase=0.1  ,      lowercase=10  ,      lowercase=0.02  ,      lowercase=None  ,      lowercase=2  ,      lowercase=2  ,      ):
							_lowerCamelCase     :			List[Any]    =    parent
							_lowerCamelCase     :			Optional[int]    =    batch_size
							_lowerCamelCase     :			Dict    =    patch_size
							_lowerCamelCase     :			List[Any]    =    max_length
							_lowerCamelCase     :			Optional[int]    =    num_mel_bins
							_lowerCamelCase     :			List[str]    =    is_training
							_lowerCamelCase     :			Optional[int]    =    use_labels
							_lowerCamelCase     :			Dict    =    hidden_size
							_lowerCamelCase     :			Union[str, Any]    =    num_hidden_layers
							_lowerCamelCase     :			List[Any]    =    num_attention_heads
							_lowerCamelCase     :			List[Any]    =    intermediate_size
							_lowerCamelCase     :			str    =    hidden_act
							_lowerCamelCase     :			str    =    hidden_dropout_prob
							_lowerCamelCase     :			List[str]    =    attention_probs_dropout_prob
							_lowerCamelCase     :			List[str]    =    type_sequence_label_size
							_lowerCamelCase     :			Optional[int]    =    initializer_range
							_lowerCamelCase     :			Dict    =    scope
							_lowerCamelCase     :			List[str]    =    frequency_stride
							_lowerCamelCase     :			int    =    time_stride

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

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

							_lowerCamelCase     :			Dict    =    self.get_config()

							return config, input_values, labels
			def 					A_    (  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=lowercase  ,      initializer_range=self.initializer_range  ,      frequency_stride=self.frequency_stride  ,      time_stride=self.time_stride  ,      )
			def 					A_    (  self  ,      lowercase  ,      lowercase  ,      lowercase  ):
							_lowerCamelCase     :			Dict    =    ASTModel(config=lowercase  )
							model.to(lowercase  )
							model.eval()
							_lowerCamelCase     :			str    =    model(lowercase  )
							self.parent.assertEqual(result.last_hidden_state.shape  ,      (self.batch_size, self.seq_length, self.hidden_size)  )






			def 					A_    (  self  ):
							_lowerCamelCase     :			List[Any]    =    self.prepare_config_and_inputs()
							(
							    (
							    _lowerCamelCase
							), (
							    _lowerCamelCase
							), (
							    _lowerCamelCase
							), 
							)     :			List[Any]    =    config_and_inputs
							_lowerCamelCase     :			int    =    {'input_values': input_values}
							return config, inputs_dict






@require_torch
class lowerCAmelCase__	(     lowercase,	lowercase,	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 					A_    (  self  ,      lowercase  ,      lowercase  ,      lowercase  ,      lowercase  ,      lowercase  ):
							if pipeline_test_casse_name == "AudioClassificationPipelineTests":
											return True

							return False
			def 					A_    (  self  ):
							_lowerCamelCase     :			Union[str, Any]    =    ASTModelTester(self  )
							_lowerCamelCase     :			Optional[Any]    =    ConfigTester(self  ,      config_class=lowercase  ,      has_text_modality=lowercase  ,      hidden_size=37  )
			def 					A_    (  self  ):
							self.config_tester.run_common_tests()
			@unittest.skip(reason='AST does not use inputs_embeds'  )
			def 					A_    (  self  ):
							pass
			def 					A_    (  self  ):
							_lowerCamelCase, _lowerCamelCase     :			Any    =    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											_lowerCamelCase     :			int    =    model_class(lowercase  )
											self.assertIsInstance(model.get_input_embeddings()  ,      (nn.Module)  )
											_lowerCamelCase     :			List[str]    =    model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(lowercase  ,      nn.Linear  )  )
			def 					A_    (  self  ):
							_lowerCamelCase, _lowerCamelCase     :			Optional[int]    =    self.model_tester.prepare_config_and_inputs_for_common()

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

											_lowerCamelCase     :			List[Any]    =    ['input_values']
											self.assertListEqual(arg_names[:1]  ,      lowercase  )
			def 					A_    (  self  ):
							_lowerCamelCase     :			Optional[Any]    =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase  )






			@slow
			def 					A_    (  self  ):
							for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_lowerCamelCase     :			int    =    ASTModel.from_pretrained(lowercase  )
											self.assertIsNotNone(lowercase  )







def      _snake_case			(				):
				_lowerCamelCase     :			Any    =    hf_hub_download(
				    repo_id='nielsr/audio-spectogram-transformer-checkpoint'							,    filename='sample_audio.flac'							,    repo_type='dataset'		)

				_lowerCamelCase, _lowerCamelCase     :			Dict    =    torchaudio.load(lowercase__		)

				return audio, sampling_rate






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






			'''simple docstring'''



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






			@slow
			def 					A_    (  self  ):
							_lowerCamelCase     :			Optional[Any]    =    self.default_feature_extractor
							_lowerCamelCase     :			str    =    ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'  ).to(lowercase  )

							_lowerCamelCase     :			List[str]    =    self.default_feature_extractor
							_lowerCamelCase, _lowerCamelCase     :			List[Any]    =    prepare_audio()
							_lowerCamelCase     :			Union[str, Any]    =    audio.squeeze().numpy()
							_lowerCamelCase     :			Dict    =    feature_extractor(lowercase  ,      sampling_rate=lowercase  ,      return_tensors='pt'  ).to(lowercase  )

							# forward pass
							with torch.no_grad():
											_lowerCamelCase     :			int    =    model(**lowercase  )

							# verify the logits
							_lowerCamelCase     :			Dict    =    torch.Size((1, 527)  )
							self.assertEqual(outputs.logits.shape  ,      lowercase  )

							_lowerCamelCase     :			Optional[Any]    =    torch.tensor([-0.87_60, -7.00_42, -8.66_02]  ).to(lowercase  )

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






import argparse


lowerCAmelCase__  :  List[str]						     =	'docs/source/_static/js/custom.js'



def   a_						(					lowerCamelCase       ):
				with open(lowerCamelCase					,			encoding='utf-8'					,			newline='\n'       ) as f:
								UpperCAmelCase__             =							f.readlines()
				UpperCAmelCase__             =							0

				# First let's put the right version
				while not lines[index].startswith('const stableVersion ='       ):
								index += 1
				UpperCAmelCase__             =							f'''const stableVersion = "v{version}"\n'''

				# Then update the dictionary
				while not lines[index].startswith('const versionMapping = {'       ):
								index += 1

				# We go until the end
				while not lines[index].startswith('}'       ):
								index += 1
				# We add the new version at the end
				lines[index - 1] += f'''    "v{version}": "v{version}",\n'''

				with open(lowerCamelCase					,			'w'					,			encoding='utf-8'					,			newline='\n'       ) as f:
								f.writelines(lowerCamelCase       )


if __name__ == "__main__":
						lowerCAmelCase__  :  List[Any]						     =	argparse.ArgumentParser()
						parser.add_argument('--version', help='Release version.')
						lowerCAmelCase__  :  Optional[int]						     =	parser.parse_args()
						update_custom_js(args.version)



