



"""simple docstring"""






import math
from typing import Dict, Iterable, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
	import torch

if is_vision_available():
	import PIL


__snake_case							:   Optional[int]      =    logging.get_logger(__name__)


def 			_lowercase				(  __snake_case					,__snake_case					,__snake_case					,__snake_case	)						->   Tuple[int, int]:
			def constraint_to_multiple_of(__snake_case					,__snake_case					,__snake_case=0					,__snake_case=None	):
						__lowerCAmelCase      :  Union[str, Any]												=       round(val / multiple	) * multiple

						if max_val is not None and x > max_val:
									__lowerCAmelCase      :  str												=       math.floor(val / multiple	) * multiple

						if x < min_val:
									__lowerCAmelCase      :  Optional[Any]												=       math.ceil(val / multiple	) * multiple

						return x

			__lowerCAmelCase      :  Union[str, Any]												=       (output_size, output_size) if isinstance(__snake_case					,__snake_case	) else output_size

			__lowerCAmelCase						,	__lowerCAmelCase      :  List[str]												=       get_image_size(__snake_case	)
			__lowerCAmelCase						,	__lowerCAmelCase      :  List[str]												=       output_size

			# determine new height and width
			__lowerCAmelCase      :  List[str]												=       output_height / input_height
			__lowerCAmelCase      :  List[str]												=       output_width / input_width

			if keep_aspect_ratio:
						# scale as little as possible
						if abs(1 - scale_width	) < abs(1 - scale_height	):
									# fit width
									__lowerCAmelCase      :  Dict												=       scale_width
						else:
									# fit height
									__lowerCAmelCase      :  Optional[int]												=       scale_height

			__lowerCAmelCase      :  Any												=       constraint_to_multiple_of(scale_height * input_height					,multiple=__snake_case	)
			__lowerCAmelCase      :  List[str]												=       constraint_to_multiple_of(scale_width * input_width					,multiple=__snake_case	)

			return (new_height, new_width)





class 			A__   (  __SCREAMING_SNAKE_CASE							):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE          =	['pixel_values']

	def __init__(     self:		Dict       ,			_SCREAMING_SNAKE_CASE:		bool = True       ,			_SCREAMING_SNAKE_CASE:		Dict[str, int] = None       ,			_SCREAMING_SNAKE_CASE:		PILImageResampling = PILImageResampling.BILINEAR       ,			_SCREAMING_SNAKE_CASE:		bool = False       ,			_SCREAMING_SNAKE_CASE:		int = 1       ,			_SCREAMING_SNAKE_CASE:		bool = True       ,			_SCREAMING_SNAKE_CASE:		Union[int, float] = 1 / 255       ,			_SCREAMING_SNAKE_CASE:		bool = True       ,			_SCREAMING_SNAKE_CASE:		Optional[Union[float, List[float]]] = None       ,			_SCREAMING_SNAKE_CASE:		Optional[Union[float, List[float]]] = None       ,			**_SCREAMING_SNAKE_CASE:		Union[str, Any]       ,			)				->       None:

				"""simple docstring"""

				super().__init__(**_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  List[Any]												=       size if size is not None else {"height": 384, "width": 384}
				__lowerCAmelCase      :  List[Any]												=       get_size_dict(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Optional[int]												=       do_resize
				__lowerCAmelCase      :  Optional[int]												=       size
				__lowerCAmelCase      :  Dict												=       keep_aspect_ratio
				__lowerCAmelCase      :  List[Any]												=       ensure_multiple_of
				__lowerCAmelCase      :  List[str]												=       resample
				__lowerCAmelCase      :  Dict												=       do_rescale
				__lowerCAmelCase      :  Tuple												=       rescale_factor
				__lowerCAmelCase      :  Tuple												=       do_normalize
				__lowerCAmelCase      :  Optional[Any]												=       image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
				__lowerCAmelCase      :  Dict												=       image_std if image_std is not None else IMAGENET_STANDARD_STD

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict       ,			_SCREAMING_SNAKE_CASE:		np.ndarray       ,			_SCREAMING_SNAKE_CASE:		Dict[str, int]       ,			_SCREAMING_SNAKE_CASE:		bool = False       ,			_SCREAMING_SNAKE_CASE:		int = 1       ,			_SCREAMING_SNAKE_CASE:		PILImageResampling = PILImageResampling.BICUBIC       ,			_SCREAMING_SNAKE_CASE:		Optional[Union[str, ChannelDimension]] = None       ,			**_SCREAMING_SNAKE_CASE:		str       ,			)				->       np.ndarray:

				"""simple docstring"""

				__lowerCAmelCase      :  Any												=       get_size_dict(_SCREAMING_SNAKE_CASE)
				if "height" not in size or "width" not in size:
							raise ValueError(F"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""")
				__lowerCAmelCase      :  str												=       get_resize_output_image_size(
				    _SCREAMING_SNAKE_CASE       ,			output_size=(size["height"], size["width"])       ,			keep_aspect_ratio=_SCREAMING_SNAKE_CASE       ,			multiple=_SCREAMING_SNAKE_CASE       ,			)
				return resize(_SCREAMING_SNAKE_CASE       ,			size=_SCREAMING_SNAKE_CASE       ,			resample=_SCREAMING_SNAKE_CASE       ,			data_format=_SCREAMING_SNAKE_CASE       ,			**_SCREAMING_SNAKE_CASE)

	def 							_SCREAMING_SNAKE_CASE   (     self:		int       ,			_SCREAMING_SNAKE_CASE:		np.ndarray       ,			_SCREAMING_SNAKE_CASE:		Union[int, float]       ,			_SCREAMING_SNAKE_CASE:		Optional[Union[str, ChannelDimension]] = None       ,			**_SCREAMING_SNAKE_CASE:		Tuple       ,			)				->       Optional[int]:

				"""simple docstring"""

				return rescale(_SCREAMING_SNAKE_CASE       ,			scale=_SCREAMING_SNAKE_CASE       ,			data_format=_SCREAMING_SNAKE_CASE       ,			**_SCREAMING_SNAKE_CASE)

	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		np.ndarray       ,			_SCREAMING_SNAKE_CASE:		Union[float, List[float]]       ,			_SCREAMING_SNAKE_CASE:		Union[float, List[float]]       ,			_SCREAMING_SNAKE_CASE:		Optional[Union[str, ChannelDimension]] = None       ,			**_SCREAMING_SNAKE_CASE:		Optional[Any]       ,			)				->       np.ndarray:

				"""simple docstring"""

				return normalize(_SCREAMING_SNAKE_CASE       ,			mean=_SCREAMING_SNAKE_CASE       ,			std=_SCREAMING_SNAKE_CASE       ,			data_format=_SCREAMING_SNAKE_CASE       ,			**_SCREAMING_SNAKE_CASE)

	def 							_SCREAMING_SNAKE_CASE   (     self:		str       ,			_SCREAMING_SNAKE_CASE:		ImageInput       ,			_SCREAMING_SNAKE_CASE:		bool = None       ,			_SCREAMING_SNAKE_CASE:		int = None       ,			_SCREAMING_SNAKE_CASE:		bool = None       ,			_SCREAMING_SNAKE_CASE:		int = None       ,			_SCREAMING_SNAKE_CASE:		PILImageResampling = None       ,			_SCREAMING_SNAKE_CASE:		bool = None       ,			_SCREAMING_SNAKE_CASE:		float = None       ,			_SCREAMING_SNAKE_CASE:		bool = None       ,			_SCREAMING_SNAKE_CASE:		Optional[Union[float, List[float]]] = None       ,			_SCREAMING_SNAKE_CASE:		Optional[Union[float, List[float]]] = None       ,			_SCREAMING_SNAKE_CASE:		Optional[Union[str, TensorType]] = None       ,			_SCREAMING_SNAKE_CASE:		ChannelDimension = ChannelDimension.FIRST       ,			**_SCREAMING_SNAKE_CASE:		List[Any]       ,			)				->       PIL.Image.Image:

				"""simple docstring"""

				__lowerCAmelCase      :  Dict												=       do_resize if do_resize is not None else self.do_resize
				__lowerCAmelCase      :  List[Any]												=       size if size is not None else self.size
				__lowerCAmelCase      :  Any												=       get_size_dict(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Tuple												=       keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
				__lowerCAmelCase      :  str												=       ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
				__lowerCAmelCase      :  str												=       resample if resample is not None else self.resample
				__lowerCAmelCase      :  str												=       do_rescale if do_rescale is not None else self.do_rescale
				__lowerCAmelCase      :  Dict												=       rescale_factor if rescale_factor is not None else self.rescale_factor
				__lowerCAmelCase      :  List[str]												=       do_normalize if do_normalize is not None else self.do_normalize
				__lowerCAmelCase      :  str												=       image_mean if image_mean is not None else self.image_mean
				__lowerCAmelCase      :  Dict												=       image_std if image_std is not None else self.image_std

				__lowerCAmelCase      :  Any												=       make_list_of_images(_SCREAMING_SNAKE_CASE)

				if not valid_images(_SCREAMING_SNAKE_CASE):
							raise ValueError(
							    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
							    "torch.Tensor, tf.Tensor or jax.ndarray.")

				if do_resize and size is None or resample is None:
							raise ValueError("Size and resample must be specified if do_resize is True.")

				if do_rescale and rescale_factor is None:
							raise ValueError("Rescale factor must be specified if do_rescale is True.")

				if do_normalize and (image_mean is None or image_std is None):
							raise ValueError("Image mean and std must be specified if do_normalize is True.")

				# All transformations expect numpy arrays.
				__lowerCAmelCase      :  Dict												=       [to_numpy_array(_SCREAMING_SNAKE_CASE) for image in images]

				if do_resize:
							__lowerCAmelCase      :  Dict												=       [self.resize(image=_SCREAMING_SNAKE_CASE       ,			size=_SCREAMING_SNAKE_CASE       ,			resample=_SCREAMING_SNAKE_CASE) for image in images]

				if do_rescale:
							__lowerCAmelCase      :  Dict												=       [self.rescale(image=_SCREAMING_SNAKE_CASE       ,			scale=_SCREAMING_SNAKE_CASE) for image in images]

				if do_normalize:
							__lowerCAmelCase      :  List[Any]												=       [self.normalize(image=_SCREAMING_SNAKE_CASE       ,			mean=_SCREAMING_SNAKE_CASE       ,			std=_SCREAMING_SNAKE_CASE) for image in images]

				__lowerCAmelCase      :  Optional[int]												=       [to_channel_dimension_format(_SCREAMING_SNAKE_CASE       ,			_SCREAMING_SNAKE_CASE) for image in images]

				__lowerCAmelCase      :  Optional[Any]												=       {"pixel_values": images}
				return BatchFeature(data=_SCREAMING_SNAKE_CASE       ,			tensor_type=_SCREAMING_SNAKE_CASE)







	def 							_SCREAMING_SNAKE_CASE   (     self:		str       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		List[Tuple] = None)				->       List[str]:

				"""simple docstring"""

				__lowerCAmelCase      :  Optional[int]												=       outputs.logits

				# Resize logits and compute semantic segmentation maps
				if target_sizes is not None:
							if len(_SCREAMING_SNAKE_CASE) != len(_SCREAMING_SNAKE_CASE):
										raise ValueError(
										    "Make sure that you pass in as many target sizes as the batch dimension of the logits")

							if is_torch_tensor(_SCREAMING_SNAKE_CASE):
										__lowerCAmelCase      :  int												=       target_sizes.numpy()

							__lowerCAmelCase      :  Dict												=       []

							for idx in range(len(_SCREAMING_SNAKE_CASE)):
										__lowerCAmelCase      :  Tuple												=       torch.nn.functional.interpolate(
										    logits[idx].unsqueeze(dim=0)       ,			size=target_sizes[idx]       ,			mode="bilinear"       ,			align_corners=_SCREAMING_SNAKE_CASE)
										__lowerCAmelCase      :  Optional[Any]												=       resized_logits[0].argmax(dim=0)
										semantic_segmentation.append(_SCREAMING_SNAKE_CASE)
				else:
							__lowerCAmelCase      :  List[str]												=       logits.argmax(dim=1)
							__lowerCAmelCase      :  int												=       [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]

				return semantic_segmentation




"""simple docstring"""






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

import datasets


__snake_case							:   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'

__snake_case							:   str      =    '\\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'

__snake_case							:   str      =    '\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 			_lowercase				(  __snake_case					,__snake_case	)						->   Union[str, Any]:
			return float((preds == labels).mean()	)


def 			_lowercase				(  __snake_case					,__snake_case	)						->   str:
			__lowerCAmelCase      :  str												=       simple_accuracy(__snake_case					,__snake_case	)
			__lowerCAmelCase      :  Any												=       float(fa_score(y_true=__snake_case					,y_pred=__snake_case	)	)
			return {
			    "accuracy": acc,
			    "f1": fa,
			}


def 			_lowercase				(  __snake_case					,__snake_case	)						->   int:
			__lowerCAmelCase      :  Union[str, Any]												=       np.array(__snake_case	)
			__lowerCAmelCase      :  Tuple												=       np.array(__snake_case	)
			__lowerCAmelCase      :  List[Any]												=       en_sentvecs.shape[0]

			# mean centering
			__lowerCAmelCase      :  Union[str, Any]												=       en_sentvecs - np.mean(__snake_case					,axis=0	)
			__lowerCAmelCase      :  int												=       in_sentvecs - np.mean(__snake_case					,axis=0	)

			__lowerCAmelCase      :  Optional[Any]												=       cdist(__snake_case					,__snake_case					,"cosine"	)
			__lowerCAmelCase      :  int												=       np.array(range(__snake_case	)	)
			__lowerCAmelCase      :  int												=       sim.argsort(axis=1	)[:, :10]
			__lowerCAmelCase      :  Optional[Any]												=       np.any(preds == actual[:, None]					,axis=1	)
			return float(matches.mean()	)





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




	'''simple docstring'''





	def 							_SCREAMING_SNAKE_CASE   (     self:		int)				->       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 							_SCREAMING_SNAKE_CASE   (     self:		List[str]       ,			_SCREAMING_SNAKE_CASE:		int       ,			_SCREAMING_SNAKE_CASE:		Optional[Any])				->       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\"]")