

from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


__snake_case							:	Union[str, Any]											=       "\\n@article{wang2019superglue,\n  title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n  author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n  journal={arXiv preprint arXiv:1905.00537},\n  year={2019}\n}\n"

__snake_case							:	Optional[Any]											=       "\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n"

__snake_case							:	Dict											=       "\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n    predictions: list of predictions to score. Depending on the SuperGlUE subset:\n        - for 'record': list of question-answer dictionaries with the following keys:\n            - 'idx': index of the question as specified by the dataset\n            - 'prediction_text': the predicted answer text\n        - for 'multirc': list of question-answer dictionaries with the following keys:\n            - 'idx': index of the question-answer pair as specified by the dataset\n            - 'prediction': the predicted answer label\n        - otherwise: list of predicted labels\n    references: list of reference labels. Depending on the SuperGLUE subset:\n        - for 'record': list of question-answers dictionaries with the following keys:\n            - 'idx': index of the question as specified by the dataset\n            - 'answers': list of possible answers\n        - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n    - for 'record':\n        - 'exact_match': Exact match between answer and gold answer\n        - 'f1': F1 score\n    - for 'multirc':\n        - 'exact_match': Exact match between answer and gold answer\n        - 'f1_m': Per-question macro-F1 score\n        - 'f1_a': Average F1 score over all answers\n    - for 'axb':\n        'matthews_correlation': Matthew Correlation\n    - for 'cb':\n        - 'accuracy': Accuracy\n        - 'f1': F1 score\n    - for all others:\n        - 'accuracy': Accuracy\nExamples:\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'copa')  # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n    >>> predictions = [0, 1]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')\n    >>> predictions = [0, 1]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0, 'f1': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'record')\n    >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]\n    >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 1.0, 'f1': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')\n    >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]\n    >>> references = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}\n\n    >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'matthews_correlation': 1.0}\n"


def  _UpperCAmelCase							(		a__   ,     a__):

			'''simple docstring'''



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


def  _UpperCAmelCase							(		a__   ,     a__   ,     a__="binary"):

			'''simple docstring'''



			a_		:		Any      				=      simple_accuracy(a__   ,     a__)
			a_		:		Dict      				=      float(fa_score(y_true=a__   ,     y_pred=a__   ,     average=a__))
			return {
			    "accuracy": acc,
			    "f1": fa,
			}


def  _UpperCAmelCase							(		a__   ,     a__):

			'''simple docstring'''



			a_		:		str      				=      {}
			for id_pred, label in zip(a__   ,     a__):
						a_		:		Optional[Any]      				=      f'''{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}'''
						a_		:		int      				=      id_pred["""prediction"""]
						if question_id in question_map:
									question_map[question_id].append((pred, label))
						else:
									a_		:		List[str]      				=      [(pred, label)]
			a_				, a_		:		Dict      				=      [], []
			for question, preds_labels in question_map.items():
						a_				, a_		:		List[str]      				=      zip(*a__)
						a_		:		Any      				=      fa_score(y_true=a__   ,     y_pred=a__   ,     average="""macro""")
						fas.append(a__)
						a_		:		List[str]      				=      int(sum(pred == label for pred, label in preds_labels) == len(a__))
						ems.append(a__)
			a_		:		List[Any]      				=      float(sum(a__) / len(a__))
			a_		:		str      				=      sum(a__) / len(a__)
			a_		:		Tuple      				=      float(fa_score(y_true=a__   ,     y_pred=[id_pred["""prediction"""] for id_pred in ids_preds]))
			return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a}



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






						def        UpperCamelCase__ (  self  )			->      List[Any]:

									if self.config_name not in [
									    "boolq",
									    "cb",
									    "copa",
									    "multirc",
									    "record",
									    "rte",
									    "wic",
									    "wsc",
									    "wsc.fixed",
									    "axb",
									    "axg",
									]:
												raise KeyError(
												    """You should supply a configuration name selected in """
												    """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]"""  )
									return datasets.MetricInfo(
									    description=_DESCRIPTION   ,	citation=_CITATION   ,	inputs_description=_KWARGS_DESCRIPTION   ,	features=datasets.Features(self._get_feature_types()  )   ,	codebase_urls=[]   ,	reference_urls=[]   ,	format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None   ,	)





						def        UpperCamelCase__ (  self  )			->      List[str]:

									if self.config_name == "record":
												return {
												    "predictions": {
												        "idx": {
												            "passage": datasets.Value("""int64"""  ),
												            "query": datasets.Value("""int64"""  ),
												        },
												        "prediction_text": datasets.Value("""string"""  ),
												    },
												    "references": {
												        "idx": {
												            "passage": datasets.Value("""int64"""  ),
												            "query": datasets.Value("""int64"""  ),
												        },
												        "answers": datasets.Sequence(datasets.Value("""string"""  )  ),
												    },
												}
									elif self.config_name == "multirc":
												return {
												    "predictions": {
												        "idx": {
												            "answer": datasets.Value("""int64"""  ),
												            "paragraph": datasets.Value("""int64"""  ),
												            "question": datasets.Value("""int64"""  ),
												        },
												        "prediction": datasets.Value("""int64"""  ),
												    },
												    "references": datasets.Value("""int64"""  ),
												}
									else:
												return {
												    "predictions": datasets.Value("""int64"""  ),
												    "references": datasets.Value("""int64"""  ),
												}





						def        UpperCamelCase__ (  self   ,	_lowercase   ,	_lowercase  )			->      Union[str, Any]:

									if self.config_name == "axb":
												return {"matthews_correlation": matthews_corrcoef(lowerCamelCase_   ,	lowerCamelCase_  )}
									elif self.config_name == "cb":
												return acc_and_fa(lowerCamelCase_   ,	lowerCamelCase_   ,	fa_avg="""macro"""  )
									elif self.config_name == "record":
												a_		:		Union[str, Any]      				=      [
												    {
												        """qas""": [
												            {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]}
												            for ref in references
												        ]
												    }
												]
												a_		:		Optional[int]      				=      {pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions}
												return evaluate_record(lowerCamelCase_   ,	lowerCamelCase_  )[0]
									elif self.config_name == "multirc":
												return evaluate_multirc(lowerCamelCase_   ,	lowerCamelCase_  )
									elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]:
												return {"accuracy": simple_accuracy(lowerCamelCase_   ,	lowerCamelCase_  )}
									else:
												raise KeyError(
												    """You should supply a configuration name selected in """
												    """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]"""  )







from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
				from PIL import Image

				from ..image_utils import load_image

if is_tf_available():
				from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING

if is_torch_available():
				import torch

				from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING

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



@add_end_docstrings(lowerCAmelCase	)
class 	_lowercase							(   lowerCAmelCase	):





	"""simple docstring"""




	def __init__(self		,       *lowerCamelCase_		,       **lowerCamelCase_		):
						"""simple docstring"""

						super().__init__(*lowerCamelCase_		,       **lowerCamelCase_		)
						requires_backends(self		,       "vision"		)
						self.check_model_type(
						    TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == "tf" else MODEL_FOR_VISION_2_SEQ_MAPPING		)




	def      UpperCamelCase_       (self		,       lowerCamelCase_=None		,       lowerCamelCase_=None		,       lowerCamelCase_=None		):
						"""simple docstring"""

						a					     =   {}
						a					     =   {}

						if prompt is not None:
											a					     =   prompt

						if generate_kwargs is not None:
											a					     =   generate_kwargs
						if max_new_tokens is not None:
											if "generate_kwargs" not in forward_kwargs:
																a					     =   {}
											if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
																raise ValueError(
																    "'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,"
																    " please use only one"		)
											a					     =   max_new_tokens
						return preprocess_params, forward_kwargs, {}




	def __call__(self		,       lowerCamelCase_		,       **lowerCamelCase_		):
						"""simple docstring"""

						return super().__call__(lowerCamelCase_		,       **lowerCamelCase_		)




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_=None		):
						"""simple docstring"""

						a					     =   load_image(lowerCamelCase_		)

						if prompt is not None:
											if not isinstance(lowerCamelCase_		,       lowerCamelCase_		):
																raise ValueError(
																    F'''Received an invalid text input, got - {type(lowerCamelCase_		)} - but expected a single string. '''
																    "Note also that one single text can be provided for conditional image to text generation."		)

											a					     =   self.model.config.model_type

											if model_type == "git":
																a					     =   self.image_processor(images=lowerCamelCase_		,       return_tensors=self.framework		)
																a					     =   self.tokenizer(text=lowerCamelCase_		,       add_special_tokens=lowerCamelCase_		).input_ids
																a					     =   [self.tokenizer.cls_token_id] + input_ids
																a					     =   torch.tensor(lowerCamelCase_		).unsqueeze(0		)
																model_inputs.update({"input_ids": input_ids}		)

											elif model_type == "pix2struct":
																a					     =   self.image_processor(images=lowerCamelCase_		,       header_text=lowerCamelCase_		,       return_tensors=self.framework		)

											elif model_type != "vision-encoder-decoder":
																# vision-encoder-decoder does not support conditional generation
																a					     =   self.image_processor(images=lowerCamelCase_		,       return_tensors=self.framework		)
																a					     =   self.tokenizer(lowerCamelCase_		,       return_tensors=self.framework		)
																model_inputs.update(lowerCamelCase_		)

											else:
																raise ValueError(F'''Model type {model_type} does not support conditional text generation'''		)

						else:
											a					     =   self.image_processor(images=lowerCamelCase_		,       return_tensors=self.framework		)

						if self.model.config.model_type == "git" and prompt is None:
											a					     =   None

						return model_inputs




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_=None		):
						"""simple docstring"""

						if (
						    "input_ids" in model_inputs
						    and isinstance(model_inputs["input_ids"]		,       lowerCamelCase_		)
						    and all(x is None for x in model_inputs["input_ids"]		)
						):
											a					     =   None

						if generate_kwargs is None:
											a					     =   {}
						# FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
						#  parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
						#  the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
						#  in the `_prepare_model_inputs` method.
						a					     =   model_inputs.pop(self.model.main_input_name		)
						a					     =   self.model.generate(lowerCamelCase_		,       **lowerCamelCase_		,       **lowerCamelCase_		)
						return model_outputs




	def      UpperCamelCase_       (self		,       lowerCamelCase_		):
						"""simple docstring"""

						a					     =   []
						for output_ids in model_outputs:
											a					     =   {
											    "generated_text": self.tokenizer.decode(
											        lowerCamelCase_		,       skip_special_tokens=lowerCamelCase_		,       )
											}
											records.append(lowerCamelCase_		)
						return records
