




'''simple docstring'''



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

import datasets


UpperCAmelCase_							:	Tuple	     =		'''\
    @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},
}
'''

UpperCAmelCase_							:	Optional[Any]	     =		'''\
    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.
'''

UpperCAmelCase_							:	int	     =		'''
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       _UpperCamelCase			(_lowerCamelCase				:  Optional[int] ,						_lowerCamelCase				:  List[str]						)-> str:




     '''simple docstring'''





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







def       _UpperCamelCase			(_lowerCamelCase				:  Tuple ,						_lowerCamelCase				:  List[str]						)-> Tuple:




     '''simple docstring'''





     __snake_case            =	simple_accuracy(_lowerCamelCase ,						_lowerCamelCase						)
     __snake_case            =	float(fa_score(y_true=_lowerCamelCase ,						y_pred=_lowerCamelCase						)						)
     return {
         "accuracy": acc,
         "f1": fa,
     }







def       _UpperCamelCase			(_lowerCamelCase				:  List[Any] ,						_lowerCamelCase				:  Optional[Any]						)-> str:




     '''simple docstring'''





     __snake_case            =	np.array(_lowerCamelCase						)
     __snake_case            =	np.array(_lowerCamelCase						)
     __snake_case            =	en_sentvecs.shape[0]

     # mean centering
     __snake_case            =	en_sentvecs - np.mean(_lowerCamelCase ,						axis=0						)
     __snake_case            =	in_sentvecs - np.mean(_lowerCamelCase ,						axis=0						)

     __snake_case            =	cdist(_lowerCamelCase ,						_lowerCamelCase ,						'''cosine'''						)
     __snake_case            =	np.array(range(_lowerCamelCase						)						)
     __snake_case            =	sim.argsort(axis=1						)[:, :10]
     __snake_case            =	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):


       def    lowerCAmelCase   ( self	)   ->	str:



            '''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    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)   ->	Optional[int]:



            '''simple docstring'''




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



from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


UpperCAmelCase_							:	int	     =		logging.get_logger(__name__)

UpperCAmelCase_							:	Dict	     =		{
    '''microsoft/swin-tiny-patch4-window7-224''': (
        '''https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json'''
    ),
    # See all Swin models at https://huggingface.co/models?filter=swin
}





class      lowerCAmelCase (			__lowerCAmelCase					, __lowerCAmelCase):
       __lowercase	:   List[Any]										=      '''swin'''

       __lowercase	:   str										=      {
           '''num_attention_heads''': '''num_heads''',
           '''num_hidden_layers''': '''num_layers''',
       }


       def __init__( self     ,	__SCREAMING_SNAKE_CASE=224     ,	__SCREAMING_SNAKE_CASE=4     ,	__SCREAMING_SNAKE_CASE=3     ,	__SCREAMING_SNAKE_CASE=96     ,	__SCREAMING_SNAKE_CASE=[2, 2, 6, 2]     ,	__SCREAMING_SNAKE_CASE=[3, 6, 12, 24]     ,	__SCREAMING_SNAKE_CASE=7     ,	__SCREAMING_SNAKE_CASE=4.0     ,	__SCREAMING_SNAKE_CASE=True     ,	__SCREAMING_SNAKE_CASE=0.0     ,	__SCREAMING_SNAKE_CASE=0.0     ,	__SCREAMING_SNAKE_CASE=0.1     ,	__SCREAMING_SNAKE_CASE="gelu"     ,	__SCREAMING_SNAKE_CASE=False     ,	__SCREAMING_SNAKE_CASE=0.02     ,	__SCREAMING_SNAKE_CASE=1E-5     ,	__SCREAMING_SNAKE_CASE=32     ,	__SCREAMING_SNAKE_CASE=None     ,	__SCREAMING_SNAKE_CASE=None     ,	**__SCREAMING_SNAKE_CASE     ,	)   ->	int:



            '''simple docstring'''




            super().__init__(**__SCREAMING_SNAKE_CASE	)

            __snake_case            =	image_size
            __snake_case            =	patch_size
            __snake_case            =	num_channels
            __snake_case            =	embed_dim
            __snake_case            =	depths
            __snake_case            =	len(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	num_heads
            __snake_case            =	window_size
            __snake_case            =	mlp_ratio
            __snake_case            =	qkv_bias
            __snake_case            =	hidden_dropout_prob
            __snake_case            =	attention_probs_dropout_prob
            __snake_case            =	drop_path_rate
            __snake_case            =	hidden_act
            __snake_case            =	use_absolute_embeddings
            __snake_case            =	layer_norm_eps
            __snake_case            =	initializer_range
            __snake_case            =	encoder_stride
            # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
            # this indicates the channel dimension after the last stage of the model
            __snake_case            =	int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE	) - 1)	)
            __snake_case            =	['''stem'''] + [F'''stage{idx}''' for idx in range(1     ,	len(__SCREAMING_SNAKE_CASE	) + 1	)]
            __snake_case       ,     __snake_case            =	get_aligned_output_features_output_indices(
                out_features=__SCREAMING_SNAKE_CASE     ,	out_indices=__SCREAMING_SNAKE_CASE     ,	stage_names=self.stage_names	)





class      lowerCAmelCase (			__lowerCAmelCase):
       __lowercase	:   Optional[int]										=      version.parse('''1.11''')


       @property
       def    lowerCAmelCase   ( self	)   ->	Mapping[str, Mapping[int, str]]:



            '''simple docstring'''




            return OrderedDict(
                [
                    ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                ]	)




       @property
       def    lowerCAmelCase   ( self	)   ->	float:



            '''simple docstring'''




            return 1E-4






