



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

import datasets


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

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

__A   			="\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n    predictions: list of predictions to score (as int64),\n        except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n    references: list of ground truth labels corresponding to the predictions (as int64),\n        except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n    \"accuracy\": Accuracy\n    \"f1\": F1 score\n    \"precision\": Precision@10\nExamples:\n\n    >>> 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\"]\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n\n    >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0, 'f1': 1.0}\n\n    >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n    >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n    >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n    >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'precision@10': 1.0}\n\n"

def        a						(      _UpperCAmelCase							:					Any ,   _UpperCAmelCase							:					str						):







		'''simple docstring'''





		return float((preds == labels).mean()						)

def        a						(      _UpperCAmelCase							:					Optional[int] ,   _UpperCAmelCase							:					List[Any]						):







		'''simple docstring'''





		__UpperCAmelCase    :     Dict													=	simple_accuracy(_UpperCAmelCase ,   _UpperCAmelCase						)
		__UpperCAmelCase    :     List[Any]													=	float(fa_score(y_true=_UpperCAmelCase ,   y_pred=_UpperCAmelCase						)						)
		return {
		    "accuracy": acc,
		    "f1": fa,
		}

def        a						(      _UpperCAmelCase							:					List[str] ,   _UpperCAmelCase							:					Dict						):







		'''simple docstring'''





		__UpperCAmelCase    :     int													=	np.array(_UpperCAmelCase						)
		__UpperCAmelCase    :     Dict													=	np.array(_UpperCAmelCase						)
		__UpperCAmelCase    :     List[str]													=	en_sentvecs.shape[0]

		# mean centering
		__UpperCAmelCase    :     Union[str, Any]													=	en_sentvecs - np.mean(_UpperCAmelCase ,   axis=0						)
		__UpperCAmelCase    :     Tuple													=	in_sentvecs - np.mean(_UpperCAmelCase ,   axis=0						)

		__UpperCAmelCase    :     List[Any]													=	cdist(_UpperCAmelCase ,   _UpperCAmelCase ,   '''cosine'''						)
		__UpperCAmelCase    :     Union[str, Any]													=	np.array(range(_UpperCAmelCase						)						)
		__UpperCAmelCase    :     List[str]													=	sim.argsort(axis=1						)[:, :10]
		__UpperCAmelCase    :     Tuple													=	np.any(preds == actual[:, None] ,   axis=1						)
		return float(matches.mean()						)

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,_KWARGS_DESCRIPTION   )
class 		UpperCAmelCase__			(			datasets.Metric   ):




			'''simple docstring'''






			def  snake_case__     (   self							: Optional[int] ):
					'''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							: List[str]       ,       a_							: Any       ,       a_							: Union[str, Any] ):
					'''simple docstring'''





					if self.config_name == "cvit-mkb-clsr":
							return {"precision@10": precision_at_aa(a_       ,       a_ )}
					elif self.config_name in ["wiki-ner"]:
							return acc_and_fa(a_       ,       a_ )
					elif self.config_name in [
					    "wnli",
					    "copa",
					    "sna",
					    "csqa",
					    "wstp",
					    "inltkh",
					    "bbca",
					    "iitp-mr",
					    "iitp-pr",
					    "actsa-sc",
					    "md",
					]:
							return {"accuracy": simple_accuracy(a_       ,       a_ )}
					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"]''' )










import warnings
from typing import Dict, List, Optional, Tuple

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


__A   			=logging.get_logger(__name__)

class 		UpperCAmelCase__			(			__UpperCamelCase   ):




			'''simple docstring'''






			UpperCamelCase									=       ["""input_ids""", """attention_mask"""]




			def __init__(   self							: List[str]       ,       a_							: List[Any]="</s>"       ,       a_							: str="<unk>"       ,       a_							: Tuple="<pad>"       ,       a_							: List[Any]=1_25       ,       a_							: Any=None       ,       **a_							: Tuple       ,       ):
					'''simple docstring'''





					if extra_ids > 0 and additional_special_tokens is None:
							__UpperCAmelCase    :     Optional[Any]													=	[F'<extra_id_{i}>' for i in range(a_ )]
					elif extra_ids > 0 and additional_special_tokens is not None:
							# Check that we have the right number of extra_id special tokens
							__UpperCAmelCase    :     Optional[Any]													=	len(set(filter(lambda a_ : bool('''extra_id''' in str(a_ ) )       ,       a_ ) ) )
							if extra_tokens != extra_ids:
									raise ValueError(
									    F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'
									    ''' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the'''
									    ''' extra_ids tokens''' )

					__UpperCAmelCase    :     str													=	AddedToken(a_       ,       lstrip=a_       ,       rstrip=a_ ) if isinstance(a_       ,       a_ ) else pad_token
					__UpperCAmelCase    :     str													=	AddedToken(a_       ,       lstrip=a_       ,       rstrip=a_ ) if isinstance(a_       ,       a_ ) else eos_token
					__UpperCAmelCase    :     int													=	AddedToken(a_       ,       lstrip=a_       ,       rstrip=a_ ) if isinstance(a_       ,       a_ ) else unk_token

					super().__init__(
					    eos_token=a_       ,       unk_token=a_       ,       pad_token=a_       ,       extra_ids=a_       ,       additional_special_tokens=a_       ,       **a_       ,       )

					__UpperCAmelCase    :     Dict													=	extra_ids

					__UpperCAmelCase    :     Any													=	2**8  # utf is 8 bits

					# define special tokens dict
					__UpperCAmelCase    :     Dict[int, str]													=	{
					    self.pad_token: 0,
					    self.eos_token: 1,
					    self.unk_token: 2,
					}
					__UpperCAmelCase    :     Optional[int]													=	len(self.special_tokens_encoder )
					__UpperCAmelCase    :     Union[str, Any]													=	len(a_ )
					for i, token in enumerate(a_ ):
							__UpperCAmelCase    :     Union[str, Any]													=	self.vocab_size + i - n
					__UpperCAmelCase    :     Dict[str, int]													=	{v: k for k, v in self.special_tokens_encoder.items()}




			@property
			def  snake_case__     (   self							: Tuple ):
					'''simple docstring'''





					return self._utf_vocab_size + self._num_special_tokens + self._extra_ids




			def  snake_case__     (   self							: Any       ,       a_							: List[int]       ,       a_							: Optional[List[int]] = None       ,       a_							: bool = False ):
					'''simple docstring'''





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

					# normal case: some special tokens
					if token_ids_a is None:
							return ([0] * len(a_ )) + [1]
					return ([0] * len(a_ )) + [1] + ([0] * len(a_ )) + [1]




			def  snake_case__     (   self							: Any       ,       a_							: List[int] ):
					'''simple docstring'''





					if len(a_ ) > 0 and token_ids[-1] == self.eos_token_id:
							warnings.warn(
							    F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'
							    ''' eos tokens being added.''' )
							return token_ids
					else:
							return token_ids + [self.eos_token_id]




			def  snake_case__     (   self							: Union[str, Any]       ,       a_							: List[int]       ,       a_							: Optional[List[int]] = None ):
					'''simple docstring'''





					__UpperCAmelCase    :     str													=	[self.eos_token_id]

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




			def  snake_case__     (   self							: Optional[Any]       ,       a_							: List[int]       ,       a_							: Optional[List[int]] = None ):
					'''simple docstring'''





					__UpperCAmelCase    :     Union[str, Any]													=	self._add_eos_if_not_present(a_ )
					if token_ids_a is None:
							return token_ids_a
					else:
							__UpperCAmelCase    :     List[str]													=	self._add_eos_if_not_present(a_ )
							return token_ids_a + token_ids_a




			def  snake_case__     (   self							: List[Any]       ,       a_							: str ):
					'''simple docstring'''





					__UpperCAmelCase    :     str													=	[chr(a_ ) for i in text.encode('''utf-8''' )]
					return tokens




			def  snake_case__     (   self							: Optional[Any]       ,       a_							: int ):
					'''simple docstring'''





					if token in self.special_tokens_encoder:
							__UpperCAmelCase    :     Union[str, Any]													=	self.special_tokens_encoder[token]
					elif token in self.added_tokens_encoder:
							__UpperCAmelCase    :     Optional[Any]													=	self.added_tokens_encoder[token]
					elif len(a_ ) != 1:
							__UpperCAmelCase    :     int													=	self.unk_token_id
					else:
							__UpperCAmelCase    :     List[str]													=	ord(a_ ) + self._num_special_tokens
					return token_id




			def  snake_case__     (   self							: Union[str, Any]       ,       a_							: Optional[int] ):
					'''simple docstring'''





					if index in self.special_tokens_decoder:
							__UpperCAmelCase    :     Dict													=	self.special_tokens_decoder[index]
					else:
							__UpperCAmelCase    :     List[Any]													=	chr(index - self._num_special_tokens )
					return token




			def  snake_case__     (   self							: int       ,       a_							: Dict ):
					'''simple docstring'''





					__UpperCAmelCase    :     List[Any]													=	b''''''
					for token in tokens:
							if token in self.special_tokens_decoder:
									__UpperCAmelCase    :     Optional[int]													=	self.special_tokens_decoder[token].encode('''utf-8''' )
							elif token in self.added_tokens_decoder:
									__UpperCAmelCase    :     List[str]													=	self.special_tokens_decoder[token].encode('''utf-8''' )
							elif token in self.special_tokens_encoder:
									__UpperCAmelCase    :     Tuple													=	token.encode('''utf-8''' )
							elif token in self.added_tokens_encoder:
									__UpperCAmelCase    :     int													=	token.encode('''utf-8''' )
							else:
									__UpperCAmelCase    :     Any													=	bytes([ord(a_ )] )
							bstring += tok_string
					__UpperCAmelCase    :     Dict													=	bstring.decode('''utf-8'''       ,       errors='''ignore''' )
					return string




			def  snake_case__     (   self							: Tuple       ,       a_							: str       ,       a_							: Optional[str] = None ):
					'''simple docstring'''





					return ()





