

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


	def __init__(						self		: Any			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: Optional[int]=1_3			,						lowerCAmelCase__		: Optional[Any]=2			,						lowerCAmelCase__		: List[str]=2_4			,						lowerCAmelCase__		: Any=1_6			,						lowerCAmelCase__		: Optional[int]=True			,						lowerCAmelCase__		: Any=True			,						lowerCAmelCase__		: str=3_2			,						lowerCAmelCase__		: Optional[Any]=5			,						lowerCAmelCase__		: Optional[int]=4			,						lowerCAmelCase__		: List[str]=3_7			,						lowerCAmelCase__		: str="gelu"			,						lowerCAmelCase__		: Any=0.1			,						lowerCAmelCase__		: Optional[int]=0.1			,						lowerCAmelCase__		: Any=1_0			,						lowerCAmelCase__		: Any=0.02			,						lowerCAmelCase__		: List[Any]=None			,						lowerCAmelCase__		: Dict=2			,						lowerCAmelCase__		: Optional[Any]=2			,						)    ->      Tuple:
			UpperCAmelCase					      =  parent
			UpperCAmelCase					      =  batch_size
			UpperCAmelCase					      =  patch_size
			UpperCAmelCase					      =  max_length
			UpperCAmelCase					      =  num_mel_bins
			UpperCAmelCase					      =  is_training
			UpperCAmelCase					      =  use_labels
			UpperCAmelCase					      =  hidden_size
			UpperCAmelCase					      =  num_hidden_layers
			UpperCAmelCase					      =  num_attention_heads
			UpperCAmelCase					      =  intermediate_size
			UpperCAmelCase					      =  hidden_act
			UpperCAmelCase					      =  hidden_dropout_prob
			UpperCAmelCase					      =  attention_probs_dropout_prob
			UpperCAmelCase					      =  type_sequence_label_size
			UpperCAmelCase					      =  initializer_range
			UpperCAmelCase					      =  scope
			UpperCAmelCase					      =  frequency_stride
			UpperCAmelCase					      =  time_stride

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


	def _UpperCamelCase	(						self		: Tuple    )    ->      Union[str, Any]:
			UpperCAmelCase					      =  floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]    )

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

			UpperCAmelCase					      =  self.get_config()

			return config, input_values, labels


	def _UpperCamelCase	(						self		: int    )    ->      Tuple:
			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 _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: Union[str, Any]    )    ->      List[Any]:
			UpperCAmelCase					      =  ASTModel(config=__UpperCamelCase    )
			model.to(__UpperCamelCase    )
			model.eval()
			UpperCAmelCase					      =  model(__UpperCamelCase    )
			self.parent.assertEqual(result.last_hidden_state.shape			,						(self.batch_size, self.seq_length, self.hidden_size)    )


	def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Tuple:
			UpperCAmelCase					      =  self.prepare_config_and_inputs()
			(
			    (
			    UpperCAmelCase       
			)      ,	(
			    UpperCAmelCase       
			)      ,	(
			    UpperCAmelCase       
			)      ,	       
			)					      =  config_and_inputs
			UpperCAmelCase					      =  {"input_values": input_values}
			return config, inputs_dict






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


	def _UpperCamelCase	(						self		: Union[str, Any]			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: Optional[int]			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: int    )    ->      Union[str, Any]:


			if pipeline_test_casse_name == "AudioClassificationPipelineTests":
					return True

			return False


	def _UpperCamelCase	(						self		: Optional[int]    )    ->      Tuple:
			UpperCAmelCase					      =  ASTModelTester(self    )
			UpperCAmelCase					      =  ConfigTester(self			,						config_class=__UpperCamelCase			,						has_text_modality=__UpperCamelCase			,						hidden_size=3_7    )


	def _UpperCamelCase	(						self		: List[str]    )    ->      Union[str, Any]:
			self.config_tester.run_common_tests()


	@unittest.skip(reason="AST does not use inputs_embeds"    )
	def _UpperCamelCase	(						self		: Dict    )    ->      Optional[Any]:
			pass


	def _UpperCamelCase	(						self		: Tuple    )    ->      Dict:
			UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

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


	def _UpperCamelCase	(						self		: List[Any]    )    ->      Tuple:
			UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

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

					UpperCAmelCase					      =  ["input_values"]
					self.assertListEqual(arg_names[:1]			,						__UpperCamelCase    )


	def _UpperCamelCase	(						self		: Dict    )    ->      Any:
			UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*__UpperCamelCase    )


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


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

def      _lowerCAmelCase(	):
		UpperCAmelCase					      =  hf_hub_download(
		    repo_id="nielsr/audio-spectogram-transformer-checkpoint"   ,       filename="sample_audio.flac"   ,       repo_type="dataset"			)

		UpperCAmelCase      ,	UpperCAmelCase					      =  torchaudio.load(lowercase__			)

		return audio, sampling_rate






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


	@cached_property
	def _UpperCamelCase	(						self		: str    )    ->      Optional[int]:
			return (
			    ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"    )
			    if is_torchaudio_available()
			    else None
			)


	@slow
	def _UpperCamelCase	(						self		: Tuple    )    ->      Tuple:
			UpperCAmelCase					      =  self.default_feature_extractor
			UpperCAmelCase					      =  ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"    ).to(__UpperCamelCase    )

			UpperCAmelCase					      =  self.default_feature_extractor
			UpperCAmelCase      ,	UpperCAmelCase					      =  prepare_audio()
			UpperCAmelCase					      =  audio.squeeze().numpy()
			UpperCAmelCase					      =  feature_extractor(__UpperCamelCase			,						sampling_rate=__UpperCamelCase			,						return_tensors="pt"    ).to(__UpperCamelCase    )

			# forward pass
			with torch.no_grad():
					UpperCAmelCase					      =  model(**__UpperCamelCase    )

			# verify the logits
			UpperCAmelCase					      =  torch.Size((1, 5_2_7)    )
			self.assertEqual(outputs.logits.shape			,						__UpperCamelCase    )

			UpperCAmelCase					      =  torch.tensor([-0.8_760, -7.0_042, -8.6_602]    ).to(__UpperCamelCase    )

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






import json
import os
import unittest

from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 						__magic_name__    (       _snake_case	,						unittest.TestCase    ):
 UpperCAmelCase							    =						LEDTokenizer
 UpperCAmelCase							    =						LEDTokenizerFast
 UpperCAmelCase							    =						True


 def _UpperCamelCase	(						self		: Tuple    )    ->      Union[str, Any]:
   super().setUp()
   UpperCAmelCase					      =  [
       "l",
       "o",
       "w",
       "e",
       "r",
       "s",
       "t",
       "i",
       "d",
       "n",
       "\u0120",
       "\u0120l",
       "\u0120n",
       "\u0120lo",
       "\u0120low",
       "er",
       "\u0120lowest",
       "\u0120newer",
       "\u0120wider",
       "<unk>",
   ]
   UpperCAmelCase					      =  dict(zip(lowerCAmelCase__			,						range(len(lowerCAmelCase__    )    )    )    )
   UpperCAmelCase					      =  ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
   UpperCAmelCase					      =  {"unk_token": "<unk>"}

   UpperCAmelCase					      =  os.path.join(self.tmpdirname			,						VOCAB_FILES_NAMES["vocab_file"]    )
   UpperCAmelCase					      =  os.path.join(self.tmpdirname			,						VOCAB_FILES_NAMES["merges_file"]    )
   with open(self.vocab_file			,						"w"			,						encoding="utf-8"    ) as fp:
     fp.write(json.dumps(lowerCAmelCase__    ) + "\n"    )
   with open(self.merges_file			,						"w"			,						encoding="utf-8"    ) as fp:
     fp.write("\n".join(lowerCAmelCase__    )    )


 def _UpperCamelCase	(						self		: Union[str, Any]			,						**lowerCAmelCase__		: Optional[int]    )    ->      Optional[int]:
   kwargs.update(self.special_tokens_map    )
   return self.tokenizer_class.from_pretrained(self.tmpdirname			,						**lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: str			,						**lowerCAmelCase__		: str    )    ->      Optional[int]:
   kwargs.update(self.special_tokens_map    )
   return self.rust_tokenizer_class.from_pretrained(self.tmpdirname			,						**lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: List[str]			,						lowerCAmelCase__		: List[Any]    )    ->      List[Any]:
   return "lower newer", "lower newer"


 @cached_property
 def _UpperCamelCase	(						self		: Dict    )    ->      str:
   return LEDTokenizer.from_pretrained("allenai/led-base-16384"    )


 @cached_property
 def _UpperCamelCase	(						self		: int    )    ->      Tuple:
   return LEDTokenizerFast.from_pretrained("allenai/led-base-16384"    )


 @require_torch
 def _UpperCamelCase	(						self		: Tuple    )    ->      List[str]:
   UpperCAmelCase					      =  ["A long paragraph for summarization.", "Another paragraph for summarization."]
   UpperCAmelCase					      =  [0, 2_5_0, 2_5_1, 1_7_8_1_8, 1_3, 3_9_1_8_6, 1_9_3_8, 4, 2]

   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(lowerCAmelCase__			,						max_length=len(lowerCAmelCase__    )			,						padding=lowerCAmelCase__			,						return_tensors="pt"    )
     self.assertIsInstance(lowerCAmelCase__			,						lowerCAmelCase__    )

     self.assertEqual((2, 9)			,						batch.input_ids.shape    )
     self.assertEqual((2, 9)			,						batch.attention_mask.shape    )
     UpperCAmelCase					      =  batch.input_ids.tolist()[0]
     self.assertListEqual(lowerCAmelCase__			,						lowerCAmelCase__    )


 @require_torch
 def _UpperCamelCase	(						self		: Union[str, Any]    )    ->      List[Any]:
   UpperCAmelCase					      =  ["A long paragraph for summarization.", "Another paragraph for summarization."]
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(lowerCAmelCase__			,						padding=lowerCAmelCase__			,						return_tensors="pt"    )
     self.assertIn("input_ids"			,						lowerCAmelCase__    )
     self.assertIn("attention_mask"			,						lowerCAmelCase__    )
     self.assertNotIn("labels"			,						lowerCAmelCase__    )
     self.assertNotIn("decoder_attention_mask"			,						lowerCAmelCase__    )


 @require_torch
 def _UpperCamelCase	(						self		: int    )    ->      int:
   UpperCAmelCase					      =  [
       "Summary of the text.",
       "Another summary.",
   ]
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(text_target=lowerCAmelCase__			,						max_length=3_2			,						padding="max_length"			,						return_tensors="pt"    )
     self.assertEqual(3_2			,						targets["input_ids"].shape[1]    )


 @require_torch
 def _UpperCamelCase	(						self		: Any    )    ->      int:
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(
         ["I am a small frog" * 1_0_2_4, "I am a small frog"]			,						padding=lowerCAmelCase__			,						truncation=lowerCAmelCase__			,						return_tensors="pt"    )
     self.assertIsInstance(lowerCAmelCase__			,						lowerCAmelCase__    )
     self.assertEqual(batch.input_ids.shape			,						(2, 5_1_2_2)    )


 @require_torch
 def _UpperCamelCase	(						self		: Dict    )    ->      Tuple:
   UpperCAmelCase					      =  ["A long paragraph for summarization."]
   UpperCAmelCase					      =  [
       "Summary of the text.",
   ]
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  tokenizer(lowerCAmelCase__			,						return_tensors="pt"    )
     UpperCAmelCase					      =  tokenizer(text_target=lowerCAmelCase__			,						return_tensors="pt"    )
     UpperCAmelCase					      =  inputs["input_ids"]
     UpperCAmelCase					      =  targets["input_ids"]
     self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()    )
     self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()    )
     self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()    )
     self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()    )


 @require_torch
 def _UpperCamelCase	(						self		: Optional[int]    )    ->      Optional[Any]:
   for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
     UpperCAmelCase					      =  ["Summary of the text.", "Another summary."]
     UpperCAmelCase					      =  [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]

     UpperCAmelCase					      =  tokenizer(lowerCAmelCase__			,						padding=lowerCAmelCase__    )
     UpperCAmelCase					      =  [[0] * len(lowerCAmelCase__    ) for x in encoded_output["input_ids"]]
     UpperCAmelCase					      =  tokenizer.pad(lowerCAmelCase__    )
     self.assertSequenceEqual(outputs["global_attention_mask"]			,						lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: List[str]    )    ->      int:
   pass


 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Union[str, Any]:
   for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
     with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"    ):
       UpperCAmelCase					      =  self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__			,						**lowerCAmelCase__    )
       UpperCAmelCase					      =  self.tokenizer_class.from_pretrained(lowerCAmelCase__			,						**lowerCAmelCase__    )
       UpperCAmelCase					      =  "A, <mask> AllenNLP sentence."
       UpperCAmelCase					      =  tokenizer_r.encode_plus(lowerCAmelCase__			,						add_special_tokens=lowerCAmelCase__			,						return_token_type_ids=lowerCAmelCase__    )
       UpperCAmelCase					      =  tokenizer_p.encode_plus(lowerCAmelCase__			,						add_special_tokens=lowerCAmelCase__			,						return_token_type_ids=lowerCAmelCase__    )
       self.assertEqual(sum(tokens_r["token_type_ids"]    )			,						sum(tokens_p["token_type_ids"]    )    )
       self.assertEqual(
           sum(tokens_r["attention_mask"]    ) / len(tokens_r["attention_mask"]    )			,						sum(tokens_p["attention_mask"]    ) / len(tokens_p["attention_mask"]    )			,						)

       UpperCAmelCase					      =  tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"]    )
       UpperCAmelCase					      =  tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"]    )
       self.assertSequenceEqual(tokens_p["input_ids"]			,						[0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2]    )
       self.assertSequenceEqual(tokens_r["input_ids"]			,						[0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2]    )

       self.assertSequenceEqual(
           lowerCAmelCase__			,						["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]    )
       self.assertSequenceEqual(
           lowerCAmelCase__			,						["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]    )



