

import json
import os
from typing import Optional, Tuple

import regex as re

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


lowerCAmelCase__      		=			logging.get_logger(__name__)

lowerCAmelCase__      		=			{
    '''vocab_file''': '''vocab.json''',
    '''merges_file''': '''merges.txt''',
}

lowerCAmelCase__      		=			{
    '''vocab_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'''},
    '''merges_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'''},
}

lowerCAmelCase__      		=			{
    '''ctrl''': 256,
}

lowerCAmelCase__      		=			{
    '''Pregnancy''': 16_8629,
    '''Christianity''': 7675,
    '''Explain''': 10_6423,
    '''Fitness''': 6_3440,
    '''Saving''': 6_3163,
    '''Ask''': 2_7171,
    '''Ass''': 9_5985,
    '''Joke''': 16_3509,
    '''Questions''': 4_5622,
    '''Thoughts''': 4_9605,
    '''Retail''': 5_2342,
    '''Feminism''': 16_4338,
    '''Writing''': 1_1992,
    '''Atheism''': 19_2263,
    '''Netflix''': 4_8616,
    '''Computing''': 3_9639,
    '''Opinion''': 4_3213,
    '''Alone''': 4_4967,
    '''Funny''': 5_8917,
    '''Gaming''': 4_0358,
    '''Human''': 4088,
    '''India''': 1331,
    '''Joker''': 7_7138,
    '''Diet''': 3_6206,
    '''Legal''': 1_1859,
    '''Norman''': 4939,
    '''Tip''': 7_2689,
    '''Weight''': 5_2343,
    '''Movies''': 4_6273,
    '''Running''': 2_3425,
    '''Science''': 2090,
    '''Horror''': 3_7793,
    '''Confession''': 6_0572,
    '''Finance''': 1_2250,
    '''Politics''': 1_6360,
    '''Scary''': 19_1985,
    '''Support''': 1_2654,
    '''Technologies''': 3_2516,
    '''Teenage''': 6_6160,
    '''Event''': 3_2769,
    '''Learned''': 6_7460,
    '''Notion''': 18_2770,
    '''Wikipedia''': 3_7583,
    '''Books''': 6665,
    '''Extract''': 7_6050,
    '''Confessions''': 10_2701,
    '''Conspiracy''': 7_5932,
    '''Links''': 6_3674,
    '''Narcissus''': 15_0425,
    '''Relationship''': 5_4766,
    '''Relationships''': 13_4796,
    '''Reviews''': 4_1671,
    '''News''': 4256,
    '''Translation''': 2_6820,
    '''multilingual''': 12_8406,
}


def 	_A  (					A__   ):






 """simple docstring"""



 __lowercase													=				set()
 __lowercase													=				word[0]
 for char in word[1:]:
  pairs.add((prev_char, char)   )
  __lowercase													=				char

 __lowercase													=				set(__UpperCamelCase   )
 return pairs






class     lowercase_			(SCREAMING_SNAKE_CASE__   ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE					:						Union[str, Any]           =    VOCAB_FILES_NAMES
  SCREAMING_SNAKE_CASE					:						Union[str, Any]           =    PRETRAINED_VOCAB_FILES_MAP
  SCREAMING_SNAKE_CASE					:						str           =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  SCREAMING_SNAKE_CASE					:						int           =    CONTROL_CODES






  def __init__(   self     :  List[Any]      ,lowercase__     :  Union[str, Any]      ,lowercase__     :  Union[str, Any]      ,lowercase__     :  Optional[int]="<unk>"      ,**lowercase__     :  str    ):
   super().__init__(unk_token=_lowercase      ,**_lowercase    )

   with open(_lowercase      ,encoding='''utf-8'''    ) as vocab_handle:
    __lowercase													=				json.load(_lowercase    )
   __lowercase													=				{v: k for k, v in self.encoder.items()}
   with open(_lowercase      ,encoding='''utf-8'''    ) as merges_handle:
    __lowercase													=				merges_handle.read().split('''\n'''    )[1:-1]
   __lowercase													=				[tuple(merge.split()    ) for merge in merges]
   __lowercase													=				dict(zip(_lowercase      ,range(len(_lowercase    )    )    )    )
   __lowercase													=				{}






  @property
  def       SCREAMING_SNAKE_CASE   (   self     :  Union[str, Any]    ):
   return len(self.encoder    )






  def       SCREAMING_SNAKE_CASE   (   self     :  str    ):
   return dict(self.encoder      ,**self.added_tokens_encoder    )






  def       SCREAMING_SNAKE_CASE   (   self     :  int      ,lowercase__     :  str    ):

   if token in self.cache:
    return self.cache[token]
   __lowercase													=				tuple(_lowercase    )
   __lowercase													=				tuple(list(word[:-1]    ) + [word[-1] + '''</w>''']    )
   __lowercase													=				get_pairs(_lowercase    )

   if not pairs:
    return token

   while True:
    __lowercase													=				min(_lowercase      ,key=lambda lowercase__    : self.bpe_ranks.get(_lowercase      ,float('''inf'''    )    )    )
    if bigram not in self.bpe_ranks:
     break
    __lowercase													=				bigram
    __lowercase													=				[]
    __lowercase													=				0
    while i < len(_lowercase    ):
     try:
      __lowercase													=				word.index(_lowercase      ,_lowercase    )
     except ValueError:
      new_word.extend(word[i:]    )
      break
     else:
      new_word.extend(word[i:j]    )
      __lowercase													=				j

     if word[i] == first and i < len(_lowercase    ) - 1 and word[i + 1] == second:
      new_word.append(first + second    )
      i += 2
     else:
      new_word.append(word[i]    )
      i += 1
    __lowercase													=				tuple(_lowercase    )
    __lowercase													=				new_word
    if len(_lowercase    ) == 1:
     break
    else:
     __lowercase													=				get_pairs(_lowercase    )
   __lowercase													=				"""@@ """.join(_lowercase    )
   __lowercase													=				word[:-4]
   __lowercase													=				word
   return word






  def       SCREAMING_SNAKE_CASE   (   self     :  List[str]      ,lowercase__     :  int    ):
   __lowercase													=				[]

   __lowercase													=				re.findall(r'''\S+\n?'''      ,_lowercase    )

   for token in words:
    split_tokens.extend(list(self.bpe(_lowercase    ).split(''' '''    )    )    )
   return split_tokens






  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[Any]      ,lowercase__     :  List[str]    ):
   return self.encoder.get(_lowercase      ,self.encoder.get(self.unk_token    )    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Any      ,lowercase__     :  List[Any]    ):
   return self.decoder.get(_lowercase      ,self.unk_token    )






  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]      ,lowercase__     :  int    ):
   __lowercase													=				""" """.join(_lowercase    ).replace('''@@ '''      ,''''''    ).strip()
   return out_string






  def       SCREAMING_SNAKE_CASE   (   self     :  List[Any]      ,lowercase__     :  int      ,lowercase__     :  str = None    ):

   if not os.path.isdir(_lowercase    ):
    logger.error(F"Vocabulary path ({save_directory}) should be a directory"    )
    return
   __lowercase													=				os.path.join(
       _lowercase      ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']    )
   __lowercase													=				os.path.join(
       _lowercase      ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']    )

   with open(_lowercase      ,'''w'''      ,encoding='''utf-8'''    ) as f:
    f.write(json.dumps(self.encoder      ,indent=2      ,sort_keys=_lowercase      ,ensure_ascii=_lowercase    ) + '''\n'''    )

   __lowercase													=				0
   with open(_lowercase      ,'''w'''      ,encoding='''utf-8'''    ) as writer:
    writer.write('''#version: 0.2\n'''    )
    for bpe_tokens, token_index in sorted(self.bpe_ranks.items()      ,key=lambda lowercase__    : kv[1]    ):
     if index != token_index:
      logger.warning(
          F"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
          ''' Please check that the tokenizer is not corrupted!'''    )
      __lowercase													=				token_index
     writer.write(''' '''.join(_lowercase    ) + '''\n'''    )
     index += 1

   return vocab_file, merge_file

  # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
  #     filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
  #     tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
  #     tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
  #     return ''.join(tokens_generated_so_far)




'''simple docstring'''






from scipy.stats import spearmanr

import datasets


lowerCAmelCase__      		=			'''
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.
'''

lowerCAmelCase__      		=			'''
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
'''

lowerCAmelCase__      		=			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   ):




  """simple docstring"""




  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   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       SCREAMING_SNAKE_CASE   (   self     :  Tuple      ,lowercase__     :  List[Any]      ,lowercase__     :  List[Any]      ,lowercase__     :  Union[str, Any]=False    ):
   __lowercase													=				spearmanr(lowercase__      ,lowercase__    )
   if return_pvalue:
    return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
   else:
    return {"spearmanr": results[0]}

