





"""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 						__snake_case   :





 """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.0_2   ,		__lowerCamelCase=None   ,		__lowerCamelCase=2   ,		__lowerCamelCase=2   ,		):



     '''simple docstring'''




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

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

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Tuple							=	floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]    )

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

     __A       :		str							=	self.get_config()

     return config, input_values, labels

 def    UpperCamelCase__(       self    ):



     '''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    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    ):



     '''simple docstring'''




     __A       :		str							=	ASTModel(config=__lowerCamelCase    )
     model.to(__lowerCamelCase    )
     model.eval()
     __A       :		str							=	model(__lowerCamelCase    )
     self.parent.assertEqual(result.last_hidden_state.shape   ,		(self.batch_size, self.seq_length, self.hidden_size)    )







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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






@require_torch
class 						__snake_case   (						SCREAMING_SNAKE_CASE__				,				SCREAMING_SNAKE_CASE__				,				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    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase    ):



     '''simple docstring'''




     if pipeline_test_casse_name == "AudioClassificationPipelineTests":
         return True

     return False

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		int							=	ASTModelTester(self    )
     __A       :		List[Any]							=	ConfigTester(self   ,		config_class=__lowerCamelCase   ,		has_text_modality=__lowerCamelCase   ,		hidden_size=37    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     self.config_tester.run_common_tests()

 @unittest.skip(reason='''AST does not use inputs_embeds'''    )
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     pass

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A					,			__A       :		Dict							=	self.model_tester.prepare_config_and_inputs_for_common()

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

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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

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

         __A       :		Dict							=	['''input_values''']
         self.assertListEqual(arg_names[:1]   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Optional[Any]							=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__lowerCamelCase    )







 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         __A       :		List[str]							=	ASTModel.from_pretrained(__lowerCamelCase    )
         self.assertIsNotNone(__lowerCamelCase    )







def 						__lowercase	(  )  ->Dict:



    '''simple docstring'''







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

    __A					,			__A       :		List[str]							=	torchaudio.load(snake_case_		)

    return audio, sampling_rate






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





 """simple docstring"""


 @cached_property
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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







 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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

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

     # forward pass
     with torch.no_grad():
         __A       :		Optional[int]							=	model(**__lowerCamelCase    )

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

     __A       :		str							=	torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]    ).to(__lowerCamelCase    )

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











"""simple docstring"""



import absl  # noqa: F401 # Here to have a nice missing dependency error message early on
import nltk  # noqa: F401 # Here to have a nice missing dependency error message early on
import numpy  # noqa: F401 # Here to have a nice missing dependency error message early on
import six  # noqa: F401 # Here to have a nice missing dependency error message early on
from rouge_score import rouge_scorer, scoring

import datasets


a_					=     """\
@inproceedings{lin-2004-rouge,
    title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",
    author = \"Lin, Chin-Yew\",
    booktitle = \"Text Summarization Branches Out\",
    month = jul,
    year = \"2004\",
    address = \"Barcelona, Spain\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W04-1013\",
    pages = \"74--81\",
}
"""

a_					=     """\
ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for
evaluating automatic summarization and machine translation software in natural language processing.
The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.

Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.

This metrics is a wrapper around Google Research reimplementation of ROUGE:
https://github.com/google-research/google-research/tree/master/rouge
"""

a_					=     """
Calculates average rouge scores for a list of hypotheses and references
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    rouge_types: A list of rouge types to calculate.
        Valid names:
        `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,
        `\"rougeL\"`: Longest common subsequence based scoring.
        `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.
        See details in https://github.com/huggingface/datasets/issues/617
    use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.
    use_aggregator: Return aggregates if this is set to True
Returns:
    rouge1: rouge_1 (precision, recall, f1),
    rouge2: rouge_2 (precision, recall, f1),
    rougeL: rouge_l (precision, recall, f1),
    rougeLsum: rouge_lsum (precision, recall, f1)
Examples:

    >>> rouge = datasets.load_metric('rouge')
    >>> predictions = [\"hello there\", \"general kenobi\"]
    >>> references = [\"hello there\", \"general kenobi\"]
    >>> results = rouge.compute(predictions=predictions, references=references)
    >>> print(list(results.keys()))
    ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']
    >>> print(results[\"rouge1\"])
    AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))
    >>> print(results[\"rouge1\"].mid.fmeasure)
    1.0
"""






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,				_KWARGS_DESCRIPTION	)
class 						__snake_case   (						datasets.Metric	):





 """simple docstring"""


 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return datasets.MetricInfo(
         description=_DESCRIPTION   ,		citation=_CITATION   ,		inputs_description=_KWARGS_DESCRIPTION   ,		features=datasets.Features(
             {
                 '''predictions''': datasets.Value('''string'''   ,		id='''sequence'''    ),
                 '''references''': datasets.Value('''string'''   ,		id='''sequence'''    ),
             }    )   ,		codebase_urls=['''https://github.com/google-research/google-research/tree/master/rouge''']   ,		reference_urls=[
             '''https://en.wikipedia.org/wiki/ROUGE_(metric)''',
             '''https://github.com/google-research/google-research/tree/master/rouge''',
         ]   ,		)







 def    UpperCamelCase__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase   ,		__lowerCamelCase=None   ,		__lowerCamelCase=True   ,		__lowerCamelCase=False    ):



     '''simple docstring'''




     if rouge_types is None:
         __A       :		Dict							=	['''rouge1''', '''rouge2''', '''rougeL''', '''rougeLsum''']

     __A       :		Dict							=	rouge_scorer.RougeScorer(rouge_types=__lowerCamelCase   ,		use_stemmer=__lowerCamelCase    )
     if use_aggregator:
         __A       :		Dict							=	scoring.BootstrapAggregator()
     else:
         __A       :		Optional[Any]							=	[]

     for ref, pred in zip(__lowerCamelCase   ,		__lowerCamelCase    ):
         __A       :		List[Any]							=	scorer.score(__lowerCamelCase   ,		__lowerCamelCase    )
         if use_aggregator:
             aggregator.add_scores(__lowerCamelCase    )
         else:
             scores.append(__lowerCamelCase    )

     if use_aggregator:
         __A       :		Optional[Any]							=	aggregator.aggregate()
     else:
         __A       :		List[Any]							=	{}
         for key in scores[0]:
             __A       :		Tuple							=	[score[key] for score in scores]

     return result




