


import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('''3.8'''):
   import importlib_metadata
else:
   import importlib.metadata as importlib_metadata



def 	_lowerCAmelCase  (							lowerCAmelCase_							:str						,  lowerCAmelCase_							:Optional[int]=False							)->Tuple:
   '''simple docstring'''






   try:
      snake_case_    			=    os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      snake_case_    			=    default
   else:
      # KEY is set, convert it to True or False.
      try:
         snake_case_    			=    strtobool(lowerCAmelCase_							)
      except ValueError:
         # More values are supported, but let's keep the message simple.
         raise ValueError(F'''If set, {key} must be yes or no.'''							)
   return _value


SCREAMING_SNAKE_CASE		:Any     						=   parse_flag_from_env('''RUN_SLOW''', default=False)
SCREAMING_SNAKE_CASE		:Optional[Any]     						=   parse_flag_from_env('''RUN_REMOTE''', default=False)
SCREAMING_SNAKE_CASE		:Dict     						=   parse_flag_from_env('''RUN_LOCAL''', default=True)
SCREAMING_SNAKE_CASE		:str     						=   parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
SCREAMING_SNAKE_CASE		:str     						=   pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
SCREAMING_SNAKE_CASE		:Optional[Any]     						=   pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
SCREAMING_SNAKE_CASE		:str     						=   pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
SCREAMING_SNAKE_CASE		:str     						=   pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''),
    reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''',
)

# Beam
SCREAMING_SNAKE_CASE		:Any     						=   pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''),
    reason='''test requires apache-beam and a compatible dill version''',
)

# Dill-cloudpickle compatibility
SCREAMING_SNAKE_CASE		:Optional[int]     						=   pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
SCREAMING_SNAKE_CASE		:Optional[Any]     						=   pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Dict							)->Any:
   '''simple docstring'''






   try:
      import faiss  # noqa
   except ImportError:
      snake_case_    			=    unittest.skip("test requires faiss"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Tuple							)->int:
   '''simple docstring'''






   try:
      import regex  # noqa
   except ImportError:
      snake_case_    			=    unittest.skip("test requires regex"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Any							)->Dict:
   '''simple docstring'''






   try:
      import elasticsearch  # noqa
   except ImportError:
      snake_case_    			=    unittest.skip("test requires elasticsearch"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:str							)->Dict:
   '''simple docstring'''






   try:
      import sqlalchemy  # noqa
   except ImportError:
      snake_case_    			=    unittest.skip("test requires sqlalchemy"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Any							)->List[Any]:
   '''simple docstring'''






   if not config.TORCH_AVAILABLE:
      snake_case_    			=    unittest.skip("test requires PyTorch"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Optional[Any]							)->List[Any]:
   '''simple docstring'''






   if not config.TF_AVAILABLE:
      snake_case_    			=    unittest.skip("test requires TensorFlow"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:List[Any]							)->Optional[Any]:
   '''simple docstring'''






   if not config.JAX_AVAILABLE:
      snake_case_    			=    unittest.skip("test requires JAX"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Optional[Any]							)->Union[str, Any]:
   '''simple docstring'''






   if not config.PIL_AVAILABLE:
      snake_case_    			=    unittest.skip("test requires Pillow"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Optional[int]							)->Dict:
   '''simple docstring'''






   try:
      import transformers  # noqa F401
   except ImportError:
      return unittest.skip("test requires transformers"							)(lowerCAmelCase_							)
   else:
      return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:str							)->int:
   '''simple docstring'''






   try:
      import tiktoken  # noqa F401
   except ImportError:
      return unittest.skip("test requires tiktoken"							)(lowerCAmelCase_							)
   else:
      return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:List[Any]							)->List[str]:
   '''simple docstring'''






   try:
      import spacy  # noqa F401
   except ImportError:
      return unittest.skip("test requires spacy"							)(lowerCAmelCase_							)
   else:
      return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Optional[Any]							)->Tuple:
   '''simple docstring'''






   def _require_spacy_model(lowerCAmelCase_							:List[str]							):
      try:
         import spacy  # noqa F401

         spacy.load(lowerCAmelCase_							)
      except ImportError:
         return unittest.skip("test requires spacy"							)(lowerCAmelCase_							)
      except OSError:
         return unittest.skip("test requires spacy model '{}'".format(lowerCAmelCase_							)							)(lowerCAmelCase_							)
      else:
         return test_case

   return _require_spacy_model



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Tuple							)->List[Any]:
   '''simple docstring'''






   try:
      import pyspark  # noqa F401
   except ImportError:
      return unittest.skip("test requires pyspark"							)(lowerCAmelCase_							)
   else:
      return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Tuple							)->Optional[int]:
   '''simple docstring'''






   try:
      import joblibspark  # noqa F401
   except ImportError:
      return unittest.skip("test requires joblibspark"							)(lowerCAmelCase_							)
   else:
      return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:str							)->List[str]:
   '''simple docstring'''






   if not _run_slow_tests or _run_slow_tests == 0:
      snake_case_    			=    unittest.skip("test is slow"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Any							)->Union[str, Any]:
   '''simple docstring'''






   if not _run_local_tests or _run_local_tests == 0:
      snake_case_    			=    unittest.skip("test is local"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Any							)->int:
   '''simple docstring'''






   if not _run_packaged_tests or _run_packaged_tests == 0:
      snake_case_    			=    unittest.skip("test is packaged"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Optional[Any]							)->Union[str, Any]:
   '''simple docstring'''






   if not _run_remote_tests or _run_remote_tests == 0:
      snake_case_    			=    unittest.skip("test requires remote"							)(lowerCAmelCase_							)
   return test_case



def 	_lowerCAmelCase  (							*lowerCAmelCase_							:int							)->List[str]:
   '''simple docstring'''






   def decorate(cls							:int							):
      for name, fn in cls.__dict__.items():
         if callable(lowerCAmelCase_							) and name.startswith("test"							):
            for decorator in decorators:
               snake_case_    			=    decorator(lowerCAmelCase_							)
            setattr(cls						,  lowerCAmelCase_						,  lowerCAmelCase_							)
      return cls

   return decorate


class 			__lowerCAmelCase   (       _a    ):






  """simple docstring"""





  pass






class 			__lowerCAmelCase   (       _a    ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE									=				0
  _SCREAMING_SNAKE_CASE									=				1
  _SCREAMING_SNAKE_CASE									=				2






@contextmanager
def 	_lowerCAmelCase  (							lowerCAmelCase_							:Dict=OfflineSimulationMode.CONNECTION_FAILS						,  lowerCAmelCase_							:str=1e-16							)->Any:
   '''simple docstring'''






   snake_case_    			=    requests.Session().request

   def timeout_request(lowerCAmelCase_							:str						,  lowerCAmelCase_							:List[str]						,  lowerCAmelCase_							:Optional[int]						,  **lowerCAmelCase_							:Dict							):
      # Change the url to an invalid url so that the connection hangs
      snake_case_    			=    """https://10.255.255.1"""
      if kwargs.get("timeout"							) is None:
         raise RequestWouldHangIndefinitelyError(
             F'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'''							)
      snake_case_    			=    timeout
      try:
         return online_request(lowerCAmelCase_						,  lowerCAmelCase_						,  **lowerCAmelCase_							)
      except Exception as e:
         # The following changes in the error are just here to make the offline timeout error prettier
         snake_case_    			=    url
         snake_case_    			=    e.args[0]
         snake_case_    			=    (max_retry_error.args[0].replace("10.255.255.1"						,  F'''OfflineMock[{url}]'''							),)
         snake_case_    			=    (max_retry_error,)
         raise

   def raise_connection_error(lowerCAmelCase_							:Tuple						,  lowerCAmelCase_							:int						,  **lowerCAmelCase_							:str							):
      raise requests.ConnectionError("Offline mode is enabled."						,  request=lowerCAmelCase_							)

   if mode is OfflineSimulationMode.CONNECTION_FAILS:
      with patch("requests.Session.send"						,  lowerCAmelCase_							):
         yield
   elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
      # inspired from https://stackoverflow.com/a/904609
      with patch("requests.Session.request"						,  lowerCAmelCase_							):
         yield
   elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
      with patch("datasets.config.HF_DATASETS_OFFLINE"						,  lowerCAmelCase_							):
         yield
   else:
      raise ValueError("Please use a value from the OfflineSimulationMode enum."							)



@contextmanager
def 	_lowerCAmelCase  (							*lowerCAmelCase_							:str						,  **lowerCAmelCase_							:Dict							)->List[Any]:
   '''simple docstring'''






   snake_case_    			=    str(Path().resolve()							)
   with tempfile.TemporaryDirectory(*lowerCAmelCase_						,  **lowerCAmelCase_							) as tmp_dir:
      try:
         os.chdir(lowerCAmelCase_							)
         yield
      finally:
         os.chdir(lowerCAmelCase_							)



@contextmanager
def 	_lowerCAmelCase  (							)->Optional[int]:
   '''simple docstring'''






   import gc

   gc.collect()
   snake_case_    			=    pa.total_allocated_bytes()
   yield
   assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."



@contextmanager
def 	_lowerCAmelCase  (							)->Optional[Any]:
   '''simple docstring'''






   import gc

   gc.collect()
   snake_case_    			=    pa.total_allocated_bytes()
   yield
   assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."



def 	_lowerCAmelCase  (							lowerCAmelCase_							:Dict						,  lowerCAmelCase_							:Dict							)->Tuple:
   '''simple docstring'''






   return deepcopy(lowerCAmelCase_							).integers(0						,  100						,  10							).tolist() == deepcopy(lowerCAmelCase_							).integers(0						,  100						,  10							).tolist()



def 	_lowerCAmelCase  (							lowerCAmelCase_							:List[str]							)->Union[str, Any]:
   '''simple docstring'''






   import decorator
   from requests.exceptions import HTTPError

   def _wrapper(lowerCAmelCase_							:Tuple						,  *lowerCAmelCase_							:List[str]						,  **lowerCAmelCase_							:List[Any]							):
      try:
         return func(*lowerCAmelCase_						,  **lowerCAmelCase_							)
      except HTTPError as err:
         if str(lowerCAmelCase_							).startswith("500"							) or str(lowerCAmelCase_							).startswith("502"							):
            pytest.xfail(str(lowerCAmelCase_							)							)
         raise err

   return decorator.decorator(_wrapper						,  lowerCAmelCase_							)


class 			__lowerCAmelCase   :






  """simple docstring"""





  def __init__(   self				:				Tuple			, _lowerCAmelCase				:				Dict			, _lowerCAmelCase				:				Union[str, Any]			, _lowerCAmelCase				:				Any     )      ->       List[Any]:




     """simple docstring"""
     snake_case_    			=    returncode
     snake_case_    			=    stdout
     snake_case_    			=    stderr






async def 	_lowerCAmelCase  (							lowerCAmelCase_							:Dict						,  lowerCAmelCase_							:List[str]							)->Union[str, Any]:
   '''simple docstring'''






   while True:
      snake_case_    			=    await stream.readline()
      if line:
         callback(lowerCAmelCase_							)
      else:
         break



async def 	_lowerCAmelCase  (							lowerCAmelCase_							:Tuple						,  lowerCAmelCase_							:List[str]=None						,  lowerCAmelCase_							:Optional[int]=None						,  lowerCAmelCase_							:int=None						,  lowerCAmelCase_							:int=False						,  lowerCAmelCase_							:str=False							)->_RunOutput:
   '''simple docstring'''






   if echo:
      print("\nRunning: "						,  " ".join(lowerCAmelCase_							)							)

   snake_case_    			=    await asyncio.create_subprocess_exec(
       cmd[0]						,  *cmd[1:]						,  stdin=lowerCAmelCase_						,  stdout=asyncio.subprocess.PIPE						,  stderr=asyncio.subprocess.PIPE						,  env=lowerCAmelCase_						,  )

   # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
   # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
   #
   # If it starts hanging, will need to switch to the following code. The problem is that no data
   # will be seen until it's done and if it hangs for example there will be no debug info.
   # out, err = await p.communicate()
   # return _RunOutput(p.returncode, out, err)

   snake_case_    			=    []
   snake_case_    			=    []

   def tee(lowerCAmelCase_							:List[str]						,  lowerCAmelCase_							:List[Any]						,  lowerCAmelCase_							:int						,  lowerCAmelCase_							:Optional[Any]=""							):
      snake_case_    			=    line.decode("utf-8"							).rstrip()
      sink.append(lowerCAmelCase_							)
      if not quiet:
         print(lowerCAmelCase_						,  lowerCAmelCase_						,  file=lowerCAmelCase_							)

    # XXX: the timeout doesn't seem to make any difference here
   await asyncio.wait(
       [
           _read_stream(p.stdout						,  lambda lowerCAmelCase_							: tee(lowerCAmelCase_						,  lowerCAmelCase_						,  sys.stdout						,  label="stdout:"							)							),
           _read_stream(p.stderr						,  lambda lowerCAmelCase_							: tee(lowerCAmelCase_						,  lowerCAmelCase_						,  sys.stderr						,  label="stderr:"							)							),
       ]						,  timeout=lowerCAmelCase_						,  )
   return _RunOutput(await p.wait()						,  lowerCAmelCase_						,  lowerCAmelCase_							)



def 	_lowerCAmelCase  (							lowerCAmelCase_							:int						,  lowerCAmelCase_							:List[Any]=None						,  lowerCAmelCase_							:Optional[Any]=None						,  lowerCAmelCase_							:List[str]=180						,  lowerCAmelCase_							:Optional[Any]=False						,  lowerCAmelCase_							:Any=True							)->_RunOutput:
   '''simple docstring'''






   snake_case_    			=    asyncio.get_event_loop()
   snake_case_    			=    loop.run_until_complete(
       _stream_subprocess(lowerCAmelCase_						,  env=lowerCAmelCase_						,  stdin=lowerCAmelCase_						,  timeout=lowerCAmelCase_						,  quiet=lowerCAmelCase_						,  echo=lowerCAmelCase_							)							)

   snake_case_    			=    """ """.join(lowerCAmelCase_							)
   if result.returncode > 0:
      snake_case_    			=    """\n""".join(result.stderr							)
      raise RuntimeError(
          F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
          F'''The combined stderr from workers follows:\n{stderr}'''							)

   # check that the subprocess actually did run and produced some output, should the test rely on
   # the remote side to do the testing
   if not result.stdout and not result.stderr:
      raise RuntimeError(F'''\'{cmd_str}\' produced no output.'''							)

   return result



def 	_lowerCAmelCase  (							)->Union[str, Any]:
   '''simple docstring'''






   snake_case_    			=    os.environ.get("PYTEST_XDIST_WORKER"						,  "gw0"							)
   snake_case_    			=    re.sub(r"^gw"						,  ""						,  lowerCAmelCase_						,  0						,  re.M							)
   return int(lowerCAmelCase_							)



def 	_lowerCAmelCase  (							)->Any:
   '''simple docstring'''






   snake_case_    			=    29_500
   snake_case_    			=    pytest_xdist_worker_id()
   return port + uniq_delta












from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


UpperCAmelCase_ :						int      =      '''\
@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}
}
'''

UpperCAmelCase_ :						Optional[Any]      =      '''\
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.
'''

UpperCAmelCase_ :						int      =      '''
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    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]	,			__magic_name__					:  Optional[Any]					)		->			Union[str, Any]:






	"""simple docstring"""



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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  int	,			__magic_name__					:  Any="binary"					)		->			Dict:






	"""simple docstring"""



	UpperCamelCase     :List[str]          =	simple_accuracy(__magic_name__	,			__magic_name__					)
	UpperCamelCase     :Dict          =	float(fa_score(y_true=__magic_name__	,			y_pred=__magic_name__	,			average=__magic_name__					)					)
	return {
	    "accuracy": acc,
	    "f1": fa,
	}

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]	,			__magic_name__					:  Optional[Any]					)		->			Optional[Any]:






	"""simple docstring"""



	UpperCamelCase     :Optional[Any]          =	{}
	for id_pred, label in zip(__magic_name__	,			__magic_name__					):
		UpperCamelCase     :str          =	f"""{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}"""
		UpperCamelCase     :Union[str, Any]          =	id_pred["""prediction"""]
		if question_id in question_map:
			question_map[question_id].append((pred, label)					)
		else:
			UpperCamelCase     :Dict          =	[(pred, label)]
	UpperCamelCase     ,      UpperCamelCase     :Optional[int]          =	[], []
	for question, preds_labels in question_map.items():
		UpperCamelCase     ,      UpperCamelCase     :Optional[Any]          =	zip(*__magic_name__					)
		UpperCamelCase     :Optional[int]          =	fa_score(y_true=__magic_name__	,			y_pred=__magic_name__	,			average="""macro"""					)
		fas.append(__magic_name__					)
		UpperCamelCase     :int          =	int(sum(pred == label for pred, label in preds_labels					) == len(__magic_name__					)					)
		ems.append(__magic_name__					)
	UpperCamelCase     :Optional[int]          =	float(sum(__magic_name__					) / len(__magic_name__					)					)
	UpperCamelCase     :str          =	sum(__magic_name__					) / len(__magic_name__					)
	UpperCamelCase     :Tuple          =	float(fa_score(y_true=__magic_name__	,			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      ):





	def 						_A (		self				:					str	):
		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 						_A (		self				:					Optional[Any]	):
		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 						_A (		self				:					List[str] ,  __lowerCamelCase				:					Tuple ,  __lowerCamelCase				:					str	):
		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":
			UpperCamelCase     :Optional[Any]          =	[
			    {
			        """qas""": [
			            {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]}
			            for ref in references
			        ]
			    }
			]
			UpperCamelCase     :Tuple          =	{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\",]"""	)
