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





	'''simple docstring'''



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


				'''simple docstring'''


				_snake_case          =      parent
				_snake_case          =      batch_size
				_snake_case          =      patch_size
				_snake_case          =      max_length
				_snake_case          =      num_mel_bins
				_snake_case          =      is_training
				_snake_case          =      use_labels
				_snake_case          =      hidden_size
				_snake_case          =      num_hidden_layers
				_snake_case          =      num_attention_heads
				_snake_case          =      intermediate_size
				_snake_case          =      hidden_act
				_snake_case          =      hidden_dropout_prob
				_snake_case          =      attention_probs_dropout_prob
				_snake_case          =      type_sequence_label_size
				_snake_case          =      initializer_range
				_snake_case          =      scope
				_snake_case          =      frequency_stride
				_snake_case          =      time_stride

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



	def 			A							(  self     :   int     ):


				'''simple docstring'''


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

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

				_snake_case          =      self.get_config()

				return config, input_values, labels



	def 			A							(  self     :   str     ):


				'''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=lowercase      ,  initializer_range=self.initializer_range      ,  frequency_stride=self.frequency_stride      ,  time_stride=self.time_stride      ,  )



	def 			A							(  self     :   Union[str, Any]      ,  lowercase     :   Optional[Any]      ,  lowercase     :   List[str]      ,  lowercase     :   Optional[Any]     ):


				'''simple docstring'''


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





	def 			A							(  self     :   Optional[int]     ):


				'''simple docstring'''


				_snake_case          =      self.prepare_config_and_inputs()
				(
				    (
				    _snake_case
				)     , (
				    _snake_case
				)     , (
				    _snake_case
				)     , 
				)          =      config_and_inputs
				_snake_case          =      {'input_values': input_values}
				return config, inputs_dict




@require_torch
class        SCREAMING_SNAKE_CASE__					(     UpperCAmelCase							,UpperCAmelCase							,unittest.TestCase ):





	'''simple docstring'''



	_UpperCAmelCase	:		Any          = (
	    (
	        ASTModel,
	        ASTForAudioClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	_UpperCAmelCase	:		Dict          = (
	    {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
	    if is_torch_available()
	    else {}
	)
	_UpperCAmelCase	:		Any          = False
	_UpperCAmelCase	:		Union[str, Any]          = False
	_UpperCAmelCase	:		Optional[int]          = False
	_UpperCAmelCase	:		int          = False



	def 			A							(  self     :   List[Any]      ,  lowercase     :   Optional[Any]      ,  lowercase     :   Optional[int]      ,  lowercase     :   Any      ,  lowercase     :   List[Any]      ,  lowercase     :   int     ):


				'''simple docstring'''


				if pipeline_test_casse_name == "AudioClassificationPipelineTests":
							return True

				return False



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


				'''simple docstring'''


				_snake_case          =      ASTModelTester(self     )
				_snake_case          =      ConfigTester(self      ,  config_class=lowercase      ,  has_text_modality=lowercase      ,  hidden_size=37     )



	def 			A							(  self     :   Optional[int]     ):


				'''simple docstring'''


				self.config_tester.run_common_tests()



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


				'''simple docstring'''


				pass



	def 			A							(  self     :   List[str]     ):


				'''simple docstring'''


				_snake_case     , _snake_case          =      self.model_tester.prepare_config_and_inputs_for_common()

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



	def 			A							(  self     :   Any     ):


				'''simple docstring'''


				_snake_case     , _snake_case          =      self.model_tester.prepare_config_and_inputs_for_common()

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

							_snake_case          =      ['input_values']
							self.assertListEqual(arg_names[:1]      ,  lowercase     )



	def 			A							(  self     :   Optional[Any]     ):


				'''simple docstring'''


				_snake_case          =      self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowercase     )





	@slow
	def 			A							(  self     :   Any     ):


				'''simple docstring'''


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






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

			_snake_case     , _snake_case          =      torchaudio.load(__lowercase			)

			return audio, sampling_rate




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





	'''simple docstring'''



	@cached_property
	def 			A							(  self     :   Union[str, Any]     ):


				'''simple docstring'''


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





	@slow
	def 			A							(  self     :   Dict     ):


				'''simple docstring'''


				_snake_case          =      self.default_feature_extractor
				_snake_case          =      ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'     ).to(lowercase     )

				_snake_case          =      self.default_feature_extractor
				_snake_case     , _snake_case          =      prepare_audio()
				_snake_case          =      audio.squeeze().numpy()
				_snake_case          =      feature_extractor(lowercase      ,  sampling_rate=lowercase      ,  return_tensors='pt'     ).to(lowercase     )

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

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

				_snake_case          =      torch.tensor([-0.8760, -7.0042, -8.6602]     ).to(lowercase     )

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

import random




class        SCREAMING_SNAKE_CASE__					:





	'''simple docstring'''



	@staticmethod
	def 			A							(  lowercase     :   str     ):


				'''simple docstring'''


				_snake_case          =      [ord(lowercase     ) for i in text]
				_snake_case          =      []
				_snake_case          =      []
				for i in plain:
							_snake_case          =      random.randint(1      ,  300     )
							_snake_case          =      (i + k) * k
							cipher.append(lowercase     )
							key.append(lowercase     )
				return cipher, key





	@staticmethod
	def 			A							(  lowercase     :   list[int]      ,  lowercase     :   list[int]     ):


				'''simple docstring'''


				_snake_case          =      []
				for i in range(len(lowercase     )     ):
							_snake_case          =      int((cipher[i] - (key[i]) ** 2) / key[i]     )
							plain.append(chr(lowercase     )     )
				return "".join(lowercase     )


if __name__ == "__main__":
			_lowerCamelCase   ,					_lowerCamelCase	:    Optional[int]          =      Onepad().encrypt('''Hello''')
			print(c, k)
			print(Onepad().decrypt(c, k))