


'''simple docstring'''




import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import DetrImageProcessor

class 		UpperCAmelCase_      (  unittest.TestCase		):





     def __init__( self       :      List[str]    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      Optional[int]=7    ,      UpperCAmelCase__       :      Union[str, Any]=3    ,      UpperCAmelCase__       :      Any=3_0    ,      UpperCAmelCase__       :      str=4_0_0    ,      UpperCAmelCase__       :      Union[str, Any]=True    ,      UpperCAmelCase__       :      Optional[int]=None    ,      UpperCAmelCase__       :      Tuple=True    ,      UpperCAmelCase__       :      Optional[int]=1 / 2_5_5    ,      UpperCAmelCase__       :      Union[str, Any]=True    ,      UpperCAmelCase__       :      List[Any]=[0.5, 0.5, 0.5]    ,      UpperCAmelCase__       :      Any=[0.5, 0.5, 0.5]    ,      UpperCAmelCase__       :      Optional[int]=True    ,      )				->  Any:
        # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
        lowerCAmelCase     =			size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}
        lowerCAmelCase     =			parent
        lowerCAmelCase     =			batch_size
        lowerCAmelCase     =			num_channels
        lowerCAmelCase     =			min_resolution
        lowerCAmelCase     =			max_resolution
        lowerCAmelCase     =			do_resize
        lowerCAmelCase     =			size
        lowerCAmelCase     =			do_rescale
        lowerCAmelCase     =			rescale_factor
        lowerCAmelCase     =			do_normalize
        lowerCAmelCase     =			image_mean
        lowerCAmelCase     =			image_std
        lowerCAmelCase     =			do_pad





     def 							__UpperCAmelCase      ( self       :      int    )				->  Dict:
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_rescale": self.do_rescale,
            "rescale_factor": self.rescale_factor,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_pad": self.do_pad,
        }





     def 							__UpperCAmelCase      ( self       :      List[Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Dict=False    )				->  str:
        if not batched:
           lowerCAmelCase     =			image_inputs[0]
           if isinstance(UpperCAmelCase__    ,      Image.Image    ):
              lowerCAmelCase     ,  lowerCAmelCase     =			image.size
           else:
              lowerCAmelCase     ,  lowerCAmelCase     =			image.shape[1], image.shape[2]
           if w < h:
              lowerCAmelCase     =			int(self.size['shortest_edge'] * h / w    )
              lowerCAmelCase     =			self.size['shortest_edge']
           elif w > h:
              lowerCAmelCase     =			self.size['shortest_edge']
              lowerCAmelCase     =			int(self.size['shortest_edge'] * w / h    )
           else:
              lowerCAmelCase     =			self.size['shortest_edge']
              lowerCAmelCase     =			self.size['shortest_edge']

        else:
           lowerCAmelCase     =			[]
           for image in image_inputs:
              lowerCAmelCase     ,  lowerCAmelCase     =			self.get_expected_values([image]    )
              expected_values.append((expected_height, expected_width)    )
           lowerCAmelCase     =			max(UpperCAmelCase__    ,      key=lambda UpperCAmelCase__    : item[0]    )[0]
           lowerCAmelCase     =			max(UpperCAmelCase__    ,      key=lambda UpperCAmelCase__    : item[1]    )[1]

        return expected_height, expected_width




@require_torch
@require_vision
class 		UpperCAmelCase_      (  __lowercase       ,	unittest.TestCase		):
     lowerCamelCase				:	List[str]		=     DetrImageProcessor if is_vision_available() else None





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  List[Any]:
        lowerCAmelCase     =			DetrImageProcessingTester(self    )





     @property
     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  int:
        return self.image_processor_tester.prepare_image_processor_dict()





     def 							__UpperCAmelCase      ( self       :      str    )				->  str:
        lowerCAmelCase     =			self.image_processing_class(**self.image_processor_dict    )
        self.assertTrue(hasattr(UpperCAmelCase__    ,      'image_mean'    )    )
        self.assertTrue(hasattr(UpperCAmelCase__    ,      'image_std'    )    )
        self.assertTrue(hasattr(UpperCAmelCase__    ,      'do_normalize'    )    )
        self.assertTrue(hasattr(UpperCAmelCase__    ,      'do_rescale'    )    )
        self.assertTrue(hasattr(UpperCAmelCase__    ,      'rescale_factor'    )    )
        self.assertTrue(hasattr(UpperCAmelCase__    ,      'do_resize'    )    )
        self.assertTrue(hasattr(UpperCAmelCase__    ,      'size'    )    )
        self.assertTrue(hasattr(UpperCAmelCase__    ,      'do_pad'    )    )





     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  List[str]:
        lowerCAmelCase     =			self.image_processing_class.from_dict(self.image_processor_dict    )
        self.assertEqual(image_processor.size    ,      {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}    )
        self.assertEqual(image_processor.do_pad    ,      UpperCAmelCase__    )

        lowerCAmelCase     =			self.image_processing_class.from_dict(
            self.image_processor_dict    ,      size=4_2    ,      max_size=8_4    ,      pad_and_return_pixel_mask=UpperCAmelCase__    )
        self.assertEqual(image_processor.size    ,      {'shortest_edge': 4_2, 'longest_edge': 8_4}    )
        self.assertEqual(image_processor.do_pad    ,      UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    )				->  Any:
        pass





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  str:
        # Initialize image_processing
        lowerCAmelCase     =			self.image_processing_class(**self.image_processor_dict    )
        # create random PIL images
        lowerCAmelCase     =			prepare_image_inputs(self.image_processor_tester    ,      equal_resolution=UpperCAmelCase__    )
        for image in image_inputs:
           self.assertIsInstance(UpperCAmelCase__    ,      Image.Image    )

        # Test not batched input
        lowerCAmelCase     =			image_processing(image_inputs[0]    ,      return_tensors='pt'    ).pixel_values

        lowerCAmelCase     ,  lowerCAmelCase     =			self.image_processor_tester.get_expected_values(UpperCAmelCase__    )

        self.assertEqual(
            encoded_images.shape    ,      (1, self.image_processor_tester.num_channels, expected_height, expected_width)    ,      )

        # Test batched
        lowerCAmelCase     ,  lowerCAmelCase     =			self.image_processor_tester.get_expected_values(UpperCAmelCase__    ,      batched=UpperCAmelCase__    )

        lowerCAmelCase     =			image_processing(UpperCAmelCase__    ,      return_tensors='pt'    ).pixel_values
        self.assertEqual(
            encoded_images.shape    ,      (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )    ,      )





     def 							__UpperCAmelCase      ( self       :      int    )				->  Tuple:
        # Initialize image_processing
        lowerCAmelCase     =			self.image_processing_class(**self.image_processor_dict    )
        # create random numpy tensors
        lowerCAmelCase     =			prepare_image_inputs(self.image_processor_tester    ,      equal_resolution=UpperCAmelCase__    ,      numpify=UpperCAmelCase__    )
        for image in image_inputs:
           self.assertIsInstance(UpperCAmelCase__    ,      np.ndarray    )

        # Test not batched input
        lowerCAmelCase     =			image_processing(image_inputs[0]    ,      return_tensors='pt'    ).pixel_values

        lowerCAmelCase     ,  lowerCAmelCase     =			self.image_processor_tester.get_expected_values(UpperCAmelCase__    )

        self.assertEqual(
            encoded_images.shape    ,      (1, self.image_processor_tester.num_channels, expected_height, expected_width)    ,      )

        # Test batched
        lowerCAmelCase     =			image_processing(UpperCAmelCase__    ,      return_tensors='pt'    ).pixel_values

        lowerCAmelCase     ,  lowerCAmelCase     =			self.image_processor_tester.get_expected_values(UpperCAmelCase__    ,      batched=UpperCAmelCase__    )

        self.assertEqual(
            encoded_images.shape    ,      (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )    ,      )





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  Any:
        # Initialize image_processing
        lowerCAmelCase     =			self.image_processing_class(**self.image_processor_dict    )
        # create random PyTorch tensors
        lowerCAmelCase     =			prepare_image_inputs(self.image_processor_tester    ,      equal_resolution=UpperCAmelCase__    ,      torchify=UpperCAmelCase__    )
        for image in image_inputs:
           self.assertIsInstance(UpperCAmelCase__    ,      torch.Tensor    )

        # Test not batched input
        lowerCAmelCase     =			image_processing(image_inputs[0]    ,      return_tensors='pt'    ).pixel_values

        lowerCAmelCase     ,  lowerCAmelCase     =			self.image_processor_tester.get_expected_values(UpperCAmelCase__    )

        self.assertEqual(
            encoded_images.shape    ,      (1, self.image_processor_tester.num_channels, expected_height, expected_width)    ,      )

        # Test batched
        lowerCAmelCase     =			image_processing(UpperCAmelCase__    ,      return_tensors='pt'    ).pixel_values

        lowerCAmelCase     ,  lowerCAmelCase     =			self.image_processor_tester.get_expected_values(UpperCAmelCase__    ,      batched=UpperCAmelCase__    )

        self.assertEqual(
            encoded_images.shape    ,      (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                expected_height,
                expected_width,
            )    ,      )





     @slow
     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  Any:
        # prepare image and target
        lowerCAmelCase     =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
        with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'    ,      'r'    ) as f:
           lowerCAmelCase     =			json.loads(f.read()    )

        lowerCAmelCase     =			{'image_id': 3_9_7_6_9, 'annotations': target}

        # encode them
        lowerCAmelCase     =			DetrImageProcessor.from_pretrained('facebook/detr-resnet-50'    )
        lowerCAmelCase     =			image_processing(images=UpperCAmelCase__    ,      annotations=UpperCAmelCase__    ,      return_tensors='pt'    )

        # verify pixel values
        lowerCAmelCase     =			torch.Size([1, 3, 8_0_0, 1_0_6_6]    )
        self.assertEqual(encoding['pixel_values'].shape    ,      UpperCAmelCase__    )

        lowerCAmelCase     =			torch.tensor([0.2_796, 0.3_138, 0.3_481]    )
        self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]    ,      UpperCAmelCase__    ,      atol=1E-4    )    )

        # verify area
        lowerCAmelCase     =			torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['area']    ,      UpperCAmelCase__    )    )
        # verify boxes
        lowerCAmelCase     =			torch.Size([6, 4]    )
        self.assertEqual(encoding['labels'][0]['boxes'].shape    ,      UpperCAmelCase__    )
        lowerCAmelCase     =			torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]    ,      UpperCAmelCase__    ,      atol=1E-3    )    )
        # verify image_id
        lowerCAmelCase     =			torch.tensor([3_9_7_6_9]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']    ,      UpperCAmelCase__    )    )
        # verify is_crowd
        lowerCAmelCase     =			torch.tensor([0, 0, 0, 0, 0, 0]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']    ,      UpperCAmelCase__    )    )
        # verify class_labels
        lowerCAmelCase     =			torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']    ,      UpperCAmelCase__    )    )
        # verify orig_size
        lowerCAmelCase     =			torch.tensor([4_8_0, 6_4_0]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']    ,      UpperCAmelCase__    )    )
        # verify size
        lowerCAmelCase     =			torch.tensor([8_0_0, 1_0_6_6]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['size']    ,      UpperCAmelCase__    )    )





     @slow
     def 							__UpperCAmelCase      ( self       :      str    )				->  str:
        # prepare image, target and masks_path
        lowerCAmelCase     =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
        with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'    ,      'r'    ) as f:
           lowerCAmelCase     =			json.loads(f.read()    )

        lowerCAmelCase     =			{'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target}

        lowerCAmelCase     =			pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic'    )

        # encode them
        lowerCAmelCase     =			DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic'    )
        lowerCAmelCase     =			image_processing(images=UpperCAmelCase__    ,      annotations=UpperCAmelCase__    ,      masks_path=UpperCAmelCase__    ,      return_tensors='pt'    )

        # verify pixel values
        lowerCAmelCase     =			torch.Size([1, 3, 8_0_0, 1_0_6_6]    )
        self.assertEqual(encoding['pixel_values'].shape    ,      UpperCAmelCase__    )

        lowerCAmelCase     =			torch.tensor([0.2_796, 0.3_138, 0.3_481]    )
        self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]    ,      UpperCAmelCase__    ,      atol=1E-4    )    )

        # verify area
        lowerCAmelCase     =			torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['area']    ,      UpperCAmelCase__    )    )
        # verify boxes
        lowerCAmelCase     =			torch.Size([6, 4]    )
        self.assertEqual(encoding['labels'][0]['boxes'].shape    ,      UpperCAmelCase__    )
        lowerCAmelCase     =			torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]    ,      UpperCAmelCase__    ,      atol=1E-3    )    )
        # verify image_id
        lowerCAmelCase     =			torch.tensor([3_9_7_6_9]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']    ,      UpperCAmelCase__    )    )
        # verify is_crowd
        lowerCAmelCase     =			torch.tensor([0, 0, 0, 0, 0, 0]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']    ,      UpperCAmelCase__    )    )
        # verify class_labels
        lowerCAmelCase     =			torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']    ,      UpperCAmelCase__    )    )
        # verify masks
        lowerCAmelCase     =			8_2_2_8_7_3
        self.assertEqual(encoding['labels'][0]['masks'].sum().item()    ,      UpperCAmelCase__    )
        # verify orig_size
        lowerCAmelCase     =			torch.tensor([4_8_0, 6_4_0]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']    ,      UpperCAmelCase__    )    )
        # verify size
        lowerCAmelCase     =			torch.tensor([8_0_0, 1_0_6_6]    )
        self.assertTrue(torch.allclose(encoding['labels'][0]['size']    ,      UpperCAmelCase__    )    )









'''simple docstring'''




from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


__snake_case    						="""\
@article{wang2019superglue,
  title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},
  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},
  journal={arXiv preprint arXiv:1905.00537},
  year={2019}
}
"""

__snake_case    						="""\
SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after
GLUE with a new set of more difficult language understanding tasks, improved
resources, and a new public leaderboard.
"""

__snake_case    						="""
Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset.
Args:
    predictions: list of predictions to score. Depending on the SuperGlUE subset:
        - for 'record': list of question-answer dictionaries with the following keys:
            - 'idx': index of the question as specified by the dataset
            - 'prediction_text': the predicted answer text
        - for 'multirc': list of question-answer dictionaries with the following keys:
            - 'idx': index of the question-answer pair as specified by the dataset
            - 'prediction': the predicted answer label
        - otherwise: list of predicted labels
    references: list of reference labels. Depending on the SuperGLUE subset:
        - for 'record': list of question-answers dictionaries with the following keys:
            - 'idx': index of the question as specified by the dataset
            - 'answers': list of possible answers
        - otherwise: list of reference labels
Returns: depending on the SuperGLUE subset:
    - for 'record':
        - 'exact_match': Exact match between answer and gold answer
        - 'f1': F1 score
    - for 'multirc':
        - 'exact_match': Exact match between answer and gold answer
        - 'f1_m': Per-question macro-F1 score
        - 'f1_a': Average F1 score over all answers
    - for 'axb':
        'matthews_correlation': Matthew Correlation
    - for 'cb':
        - 'accuracy': Accuracy
        - 'f1': F1 score
    - for all others:
        - 'accuracy': Accuracy
Examples:

    >>> super_glue_metric = datasets.load_metric('super_glue', 'copa')  # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]
    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')
    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0, 'f1': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'record')
    >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]
    >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 1.0, 'f1': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')
    >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]
    >>> references = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}

    >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')
    >>> references = [0, 1]
    >>> predictions = [0, 1]
    >>> results = super_glue_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'matthews_correlation': 1.0}
"""





def 	a_					( lowerCamelCase	:     str	, lowerCamelCase	:     Union[str, Any]				):
   return float((preds == labels).mean()				)





def 	a_					( lowerCamelCase	:     Union[str, Any]	, lowerCamelCase	:     Dict	, lowerCamelCase	:     str="binary"				):
   lowerCAmelCase     =			simple_accuracy(lowerCamelCase	, lowerCamelCase				)
   lowerCAmelCase     =			float(fa_score(y_true=lowerCamelCase	, y_pred=lowerCamelCase	, average=lowerCamelCase				)				)
   return {
       "accuracy": acc,
       "f1": fa,
   }





def 	a_					( lowerCamelCase	:     List[Any]	, lowerCamelCase	:     List[Any]				):
   lowerCAmelCase     =			{}
   for id_pred, label in zip(lowerCamelCase	, lowerCamelCase				):
      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(*lowerCamelCase				)
      lowerCAmelCase     =			fa_score(y_true=lowerCamelCase	, y_pred=lowerCamelCase	, average='macro'				)
      fas.append(lowerCamelCase				)
      lowerCAmelCase     =			int(sum(pred == label for pred, label in preds_labels				) == len(lowerCamelCase				)				)
      ems.append(lowerCamelCase				)
   lowerCAmelCase     =			float(sum(lowerCamelCase				) / len(lowerCamelCase				)				)
   lowerCAmelCase     =			sum(lowerCamelCase				) / len(lowerCamelCase				)
   lowerCAmelCase     =			float(fa_score(y_true=lowerCamelCase	, 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 		UpperCAmelCase_      (  datasets.Metric		):





     def 							__UpperCAmelCase      ( self       :      List[str]    )				->  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       :      Union[str, Any]    )				->  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       :      List[str]    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      Optional[Any]    )				->  Any:
        if self.config_name == "axb":
           return {"matthews_correlation": matthews_corrcoef(UpperCAmelCase__    ,      UpperCAmelCase__    )}
        elif self.config_name == "cb":
           return acc_and_fa(UpperCAmelCase__    ,      UpperCAmelCase__    ,      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(UpperCAmelCase__    ,      UpperCAmelCase__    )[0]
        elif self.config_name == "multirc":
           return evaluate_multirc(UpperCAmelCase__    ,      UpperCAmelCase__    )
        elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]:
           return {"accuracy": simple_accuracy(UpperCAmelCase__    ,      UpperCAmelCase__    )}
        else:
           raise KeyError(
               'You should supply a configuration name selected in '
               '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]'    )





