


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

import datasets


UpperCAmelCase   :    Optional[int]     =		"\\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"

UpperCAmelCase   :    Union[str, Any]     =		"\\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"

UpperCAmelCase   :    List[Any]     =		"\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						(							lowerCamelCase__		:						Optional[int]  ,							lowerCamelCase__		:						Union[str, Any]      ):





			'''simple docstring'''




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






def 	__lowerCamelCase						(							lowerCamelCase__		:						Optional[Any]  ,							lowerCamelCase__		:						Union[str, Any]      ):





			'''simple docstring'''




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






def 	__lowerCamelCase						(							lowerCamelCase__		:						Any  ,							lowerCamelCase__		:						Optional[Any]      ):





			'''simple docstring'''




			lowerCamelCase    		=  np.array(lowerCamelCase__      )
			lowerCamelCase    		=  np.array(lowerCamelCase__      )
			lowerCamelCase    		=  en_sentvecs.shape[0]

			# mean centering
			lowerCamelCase    		=  en_sentvecs - np.mean(lowerCamelCase__  ,							axis=0      )
			lowerCamelCase    		=  in_sentvecs - np.mean(lowerCamelCase__  ,							axis=0      )

			lowerCamelCase    		=  cdist(lowerCamelCase__  ,							lowerCamelCase__  ,							"""cosine"""      )
			lowerCamelCase    		=  np.array(range(lowerCamelCase__      )      )
			lowerCamelCase    		=  sim.argsort(axis=1      )[:, :10]
			lowerCamelCase    		=  np.any(preds == actual[:, None]  ,							axis=1      )
			return float(matches.mean()      )







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



		"""simple docstring"""

		def 					__A   ( self	)  -> List[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 					__A   ( self		,      A		,      A	)  -> Tuple:







					'''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\"]"""	)





from math import ceil
from typing import List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging


UpperCAmelCase   :    Any     =		logging.get_logger(__name__)







class        __lowercase       (							a_  ):



		"""simple docstring"""

		UpperCamelCase     :					List[Any]			       =		["audio_values", "audio_mask"]







		def __init__( self		,      A=20_48		,      A=1		,      A=[16, 16]		,      A=1_28		,      A=4_41_00		,      A=86		,      A=20_48		,      A=0.0		,      **A		,      )  -> Dict:







					'''simple docstring'''







					super().__init__(
					    feature_size=A		,      sampling_rate=A		,      padding_value=A		,      **A		,      )

					lowerCamelCase    		=  spectrogram_length
					lowerCamelCase    		=  num_channels
					lowerCamelCase    		=  patch_size
					lowerCamelCase    		=  feature_size // self.patch_size[1]
					lowerCamelCase    		=  n_fft
					lowerCamelCase    		=  sampling_rate // hop_length_to_sampling_rate
					lowerCamelCase    		=  sampling_rate
					lowerCamelCase    		=  padding_value
					lowerCamelCase    		=  mel_filter_bank(
					    num_frequency_bins=1 + n_fft // 2		,      num_mel_filters=A		,      min_frequency=0.0		,      max_frequency=22050.0		,      sampling_rate=A		,      norm="""slaney"""		,      mel_scale="""slaney"""		,      ).T







		def 					__A   ( self		,      A	)  -> np.ndarray:







					'''simple docstring'''







					lowerCamelCase    		=  spectrogram(
					    A		,      window_function(self.n_fft		,      """hann"""	)		,      frame_length=self.n_fft		,      hop_length=self.hop_length		,      power=2.0		,      mel_filters=self.mel_filters.T		,      log_mel="""dB"""		,      db_range=80.0		,      )
					lowerCamelCase    		=  log_spec[:, :-1]
					lowerCamelCase    		=  log_spec - 20.0
					lowerCamelCase    		=  np.clip(log_spec / 40.0		,      -2.0		,      0.0	) + 1.0
					return log_spec







		def __call__( self		,      A		,      A = None		,      A = True		,      A = None		,      A = False		,      A = False		,      **A		,      )  -> BatchFeature:







					'''simple docstring'''







					if sampling_rate is not None:
								if sampling_rate != self.sampling_rate:
											raise ValueError(
											    """This feature extractor is set to support sampling rate"""
											    F' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled'
											    F' with {self.sampling_rate} and not {sampling_rate}.'	)
					else:
								logger.warning(
								    """It is strongly recommended to pass the `sampling_rate` argument to this function. """
								    """Failing to do so can result in silent errors that might be hard to debug."""	)

					lowerCamelCase    		=  isinstance(A		,      np.ndarray	) and len(raw_speech.shape	) > 1
					if is_batched_numpy and len(raw_speech.shape	) > 2:
								raise ValueError(F'Only mono-channel audio is supported for input to {self}'	)
					lowerCamelCase    		=  is_batched_numpy or (
					    isinstance(A		,      (list, tuple)	) and (isinstance(raw_speech[0]		,      (np.ndarray, tuple, list)	))
					)
					if is_batched:
								lowerCamelCase    		=  [np.asarray([speech]		,      dtype=np.floataa	).T for speech in raw_speech]
					elif not is_batched and not isinstance(A		,      np.ndarray	):
								lowerCamelCase    		=  np.asarray(A		,      dtype=np.floataa	)
					elif isinstance(A		,      np.ndarray	) and raw_speech.dtype is np.dtype(np.floataa	):
								lowerCamelCase    		=  raw_speech.astype(np.floataa	)
					# always return batch
					if not is_batched:
								lowerCamelCase    		=  [np.asarray([raw_speech]	).T]

					# Convert audio signals to log mel spectrograms, truncate by time axis
					lowerCamelCase    		=  [
					    self._np_extract_fbank_features(waveform.squeeze()	).T[: self.spectrogram_length] for waveform in raw_speech
					]
					if isinstance(audio_features[0]		,      A	):
								lowerCamelCase    		=  [np.asarray(A		,      dtype=np.floataa	) for feature in audio_features]

					# Create audio attention mask
					lowerCamelCase    		=  max(
					    [ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len for feature in audio_features]	)  # The maximum number of audio patches in a batch
					if return_attention_mask:
								lowerCamelCase    		=  [
								    (ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len) * [1]
								    + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]	) * self.freq_len) * [0]
								    for feature in audio_features
								]
								lowerCamelCase    		=  np.array(A	).astype(np.floataa	)

					# convert into correct format for padding
					lowerCamelCase    		=  max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
					lowerCamelCase    		=  np.ones([len(A	), 1, max_time_len, self.feature_size]	).astype(np.floataa	)
					lowerCamelCase    		=  padded_audio_features * self.padding_value
					for i in range(len(A	)	):
								lowerCamelCase    		=  audio_features[i]
								lowerCamelCase    		=  feature

					# return as BatchFeature
					if return_attention_mask:
								lowerCamelCase    		=  {"""audio_values""": padded_audio_features, """audio_mask""": audio_mask}
					else:
								lowerCamelCase    		=  {"""audio_values""": padded_audio_features}

					lowerCamelCase    		=  BatchFeature(data=A		,      tensor_type=A	)
					return encoded_inputs

