
'''simple docstring'''







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

import datasets


_snake_case				:   int			 =				"""\
    @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},
}
"""

_snake_case				:   Tuple			 =				"""\
    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.
"""

_snake_case				:   Optional[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 			_a		(	_SCREAMING_SNAKE_CASE		:   List[str]	,			_SCREAMING_SNAKE_CASE		:   Optional[Any]  ):
						return float((preds == labels).mean()  )



def 			_a		(	_SCREAMING_SNAKE_CASE		:   Any	,			_SCREAMING_SNAKE_CASE		:   Tuple  ):
						_SCREAMING_SNAKE_CASE				= simple_accuracy(SCREAMING_SNAKE_CASE_	,			SCREAMING_SNAKE_CASE_  )
						_SCREAMING_SNAKE_CASE				= float(fa_score(y_true=SCREAMING_SNAKE_CASE_	,			y_pred=SCREAMING_SNAKE_CASE_  )  )
						return {
						    "accuracy": acc,
						    "f1": fa,
						}



def 			_a		(	_SCREAMING_SNAKE_CASE		:   str	,			_SCREAMING_SNAKE_CASE		:   Tuple  ):
						_SCREAMING_SNAKE_CASE				= np.array(SCREAMING_SNAKE_CASE_  )
						_SCREAMING_SNAKE_CASE				= np.array(SCREAMING_SNAKE_CASE_  )
						_SCREAMING_SNAKE_CASE				= en_sentvecs.shape[0]

						# mean centering
						_SCREAMING_SNAKE_CASE				= en_sentvecs - np.mean(SCREAMING_SNAKE_CASE_	,			axis=0  )
						_SCREAMING_SNAKE_CASE				= in_sentvecs - np.mean(SCREAMING_SNAKE_CASE_	,			axis=0  )

						_SCREAMING_SNAKE_CASE				= cdist(SCREAMING_SNAKE_CASE_	,			SCREAMING_SNAKE_CASE_	,			"cosine"  )
						_SCREAMING_SNAKE_CASE				= np.array(range(SCREAMING_SNAKE_CASE_  )  )
						_SCREAMING_SNAKE_CASE				= sim.argsort(axis=1  )[:, :10]
						_SCREAMING_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     lowercase       (				self      ):







								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     lowercase       (				self					,						UpperCamelCase					,						UpperCamelCase      ):







								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 os
from typing import List, Optional, Union

from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
from ..auto import AutoTokenizer


class 			lowerCAmelCase (				__UpperCAmelCase			):
		a							:					Optional[int]       =					["""image_processor""", """tokenizer"""]
		a							:					Optional[int]       =					"""BlipImageProcessor"""
		a							:					Optional[int]       =					"""AutoTokenizer"""




		def __init__(				self					,						UpperCamelCase					,						UpperCamelCase					,						UpperCamelCase      ):
								super().__init__(UpperCamelCase					,						UpperCamelCase      )

								# add QFormer tokenizer
								_SCREAMING_SNAKE_CASE				= qformer_tokenizer




		def __call__(				self					,						UpperCamelCase = None					,						UpperCamelCase = None					,						UpperCamelCase = True					,						UpperCamelCase = False					,						UpperCamelCase = None					,						UpperCamelCase = None					,						UpperCamelCase = 0					,						UpperCamelCase = None					,						UpperCamelCase = None					,						UpperCamelCase = False					,						UpperCamelCase = False					,						UpperCamelCase = False					,						UpperCamelCase = False					,						UpperCamelCase = False					,						UpperCamelCase = True					,						UpperCamelCase = None					,						**UpperCamelCase					,						):
								if images is None and text is None:
														raise ValueError("You have to specify at least images or text."      )

								_SCREAMING_SNAKE_CASE				= BatchFeature()

								if text is not None:
														_SCREAMING_SNAKE_CASE				= self.tokenizer(
														    text=UpperCamelCase					,						add_special_tokens=UpperCamelCase					,						padding=UpperCamelCase					,						truncation=UpperCamelCase					,						max_length=UpperCamelCase					,						stride=UpperCamelCase					,						pad_to_multiple_of=UpperCamelCase					,						return_attention_mask=UpperCamelCase					,						return_overflowing_tokens=UpperCamelCase					,						return_special_tokens_mask=UpperCamelCase					,						return_offsets_mapping=UpperCamelCase					,						return_token_type_ids=UpperCamelCase					,						return_length=UpperCamelCase					,						verbose=UpperCamelCase					,						return_tensors=UpperCamelCase					,						**UpperCamelCase					,						)
														encoding.update(UpperCamelCase      )
														_SCREAMING_SNAKE_CASE				= self.qformer_tokenizer(
														    text=UpperCamelCase					,						add_special_tokens=UpperCamelCase					,						padding=UpperCamelCase					,						truncation=UpperCamelCase					,						max_length=UpperCamelCase					,						stride=UpperCamelCase					,						pad_to_multiple_of=UpperCamelCase					,						return_attention_mask=UpperCamelCase					,						return_overflowing_tokens=UpperCamelCase					,						return_special_tokens_mask=UpperCamelCase					,						return_offsets_mapping=UpperCamelCase					,						return_token_type_ids=UpperCamelCase					,						return_length=UpperCamelCase					,						verbose=UpperCamelCase					,						return_tensors=UpperCamelCase					,						**UpperCamelCase					,						)
														_SCREAMING_SNAKE_CASE				= qformer_text_encoding.pop("input_ids"      )
														_SCREAMING_SNAKE_CASE				= qformer_text_encoding.pop("attention_mask"      )

								if images is not None:
														_SCREAMING_SNAKE_CASE				= self.image_processor(UpperCamelCase					,						return_tensors=UpperCamelCase      )
														encoding.update(UpperCamelCase      )

								return encoding




		def     lowercase       (				self					,						*UpperCamelCase					,						**UpperCamelCase      ):
								return self.tokenizer.batch_decode(*UpperCamelCase					,						**UpperCamelCase      )




		def     lowercase       (				self					,						*UpperCamelCase					,						**UpperCamelCase      ):
								return self.tokenizer.decode(*UpperCamelCase					,						**UpperCamelCase      )




		@property
		# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
		def     lowercase       (				self      ):
								_SCREAMING_SNAKE_CASE				= self.tokenizer.model_input_names
								_SCREAMING_SNAKE_CASE				= self.image_processor.model_input_names
								return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names      )      )




		def     lowercase       (				self					,						UpperCamelCase					,						**UpperCamelCase      ):
								if os.path.isfile(UpperCamelCase      ):
														raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file'      )
								os.makedirs(UpperCamelCase					,						exist_ok=UpperCamelCase      )
								_SCREAMING_SNAKE_CASE				= os.path.join(UpperCamelCase					,						"qformer_tokenizer"      )
								self.qformer_tokenizer.save_pretrained(UpperCamelCase      )
								return super().save_pretrained(UpperCamelCase					,						**UpperCamelCase      )




		@classmethod
		def     lowercase       (				cls					,						UpperCamelCase					,						**UpperCamelCase      ):
								_SCREAMING_SNAKE_CASE				= AutoTokenizer.from_pretrained(UpperCamelCase					,						subfolder="qformer_tokenizer"      )
								_SCREAMING_SNAKE_CASE				= cls._get_arguments_from_pretrained(UpperCamelCase					,						**UpperCamelCase      )
								args.append(UpperCamelCase      )
								return cls(*UpperCamelCase      )