





import faiss  # 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 requests  # noqa: F401 # Here to have a nice missing dependency error message early on
import sklearn  # noqa: F401 # Here to have a nice missing dependency error message early on
import tqdm  # noqa: F401 # Here to have a nice missing dependency error message early on
from mauve import compute_mauve  # From: mauve-text

import datasets


UpperCamelCase__   : Any					  = """\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n  title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n  author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n  booktitle = {NeurIPS},\n  year      = {2021}\n}\n\n"""

UpperCamelCase__   : Optional[int]					  = """\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n"""

UpperCamelCase__   : List[Any]					  = """\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n    predictions: list of generated text to score. Each predictions\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\nOptional Args:\n    num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n    pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n    kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n    kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n    kmeans_max_iter: maximum number of k-means iterations. Default 500\n    featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n    device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n    max_text_length: maximum number of tokens to consider. Default 1024\n    divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n    mauve_scaling_factor: \"c\" from the paper. Default 5.\n    verbose: If True (default), print running time updates\n    seed: random seed to initialize k-means cluster assignments.\nReturns:\n    mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n    frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n    divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n    p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n    q_hist: same as above, but with q_text.\nExamples:\n\n    >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n    >>> import datasets\n    >>> mauve = datasets.load_metric(\'mauve\')\n    >>> predictions = [\"hello there\", \"general kenobi\"]\n    >>> references = [\"hello there\", \"general kenobi\"]\n    >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n    >>> print(out.mauve) # doctest: +SKIP\n    1.0\n"""







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







     '''simple docstring'''

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






      '''simple docstring'''







      return datasets.MetricInfo(
          description=_DESCRIPTION ,					citation=_CITATION ,					homepage="""https://github.com/krishnap25/mauve""" ,					inputs_description=_KWARGS_DESCRIPTION ,					features=datasets.Features(
              {
                  """predictions""": datasets.Value("""string""" ,					id="""sequence"""		),
                  """references""": datasets.Value("""string""" ,					id="""sequence"""		),
              }		) ,					codebase_urls=["""https://github.com/krishnap25/mauve"""] ,					reference_urls=[
              """https://arxiv.org/abs/2102.01454""",
              """https://github.com/krishnap25/mauve""",
          ] ,					)





     def        SCREAMING_SNAKE_CASE							(						self    :  str ,					__lowercase    :  Optional[Any] ,					__lowercase    :  Optional[Any] ,					__lowercase    :  List[str]=None ,					__lowercase    :  Union[str, Any]=None ,					__lowercase    :  List[Any]=None ,					__lowercase    :  List[Any]=None ,					__lowercase    :  Optional[int]="auto" ,					__lowercase    :  Dict=-1 ,					__lowercase    :  Tuple=0.9 ,					__lowercase    :  str=5 ,					__lowercase    :  Dict=5_00 ,					__lowercase    :  Optional[Any]="gpt2-large" ,					__lowercase    :  int=-1 ,					__lowercase    :  str=10_24 ,					__lowercase    :  List[Any]=25 ,					__lowercase    :  Optional[int]=5 ,					__lowercase    :  Any=True ,					__lowercase    :  List[str]=25 ,					):






      '''simple docstring'''







      UpperCAmelCase_								=     compute_mauve(
          p_text=lowerCAmelCase_ ,					q_text=lowerCAmelCase_ ,					p_features=lowerCAmelCase_ ,					q_features=lowerCAmelCase_ ,					p_tokens=lowerCAmelCase_ ,					q_tokens=lowerCAmelCase_ ,					num_buckets=lowerCAmelCase_ ,					pca_max_data=lowerCAmelCase_ ,					kmeans_explained_var=lowerCAmelCase_ ,					kmeans_num_redo=lowerCAmelCase_ ,					kmeans_max_iter=lowerCAmelCase_ ,					featurize_model_name=lowerCAmelCase_ ,					device_id=lowerCAmelCase_ ,					max_text_length=lowerCAmelCase_ ,					divergence_curve_discretization_size=lowerCAmelCase_ ,					mauve_scaling_factor=lowerCAmelCase_ ,					verbose=lowerCAmelCase_ ,					seed=lowerCAmelCase_ ,					)
      return out









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		)		)


