






"""simple docstring"""


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

import datasets


lowercase_				     =     '\\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'

lowercase_				     =     '\\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'

lowercase_				     =     '\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 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase ):




  """simple docstring"""







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



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase ):




  """simple docstring"""







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



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase ):




  """simple docstring"""







  __A									= np.array(__UpperCamelCase )
  __A									= np.array(__UpperCamelCase )
  __A									= en_sentvecs.shape[0]

  # mean centering
  __A									= en_sentvecs - np.mean(__UpperCamelCase		,       axis=0 )
  __A									= in_sentvecs - np.mean(__UpperCamelCase		,       axis=0 )

  __A									= cdist(__UpperCamelCase		,       __UpperCamelCase		,       '''cosine''' )
  __A									= np.array(range(__UpperCamelCase ) )
  __A									= sim.argsort(axis=1 )[:, :1_0]
  __A									= np.any(preds == actual[:, None]		,       axis=1 )
  return float(matches.mean() )





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


   '''simple docstring'''

   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''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 				_SCREAMING_SNAKE_CASE				(	self :     Tuple,       _lowerCamelCase :     List[str],       _lowerCamelCase :     Tuple  ):

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

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowercase_				     =     random.Random()

if is_torch_available():
       import torch



def 					lowerCAmelCase				(    __UpperCamelCase		,       __UpperCamelCase=1.0		,       __UpperCamelCase=None		,       __UpperCamelCase=None ):




  """simple docstring"""







  if rng is None:
    __A									= global_rng

  __A									= []
  for batch_idx in range(shape[0] ):
    values.append([] )
    for _ in range(shape[1] ):
      values[-1].append(rng.random() * scale )

  return values


class 					snake_case		(							unittest.TestCase						):


   '''simple docstring'''

   def __init__(	self :     Any,       _lowerCamelCase :     List[str],       _lowerCamelCase :     Any=7,       _lowerCamelCase :     Optional[int]=4_00,       _lowerCamelCase :     Optional[int]=20_00,       _lowerCamelCase :     Dict=1,       _lowerCamelCase :     Optional[Any]=0.0,       _lowerCamelCase :     int=1_60_00,       _lowerCamelCase :     Optional[int]=True,       _lowerCamelCase :     Dict=True,       ):

     '''simple docstring'''
     __A									= parent
     __A									= batch_size
     __A									= min_seq_length
     __A									= max_seq_length
     __A									= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
     __A									= feature_size
     __A									= padding_value
     __A									= sampling_rate
     __A									= return_attention_mask
     __A									= do_normalize


   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     return {
         "feature_size": self.feature_size,
         "padding_value": self.padding_value,
         "sampling_rate": self.sampling_rate,
         "return_attention_mask": self.return_attention_mask,
         "do_normalize": self.do_normalize,
     }






   def 				_SCREAMING_SNAKE_CASE				(	self :     Any,       _lowerCamelCase :     Optional[Any]=False,       _lowerCamelCase :     int=False  ):

     '''simple docstring'''
     def _flatten(_lowerCamelCase :     List[str]  ):
       return list(itertools.chain(*_lowerCamelCase  )  )

     if equal_length:
       __A									= floats_list((self.batch_size, self.max_seq_length)  )
     else:
       # make sure that inputs increase in size
       __A									= [
           _flatten(floats_list((x, self.feature_size)  )  )
           for x in range(self.min_seq_length,       self.max_seq_length,       self.seq_length_diff  )
       ]

     if numpify:
       __A									= [np.asarray(_lowerCamelCase  ) for x in speech_inputs]

     return speech_inputs





@require_torch
@require_torchaudio
class 					snake_case		(							_lowerCAmelCase   ,	unittest.TestCase						):


   '''simple docstring'''

   A_						:	int						 = ASTFeatureExtractor


   def 				_SCREAMING_SNAKE_CASE				(	self :     Tuple  ):

     '''simple docstring'''
     __A									= ASTFeatureExtractionTester(self  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Dict  ):

     '''simple docstring'''
     # Tests that all call wrap to encode_plus and batch_encode_plus
     __A									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     # create three inputs of length 800, 1000, and 1200
     __A									= [floats_list((1, x)  )[0] for x in range(8_00,       14_00,       2_00  )]
     __A									= [np.asarray(_lowerCamelCase  ) for speech_input in speech_inputs]

     # Test not batched input
     __A									= feat_extract(speech_inputs[0],       return_tensors='''np'''  ).input_values
     __A									= feat_extract(np_speech_inputs[0],       return_tensors='''np'''  ).input_values
     self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )

     # Test batched
     __A									= feat_extract(_lowerCamelCase,       padding=_lowerCamelCase,       return_tensors='''np'''  ).input_values
     __A									= feat_extract(_lowerCamelCase,       padding=_lowerCamelCase,       return_tensors='''np'''  ).input_values
     for enc_seq_a, enc_seq_a in zip(_lowerCamelCase,       _lowerCamelCase  ):
       self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )

     # Test 2-D numpy arrays are batched.
     __A									= [floats_list((1, x)  )[0] for x in (8_00, 8_00, 8_00)]
     __A									= np.asarray(_lowerCamelCase  )
     __A									= feat_extract(_lowerCamelCase,       return_tensors='''np'''  ).input_values
     __A									= feat_extract(_lowerCamelCase,       return_tensors='''np'''  ).input_values
     for enc_seq_a, enc_seq_a in zip(_lowerCamelCase,       _lowerCamelCase  ):
       self.assertTrue(np.allclose(_lowerCamelCase,       _lowerCamelCase,       atol=1e-3  )  )


   @require_torch
   def 				_SCREAMING_SNAKE_CASE				(	self :     Union[str, Any]  ):

     '''simple docstring'''
     import torch

     __A									= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A									= np.random.rand(1_00  ).astype(np.floataa  )
     __A									= np_speech_inputs.tolist()

     for inputs in [py_speech_inputs, np_speech_inputs]:
       __A									= feature_extractor.pad([{'''input_values''': inputs}],       return_tensors='''np'''  )
       self.assertTrue(np_processed.input_values.dtype == np.floataa  )
       __A									= feature_extractor.pad([{'''input_values''': inputs}],       return_tensors='''pt'''  )
       self.assertTrue(pt_processed.input_values.dtype == torch.floataa  )


   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[int],       _lowerCamelCase :     Union[str, Any]  ):

     '''simple docstring'''
     from datasets import load_dataset

     __A									= load_dataset('''hf-internal-testing/librispeech_asr_dummy''',       '''clean''',       split='''validation'''  )
     # automatic decoding with librispeech
     __A									= ds.sort('''id'''  ).select(range(_lowerCamelCase  )  )[:num_samples]['''audio''']

     return [x["array"] for x in speech_samples]






   @require_torch
   def 				_SCREAMING_SNAKE_CASE				(	self :     Optional[Any]  ):

     '''simple docstring'''
     # fmt: off
     __A									= torch.tensor(
         [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76,
          -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33,
          -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36,
          -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69]  )
     # fmt: on

     __A									= self._load_datasamples(1  )
     __A									= ASTFeatureExtractor()
     __A									= feature_extractor(_lowerCamelCase,       return_tensors='''pt'''  ).input_values
     self.assertEquals(input_values.shape,       (1, 10_24, 1_28)  )
     self.assertTrue(torch.allclose(input_values[0, 0, :30],       _lowerCamelCase,       atol=1e-4  )  )




