





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_					:   int 							=						"""\\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_					:   List[str] 							=						"""\\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_					:   Dict 							=						"""\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      lowercase__    (							datasets.Metric  ):







  def 	UpperCAmelCase__		(	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 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase    ,						_lowercase=None    ,						_lowercase=None    ,						_lowercase=None    ,						_lowercase=None    ,						_lowercase="auto"    ,						_lowercase=-1    ,						_lowercase=0.9    ,						_lowercase=5    ,						_lowercase=500    ,						_lowercase="gpt2-large"    ,						_lowercase=-1    ,						_lowercase=1_024    ,						_lowercase=25    ,						_lowercase=5    ,						_lowercase=True    ,						_lowercase=25    ,						):
       lowerCAmelCase_					:       List[str]    =		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







def 							_lowerCAmelCase (  _a   :					int					,   _a   :					bool = False			)	->			bool:
     if n == 2:
          return True
     if not n % 2 or n < 2:
          return False
     if n > 5 and n % 10 not in (1, 3, 7, 9):  # can quickly check last digit
          return False
     if n > 3_31_70_44_06_46_79_88_73_85_96_19_81 and not allow_probable:
          raise ValueError(
              """Warning: upper bound of deterministic test is exceeded. """
              """Pass allow_probable=True to allow probabilistic test. """
              """A return value of True indicates a probable prime."""			)
     # array bounds provided by analysis
     lowerCAmelCase_					:       Optional[int]    =		[
         20_47,
         1_37_36_53,
         25_32_60_01,
         32_15_03_17_51,
         2_15_23_02_89_87_47,
         3_47_47_49_66_03_83,
         3_41_55_00_71_72_83_21,
         1,
         3_82_51_23_05_65_46_41_30_51,
         1,
         1,
         31_86_65_85_78_34_03_11_51_16_74_61,
         3_31_70_44_06_46_79_88_73_85_96_19_81,
     ]

     lowerCAmelCase_					:       Dict    =		[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
     for idx, _p in enumerate(_a					,   1			):
          if n < _p:
               # then we have our last prime to check
               lowerCAmelCase_					:       str    =		primes[:idx]
               break
     lowerCAmelCase_   ,  lowerCAmelCase_					:       Optional[Any]    =		n - 1, 0
     # break up n -1 into a power of 2 (s) and
     # remaining odd component
     # essentially, solve for d * 2 ** s == n - 1
     while d % 2 == 0:
          d //= 2
          s += 1
     for prime in plist:
          lowerCAmelCase_					:       Tuple    =		False
          for r in range(_a			):
               lowerCAmelCase_					:       Tuple    =		pow(_a					,   d * 2**r					,   _a			)
               # see article for analysis explanation for m
               if (r == 0 and m == 1) or ((m + 1) % n == 0):
                    lowerCAmelCase_					:       List[Any]    =		True
                    # this loop will not determine compositeness
                    break
          if pr:
               continue
          # if pr is False, then the above loop never evaluated to true,
          # and the n MUST be composite
          return False
     return True






def 							_lowerCAmelCase (  )	->			None:
     assert not miller_rabin(5_61			)
     assert miller_rabin(5_63			)
     # 2047

     assert not miller_rabin(83_82_01			)
     assert miller_rabin(83_82_07			)
     # 1_373_653

     assert not miller_rabin(17_31_60_01			)
     assert miller_rabin(17_31_60_17			)
     # 25_326_001

     assert not miller_rabin(30_78_38_66_41			)
     assert miller_rabin(30_78_38_66_53			)
     # 3_215_031_751

     assert not miller_rabin(1_71_30_45_57_48_01			)
     assert miller_rabin(1_71_30_45_57_48_19			)
     # 2_152_302_898_747

     assert not miller_rabin(2_77_97_99_72_83_07			)
     assert miller_rabin(2_77_97_99_72_83_27			)
     # 3_474_749_660_383

     assert not miller_rabin(1_13_85_00_23_90_94_41			)
     assert miller_rabin(1_13_85_00_23_90_95_27			)
     # 341_550_071_728_321

     assert not miller_rabin(1_27_50_41_01_88_48_80_43_51			)
     assert miller_rabin(1_27_50_41_01_88_48_80_43_91			)
     # 3_825_123_056_546_413_051

     assert not miller_rabin(7_96_66_46_44_58_50_77_87_79_18_67			)
     assert miller_rabin(7_96_66_46_44_58_50_77_87_79_19_51			)
     # 318_665_857_834_031_151_167_461

     assert not miller_rabin(55_28_40_67_74_46_64_78_97_66_03_33			)
     assert miller_rabin(55_28_40_67_74_46_64_78_97_66_03_59			)
     # 3_317_044_064_679_887_385_961_981
     # upper limit for probabilistic test


if __name__ == "__main__":
      test_miller_rabin()
