





from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


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

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

A_												=     "\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) ->Tuple:
					return float((preds == labels).mean())





def    __UpperCamelCase      (    a,     a,     a="binary") ->Union[str, Any]:
					lowerCamelCase__       =       simple_accuracy(a,     a)
					lowerCamelCase__       =       float(fa_score(y_true=a,     y_pred=a,     average=a))
					return {
					    "accuracy": acc,
					    "f1": fa,
					}





def    __UpperCamelCase      (    a,     a) ->Tuple:
					lowerCamelCase__       =       {}
					for id_pred, label in zip(a,     a):
										lowerCamelCase__       =       f"{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}"
										lowerCamelCase__       =       id_pred["prediction"]
										if question_id in question_map:
															question_map[question_id].append((pred, label))
										else:
															lowerCamelCase__       =       [(pred, label)]
					lowerCamelCase__    ,		lowerCamelCase__       =       [], []
					for question, preds_labels in question_map.items():
										lowerCamelCase__    ,		lowerCamelCase__       =       zip(*a)
										lowerCamelCase__       =       fa_score(y_true=a,     y_pred=a,     average="macro")
										fas.append(a)
										lowerCamelCase__       =       int(sum(pred == label for pred, label in preds_labels) == len(a))
										ems.append(a)
					lowerCamelCase__       =       float(sum(a) / len(a))
					lowerCamelCase__       =       sum(a) / len(a)
					lowerCamelCase__       =       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 SCREAMING_SNAKE_CASE_ (					datasets.Metric   ):





					"""simple docstring"""


					def 					__magic_name__ ( self	):
										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 					__magic_name__ ( self	):
										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 					__magic_name__ ( self	,  _lowerCAmelCase	,  _lowerCAmelCase	):
										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":
															lowerCamelCase__       =       [
															    {
															        "qas": [
															            {"id": ref["idx"]["query"], "answers": [{"text": ans} for ans in ref["answers"]]}
															            for ref in references
															        ]
															    }
															]
															lowerCamelCase__       =       {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\",]"	)








import json
import os
import shutil
import tempfile
import unittest

import numpy as np

from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
						from PIL import Image

						from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor

@require_tokenizers
@require_vision
class SCREAMING_SNAKE_CASE_ (					unittest.TestCase   ):





					"""simple docstring"""


					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       tempfile.mkdtemp()

										# fmt: off
										lowerCamelCase__       =       ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"]
										# fmt: on
										lowerCamelCase__       =       os.path.join(self.tmpdirname	,  VOCAB_FILES_NAMES["vocab_file"]	)
										with open(self.vocab_file	,  "w"	,  encoding="utf-8"	) as vocab_writer:
															vocab_writer.write("".join([x + "\n" for x in vocab_tokens]	)	)

										lowerCamelCase__       =       {
										    "do_resize": True,
										    "size": {"height": 18, "width": 18},
										    "do_normalize": True,
										    "image_mean": [0.5, 0.5, 0.5],
										    "image_std": [0.5, 0.5, 0.5],
										}
										lowerCamelCase__       =       os.path.join(self.tmpdirname	,  _lowerCAmelCase	)
										with open(self.image_processor_file	,  "w"	,  encoding="utf-8"	) as fp:
															json.dump(_lowerCAmelCase	,  _lowerCAmelCase	)





					def 					__magic_name__ ( self	,  **_lowerCAmelCase	):
										return BertTokenizer.from_pretrained(self.tmpdirname	,  **_lowerCAmelCase	)





					def 					__magic_name__ ( self	,  **_lowerCAmelCase	):
										return ViTImageProcessor.from_pretrained(self.tmpdirname	,  **_lowerCAmelCase	)





					def 					__magic_name__ ( self	):
										shutil.rmtree(self.tmpdirname	)





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       [np.random.randint(255	,  size=(3, 30, 400)	,  dtype=np.uinta	)]

										lowerCamelCase__       =       [Image.fromarray(np.moveaxis(_lowerCAmelCase	,  0	,  -1	)	) for x in image_inputs]

										return image_inputs





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_tokenizer()
										lowerCamelCase__       =       self.get_image_processor()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										processor.save_pretrained(self.tmpdirname	)
										lowerCamelCase__       =       VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname	)

										self.assertEqual(processor.tokenizer.get_vocab()	,  tokenizer.get_vocab()	)
										self.assertIsInstance(processor.tokenizer	,  (BertTokenizer, BertTokenizerFast)	)

										self.assertEqual(processor.image_processor.to_json_string()	,  image_processor.to_json_string()	)
										self.assertIsInstance(processor.image_processor	,  _lowerCAmelCase	)





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       VisionTextDualEncoderProcessor(
										    tokenizer=self.get_tokenizer()	,  image_processor=self.get_image_processor()	)
										processor.save_pretrained(self.tmpdirname	)

										lowerCamelCase__       =       self.get_tokenizer(bos_token="(BOS)"	,  eos_token="(EOS)"	)
										lowerCamelCase__       =       self.get_image_processor(do_normalize=_lowerCAmelCase	,  padding_value=1.0	)

										lowerCamelCase__       =       VisionTextDualEncoderProcessor.from_pretrained(
										    self.tmpdirname	,  bos_token="(BOS)"	,  eos_token="(EOS)"	,  do_normalize=_lowerCAmelCase	,  padding_value=1.0	)

										self.assertEqual(processor.tokenizer.get_vocab()	,  tokenizer_add_kwargs.get_vocab()	)
										self.assertIsInstance(processor.tokenizer	,  (BertTokenizer, BertTokenizerFast)	)

										self.assertEqual(processor.image_processor.to_json_string()	,  image_processor_add_kwargs.to_json_string()	)
										self.assertIsInstance(processor.image_processor	,  _lowerCAmelCase	)





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       self.prepare_image_inputs()

										lowerCamelCase__       =       image_processor(_lowerCAmelCase	,  return_tensors="np"	)
										lowerCamelCase__       =       processor(images=_lowerCAmelCase	,  return_tensors="np"	)

										for key in input_feat_extract.keys():
															self.assertAlmostEqual(input_feat_extract[key].sum()	,  input_processor[key].sum()	,  delta=1E-2	)





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       "lower newer"

										lowerCamelCase__       =       processor(text=_lowerCAmelCase	)

										lowerCamelCase__       =       tokenizer(_lowerCAmelCase	)

										for key in encoded_tok.keys():
															self.assertListEqual(encoded_tok[key]	,  encoded_processor[key]	)





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       "lower newer"
										lowerCamelCase__       =       self.prepare_image_inputs()

										lowerCamelCase__       =       processor(text=_lowerCAmelCase	,  images=_lowerCAmelCase	)

										self.assertListEqual(list(inputs.keys()	)	,  ["input_ids", "token_type_ids", "attention_mask", "pixel_values"]	)

										# test if it raises when no input is passed
										with self.assertRaises(_lowerCAmelCase	):
															processor()





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

										lowerCamelCase__       =       processor.batch_decode(_lowerCAmelCase	)
										lowerCamelCase__       =       tokenizer.batch_decode(_lowerCAmelCase	)

										self.assertListEqual(_lowerCAmelCase	,  _lowerCAmelCase	)






					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       "lower newer"
										lowerCamelCase__       =       self.prepare_image_inputs()

										lowerCamelCase__       =       processor(text=_lowerCAmelCase	,  images=_lowerCAmelCase	)

										self.assertListEqual(list(inputs.keys()	)	,  processor.model_input_names	)

