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

import datasets


__magic_name__									=					"\\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"

__magic_name__									=					"\\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"

__magic_name__									=					"\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"""






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




def      __lowerCamelCase	(		UpperCamelCase__					,  UpperCamelCase__   ):


	"""simple docstring"""






	_UpperCAmelCase			=    np.array(UpperCamelCase__   )
	_UpperCAmelCase			=    np.array(UpperCamelCase__   )
	_UpperCAmelCase			=    en_sentvecs.shape[0]

	# mean centering
	_UpperCAmelCase			=    en_sentvecs - np.mean(UpperCamelCase__					,  axis=0   )
	_UpperCAmelCase			=    in_sentvecs - np.mean(UpperCamelCase__					,  axis=0   )

	_UpperCAmelCase			=    cdist(UpperCamelCase__					,  UpperCamelCase__					,  "cosine"   )
	_UpperCAmelCase			=    np.array(range(UpperCamelCase__   )   )
	_UpperCAmelCase			=    sim.argsort(axis=1   )[:, :10]
	_UpperCAmelCase			=    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    _a (   self )				->				List[str]:



								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_ )				->				Union[str, Any]:



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










import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Union

import torch
from torch import nn

from ...models.controlnet import ControlNetModel, ControlNetOutput
from ...models.modeling_utils import ModelMixin
from ...utils import logging


SCREAMING_SNAKE_CASE__     :     Union[str, Any]		    =       logging.get_logger(__name__)



class       a_       (     SCREAMING_SNAKE_CASE__     ):





	def __init__(							self      ,     SCREAMING_SNAKE_CASE      )  ->					Union[str, Any]:




				"""simple docstring"""



				super().__init__()
				SCREAMING_SNAKE_CASE_								=						nn.ModuleList(SCREAMING_SNAKE_CASE      )





	def 						A_(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE = None      ,     SCREAMING_SNAKE_CASE = None      ,     SCREAMING_SNAKE_CASE = None      ,     SCREAMING_SNAKE_CASE = None      ,     SCREAMING_SNAKE_CASE = False      ,     SCREAMING_SNAKE_CASE = True      ,     )  ->					Union[ControlNetOutput, Tuple]:




				"""simple docstring"""



				for i, (image, scale, controlnet) in enumerate(zip(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     self.nets      )      ):
							SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_								=						controlnet(
							    SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     )

							# merge samples
							if i == 0:
										SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_								=						down_samples, mid_sample
							else:
										SCREAMING_SNAKE_CASE_								=						[
										    samples_prev + samples_curr
										    for samples_prev, samples_curr in zip(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )
										]
										mid_block_res_sample += mid_sample

				return down_block_res_samples, mid_block_res_sample





	def 						A_(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE = True      ,     SCREAMING_SNAKE_CASE = None      ,     SCREAMING_SNAKE_CASE = False      ,     SCREAMING_SNAKE_CASE = None      ,     )  ->					int:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						0
				SCREAMING_SNAKE_CASE_								=						save_directory
				for controlnet in self.nets:
							controlnet.save_pretrained(
							    SCREAMING_SNAKE_CASE      ,     is_main_process=SCREAMING_SNAKE_CASE      ,     save_function=SCREAMING_SNAKE_CASE      ,     safe_serialization=SCREAMING_SNAKE_CASE      ,     variant=SCREAMING_SNAKE_CASE      ,     )

							idx += 1
							SCREAMING_SNAKE_CASE_								=						model_path_to_save + f'_{idx}'





	@classmethod
	def 						A_(							cls      ,     SCREAMING_SNAKE_CASE      ,     **SCREAMING_SNAKE_CASE      )  ->					Tuple:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						0
				SCREAMING_SNAKE_CASE_								=						[]

				# load controlnet and append to list until no controlnet directory exists anymore
				# first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained`
				# second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ...
				SCREAMING_SNAKE_CASE_								=						pretrained_model_path
				while os.path.isdir(SCREAMING_SNAKE_CASE      ):
							SCREAMING_SNAKE_CASE_								=						ControlNetModel.from_pretrained(SCREAMING_SNAKE_CASE      ,     **SCREAMING_SNAKE_CASE      )
							controlnets.append(SCREAMING_SNAKE_CASE      )

							idx += 1
							SCREAMING_SNAKE_CASE_								=						pretrained_model_path + f'_{idx}'

				logger.info(f'{len(SCREAMING_SNAKE_CASE      )} controlnets loaded from {pretrained_model_path}.'      )

				if len(SCREAMING_SNAKE_CASE      ) == 0:
							raise ValueError(
							    f'No ControlNets found under {os.path.dirname(SCREAMING_SNAKE_CASE      )}. Expected at least {pretrained_model_path + "_0"}.'      )

				return cls(SCREAMING_SNAKE_CASE      )
