





"""simple docstring"""





import numpy as np
from scipy.spatial.distance import cdist
from sklearn.metrics import fa_score

import datasets


__A											=						"""\
    @inproceedings{kakwani2020indicnlpsuite,
    title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},
    author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},
    year={2020},
    booktitle={Findings of EMNLP},
}
"""

__A											=						"""\
    IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide
    variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.
"""

__A											=						"""
Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset.
Args:
    predictions: list of predictions to score (as int64),
        except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).
    references: list of ground truth labels corresponding to the predictions (as int64),
        except for 'cvit-mkb-clsr' where each reference is a vector (of float32).
Returns: depending on the IndicGLUE subset, one or several of:
    \"accuracy\": Accuracy
    \"f1\": F1 score
    \"precision\": Precision@10
Examples:

    >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli')  # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0}

    >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0, 'f1': 1.0}

    >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')
    >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]
    >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]
    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'precision@10': 1.0}

"""
def 					__A  (_SCREAMING_SNAKE_CASE	,  _SCREAMING_SNAKE_CASE     )   ->Optional[int]:





  """simple docstring"""


  return float((preds == labels).mean()     )
def 					__A  (_SCREAMING_SNAKE_CASE	,  _SCREAMING_SNAKE_CASE     )   ->int:





  """simple docstring"""


  lowerCAmelCase__     :str											=				simple_accuracy(_SCREAMING_SNAKE_CASE	,  _SCREAMING_SNAKE_CASE     )
  lowerCAmelCase__     :int											=				float(fa_score(y_true=_SCREAMING_SNAKE_CASE	,  y_pred=_SCREAMING_SNAKE_CASE     )     )
  return {
      "accuracy": acc,
      "f1": fa,
  }
def 					__A  (_SCREAMING_SNAKE_CASE	,  _SCREAMING_SNAKE_CASE     )   ->int:





  """simple docstring"""


  lowerCAmelCase__     :int											=				np.array(_SCREAMING_SNAKE_CASE     )
  lowerCAmelCase__     :Optional[Any]											=				np.array(_SCREAMING_SNAKE_CASE     )
  lowerCAmelCase__     :List[str]											=				en_sentvecs.shape[0]

  # mean centering
  lowerCAmelCase__     :List[Any]											=				en_sentvecs - np.mean(_SCREAMING_SNAKE_CASE	,  axis=0     )
  lowerCAmelCase__     :Union[str, Any]											=				in_sentvecs - np.mean(_SCREAMING_SNAKE_CASE	,  axis=0     )

  lowerCAmelCase__     :Tuple											=				cdist(_SCREAMING_SNAKE_CASE	,  _SCREAMING_SNAKE_CASE	,  'cosine'     )
  lowerCAmelCase__     :str											=				np.array(range(_SCREAMING_SNAKE_CASE     )     )
  lowerCAmelCase__     :int											=				sim.argsort(axis=1     )[:, :10]
  lowerCAmelCase__     :Optional[Any]											=				np.any(preds == actual[:, None]	,  axis=1     )
  return float(matches.mean()     )






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,  _KWARGS_DESCRIPTION			)
class    _lowerCAmelCase  (	datasets.Metric			):
       """simple docstring"""




       def 	snake_case		(       self ):



         '''simple docstring'''

         if self.config_name not in [
             "wnli",
             "copa",
             "sna",
             "csqa",
             "wstp",
             "inltkh",
             "bbca",
             "cvit-mkb-clsr",
             "iitp-mr",
             "iitp-pr",
             "actsa-sc",
             "md",
             "wiki-ner",
         ]:
           raise KeyError(
               'You should supply a configuration name selected in '
               '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", '
               '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", '
               '"wiki-ner"]' )
         return datasets.MetricInfo(
             description=_DESCRIPTION       ,					citation=_CITATION       ,					inputs_description=_KWARGS_DESCRIPTION       ,					features=datasets.Features(
                 {
                     'predictions': datasets.Value('int64' )
                     if self.config_name != 'cvit-mkb-clsr'
                     else datasets.Sequence(datasets.Value('float32' ) ),
                     'references': datasets.Value('int64' )
                     if self.config_name != 'cvit-mkb-clsr'
                     else datasets.Sequence(datasets.Value('float32' ) ),
                 } )       ,					codebase_urls=[]       ,					reference_urls=[]       ,					format='numpy' if self.config_name != 'cvit-mkb-clsr' else None       ,					)






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         if self.config_name == "cvit-mkb-clsr":
           return {"precision@10": precision_at_aa(__UpperCAmelCase       ,					__UpperCAmelCase )}
         elif self.config_name in ["wiki-ner"]:
           return acc_and_fa(__UpperCAmelCase       ,					__UpperCAmelCase )
         elif self.config_name in [
             "wnli",
             "copa",
             "sna",
             "csqa",
             "wstp",
             "inltkh",
             "bbca",
             "iitp-mr",
             "iitp-pr",
             "actsa-sc",
             "md",
         ]:
           return {"accuracy": simple_accuracy(__UpperCAmelCase       ,					__UpperCAmelCase )}
         else:
           raise KeyError(
               'You should supply a configuration name selected in '
               '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", '
               '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", '
               '"wiki-ner"]' )







"""simple docstring"""





import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_roberta import RobertaTokenizer


__A											=						logging.get_logger(__name__)

__A											=						{"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

__A											=						{
    """vocab_file""": {
        """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/vocab.json""",
        """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/vocab.json""",
        """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json""",
        """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/vocab.json""",
        """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json""",
        """roberta-large-openai-detector""": (
            """https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json"""
        ),
    },
    """merges_file""": {
        """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/merges.txt""",
        """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/merges.txt""",
        """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt""",
        """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/merges.txt""",
        """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt""",
        """roberta-large-openai-detector""": (
            """https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt"""
        ),
    },
    """tokenizer_file""": {
        """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/tokenizer.json""",
        """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/tokenizer.json""",
        """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json""",
        """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json""",
        """roberta-base-openai-detector""": (
            """https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json"""
        ),
        """roberta-large-openai-detector""": (
            """https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json"""
        ),
    },
}

__A											=						{
    """roberta-base""": 512,
    """roberta-large""": 512,
    """roberta-large-mnli""": 512,
    """distilroberta-base""": 512,
    """roberta-base-openai-detector""": 512,
    """roberta-large-openai-detector""": 512,
}






class    _lowerCAmelCase  (	a			):
       """simple docstring"""




       __magic_name__	:str						    =   VOCAB_FILES_NAMES
       __magic_name__	:List[Any]						    =   PRETRAINED_VOCAB_FILES_MAP
       __magic_name__	:Optional[Any]						    =   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       __magic_name__	:str						    =   ["""input_ids""", """attention_mask"""]
       __magic_name__	:Any						    =   RobertaTokenizer






       def __init__(       self       ,					__UpperCAmelCase=None       ,					__UpperCAmelCase=None       ,					__UpperCAmelCase=None       ,					__UpperCAmelCase="replace"       ,					__UpperCAmelCase="<s>"       ,					__UpperCAmelCase="</s>"       ,					__UpperCAmelCase="</s>"       ,					__UpperCAmelCase="<s>"       ,					__UpperCAmelCase="<unk>"       ,					__UpperCAmelCase="<pad>"       ,					__UpperCAmelCase="<mask>"       ,					__UpperCAmelCase=False       ,					__UpperCAmelCase=True       ,					**__UpperCAmelCase       ,					):



         '''simple docstring'''

         super().__init__(
             __UpperCAmelCase       ,					__UpperCAmelCase       ,					tokenizer_file=__UpperCAmelCase       ,					errors=__UpperCAmelCase       ,					bos_token=__UpperCAmelCase       ,					eos_token=__UpperCAmelCase       ,					sep_token=__UpperCAmelCase       ,					cls_token=__UpperCAmelCase       ,					unk_token=__UpperCAmelCase       ,					pad_token=__UpperCAmelCase       ,					mask_token=__UpperCAmelCase       ,					add_prefix_space=__UpperCAmelCase       ,					trim_offsets=__UpperCAmelCase       ,					**__UpperCAmelCase       ,					)

         lowerCAmelCase__     :Dict											=				json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
         if pre_tok_state.get('add_prefix_space'       ,					__UpperCAmelCase ) != add_prefix_space:
           lowerCAmelCase__     :Optional[int]											=				getattr(__UpperCAmelCase       ,					pre_tok_state.pop('type' ) )
           lowerCAmelCase__     :List[Any]											=				add_prefix_space
           lowerCAmelCase__     :str											=				pre_tok_class(**__UpperCAmelCase )

         lowerCAmelCase__     :List[str]											=				add_prefix_space

         lowerCAmelCase__     :str											=				'post_processor'
         lowerCAmelCase__     :Optional[Any]											=				getattr(self.backend_tokenizer       ,					__UpperCAmelCase       ,					__UpperCAmelCase )
         if tokenizer_component_instance:
           lowerCAmelCase__     :Optional[Any]											=				json.loads(tokenizer_component_instance.__getstate__() )

           # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
           if "sep" in state:
             lowerCAmelCase__     :Any											=				tuple(state['sep'] )
           if "cls" in state:
             lowerCAmelCase__     :int											=				tuple(state['cls'] )

           lowerCAmelCase__     :List[Any]											=				False

           if state.get('add_prefix_space'       ,					__UpperCAmelCase ) != add_prefix_space:
             lowerCAmelCase__     :Union[str, Any]											=				add_prefix_space
             lowerCAmelCase__     :Any											=				True

           if state.get('trim_offsets'       ,					__UpperCAmelCase ) != trim_offsets:
             lowerCAmelCase__     :Union[str, Any]											=				trim_offsets
             lowerCAmelCase__     :Optional[int]											=				True

           if changes_to_apply:
             lowerCAmelCase__     :str											=				getattr(__UpperCAmelCase       ,					state.pop('type' ) )
             lowerCAmelCase__     :Any											=				component_class(**__UpperCAmelCase )
             setattr(self.backend_tokenizer       ,					__UpperCAmelCase       ,					__UpperCAmelCase )






       @property
       def 	snake_case		(       self ):



         '''simple docstring'''

         if self._mask_token is None:
           if self.verbose:
             logger.error('Using mask_token, but it is not set yet.' )
           return None
         return str(self._mask_token )






       @mask_token.setter
       def 	snake_case		(       self       ,					__UpperCAmelCase ):



         '''simple docstring'''

         lowerCAmelCase__     :List[Any]											=				AddedToken(__UpperCAmelCase       ,					lstrip=__UpperCAmelCase       ,					rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase       ,					__UpperCAmelCase ) else value
         lowerCAmelCase__     :List[str]											=				value






       def 	snake_case		(       self       ,					*__UpperCAmelCase       ,					**__UpperCAmelCase ):



         '''simple docstring'''

         lowerCAmelCase__     :Optional[Any]											=				kwargs.get('is_split_into_words'       ,					__UpperCAmelCase )
         assert self.add_prefix_space or not is_split_into_words, (
             F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
             "to use it with pretokenized inputs."
         )

         return super()._batch_encode_plus(*__UpperCAmelCase       ,					**__UpperCAmelCase )






       def 	snake_case		(       self       ,					*__UpperCAmelCase       ,					**__UpperCAmelCase ):



         '''simple docstring'''

         lowerCAmelCase__     :Any											=				kwargs.get('is_split_into_words'       ,					__UpperCAmelCase )

         assert self.add_prefix_space or not is_split_into_words, (
             F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
             "to use it with pretokenized inputs."
         )

         return super()._encode_plus(*__UpperCAmelCase       ,					**__UpperCAmelCase )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase = None ):



         '''simple docstring'''

         lowerCAmelCase__     :Union[str, Any]											=				self._tokenizer.model.save(__UpperCAmelCase       ,					name=__UpperCAmelCase )
         return tuple(__UpperCAmelCase )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase=None ):



         '''simple docstring'''

         lowerCAmelCase__     :str											=				[self.bos_token_id] + token_ids_a + [self.eos_token_id]
         if token_ids_a is None:
           return output

         return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase = None ):



         '''simple docstring'''

         lowerCAmelCase__     :List[Any]											=				[self.sep_token_id]
         lowerCAmelCase__     :int											=				[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]
