


"""simple docstring"""
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__SCREAMING_SNAKE_CASE							:      str						=      logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE							:      str						=      '▁'

__SCREAMING_SNAKE_CASE							:      List[str]						=      {
    'vocab_file': 'vocab.json',
    'spm_file': 'sentencepiece.bpe.model',
}

__SCREAMING_SNAKE_CASE							:      Optional[int]						=      {
    'vocab_file': {
        'facebook/s2t-small-librispeech-asr': (
            'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json'
        ),
    },
    'spm_file': {
        'facebook/s2t-small-librispeech-asr': (
            'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model'
        )
    },
}

__SCREAMING_SNAKE_CASE							:      List[str]						=      {
    'facebook/s2t-small-librispeech-asr': 1_024,
}

__SCREAMING_SNAKE_CASE							:      str						=      ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de']

__SCREAMING_SNAKE_CASE							:      Dict						=      {'mustc': MUSTC_LANGS}





class        __A       (__SCREAMING_SNAKE_CASE):





       '''simple docstring'''

       __lowercase:						Tuple							 =      VOCAB_FILES_NAMES
       __lowercase:						Any							 =      PRETRAINED_VOCAB_FILES_MAP
       __lowercase:						List[Any]							 =      MAX_MODEL_INPUT_SIZES
       __lowercase:						str							 =      ["input_ids", "attention_mask"]

       __lowercase:						List[int]							 =      []



       def __init__(			self							: int						,    UpperCAmelCase_							: Any						,    UpperCAmelCase_							: str						,    UpperCAmelCase_							: List[Any]="<s>"						,    UpperCAmelCase_							: Tuple="</s>"						,    UpperCAmelCase_							: Optional[int]="<pad>"						,    UpperCAmelCase_							: Dict="<unk>"						,    UpperCAmelCase_							: Union[str, Any]=False						,    UpperCAmelCase_							: Tuple=False						,    UpperCAmelCase_							: Any=None						,    UpperCAmelCase_							: Tuple=None						,    UpperCAmelCase_							: str = None						,    **UpperCAmelCase_							: str						,    )   ->None:



              """simple docstring"""



              snake_case_          =						{} if sp_model_kwargs is None else sp_model_kwargs

              super().__init__(
                  bos_token=__UpperCAmelCase						,    eos_token=__UpperCAmelCase						,    unk_token=__UpperCAmelCase						,    pad_token=__UpperCAmelCase						,    do_upper_case=__UpperCAmelCase						,    do_lower_case=__UpperCAmelCase						,    tgt_lang=__UpperCAmelCase						,    lang_codes=__UpperCAmelCase						,    sp_model_kwargs=self.sp_model_kwargs						,    **__UpperCAmelCase						,    )
              snake_case_          =						do_upper_case
              snake_case_          =						do_lower_case

              snake_case_          =						load_json(__UpperCAmelCase    )
              snake_case_          =						{v: k for k, v in self.encoder.items()}
              snake_case_          =						spm_file
              snake_case_          =						load_spm(__UpperCAmelCase						,    self.sp_model_kwargs    )

              if lang_codes is not None:
                     snake_case_          =						lang_codes
                     snake_case_          =						LANGUAGES[lang_codes]
                     snake_case_          =						[F"""<lang:{lang}>""" for lang in self.langs]
                     snake_case_          =						{lang: self.sp_model.PieceToId(F"""<lang:{lang}>"""    ) for lang in self.langs}

                     snake_case_          =						self.lang_tokens
                     snake_case_          =						tgt_lang if tgt_lang is not None else self.langs[0]

                     self.set_tgt_lang_special_tokens(self._tgt_lang    )
              else:
                     snake_case_          =						{}



       @property
       def 						lowerCAmelCase    (			self							: Union[str, Any]    )   ->int:



              """simple docstring"""



              return len(self.encoder    )



       @property
       def 						lowerCAmelCase    (			self							: str    )   ->str:



              """simple docstring"""



              return self._tgt_lang



       @tgt_lang.setter
       def 						lowerCAmelCase    (			self							: Optional[int]						,    UpperCAmelCase_							: Any    )   ->None:



              """simple docstring"""



              snake_case_          =						new_tgt_lang
              self.set_tgt_lang_special_tokens(__UpperCAmelCase    )



       def 						lowerCAmelCase    (			self							: Union[str, Any]						,    UpperCAmelCase_							: List[Any]    )   ->None:



              """simple docstring"""



              snake_case_          =						self.lang_code_to_id[tgt_lang]
              snake_case_          =						[lang_code_id]



       def 						lowerCAmelCase    (			self							: Union[str, Any]						,    UpperCAmelCase_							: Any    )   ->List[str]:



              """simple docstring"""



              return self.sp_model.encode(__UpperCAmelCase						,    out_type=__UpperCAmelCase    )



       def 						lowerCAmelCase    (			self							: List[str]						,    UpperCAmelCase_							: List[Any]    )   ->Any:



              """simple docstring"""



              return self.encoder.get(__UpperCAmelCase						,    self.encoder[self.unk_token]    )



       def 						lowerCAmelCase    (			self							: Dict						,    UpperCAmelCase_							: Any    )   ->str:



              """simple docstring"""



              return self.decoder.get(__UpperCAmelCase						,    self.unk_token    )



       def 						lowerCAmelCase    (			self							: List[str]						,    UpperCAmelCase_							: str    )   ->str:



              """simple docstring"""



              snake_case_          =						[]
              snake_case_          =						""""""
              for token in tokens:
                     # make sure that special tokens are not decoded using sentencepiece model
                     if token in self.all_special_tokens:
                            snake_case_          =						self.sp_model.decode(__UpperCAmelCase    )
                            out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
                            snake_case_          =						[]
                     else:
                            current_sub_tokens.append(__UpperCAmelCase    )
              snake_case_          =						self.sp_model.decode(__UpperCAmelCase    )
              out_string += decoded.upper() if self.do_upper_case else decoded
              return out_string.strip()



       def 						lowerCAmelCase    (			self							: Optional[int]						,    UpperCAmelCase_							: Union[str, Any]						,    UpperCAmelCase_							: List[Any]=None    )   ->List[int]:



              """simple docstring"""



              if token_ids_a is None:
                     return self.prefix_tokens + token_ids_a + [self.eos_token_id]
              # We don't expect to process pairs, but leave the pair logic for API consistency
              return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]



       def 						lowerCAmelCase    (			self							: Optional[Any]						,    UpperCAmelCase_							: Dict						,    UpperCAmelCase_							: Optional[Any] = None						,    UpperCAmelCase_							: int = False    )   ->List[int]:



              """simple docstring"""



              if already_has_special_tokens:
                     return super().get_special_tokens_mask(
                         token_ids_a=__UpperCAmelCase						,    token_ids_a=__UpperCAmelCase						,    already_has_special_tokens=__UpperCAmelCase    )

              snake_case_          =						[1] * len(self.prefix_tokens    )
              snake_case_          =						[1]
              if token_ids_a is None:
                     return prefix_ones + ([0] * len(__UpperCAmelCase    )) + suffix_ones
              return prefix_ones + ([0] * len(__UpperCAmelCase    )) + ([0] * len(__UpperCAmelCase    )) + suffix_ones



       def 						lowerCAmelCase    (			self							: Any    )   ->Dict:



              """simple docstring"""



              snake_case_          =						self.encoder.copy()
              vocab.update(self.added_tokens_encoder    )
              return vocab



       def __getstate__(			self							: Dict    )   ->Dict:



              """simple docstring"""



              snake_case_          =						self.__dict__.copy()
              snake_case_          =						None
              return state



       def __setstate__(			self							: Any						,    UpperCAmelCase_							: Optional[int]    )   ->None:



              """simple docstring"""



              snake_case_          =						d

              # for backward compatibility
              if not hasattr(self						,    """sp_model_kwargs"""    ):
                     snake_case_          =						{}

              snake_case_          =						load_spm(self.spm_file						,    self.sp_model_kwargs    )



       def 						lowerCAmelCase    (			self							: Tuple						,    UpperCAmelCase_							: Optional[Any]						,    UpperCAmelCase_							: Union[str, Any] = None    )   ->Tuple[str]:



              """simple docstring"""



              snake_case_          =						Path(__UpperCAmelCase    )
              assert save_dir.is_dir(), F"""{save_directory} should be a directory"""
              snake_case_          =						save_dir / (
                  (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""]
              )
              snake_case_          =						save_dir / (
                  (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""]
              )

              save_json(self.encoder						,    __UpperCAmelCase    )

              if os.path.abspath(self.spm_file    ) != os.path.abspath(__UpperCAmelCase    ) and os.path.isfile(self.spm_file    ):
                     copyfile(self.spm_file						,    __UpperCAmelCase    )
              elif not os.path.isfile(self.spm_file    ):
                     with open(__UpperCAmelCase						,    """wb"""    ) as fi:
                            snake_case_          =						self.sp_model.serialized_model_proto()
                            fi.write(__UpperCAmelCase    )

              return (str(__UpperCAmelCase    ), str(__UpperCAmelCase    ))







def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)      ->			int:
       snake_case_          =						sentencepiece.SentencePieceProcessor(**lowerCAmelCase__			)
       spm.Load(str(lowerCAmelCase__			)			)
       return spm







def   _a			( _SCREAMING_SNAKE_CASE			)      ->			Dict:





       with open(lowerCAmelCase__			,	"""r"""			) as f:
              return json.load(lowerCAmelCase__			)







def   _a			( _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE			)      ->			List[str]:





       with open(lowerCAmelCase__			,	"""w"""			) as f:
              json.dump(lowerCAmelCase__			,	lowerCAmelCase__			,	indent=2			)







"""simple docstring"""
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


__SCREAMING_SNAKE_CASE							:      Dict						=      '\\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'

__SCREAMING_SNAKE_CASE							:      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'

__SCREAMING_SNAKE_CASE							:      Tuple						=      '\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        __A       (datasets.Metric):





							'''simple docstring'''

							def 						lowerCAmelCase    (			self							: Tuple    )   ->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 						lowerCAmelCase    (			self							: Optional[int]						,    UpperCAmelCase_							: Tuple						,    UpperCAmelCase_							: Any						,    UpperCAmelCase_							: Optional[Any]=None						,    UpperCAmelCase_							: Optional[Any]=None						,    UpperCAmelCase_							: List[Any]=None						,    UpperCAmelCase_							: Any=None						,    UpperCAmelCase_							: int="auto"						,    UpperCAmelCase_							: Dict=-1						,    UpperCAmelCase_							: Optional[Any]=0.9						,    UpperCAmelCase_							: Dict=5						,    UpperCAmelCase_							: Optional[int]=500						,    UpperCAmelCase_							: Any="gpt2-large"						,    UpperCAmelCase_							: Union[str, Any]=-1						,    UpperCAmelCase_							: Optional[Any]=1_024						,    UpperCAmelCase_							: Dict=25						,    UpperCAmelCase_							: Optional[Any]=5						,    UpperCAmelCase_							: int=True						,    UpperCAmelCase_							: Union[str, Any]=25						,    )   ->List[Any]:



														"""simple docstring"""



														snake_case_          =						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



