
'''simple docstring'''


from scipy.stats import spearmanr

import datasets


__lowercase							:   Optional[Any]					=     '''
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
'''

__lowercase							:   Dict					=     '''
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {\'spearmanr\': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results[\'spearmanr\'])
        -0.7
        >>> print(round(results[\'spearmanr_pvalue\'], 2))
        0.19
'''

__lowercase							:   Tuple					=     r'''\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@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, {\.I}lhan 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, Ant{\^o}nio 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 	__lowercase				(  datasets.Metric    ):

			def        UpperCAmelCase__ (self      ):
								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.spearmanr.html''']			,   )






			def        UpperCAmelCase__ (self			,   A			,   A			,   A=False      ):
								lowerCamelCase_					:      int     =		spearmanr(A			,   A      )
								if return_pvalue:
													return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
								else:
													return {"spearmanr": results[0]}




'''simple docstring'''


import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


__lowercase							:   Any					=     logging.get_logger(__name__)

__lowercase							:   List[str]					=     '''▁'''

__lowercase							:   Optional[Any]					=     {'''vocab_file''': '''sentencepiece.bpe.model'''}

__lowercase							:   List[str]					=     {
    '''vocab_file''': {
        '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''',
        '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''',
        '''xlm-roberta-large-finetuned-conll02-dutch''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll02-spanish''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll03-english''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll03-german''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model'''
        ),
    }
}

__lowercase							:   Union[str, Any]					=     {
    '''xlm-roberta-base''': 512,
    '''xlm-roberta-large''': 512,
    '''xlm-roberta-large-finetuned-conll02-dutch''': 512,
    '''xlm-roberta-large-finetuned-conll02-spanish''': 512,
    '''xlm-roberta-large-finetuned-conll03-english''': 512,
    '''xlm-roberta-large-finetuned-conll03-german''': 512,
}

class 	__lowercase				(  _lowercase    ):
			lowerCamelCase			:		Any	      =			VOCAB_FILES_NAMES
			lowerCamelCase			:		Optional[int]	      =			PRETRAINED_VOCAB_FILES_MAP
			lowerCamelCase			:		str	      =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			lowerCamelCase			:		Union[str, Any]	      =			["input_ids", "attention_mask"]

			def __init__(self			,   A			,   A="<s>"			,   A="</s>"			,   A="</s>"			,   A="<s>"			,   A="<unk>"			,   A="<pad>"			,   A="<mask>"			,   A = None			,   **A			,   ):
								# Mask token behave like a normal word, i.e. include the space before it
								lowerCamelCase_					:      Tuple     =		AddedToken(A			,   lstrip=A			,   rstrip=A      ) if isinstance(A			,   A      ) else mask_token

								lowerCamelCase_					:      Dict     =		{} if sp_model_kwargs is None else sp_model_kwargs

								super().__init__(
								    bos_token=A			,   eos_token=A			,   unk_token=A			,   sep_token=A			,   cls_token=A			,   pad_token=A			,   mask_token=A			,   sp_model_kwargs=self.sp_model_kwargs			,   **A			,   )

								lowerCamelCase_					:      Any     =		spm.SentencePieceProcessor(**self.sp_model_kwargs      )
								self.sp_model.Load(str(A      )      )
								lowerCamelCase_					:      Tuple     =		vocab_file

								# Original fairseq vocab and spm vocab must be "aligned":
								# Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
								# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
								# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
								# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

								# Mimic fairseq token-to-id alignment for the first 4 token
								lowerCamelCase_					:      str     =		{'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

								# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
								lowerCamelCase_					:      int     =		1

								lowerCamelCase_					:      Union[str, Any]     =		len(self.sp_model      ) + self.fairseq_offset
								lowerCamelCase_					:      Any     =		{v: k for k, v in self.fairseq_tokens_to_ids.items()}

			def __getstate__(self      ):
								lowerCamelCase_					:      Any     =		self.__dict__.copy()
								lowerCamelCase_					:      Optional[Any]     =		None
								lowerCamelCase_					:      int     =		self.sp_model.serialized_model_proto()
								return state

			def __setstate__(self			,   A      ):
								lowerCamelCase_					:      Any     =		d

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

								lowerCamelCase_					:      List[Any]     =		spm.SentencePieceProcessor(**self.sp_model_kwargs      )
								self.sp_model.LoadFromSerializedProto(self.sp_model_proto      )

			def        UpperCAmelCase__ (self			,   A			,   A = None      ):

								if token_ids_a is None:
													return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
								lowerCamelCase_					:      Optional[int]     =		[self.cls_token_id]
								lowerCamelCase_					:      Optional[int]     =		[self.sep_token_id]
								return cls + token_ids_a + sep + sep + token_ids_a + sep

			def        UpperCAmelCase__ (self			,   A			,   A = None			,   A = False      ):

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

								if token_ids_a is None:
													return [1] + ([0] * len(A      )) + [1]
								return [1] + ([0] * len(A      )) + [1, 1] + ([0] * len(A      )) + [1]

			def        UpperCAmelCase__ (self			,   A			,   A = None      ):
								lowerCamelCase_					:      List[str]     =		[self.sep_token_id]
								lowerCamelCase_					:      List[Any]     =		[self.cls_token_id]

								if token_ids_a is None:
													return len(cls + token_ids_a + sep      ) * [0]
								return len(cls + token_ids_a + sep + sep + token_ids_a + sep      ) * [0]

			@property
			def        UpperCAmelCase__ (self      ):
								return len(self.sp_model      ) + self.fairseq_offset + 1  # Add the <mask> token

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      str     =		{self.convert_ids_to_tokens(A      ): i for i in range(self.vocab_size      )}
								vocab.update(self.added_tokens_encoder      )
								return vocab

			def        UpperCAmelCase__ (self			,   A      ):
								return self.sp_model.encode(A			,   out_type=A      )

			def        UpperCAmelCase__ (self			,   A      ):
								if token in self.fairseq_tokens_to_ids:
													return self.fairseq_tokens_to_ids[token]
								lowerCamelCase_					:      int     =		self.sp_model.PieceToId(A      )

								# Need to return unknown token if the SP model returned 0
								return spm_id + self.fairseq_offset if spm_id else self.unk_token_id

			def        UpperCAmelCase__ (self			,   A      ):
								if index in self.fairseq_ids_to_tokens:
													return self.fairseq_ids_to_tokens[index]
								return self.sp_model.IdToPiece(index - self.fairseq_offset      )

			def        UpperCAmelCase__ (self			,   A      ):
								lowerCamelCase_					:      Optional[int]     =		''''''.join(A      ).replace(A			,   ''' '''      ).strip()
								return out_string






			def        UpperCAmelCase__ (self			,   A			,   A = None      ):
								if not os.path.isdir(A      ):
													logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""      )
													return
								lowerCamelCase_					:      str     =		os.path.join(
								    A			,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']      )

								if os.path.abspath(self.vocab_file      ) != os.path.abspath(A      ) and os.path.isfile(self.vocab_file      ):
													copyfile(self.vocab_file			,   A      )
								elif not os.path.isfile(self.vocab_file      ):
													with open(A			,   '''wb'''      ) as fi:
																		lowerCamelCase_					:      Optional[Any]     =		self.sp_model.serialized_model_proto()
																		fi.write(A      )

								return (out_vocab_file,)


