






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


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

'''

_a      	=  '''\
MAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.

MAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.

For details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).

This metrics is a wrapper around the official implementation of MAUVE:
https://github.com/krishnap25/mauve
'''

_a      	=  '''
Calculates MAUVE scores between two lists of generated text and reference text.
Args:
    predictions: list of generated text to score. Each predictions
        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.
Optional Args:
    num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer
    pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1
    kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9
    kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5
    kmeans_max_iter: maximum number of k-means iterations. Default 500
    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\'].
    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
    max_text_length: maximum number of tokens to consider. Default 1024
    divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25
    mauve_scaling_factor: "c" from the paper. Default 5.
    verbose: If True (default), print running time updates
    seed: random seed to initialize k-means cluster assignments.
Returns:
    mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,
    frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,
    divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,
    p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,
    q_hist: same as above, but with q_text.
Examples:

    >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest
    >>> import datasets
    >>> mauve = datasets.load_metric(\'mauve\')
    >>> predictions = ["hello there", "general kenobi"]
    >>> references = ["hello there", "general kenobi"]
    >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP
    >>> print(out.mauve) # doctest: +SKIP
    1.0
'''





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





	"""simple docstring"""






	def        UpperCamelCase    (							self    ):
							"""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        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase=None       ,    UpperCAmelCase=None       ,    UpperCAmelCase=None       ,    UpperCAmelCase=None       ,    UpperCAmelCase="auto"       ,    UpperCAmelCase=-1       ,    UpperCAmelCase=0.9       ,    UpperCAmelCase=5       ,    UpperCAmelCase=500       ,    UpperCAmelCase="gpt2-large"       ,    UpperCAmelCase=-1       ,    UpperCAmelCase=1024       ,    UpperCAmelCase=25       ,    UpperCAmelCase=5       ,    UpperCAmelCase=True       ,    UpperCAmelCase=25       ,    ):
							"""simple docstring"""







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








import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
_a      	=  {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}





@is_pipeline_test
class __lowerCamelCase (      unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__								=      MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
	UpperCamelCase__								=      TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

	if model_mapping is not None:
		UpperCamelCase__								=      {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
	if tf_model_mapping is not None:
		UpperCamelCase__								=      {
		    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
		}

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			ZeroShotClassificationPipeline(
							    model=UpperCAmelCase       ,    tokenizer=UpperCAmelCase       ,    candidate_labels=['polics', 'health']    )
							return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]

	def        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			classifier('Who are you voting for in 2020?'       ,    candidate_labels='politics'    )
							self.assertEqual(UpperCAmelCase       ,    {'sequence': ANY(UpperCAmelCase    ), 'labels': [ANY(UpperCAmelCase    )], 'scores': [ANY(UpperCAmelCase    )]}    )

							# No kwarg
							_UpperCAmelCase									=			classifier('Who are you voting for in 2020?'       ,    ['politics']    )
							self.assertEqual(UpperCAmelCase       ,    {'sequence': ANY(UpperCAmelCase    ), 'labels': [ANY(UpperCAmelCase    )], 'scores': [ANY(UpperCAmelCase    )]}    )

							_UpperCAmelCase									=			classifier('Who are you voting for in 2020?'       ,    candidate_labels=['politics']    )
							self.assertEqual(UpperCAmelCase       ,    {'sequence': ANY(UpperCAmelCase    ), 'labels': [ANY(UpperCAmelCase    )], 'scores': [ANY(UpperCAmelCase    )]}    )

							_UpperCAmelCase									=			classifier('Who are you voting for in 2020?'       ,    candidate_labels='politics, public health'    )
							self.assertEqual(
							    UpperCAmelCase       ,    {'sequence': ANY(UpperCAmelCase    ), 'labels': [ANY(UpperCAmelCase    ), ANY(UpperCAmelCase    )], 'scores': [ANY(UpperCAmelCase    ), ANY(UpperCAmelCase    )]}    )
							self.assertAlmostEqual(sum(nested_simplify(outputs['scores']    )    )       ,    1.0    )

							_UpperCAmelCase									=			classifier('Who are you voting for in 2020?'       ,    candidate_labels=['politics', 'public health']    )
							self.assertEqual(
							    UpperCAmelCase       ,    {'sequence': ANY(UpperCAmelCase    ), 'labels': [ANY(UpperCAmelCase    ), ANY(UpperCAmelCase    )], 'scores': [ANY(UpperCAmelCase    ), ANY(UpperCAmelCase    )]}    )
							self.assertAlmostEqual(sum(nested_simplify(outputs['scores']    )    )       ,    1.0    )

							_UpperCAmelCase									=			classifier(
							    'Who are you voting for in 2020?'       ,    candidate_labels='politics'       ,    hypothesis_template='This text is about {}'    )
							self.assertEqual(UpperCAmelCase       ,    {'sequence': ANY(UpperCAmelCase    ), 'labels': [ANY(UpperCAmelCase    )], 'scores': [ANY(UpperCAmelCase    )]}    )

							# https://github.com/huggingface/transformers/issues/13846
							_UpperCAmelCase									=			classifier(['I am happy']       ,    ['positive', 'negative']    )
							self.assertEqual(
							    UpperCAmelCase       ,    [
							        {'sequence': ANY(UpperCAmelCase    ), 'labels': [ANY(UpperCAmelCase    ), ANY(UpperCAmelCase    )], 'scores': [ANY(UpperCAmelCase    ), ANY(UpperCAmelCase    )]}
							        for i in range(1    )
							    ]       ,    )
							_UpperCAmelCase									=			classifier(['I am happy', 'I am sad']       ,    ['positive', 'negative']    )
							self.assertEqual(
							    UpperCAmelCase       ,    [
							        {'sequence': ANY(UpperCAmelCase    ), 'labels': [ANY(UpperCAmelCase    ), ANY(UpperCAmelCase    )], 'scores': [ANY(UpperCAmelCase    ), ANY(UpperCAmelCase    )]}
							        for i in range(2    )
							    ]       ,    )

							with self.assertRaises(UpperCAmelCase    ):
													classifier(''       ,    candidate_labels='politics'    )

							with self.assertRaises(UpperCAmelCase    ):
													classifier(UpperCAmelCase       ,    candidate_labels='politics'    )

							with self.assertRaises(UpperCAmelCase    ):
													classifier('Who are you voting for in 2020?'       ,    candidate_labels=''    )

							with self.assertRaises(UpperCAmelCase    ):
													classifier('Who are you voting for in 2020?'       ,    candidate_labels=UpperCAmelCase    )

							with self.assertRaises(UpperCAmelCase    ):
													classifier(
													    'Who are you voting for in 2020?'       ,    candidate_labels='politics'       ,    hypothesis_template='Not formatting template'       ,    )

							with self.assertRaises(UpperCAmelCase    ):
													classifier(
													    'Who are you voting for in 2020?'       ,    candidate_labels='politics'       ,    hypothesis_template=UpperCAmelCase       ,    )

							self.run_entailment_id(UpperCAmelCase    )

	def        UpperCamelCase    (							self       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			zero_shot_classifier.model.config
							_UpperCAmelCase									=			config.labelaid
							_UpperCAmelCase									=			zero_shot_classifier.entailment_id

							_UpperCAmelCase									=			{'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2}
							self.assertEqual(zero_shot_classifier.entailment_id       ,    -1    )

							_UpperCAmelCase									=			{'entailment': 0, 'neutral': 1, 'contradiction': 2}
							self.assertEqual(zero_shot_classifier.entailment_id       ,    0    )

							_UpperCAmelCase									=			{'ENTAIL': 0, 'NON-ENTAIL': 1}
							self.assertEqual(zero_shot_classifier.entailment_id       ,    0    )

							_UpperCAmelCase									=			{'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0}
							self.assertEqual(zero_shot_classifier.entailment_id       ,    2    )

							_UpperCAmelCase									=			original_labelaid
							self.assertEqual(UpperCAmelCase       ,    zero_shot_classifier.entailment_id    )

	@require_torch
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			pipeline(
							    'zero-shot-classification'       ,    model='sshleifer/tiny-distilbert-base-cased-distilled-squad'       ,    framework='pt'       ,    )
							# There was a regression in 4.10 for this
							# Adding a test so we don't make the mistake again.
							# https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
							zero_shot_classifier(
							    'Who are you voting for in 2020?' * 100       ,    candidate_labels=['politics', 'public health', 'science']    )

	@require_torch
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			pipeline(
							    'zero-shot-classification'       ,    model='sshleifer/tiny-distilbert-base-cased-distilled-squad'       ,    framework='pt'       ,    )
							_UpperCAmelCase									=			zero_shot_classifier(
							    'Who are you voting for in 2020?'       ,    candidate_labels=['politics', 'public health', 'science']    )

							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        'sequence': 'Who are you voting for in 2020?',
							        'labels': ['science', 'public health', 'politics'],
							        'scores': [0.3_33, 0.3_33, 0.3_33],
							    }       ,    )

	@require_tf
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			pipeline(
							    'zero-shot-classification'       ,    model='sshleifer/tiny-distilbert-base-cased-distilled-squad'       ,    framework='tf'       ,    )
							_UpperCAmelCase									=			zero_shot_classifier(
							    'Who are you voting for in 2020?'       ,    candidate_labels=['politics', 'public health', 'science']    )

							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        'sequence': 'Who are you voting for in 2020?',
							        'labels': ['science', 'public health', 'politics'],
							        'scores': [0.3_33, 0.3_33, 0.3_33],
							    }       ,    )

	@slow
	@require_torch
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			pipeline('zero-shot-classification'       ,    model='roberta-large-mnli'       ,    framework='pt'    )
							_UpperCAmelCase									=			zero_shot_classifier(
							    'Who are you voting for in 2020?'       ,    candidate_labels=['politics', 'public health', 'science']    )

							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        'sequence': 'Who are you voting for in 2020?',
							        'labels': ['politics', 'public health', 'science'],
							        'scores': [0.9_76, 0.0_15, 0.0_09],
							    }       ,    )
							_UpperCAmelCase									=			zero_shot_classifier(
							    'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'
							    ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'
							    ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'
							    ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'
							    ' machine translation tasks show these models to be superior in quality while being more parallelizable'
							    ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'
							    ' English-to-German translation task, improving over the existing best results, including ensembles by'
							    ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'
							    ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'
							    ' fraction of the training costs of the best models from the literature. We show that the Transformer'
							    ' generalizes well to other tasks by applying it successfully to English constituency parsing both with'
							    ' large and limited training data.'       ,    candidate_labels=['machine learning', 'statistics', 'translation', 'vision']       ,    multi_label=UpperCAmelCase       ,    )
							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        'sequence': (
							            'The dominant sequence transduction models are based on complex recurrent or convolutional neural'
							            ' networks in an encoder-decoder configuration. The best performing models also connect the'
							            ' encoder and decoder through an attention mechanism. We propose a new simple network'
							            ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'
							            ' and convolutions entirely. Experiments on two machine translation tasks show these models to be'
							            ' superior in quality while being more parallelizable and requiring significantly less time to'
							            ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'
							            ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'
							            ' English-to-French translation task, our model establishes a new single-model state-of-the-art'
							            ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'
							            ' costs of the best models from the literature. We show that the Transformer generalizes well to'
							            ' other tasks by applying it successfully to English constituency parsing both with large and'
							            ' limited training data.'
							        ),
							        'labels': ['translation', 'machine learning', 'vision', 'statistics'],
							        'scores': [0.8_17, 0.7_13, 0.0_18, 0.0_18],
							    }       ,    )

	@slow
	@require_tf
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			pipeline('zero-shot-classification'       ,    model='roberta-large-mnli'       ,    framework='tf'    )
							_UpperCAmelCase									=			zero_shot_classifier(
							    'Who are you voting for in 2020?'       ,    candidate_labels=['politics', 'public health', 'science']    )

							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        'sequence': 'Who are you voting for in 2020?',
							        'labels': ['politics', 'public health', 'science'],
							        'scores': [0.9_76, 0.0_15, 0.0_09],
							    }       ,    )
							_UpperCAmelCase									=			zero_shot_classifier(
							    'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks'
							    ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder'
							    ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based'
							    ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two'
							    ' machine translation tasks show these models to be superior in quality while being more parallelizable'
							    ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014'
							    ' English-to-German translation task, improving over the existing best results, including ensembles by'
							    ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new'
							    ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small'
							    ' fraction of the training costs of the best models from the literature. We show that the Transformer'
							    ' generalizes well to other tasks by applying it successfully to English constituency parsing both with'
							    ' large and limited training data.'       ,    candidate_labels=['machine learning', 'statistics', 'translation', 'vision']       ,    multi_label=UpperCAmelCase       ,    )
							self.assertEqual(
							    nested_simplify(UpperCAmelCase    )       ,    {
							        'sequence': (
							            'The dominant sequence transduction models are based on complex recurrent or convolutional neural'
							            ' networks in an encoder-decoder configuration. The best performing models also connect the'
							            ' encoder and decoder through an attention mechanism. We propose a new simple network'
							            ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence'
							            ' and convolutions entirely. Experiments on two machine translation tasks show these models to be'
							            ' superior in quality while being more parallelizable and requiring significantly less time to'
							            ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,'
							            ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014'
							            ' English-to-French translation task, our model establishes a new single-model state-of-the-art'
							            ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training'
							            ' costs of the best models from the literature. We show that the Transformer generalizes well to'
							            ' other tasks by applying it successfully to English constituency parsing both with large and'
							            ' limited training data.'
							        ),
							        'labels': ['translation', 'machine learning', 'vision', 'statistics'],
							        'scores': [0.8_17, 0.7_13, 0.0_18, 0.0_18],
							    }       ,    )
