





import json
import os
import shutil
import tempfile
from unittest import TestCase

from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available


if is_torch_available() and is_datasets_available() and is_faiss_available():
				from transformers.models.rag.configuration_rag import RagConfig
				from transformers.models.rag.tokenization_rag import RagTokenizer







@require_faiss
@require_torch
class   _UpperCamelCase  (       A_  ):







					'''simple docstring'''

					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     tempfile.mkdtemp()
						UpperCAmelCase_								=     8

						# DPR tok
						UpperCAmelCase_								=     [
						    """[UNK]""",
						    """[CLS]""",
						    """[SEP]""",
						    """[PAD]""",
						    """[MASK]""",
						    """want""",
						    """##want""",
						    """##ed""",
						    """wa""",
						    """un""",
						    """runn""",
						    """##ing""",
						    """,""",
						    """low""",
						    """lowest""",
						]
						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""dpr_tokenizer"""		)
						os.makedirs(__lowercase ,					exist_ok=__lowercase		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					DPR_VOCAB_FILES_NAMES["""vocab_file"""]		)
						with open(self.vocab_file ,					"""w""" ,					encoding="""utf-8"""		) as vocab_writer:
							vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)

						# BART tok
						UpperCAmelCase_								=     [
						    """l""",
						    """o""",
						    """w""",
						    """e""",
						    """r""",
						    """s""",
						    """t""",
						    """i""",
						    """d""",
						    """n""",
						    """\u0120""",
						    """\u0120l""",
						    """\u0120n""",
						    """\u0120lo""",
						    """\u0120low""",
						    """er""",
						    """\u0120lowest""",
						    """\u0120newer""",
						    """\u0120wider""",
						    """<unk>""",
						]
						UpperCAmelCase_								=     dict(zip(__lowercase ,					range(len(__lowercase		)		)		)		)
						UpperCAmelCase_								=     ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
						UpperCAmelCase_								=     {"""unk_token""": """<unk>"""}

						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""bart_tokenizer"""		)
						os.makedirs(__lowercase ,					exist_ok=__lowercase		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					BART_VOCAB_FILES_NAMES["""vocab_file"""]		)
						UpperCAmelCase_								=     os.path.join(__lowercase ,					BART_VOCAB_FILES_NAMES["""merges_file"""]		)
						with open(self.vocab_file ,					"""w""" ,					encoding="""utf-8"""		) as fp:
							fp.write(json.dumps(__lowercase		) + """\n"""		)
						with open(self.merges_file ,					"""w""" ,					encoding="""utf-8"""		) as fp:
							fp.write("""\n""".join(__lowercase		)		)





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






						'''simple docstring'''







						return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname ,					"""dpr_tokenizer"""		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname ,					"""bart_tokenizer"""		)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						shutil.rmtree(self.tmpdirname		)





					@require_tokenizers
					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					"""rag_tokenizer"""		)
						UpperCAmelCase_								=     RagConfig(question_encoder=DPRConfig().to_dict() ,					generator=BartConfig().to_dict()		)
						UpperCAmelCase_								=     RagTokenizer(question_encoder=self.get_dpr_tokenizer() ,					generator=self.get_bart_tokenizer()		)
						rag_config.save_pretrained(__lowercase		)
						rag_tokenizer.save_pretrained(__lowercase		)
						UpperCAmelCase_								=     RagTokenizer.from_pretrained(__lowercase ,					config=__lowercase		)
						self.assertIsInstance(new_rag_tokenizer.question_encoder ,					__lowercase		)
						self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() ,					rag_tokenizer.question_encoder.get_vocab()		)
						self.assertIsInstance(new_rag_tokenizer.generator ,					__lowercase		)
						self.assertEqual(new_rag_tokenizer.generator.get_vocab() ,					rag_tokenizer.generator.get_vocab()		)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     RagTokenizer.from_pretrained("""facebook/rag-token-nq"""		)
						UpperCAmelCase_								=     [
						    """who got the first nobel prize in physics""",
						    """when is the next deadpool movie being released""",
						    """which mode is used for short wave broadcast service""",
						    """who is the owner of reading football club""",
						    """when is the next scandal episode coming out""",
						    """when is the last time the philadelphia won the superbowl""",
						    """what is the most current adobe flash player version""",
						    """how many episodes are there in dragon ball z""",
						    """what is the first step in the evolution of the eye""",
						    """where is gall bladder situated in human body""",
						    """what is the main mineral in lithium batteries""",
						    """who is the president of usa right now""",
						    """where do the greasers live in the outsiders""",
						    """panda is a national animal of which country""",
						    """what is the name of manchester united stadium""",
						]
						UpperCAmelCase_								=     tokenizer(__lowercase		)
						self.assertIsNotNone(__lowercase		)





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






						'''simple docstring'''







						UpperCAmelCase_								=     RagTokenizer.from_pretrained("""facebook/rag-sequence-nq"""		)
						UpperCAmelCase_								=     [
						    """who got the first nobel prize in physics""",
						    """when is the next deadpool movie being released""",
						    """which mode is used for short wave broadcast service""",
						    """who is the owner of reading football club""",
						    """when is the next scandal episode coming out""",
						    """when is the last time the philadelphia won the superbowl""",
						    """what is the most current adobe flash player version""",
						    """how many episodes are there in dragon ball z""",
						    """what is the first step in the evolution of the eye""",
						    """where is gall bladder situated in human body""",
						    """what is the main mineral in lithium batteries""",
						    """who is the president of usa right now""",
						    """where do the greasers live in the outsiders""",
						    """panda is a national animal of which country""",
						    """what is the name of manchester united stadium""",
						]
						UpperCAmelCase_								=     tokenizer(__lowercase		)
						self.assertIsNotNone(__lowercase		)









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    :  Optional[int] ,					__lowercase    :  Union[str, Any] ,					__lowercase    :  Optional[int]=13 ,					__lowercase    :  Union[str, Any]=2 ,					__lowercase    :  Union[str, Any]=24 ,					__lowercase    :  Tuple=16 ,					__lowercase    :  Any=True ,					__lowercase    :  List[str]=True ,					__lowercase    :  List[Any]=32 ,					__lowercase    :  Tuple=5 ,					__lowercase    :  List[str]=4 ,					__lowercase    :  Optional[Any]=37 ,					__lowercase    :  Tuple="gelu" ,					__lowercase    :  Any=0.1 ,					__lowercase    :  Optional[int]=0.1 ,					__lowercase    :  Tuple=10 ,					__lowercase    :  List[str]=0.02 ,					__lowercase    :  str=None ,					__lowercase    :  Any=2 ,					__lowercase    :  Optional[int]=2 ,					):






						'''simple docstring'''







						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        SCREAMING_SNAKE_CASE							(						self    :  int		):






						'''simple docstring'''







						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        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''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        SCREAMING_SNAKE_CASE							(						self    :  List[str] ,					__lowercase    :  int ,					__lowercase    :  Dict ,					__lowercase    :  Optional[Any]		):






						'''simple docstring'''







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





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.prepare_config_and_inputs()
						(
						    (
						    UpperCAmelCase_
						)						,	(
						    UpperCAmelCase_
						)						,	(
						    UpperCAmelCase_
						)						,	
						)								=     config_and_inputs
						UpperCAmelCase_								=     {"""input_values""": input_values}
						return config, inputs_dict







@require_torch
class   _UpperCamelCase  (       A_						,       A_						,       unittest.TestCase  ):







					'''simple docstring'''

					lowerCamelCase     :     Any			    =       (
					    (
					        ASTModel,
					        ASTForAudioClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					lowerCamelCase     :     Optional[Any]			    =       (
					    {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
					    if is_torch_available()
					    else {}
					)
					lowerCamelCase     :     Union[str, Any]			    =       False
					lowerCamelCase     :     Tuple			    =       False
					lowerCamelCase     :     List[str]			    =       False
					lowerCamelCase     :     List[Any]			    =       False





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any] ,					__lowercase    :  Union[str, Any] ,					__lowercase    :  List[str] ,					__lowercase    :  int ,					__lowercase    :  str ,					__lowercase    :  Dict		):






						'''simple docstring'''







						if pipeline_test_casse_name == "AudioClassificationPipelineTests":
							return True

						return False





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     ASTModelTester(self		)
						UpperCAmelCase_								=     ConfigTester(self ,					config_class=__lowercase ,					has_text_modality=__lowercase ,					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    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()

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





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							UpperCAmelCase_								=     model_class(__lowercase		)
							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] ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowercase		)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







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




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

	UpperCAmelCase_						,	UpperCAmelCase_								=     torchaudio.load(A   )

	return audio, sampling_rate







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







					'''simple docstring'''

					@cached_property
					def        SCREAMING_SNAKE_CASE							(						self    :  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'''







						UpperCAmelCase_								=     self.default_feature_extractor
						UpperCAmelCase_								=     ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""		).to(__lowercase		)

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

						# forward pass
						with torch.no_grad():
							UpperCAmelCase_								=     model(**__lowercase		)

						# verify the logits
						UpperCAmelCase_								=     torch.Size((1, 5_27)		)
						self.assertEqual(outputs.logits.shape ,					__lowercase		)

						UpperCAmelCase_								=     torch.tensor([-0.8760, -7.0042, -8.6602]		).to(__lowercase		)

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


