



from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor



class      _UpperCAmelCase      :




     def __init__(					self			,    a__			,    a__=3			,    a__=3_2			,    a__=3			,    a__=1_0			,    a__=[1_0, 2_0, 3_0, 4_0]			,    a__=[1, 1, 2, 1]			,    a__=True			,    a__=True			,    a__="relu"			,    a__=3			,    a__=None			,    ):
         A__					=       parent
         A__					=       batch_size
         A__					=       image_size
         A__					=       num_channels
         A__					=       embeddings_size
         A__					=       hidden_sizes
         A__					=       depths
         A__					=       is_training
         A__					=       use_labels
         A__					=       hidden_act
         A__					=       num_labels
         A__					=       scope
         A__					=       len(a__)




     def 		snake_case_		(					self):
         A__					=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

         A__					=       None
         if self.use_labels:
             A__					=       ids_tensor([self.batch_size]			,    self.num_labels)

         A__					=       self.get_config()
         return config, pixel_values, labels




     def 		snake_case_		(					self):
         return RegNetConfig(
             num_channels=self.num_channels			,    embeddings_size=self.embeddings_size			,    hidden_sizes=self.hidden_sizes			,    depths=self.depths			,    hidden_act=self.hidden_act			,    num_labels=self.num_labels			,    )




     def 		snake_case_		(					self			,    a__			,    a__			,    a__):
         A__					=       TFRegNetModel(config=a__)
         A__					=       model(a__			,    training=a__)
         # expected last hidden states: B, C, H // 32, W // 32
         self.parent.assertEqual(
             result.last_hidden_state.shape			,    (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)			,    )




     def 		snake_case_		(					self			,    a__			,    a__			,    a__):
         A__					=       self.num_labels
         A__					=       TFRegNetForImageClassification(a__)
         A__					=       model(a__			,    labels=a__			,    training=a__)
         self.parent.assertEqual(result.logits.shape			,    (self.batch_size, self.num_labels))




     def 		snake_case_		(					self):
         A__					=       self.prepare_config_and_inputs()
         A__			,						A__			,						A__					=       config_and_inputs
         A__					=       {'''pixel_values''': pixel_values}
         return config, inputs_dict







@require_tf
class      _UpperCAmelCase      (							A__      ,   A__      ,   unittest.TestCase  ):
     UpperCamelCase__		     =					(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
     UpperCamelCase__		     =					(
         {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
         if is_tf_available()
         else {}
     )

     UpperCamelCase__		     =					False
     UpperCamelCase__		     =					False
     UpperCamelCase__		     =					False
     UpperCamelCase__		     =					False
     UpperCamelCase__		     =					False




     def 		snake_case_		(					self):
         A__					=       TFRegNetModelTester(self)
         A__					=       ConfigTester(self			,    config_class=a__			,    has_text_modality=a__)




     def 		snake_case_		(					self):
         return




     @unittest.skip(reason='''RegNet does not use inputs_embeds''')
     def 		snake_case_		(					self):
         pass




     @unittest.skipIf(
         not is_tf_available() or len(tf.config.list_physical_devices('''GPU''')) == 0			,    reason='''TF does not support backprop for grouped convolutions on CPU.'''			,    )
     @slow
     def 		snake_case_		(					self):
         super().test_keras_fit()




     @unittest.skip(reason='''RegNet does not support input and output embeddings''')
     def 		snake_case_		(					self):
         pass




     def 		snake_case_		(					self):
         A__			,						A__					=       self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             A__					=       model_class(a__)
             A__					=       inspect.signature(model.call)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             A__					=       [*signature.parameters.keys()]

             A__					=       ['''pixel_values''']
             self.assertListEqual(arg_names[:1]			,    a__)




     def 		snake_case_		(					self):
         A__					=       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a__)




     def 		snake_case_		(					self):
         def check_hidden_states_output(a__			,    a__			,    a__):
             A__					=       model_class(a__)
             A__					=       model(**self._prepare_for_class(a__			,    a__)			,    training=a__)

             A__					=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             A__					=       self.model_tester.num_stages
             self.assertEqual(len(a__)			,    expected_num_stages + 1)

             # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
             self.assertListEqual(
                 list(hidden_states[0].shape[-2:])			,    [self.model_tester.image_size // 2, self.model_tester.image_size // 2]			,    )

         A__			,						A__					=       self.model_tester.prepare_config_and_inputs_for_common()
         A__					=       ['''basic''', '''bottleneck''']
         for model_class in self.all_model_classes:
             for layer_type in layers_type:
                 A__					=       layer_type
                 A__					=       True
                 check_hidden_states_output(a__			,    a__			,    a__)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 A__					=       True

                 check_hidden_states_output(a__			,    a__			,    a__)




     def 		snake_case_		(					self):
         A__			,						A__					=       self.model_tester.prepare_config_and_inputs_for_common()

         def check_equivalence(a__			,    a__			,    a__			,    a__={}):
             A__					=       model(a__			,    return_dict=a__			,    **a__)
             A__					=       model(a__			,    return_dict=a__			,    **a__).to_tuple()

             def recursive_check(a__			,    a__):
                 if isinstance(a__			,    (List, Tuple)):
                     for tuple_iterable_value, dict_iterable_value in zip(a__			,    a__):
                         recursive_check(a__			,    a__)
                 elif tuple_object is None:
                     return
                 else:
                     self.assertTrue(
                         all(tf.equal(a__			,    a__))			,    msg=(
                             '''Tuple and dict output are not equal. Difference:'''
                             F" {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}"
                         )			,    )

                 recursive_check(a__			,    a__)

         for model_class in self.all_model_classes:
             A__					=       model_class(a__)

             A__					=       self._prepare_for_class(a__			,    a__)
             A__					=       self._prepare_for_class(a__			,    a__)
             check_equivalence(a__			,    a__			,    a__)

             A__					=       self._prepare_for_class(a__			,    a__			,    return_labels=a__)
             A__					=       self._prepare_for_class(a__			,    a__			,    return_labels=a__)
             check_equivalence(a__			,    a__			,    a__)

             A__					=       self._prepare_for_class(a__			,    a__)
             A__					=       self._prepare_for_class(a__			,    a__)
             check_equivalence(a__			,    a__			,    a__			,    {'''output_hidden_states''': True})

             A__					=       self._prepare_for_class(a__			,    a__			,    return_labels=a__)
             A__					=       self._prepare_for_class(a__			,    a__			,    return_labels=a__)
             check_equivalence(a__			,    a__			,    a__			,    {'''output_hidden_states''': True})




     def 		snake_case_		(					self):
         A__					=       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*a__)




     @slow
     def 		snake_case_		(					self):
         for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             A__					=       TFRegNetModel.from_pretrained(a__)
             self.assertIsNotNone(a__)







def 		lowerCAmelCase__     (       )->	int:
    A__					=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
    return image



@require_tf
@require_vision
class      _UpperCAmelCase      (							unittest.TestCase  ):




     @cached_property
     def 		snake_case_		(					self):
         return (
             AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
             if is_vision_available()
             else None
         )




     @slow
     def 		snake_case_		(					self):
         A__					=       TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

         A__					=       self.default_image_processor
         A__					=       prepare_img()
         A__					=       image_processor(images=a__			,    return_tensors='''tf''')

         # forward pass
         A__					=       model(**a__			,    training=a__)

         # verify the logits
         A__					=       tf.TensorShape((1, 1_0_0_0))
         self.assertEqual(outputs.logits.shape			,    a__)

         A__					=       tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6])

         tf.debugging.assert_near(outputs.logits[0, :3]			,    a__			,    atol=1e-4)





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


_lowercase    	=		"\\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"

_lowercase    	=		"\\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"

_lowercase    	=		"\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  ):




     def 		snake_case_		(					self):
         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 		snake_case_		(					self			,    a__			,    a__			,    a__=None			,    a__=None			,    a__=None			,    a__=None			,    a__="auto"			,    a__=-1			,    a__=0.9			,    a__=5			,    a__=5_0_0			,    a__="gpt2-large"			,    a__=-1			,    a__=1_0_2_4			,    a__=2_5			,    a__=5			,    a__=True			,    a__=2_5			,    ):
         A__					=       compute_mauve(
             p_text=a__			,    q_text=a__			,    p_features=a__			,    q_features=a__			,    p_tokens=a__			,    q_tokens=a__			,    num_buckets=a__			,    pca_max_data=a__			,    kmeans_explained_var=a__			,    kmeans_num_redo=a__			,    kmeans_max_iter=a__			,    featurize_model_name=a__			,    device_id=a__			,    max_text_length=a__			,    divergence_curve_discretization_size=a__			,    mauve_scaling_factor=a__			,    verbose=a__			,    seed=a__			,    )
         return out
