



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		,__lowerCamelCase		,__lowerCamelCase=13		,__lowerCamelCase=2		,__lowerCamelCase=24		,__lowerCamelCase=16		,__lowerCamelCase=True		,__lowerCamelCase=True		,__lowerCamelCase=32		,__lowerCamelCase=5		,__lowerCamelCase=4		,__lowerCamelCase=37		,__lowerCamelCase="gelu"		,__lowerCamelCase=0.1		,__lowerCamelCase=0.1		,__lowerCamelCase=10		,__lowerCamelCase=0.02		,__lowerCamelCase=None		,__lowerCamelCase=2		,__lowerCamelCase=2		,)					->      Dict:

						"""simple docstring"""






						lowerCAmelCase__					:    Tuple												=					parent
						lowerCAmelCase__					:    Union[str, Any]												=					batch_size
						lowerCAmelCase__					:    Tuple												=					patch_size
						lowerCAmelCase__					:    str												=					max_length
						lowerCAmelCase__					:    Union[str, Any]												=					num_mel_bins
						lowerCAmelCase__					:    Union[str, Any]												=					is_training
						lowerCAmelCase__					:    Union[str, Any]												=					use_labels
						lowerCAmelCase__					:    List[str]												=					hidden_size
						lowerCAmelCase__					:    List[Any]												=					num_hidden_layers
						lowerCAmelCase__					:    Dict												=					num_attention_heads
						lowerCAmelCase__					:    int												=					intermediate_size
						lowerCAmelCase__					:    Optional[int]												=					hidden_act
						lowerCAmelCase__					:    Optional[int]												=					hidden_dropout_prob
						lowerCAmelCase__					:    Tuple												=					attention_probs_dropout_prob
						lowerCAmelCase__					:    Optional[int]												=					type_sequence_label_size
						lowerCAmelCase__					:    Any												=					initializer_range
						lowerCAmelCase__					:    Optional[int]												=					scope
						lowerCAmelCase__					:    Union[str, Any]												=					frequency_stride
						lowerCAmelCase__					:    Union[str, Any]												=					time_stride

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



		def 		lowerCAmelCase__				(self			)					->      int:

						"""simple docstring"""






						lowerCAmelCase__					:    int												=					floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]			)

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

						lowerCAmelCase__					:    str												=					self.get_config()

						return config, input_values, labels



		def 		lowerCAmelCase__				(self			)					->      List[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=__lowerCamelCase		,initializer_range=self.initializer_range		,frequency_stride=self.frequency_stride		,time_stride=self.time_stride		,)



		def 		lowerCAmelCase__				(self		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase			)					->      Optional[int]:

						"""simple docstring"""






						lowerCAmelCase__					:    Union[str, Any]												=					ASTModel(config=__lowerCamelCase			)
						model.to(__lowerCamelCase			)
						model.eval()
						lowerCAmelCase__					:    Any												=					model(__lowerCamelCase			)
						self.parent.assertEqual(result.last_hidden_state.shape		,(self.batch_size, self.seq_length, self.hidden_size)			)



		def 		lowerCAmelCase__				(self			)					->      int:

						"""simple docstring"""






						lowerCAmelCase__					:    List[str]												=					self.prepare_config_and_inputs()
						(
						    (
						    lowerCAmelCase__
						)						,		(
						    lowerCAmelCase__
						)						,		(
						    lowerCAmelCase__
						)						,		
						)					:    Dict												=					config_and_inputs
						lowerCAmelCase__					:    List[Any]												=					{'''input_values''': input_values}
						return config, inputs_dict



@require_torch
class 	lowerCamelCase__      (							lowerCamelCase__				,    lowerCamelCase__				,    unittest.TestCase):




		'''simple docstring'''



		snake_case_     =(
		    (
		        ASTModel,
		        ASTForAudioClassification,
		    )
		    if is_torch_available()
		    else ()
		)
		snake_case_     =(
		    {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
		    if is_torch_available()
		    else {}
		)
		snake_case_     =False
		snake_case_     =False
		snake_case_     =False
		snake_case_     =False



		def 		lowerCAmelCase__				(self		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase			)					->      Optional[Any]:

						"""simple docstring"""






						if pipeline_test_casse_name == "AudioClassificationPipelineTests":
										return True

						return False



		def 		lowerCAmelCase__				(self			)					->      int:

						"""simple docstring"""






						lowerCAmelCase__					:    str												=					ASTModelTester(self			)
						lowerCAmelCase__					:    Tuple												=					ConfigTester(self		,config_class=__lowerCamelCase		,has_text_modality=__lowerCamelCase		,hidden_size=37			)



		def 		lowerCAmelCase__				(self			)					->      int:

						"""simple docstring"""






						self.config_tester.run_common_tests()



		@unittest.skip(reason='''AST does not use inputs_embeds'''			)
		def 		lowerCAmelCase__				(self			)					->      List[str]:

						"""simple docstring"""






						pass



		def 		lowerCAmelCase__				(self			)					->      Union[str, Any]:

						"""simple docstring"""






						lowerCAmelCase__						,		lowerCAmelCase__					:    int												=					self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										lowerCAmelCase__					:    Optional[Any]												=					model_class(__lowerCamelCase			)
										self.assertIsInstance(model.get_input_embeddings()		,(nn.Module)			)
										lowerCAmelCase__					:    Dict												=					model.get_output_embeddings()
										self.assertTrue(x is None or isinstance(__lowerCamelCase		,nn.Linear			)			)



		def 		lowerCAmelCase__				(self			)					->      Union[str, Any]:

						"""simple docstring"""






						lowerCAmelCase__						,		lowerCAmelCase__					:    Any												=					self.model_tester.prepare_config_and_inputs_for_common()

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

										lowerCAmelCase__					:    Optional[int]												=					['''input_values''']
										self.assertListEqual(arg_names[:1]		,__lowerCamelCase			)



		def 		lowerCAmelCase__				(self			)					->      Dict:

						"""simple docstring"""






						lowerCAmelCase__					:    Optional[int]												=					self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowerCamelCase			)



		@slow
		def 		lowerCAmelCase__				(self			)					->      Union[str, Any]:

						"""simple docstring"""






						for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowerCAmelCase__					:    Optional[int]												=					ASTModel.from_pretrained(__lowerCamelCase			)
										self.assertIsNotNone(__lowerCamelCase			)






def      lowerCAmelCase__		(   ):





				'''simple docstring'''

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

				lowerCAmelCase__						,		lowerCAmelCase__					:    int												=					torchaudio.load(lowerCamelCase_)

				return audio, sampling_rate



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




		'''simple docstring'''



		@cached_property
		def 		lowerCAmelCase__				(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 		lowerCAmelCase__				(self			)					->      Optional[int]:

						"""simple docstring"""






						lowerCAmelCase__					:    int												=					self.default_feature_extractor
						lowerCAmelCase__					:    List[str]												=					ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''			).to(__lowerCamelCase			)

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

						# forward pass
						with torch.no_grad():
										lowerCAmelCase__					:    str												=					model(**__lowerCamelCase			)

						# verify the logits
						lowerCAmelCase__					:    Union[str, Any]												=					torch.Size((1, 5_27)			)
						self.assertEqual(outputs.logits.shape		,__lowerCamelCase			)

						lowerCAmelCase__					:    List[str]												=					torch.tensor([-0.8760, -7.0042, -8.6602]			).to(__lowerCamelCase			)

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






import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer






def      lowerCAmelCase__		(   lowerCamelCase_		:		int	,lowerCamelCase_		:		Optional[Any]	,lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Any=True	,lowerCamelCase_		:		Tuple="pt"):





				'''simple docstring'''

				lowerCAmelCase__					:    Tuple												=					{'''add_prefix_space''': True} if isinstance(lowerCamelCase_	,lowerCamelCase_) and not line.startswith(''' ''') else {}
				lowerCAmelCase__					:    Union[str, Any]												=					padding_side
				return tokenizer(
				    [line]	,max_length=lowerCamelCase_	,padding='''max_length''' if pad_to_max_length else None	,truncation=lowerCamelCase_	,return_tensors=lowerCamelCase_	,add_special_tokens=lowerCamelCase_	,**lowerCamelCase_	,)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Dict	,lowerCamelCase_		:		Any=None	,):





				'''simple docstring'''

				lowerCAmelCase__					:    List[Any]												=					input_ids.ne(lowerCamelCase_).any(dim=0)
				if attention_mask is None:
								return input_ids[:, keep_column_mask]
				else:
								return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		def __init__(self		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase="train"		,__lowerCamelCase=None		,__lowerCamelCase=None		,__lowerCamelCase=None		,__lowerCamelCase=""		,)					->      List[str]:

						"""simple docstring"""






						super().__init__()
						lowerCAmelCase__					:    str												=					Path(__lowerCamelCase			).joinpath(type_path + '''.source'''			)
						lowerCAmelCase__					:    int												=					Path(__lowerCamelCase			).joinpath(type_path + '''.target'''			)
						lowerCAmelCase__					:    Tuple												=					self.get_char_lens(self.src_file			)
						lowerCAmelCase__					:    Dict												=					max_source_length
						lowerCAmelCase__					:    Optional[int]												=					max_target_length
						assert min(self.src_lens			) > 0, f"""found empty line in {self.src_file}"""
						lowerCAmelCase__					:    Tuple												=					tokenizer
						lowerCAmelCase__					:    List[Any]												=					prefix
						if n_obs is not None:
										lowerCAmelCase__					:    Optional[Any]												=					self.src_lens[:n_obs]
						lowerCAmelCase__					:    Any												=					src_lang
						lowerCAmelCase__					:    Optional[Any]												=					tgt_lang



		def __len__(self			)					->      str:

						"""simple docstring"""






						return len(self.src_lens			)



		def __getitem__(self		,__lowerCamelCase			)					->      Dict[str, torch.Tensor]:

						"""simple docstring"""






						lowerCAmelCase__					:    List[Any]												=					index + 1  # linecache starts at 1
						lowerCAmelCase__					:    Any												=					self.prefix + linecache.getline(str(self.src_file			)		,__lowerCamelCase			).rstrip('''\n'''			)
						lowerCAmelCase__					:    Any												=					linecache.getline(str(self.tgt_file			)		,__lowerCamelCase			).rstrip('''\n'''			)
						assert source_line, f"""empty source line for index {index}"""
						assert tgt_line, f"""empty tgt line for index {index}"""

						# Need to add eos token manually for T5
						if isinstance(self.tokenizer		,__lowerCamelCase			):
										source_line += self.tokenizer.eos_token
										tgt_line += self.tokenizer.eos_token

						# Pad source and target to the right
						lowerCAmelCase__					:    List[str]												=					(
						    self.tokenizer.question_encoder if isinstance(self.tokenizer		,__lowerCamelCase			) else self.tokenizer
						)
						lowerCAmelCase__					:    Dict												=					self.tokenizer.generator if isinstance(self.tokenizer		,__lowerCamelCase			) else self.tokenizer

						lowerCAmelCase__					:    Union[str, Any]												=					encode_line(__lowerCamelCase		,__lowerCamelCase		,self.max_source_length		,'''right'''			)
						lowerCAmelCase__					:    Any												=					encode_line(__lowerCamelCase		,__lowerCamelCase		,self.max_target_length		,'''right'''			)

						lowerCAmelCase__					:    List[str]												=					source_inputs['''input_ids'''].squeeze()
						lowerCAmelCase__					:    str												=					target_inputs['''input_ids'''].squeeze()
						lowerCAmelCase__					:    Tuple												=					source_inputs['''attention_mask'''].squeeze()
						return {
						    "input_ids": source_ids,
						    "attention_mask": src_mask,
						    "decoder_input_ids": target_ids,
						}



		@staticmethod
		def 		lowerCAmelCase__				(__lowerCamelCase			)					->      List[str]:

						"""simple docstring"""






						return [len(__lowerCamelCase			) for x in Path(__lowerCamelCase			).open().readlines()]



		def 		lowerCAmelCase__				(self		,__lowerCamelCase			)					->      Dict[str, torch.Tensor]:

						"""simple docstring"""






						lowerCAmelCase__					:    Union[str, Any]												=					torch.stack([x['''input_ids'''] for x in batch]			)
						lowerCAmelCase__					:    Union[str, Any]												=					torch.stack([x['''attention_mask'''] for x in batch]			)
						lowerCAmelCase__					:    List[Any]												=					torch.stack([x['''decoder_input_ids'''] for x in batch]			)
						lowerCAmelCase__					:    Any												=					(
						    self.tokenizer.generator.pad_token_id
						    if isinstance(self.tokenizer		,__lowerCamelCase			)
						    else self.tokenizer.pad_token_id
						)
						lowerCAmelCase__					:    Tuple												=					(
						    self.tokenizer.question_encoder.pad_token_id
						    if isinstance(self.tokenizer		,__lowerCamelCase			)
						    else self.tokenizer.pad_token_id
						)
						lowerCAmelCase__					:    Dict												=					trim_batch(__lowerCamelCase		,__lowerCamelCase			)
						lowerCAmelCase__						,		lowerCAmelCase__					:    Union[str, Any]												=					trim_batch(__lowerCamelCase		,__lowerCamelCase		,attention_mask=__lowerCamelCase			)
						lowerCAmelCase__					:    Union[str, Any]												=					{
						    '''input_ids''': source_ids,
						    '''attention_mask''': source_mask,
						    '''decoder_input_ids''': y,
						}
						return batch


__snake_case    :		Any  =getLogger(__name__)






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[List]):





				'''simple docstring'''

				return list(itertools.chain.from_iterable(lowerCamelCase_))






def      lowerCAmelCase__		(   lowerCamelCase_		:		str):





				'''simple docstring'''

				lowerCAmelCase__					:    int												=					get_git_info()
				save_json(lowerCamelCase_	,os.path.join(lowerCamelCase_	,'''git_log.json'''))






def      lowerCAmelCase__		(   lowerCamelCase_		:		Tuple	,lowerCamelCase_		:		Union[str, Any]	,lowerCamelCase_		:		Tuple=4	,**lowerCamelCase_		:		List[str]):





				'''simple docstring'''

				with open(lowerCamelCase_	,'''w''') as f:
								json.dump(lowerCamelCase_	,lowerCamelCase_	,indent=lowerCamelCase_	,**lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Tuple):





				'''simple docstring'''

				with open(lowerCamelCase_) as f:
								return json.load(lowerCamelCase_)






def      lowerCAmelCase__		(   ):





				'''simple docstring'''

				lowerCAmelCase__					:    str												=					git.Repo(search_parent_directories=lowerCamelCase_)
				lowerCAmelCase__					:    List[Any]												=					{
				    '''repo_id''': str(lowerCamelCase_),
				    '''repo_sha''': str(repo.head.object.hexsha),
				    '''repo_branch''': str(repo.active_branch),
				    '''hostname''': str(socket.gethostname()),
				}
				return repo_infos






def      lowerCAmelCase__		(   lowerCamelCase_		:		Callable	,lowerCamelCase_		:		Iterable):





				'''simple docstring'''

				return list(map(lowerCamelCase_	,lowerCamelCase_))






def      lowerCAmelCase__		(   lowerCamelCase_		:		Any	,lowerCamelCase_		:		Optional[Any]):





				'''simple docstring'''

				with open(lowerCamelCase_	,'''wb''') as f:
								return pickle.dump(lowerCamelCase_	,lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		int):





				'''simple docstring'''

				def remove_articles(lowerCamelCase_		:		List[str]):
								return re.sub(r'''\b(a|an|the)\b'''	,''' '''	,lowerCamelCase_)

				def white_space_fix(lowerCamelCase_		:		Optional[int]):
								return " ".join(text.split())

				def remove_punc(lowerCamelCase_		:		List[str]):
								lowerCAmelCase__					:    List[Any]												=					set(string.punctuation)
								return "".join(ch for ch in text if ch not in exclude)

				def lower(lowerCamelCase_		:		Optional[int]):
								return text.lower()

				return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_))))






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[Any]	,lowerCamelCase_		:		Optional[int]):





				'''simple docstring'''

				lowerCAmelCase__					:    Optional[Any]												=					normalize_answer(lowerCamelCase_).split()
				lowerCAmelCase__					:    str												=					normalize_answer(lowerCamelCase_).split()
				lowerCAmelCase__					:    str												=					Counter(lowerCamelCase_) & Counter(lowerCamelCase_)
				lowerCAmelCase__					:    Dict												=					sum(common.values())
				if num_same == 0:
								return 0
				lowerCAmelCase__					:    Optional[int]												=					1.0 * num_same / len(lowerCamelCase_)
				lowerCAmelCase__					:    Optional[Any]												=					1.0 * num_same / len(lowerCamelCase_)
				lowerCAmelCase__					:    Optional[Any]												=					(2 * precision * recall) / (precision + recall)
				return fa






def      lowerCAmelCase__		(   lowerCamelCase_		:		Union[str, Any]	,lowerCamelCase_		:		Any):





				'''simple docstring'''

				return normalize_answer(lowerCamelCase_) == normalize_answer(lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[str]	,lowerCamelCase_		:		List[str]):





				'''simple docstring'''

				assert len(lowerCamelCase_) == len(lowerCamelCase_)
				lowerCAmelCase__					:    List[str]												=					0
				for hypo, pred in zip(lowerCamelCase_	,lowerCamelCase_):
								em += exact_match_score(lowerCamelCase_	,lowerCamelCase_)
				if len(lowerCamelCase_) > 0:
								em /= len(lowerCamelCase_)
				return {"em": em}






def      lowerCAmelCase__		(   lowerCamelCase_		:		int):





				'''simple docstring'''

				return model_prefix.startswith('''rag''')






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[str]	,lowerCamelCase_		:		Dict	,lowerCamelCase_		:		str):





				'''simple docstring'''

				lowerCAmelCase__					:    Any												=					{p: p for p in extra_params}
				# T5 models don't have `dropout` param, they have `dropout_rate` instead
				lowerCAmelCase__					:    Optional[int]												=					'''dropout_rate'''
				for p in extra_params:
								if getattr(lowerCamelCase_	,lowerCamelCase_	,lowerCamelCase_):
												if not hasattr(lowerCamelCase_	,lowerCamelCase_) and not hasattr(lowerCamelCase_	,equivalent_param[p]):
																logger.info('''config doesn\'t have a `{}` attribute'''.format(lowerCamelCase_))
																delattr(lowerCamelCase_	,lowerCamelCase_)
																continue
												lowerCAmelCase__					:    Dict												=					p if hasattr(lowerCamelCase_	,lowerCamelCase_) else equivalent_param[p]
												setattr(lowerCamelCase_	,lowerCamelCase_	,getattr(lowerCamelCase_	,lowerCamelCase_))
												delattr(lowerCamelCase_	,lowerCamelCase_)
				return hparams, config

