




'''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 BatchEncoding, PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase_					=   logging.get_logger(__name__)

UpperCAmelCase_					=   """▁"""

UpperCAmelCase_					=   {
    """vocab_file""": """vocab.json""",
    """spm_file""": """sentencepiece.bpe.model""",
    """tokenizer_config_file""": """tokenizer_config.json""",
}

UpperCAmelCase_					=   {
    """vocab_file""": {
        """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json""",
        """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json""",
    },
    """spm_file""": {
        """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model""",
        """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model""",
    },
    """tokenizer_config_file""": {
        """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json""",
        """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json""",
    },
}

UpperCAmelCase_					=   {
    """facebook/m2m100_418M""": 10_24,
}

# fmt: off
UpperCAmelCase_					=   {
    """m2m100""": ["""af""", """am""", """ar""", """ast""", """az""", """ba""", """be""", """bg""", """bn""", """br""", """bs""", """ca""", """ceb""", """cs""", """cy""", """da""", """de""", """el""", """en""", """es""", """et""", """fa""", """ff""", """fi""", """fr""", """fy""", """ga""", """gd""", """gl""", """gu""", """ha""", """he""", """hi""", """hr""", """ht""", """hu""", """hy""", """id""", """ig""", """ilo""", """is""", """it""", """ja""", """jv""", """ka""", """kk""", """km""", """kn""", """ko""", """lb""", """lg""", """ln""", """lo""", """lt""", """lv""", """mg""", """mk""", """ml""", """mn""", """mr""", """ms""", """my""", """ne""", """nl""", """no""", """ns""", """oc""", """or""", """pa""", """pl""", """ps""", """pt""", """ro""", """ru""", """sd""", """si""", """sk""", """sl""", """so""", """sq""", """sr""", """ss""", """su""", """sv""", """sw""", """ta""", """th""", """tl""", """tn""", """tr""", """uk""", """ur""", """uz""", """vi""", """wo""", """xh""", """yi""", """yo""", """zh""", """zu"""],
    """wmt21""": ["""en""", """ha""", """is""", """ja""", """cs""", """ru""", """zh""", """de"""]
}





class  __lowercase    (	_a			):
   _a    						=   VOCAB_FILES_NAMES
   _a    						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   _a    						=   PRETRAINED_VOCAB_FILES_MAP
   _a    						=   ["input_ids", "attention_mask"]

   _a    						=   []
   _a    						=   []







   def __init__(						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase=None   ,				UpperCamelCase=None   ,				UpperCamelCase="<s>"   ,				UpperCamelCase="</s>"   ,				UpperCamelCase="</s>"   ,				UpperCamelCase="<pad>"   ,				UpperCamelCase="<unk>"   ,				UpperCamelCase="m2m100"   ,				UpperCamelCase = None   ,				UpperCamelCase=8   ,				**UpperCamelCase   ,				)					->     Tuple:
     __a								=       {} if sp_model_kwargs is None else sp_model_kwargs

     __a								=       language_codes
     __a								=       FAIRSEQ_LANGUAGE_CODES[language_codes]
     __a								=       {lang_code: f"__{lang_code}__" for lang_code in fairseq_language_code}

     __a								=       kwargs.get('additional_special_tokens'   ,				[]   )
     kwargs["additional_special_tokens"] += [
         self.get_lang_token(__lowerCamelCase   )
         for lang_code in fairseq_language_code
         if self.get_lang_token(__lowerCamelCase   ) not in kwargs["additional_special_tokens"]
     ]

     super().__init__(
         src_lang=__lowerCamelCase   ,				tgt_lang=__lowerCamelCase   ,				bos_token=__lowerCamelCase   ,				eos_token=__lowerCamelCase   ,				sep_token=__lowerCamelCase   ,				unk_token=__lowerCamelCase   ,				pad_token=__lowerCamelCase   ,				language_codes=__lowerCamelCase   ,				sp_model_kwargs=self.sp_model_kwargs   ,				num_madeup_words=__lowerCamelCase   ,				**__lowerCamelCase   ,				)

     __a								=       vocab_file
     __a								=       load_json(__lowerCamelCase   )
     __a								=       {v: k for k, v in self.encoder.items()}
     __a								=       spm_file
     __a								=       load_spm(__lowerCamelCase   ,				self.sp_model_kwargs   )

     __a								=       len(self.encoder   )

     __a								=       {
         self.get_lang_token(__lowerCamelCase   ): self.encoder_size + i for i, lang_code in enumerate(__lowerCamelCase   )
     }
     __a								=       {lang_code: self.encoder_size + i for i, lang_code in enumerate(__lowerCamelCase   )}
     __a								=       {v: k for k, v in self.lang_token_to_id.items()}

     __a								=       src_lang if src_lang is not None else 'en'
     __a								=       tgt_lang
     __a								=       self.get_lang_id(self._src_lang   )
     self.set_src_lang_special_tokens(self._src_lang   )

     __a								=       num_madeup_words







   @property
   def 		UpperCamelCase__      (						self   )					->     Tuple:
     return len(self.encoder   ) + len(self.lang_token_to_id   )







   @property
   def 		UpperCamelCase__      (						self   )					->     Dict:
     return self._src_lang







   @src_lang.setter
   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Any:
     __a								=       new_src_lang
     self.set_src_lang_special_tokens(self._src_lang   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     int:
     return self.sp_model.encode(__lowerCamelCase   ,				out_type=__lowerCamelCase   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Tuple:
     if token in self.lang_token_to_id:
       return self.lang_token_to_id[token]
     return self.encoder.get(__lowerCamelCase   ,				self.encoder[self.unk_token]   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     str:
     if index in self.id_to_lang_token:
       return self.id_to_lang_token[index]
     return self.decoder.get(__lowerCamelCase   ,				self.unk_token   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Union[str, Any]:
     __a								=       []
     __a								=       ''
     for token in tokens:
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
         out_string += self.sp_model.decode(__lowerCamelCase   ) + token
         __a								=       []
       else:
         current_sub_tokens.append(__lowerCamelCase   )
     out_string += self.sp_model.decode(__lowerCamelCase   )
     return out_string.strip()







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase = None   ,				UpperCamelCase = False   )					->     Optional[Any]:

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

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







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase = None   )					->     Dict:
     if token_ids_a is None:
       return self.prefix_tokens + token_ids_a + self.suffix_tokens
     # 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.suffix_tokens







   def 		UpperCamelCase__      (						self   )					->     str:
     __a								=       {self.convert_ids_to_tokens(__lowerCamelCase   ): i for i in range(self.vocab_size   )}
     vocab.update(self.added_tokens_encoder   )
     return vocab







   def __getstate__(						self   )					->     Union[str, Any]:
     __a								=       self.__dict__.copy()
     __a								=       None
     return state







   def __setstate__(						self   ,				UpperCamelCase   )					->     List[str]:
     __a								=       d

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

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







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase = None   )					->     List[str]:
     __a								=       Path(__lowerCamelCase   )
     if not save_dir.is_dir():
       raise OSError(f"{save_directory} should be a directory"   )
     __a								=       save_dir / (
         (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['vocab_file']
     )
     __a								=       save_dir / (
         (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['spm_file']
     )

     save_json(self.encoder   ,				__lowerCamelCase   )

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

     return (str(__lowerCamelCase   ), str(__lowerCamelCase   ))







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase = "en"   ,				UpperCamelCase = None   ,				UpperCamelCase = "ro"   ,				**UpperCamelCase   ,				)					->     List[str]:
     __a								=       src_lang
     __a								=       tgt_lang
     self.set_src_lang_special_tokens(self.src_lang   )
     return super().prepare_seqaseq_batch(__lowerCamelCase   ,				__lowerCamelCase   ,				**__lowerCamelCase   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				**UpperCamelCase   )					->     List[str]:
     if src_lang is None or tgt_lang is None:
       raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model'   )
     __a								=       src_lang
     __a								=       self(__lowerCamelCase   ,				add_special_tokens=__lowerCamelCase   ,				**__lowerCamelCase   )
     __a								=       self.get_lang_id(__lowerCamelCase   )
     __a								=       tgt_lang_id
     return inputs







   def 		UpperCamelCase__      (						self   )					->     Union[str, Any]:
     self.set_src_lang_special_tokens(self.src_lang   )







   def 		UpperCamelCase__      (						self   )					->     Optional[Any]:
     self.set_tgt_lang_special_tokens(self.tgt_lang   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Tuple:
     __a								=       self.get_lang_token(__lowerCamelCase   )
     __a								=       self.lang_token_to_id[lang_token]
     __a								=       [self.cur_lang_id]
     __a								=       [self.eos_token_id]







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Optional[int]:
     __a								=       self.get_lang_token(__lowerCamelCase   )
     __a								=       self.lang_token_to_id[lang_token]
     __a								=       [self.cur_lang_id]
     __a								=       [self.eos_token_id]







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     List[str]:
     return self.lang_code_to_token[lang]







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     str:
     __a								=       self.get_lang_token(__lowerCamelCase   )
     return self.lang_token_to_id[lang_token]


def     SCREAMING_SNAKE_CASE							(   a_						:				Any					,       a_						:				str      ):
  __a								=       sentencepiece.SentencePieceProcessor(**__lowerCAmelCase      )
  spm.Load(str(__lowerCAmelCase      )      )
  return spm


def     SCREAMING_SNAKE_CASE							(   a_						:				List[str]      ):
  with open(__lowerCAmelCase					,       'r'      ) as f:
    return json.load(__lowerCAmelCase      )


def     SCREAMING_SNAKE_CASE							(   a_						:				List[Any]					,       a_						:				Dict      ):
  with open(__lowerCAmelCase					,       'w'      ) as f:
    json.dump(__lowerCAmelCase					,       __lowerCAmelCase					,       indent=2      )









from scipy.stats import pearsonr

import datasets


__magic_name__  :  Union[str, Any]					=       """
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""


__magic_name__  :  Tuple					=       """
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results['pearsonr'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        ['p-value', 'pearsonr']
        >>> print(round(results['pearsonr'], 2))
        -0.74
        >>> print(round(results['p-value'], 2))
        0.15
"""


__magic_name__  :  int					=       """
@article{2020SciPy-NMeth,
author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
      Haberland, Matt and Reddy, Tyler and Cournapeau, David and
      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
      Kern, Robert and Larson, Eric and Carey, C J and
      Polat, Ilhan and Feng, Yu and Moore, Eric W. and
      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
      Harris, Charles R. and Archibald, Anne M. and
      Ribeiro, Antonio H. and Pedregosa, Fabian and
      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
      Computing in Python}},
journal = {Nature Methods},
year    = {2020},
volume  = {17},
pages   = {261--272},
adsurl  = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,					_KWARGS_DESCRIPTION			)
class     SCREAMING_SNAKE_CASE__		(datasets.Metric			):
     def        A__      (						self	:		List[str]						):



       """simple docstring"""
       return datasets.MetricInfo(
           description=_DESCRIPTION       ,						citation=_CITATION       ,						inputs_description=_KWARGS_DESCRIPTION       ,						features=datasets.Features(
               {
                   '''predictions''': datasets.Value('''float'''						),
                   '''references''': datasets.Value('''float'''						),
               }						)       ,						reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html''']       ,						)



     def        A__      (						self	:		Any       ,						__lowerCamelCase	:		int       ,						__lowerCamelCase	:		Tuple       ,						__lowerCamelCase	:		Dict=False						):



       """simple docstring"""
       if return_pvalue:
         lowerCAmelCase__										=      pearsonr(__lowerCamelCase       ,						__lowerCamelCase						)
         return {"pearsonr": results[0], "p-value": results[1]}
       else:
         return {"pearsonr": float(pearsonr(__lowerCamelCase       ,						__lowerCamelCase						)[0]						)}

