


import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


SCREAMING_SNAKE_CASE		:Optional[Any]     						=   logging.get_logger(__name__)


@dataclass
class 			__lowerCAmelCase   :






  """simple docstring"""





  _SCREAMING_SNAKE_CASE									=				field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys()    )}    )
  _SCREAMING_SNAKE_CASE									=				field(
      metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'}    )
  _SCREAMING_SNAKE_CASE									=				field(
      default=128       ,     metadata={
          'help': (
              'The maximum total input sequence length after tokenization. Sequences longer '
              'than this will be truncated, sequences shorter will be padded.'
          )
      }       ,     )
  _SCREAMING_SNAKE_CASE									=				field(
      default=_a       ,     metadata={'help': 'Overwrite the cached training and evaluation sets'}    )



  def     lowerCAmelCase__     (   self				:				Dict     )      ->       List[str]:




     """simple docstring"""
     snake_case_    			=    self.task_name.lower()






class 			__lowerCAmelCase   (       _a    ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE									=				"""train"""
  _SCREAMING_SNAKE_CASE									=				"""dev"""
  _SCREAMING_SNAKE_CASE									=				"""test"""






class 			__lowerCAmelCase   (       _a    ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE									=				42
  _SCREAMING_SNAKE_CASE									=				42
  _SCREAMING_SNAKE_CASE									=				42



  def __init__(   self				:				List[Any]			, _lowerCAmelCase				:				GlueDataTrainingArguments			, _lowerCAmelCase				:				PreTrainedTokenizerBase			, _lowerCAmelCase				:				Optional[int] = None			, _lowerCAmelCase				:				Union[str, Split] = Split.train			, _lowerCAmelCase				:				Optional[str] = None			, )      ->       Optional[Any]:




     """simple docstring"""
     warnings.warn(
         "This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
         "library. You can have a look at this example script for pointers: "
         "https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py"			, __lowerCamelCase			, )
     snake_case_    			=    args
     snake_case_    			=    glue_processors[args.task_name]()
     snake_case_    			=    glue_output_modes[args.task_name]
     if isinstance(__lowerCamelCase			, __lowerCamelCase     ):
        try:
           snake_case_    			=    Split[mode]
        except KeyError:
           raise KeyError("mode is not a valid split name"     )
        # Load data features from cache or dataset file
     snake_case_    			=    os.path.join(
         cache_dir if cache_dir is not None else args.data_dir			, F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}'''			, )
     snake_case_    			=    self.processor.get_labels()
     if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
         "RobertaTokenizer",
         "RobertaTokenizerFast",
         "XLMRobertaTokenizer",
         "BartTokenizer",
         "BartTokenizerFast",
     ):
        # HACK(label indices are swapped in RoBERTa pretrained model)
        snake_case_    			=    label_list[2], label_list[1]
     snake_case_    			=    label_list

     # Make sure only the first process in distributed training processes the dataset,
     # and the others will use the cache.
     snake_case_    			=    cached_features_file + """.lock"""
     with FileLock(__lowerCamelCase     ):
        if os.path.exists(__lowerCamelCase     ) and not args.overwrite_cache:
           snake_case_    			=    time.time()
           snake_case_    			=    torch.load(__lowerCamelCase     )
           logger.info(
               F'''Loading features from cached file {cached_features_file} [took %.3f s]'''			, time.time() - start     )
        else:
           logger.info(F'''Creating features from dataset file at {args.data_dir}'''     )

           if mode == Split.dev:
              snake_case_    			=    self.processor.get_dev_examples(args.data_dir     )
           elif mode == Split.test:
              snake_case_    			=    self.processor.get_test_examples(args.data_dir     )
           else:
              snake_case_    			=    self.processor.get_train_examples(args.data_dir     )
           if limit_length is not None:
              snake_case_    			=    examples[:limit_length]
           snake_case_    			=    glue_convert_examples_to_features(
               __lowerCamelCase			, __lowerCamelCase			, max_length=args.max_seq_length			, label_list=__lowerCamelCase			, output_mode=self.output_mode			, )
           snake_case_    			=    time.time()
           torch.save(self.features			, __lowerCamelCase     )
           # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
           logger.info(
               F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''     )



  def __len__(   self				:				int     )      ->       str:




     """simple docstring"""
     return len(self.features     )



  def __getitem__(   self				:				Optional[int]			, _lowerCAmelCase				:				Any     )      ->       List[str]:




     """simple docstring"""
     return self.features[i]



  def     lowerCAmelCase__     (   self				:				int     )      ->       Any:




     """simple docstring"""
     return self.label_list












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