





from sklearn.metrics import fa_score, matthews_corrcoef

import datasets

from .record_evaluation import evaluate as evaluate_record


UpperCAmelCase_     							= '\\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'

UpperCAmelCase_     							= '\\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'

UpperCAmelCase_     							= '\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 		lowerCAmelCase_    (  __UpperCAmelCase:			Dict		,   __UpperCAmelCase:			List[Any]      )      ->	List[str]:
    return float((preds == labels).mean()      )




def 		lowerCAmelCase_    (  __UpperCAmelCase:			Union[str, Any]		,   __UpperCAmelCase:			List[str]		,   __UpperCAmelCase:			Any="binary"      )      ->	List[str]:
    UpperCamelCase__							:				Any          =      simple_accuracy(__UpperCAmelCase		,   __UpperCAmelCase      )
    UpperCamelCase__							:				Tuple          =      float(fa_score(y_true=__UpperCAmelCase		,   y_pred=__UpperCAmelCase		,   average=__UpperCAmelCase      )      )
    return {
        "accuracy": acc,
        "f1": fa,
    }




def 		lowerCAmelCase_    (  __UpperCAmelCase:			int		,   __UpperCAmelCase:			Union[str, Any]      )      ->	Dict:
    UpperCamelCase__							:				Union[str, Any]          =      {}
    for id_pred, label in zip(__UpperCAmelCase		,   __UpperCAmelCase      ):
        UpperCamelCase__							:				Tuple          =      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__							:				Optional[int]          =      [(pred, label)]
    UpperCamelCase__   ,UpperCamelCase__							:				str          =      [], []
    for question, preds_labels in question_map.items():
        UpperCamelCase__   ,UpperCamelCase__							:				Dict          =      zip(*__UpperCAmelCase      )
        UpperCamelCase__							:				int          =      fa_score(y_true=__UpperCAmelCase		,   y_pred=__UpperCAmelCase		,   average='''macro'''      )
        fas.append(__UpperCAmelCase      )
        UpperCamelCase__							:				Optional[int]          =      int(sum(pred == label for pred, label in preds_labels      ) == len(__UpperCAmelCase      )      )
        ems.append(__UpperCAmelCase      )
    UpperCamelCase__							:				str          =      float(sum(__UpperCAmelCase      ) / len(__UpperCAmelCase      )      )
    UpperCamelCase__							:				str          =      sum(__UpperCAmelCase      ) / len(__UpperCAmelCase      )
    UpperCamelCase__							:				Dict          =      float(fa_score(y_true=__UpperCAmelCase		,   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     lowercase__       (	datasets.Metric				):

   '''simple docstring'''


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






       """simple docstring"""
       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]:






       """simple docstring"""
       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,		__magic_name__,		__magic_name__							) ->      Union[str, Any]:






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








import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()




def 		lowerCAmelCase_    (  __UpperCAmelCase:			str		,   __UpperCAmelCase:			str		,   __UpperCAmelCase:			str		,   __UpperCAmelCase:			PreTrainedTokenizer		,   __UpperCAmelCase:			int		,   __UpperCAmelCase:			Optional[int] = None		,   )      ->	List[Any]:
    UpperCamelCase__							:				Dict          =      {}

    if train_file is not None:
        UpperCamelCase__							:				str          =      [train_file]
    if eval_file is not None:
        UpperCamelCase__							:				Union[str, Any]          =      [eval_file]
    if test_file is not None:
        UpperCamelCase__							:				Tuple          =      [test_file]

    UpperCamelCase__							:				Optional[Any]          =      datasets.load_dataset('''csv'''		,   data_files=__UpperCAmelCase      )
    UpperCamelCase__							:				List[Any]          =      list(ds[list(files.keys()      )[0]].features.keys()      )
    UpperCamelCase__							:				str          =      features_name.pop(__UpperCAmelCase      )
    UpperCamelCase__							:				List[str]          =      list(set(ds[list(files.keys()      )[0]][label_name]      )      )
    UpperCamelCase__							:				Optional[Any]          =      {label: i for i, label in enumerate(__UpperCAmelCase      )}
    UpperCamelCase__							:				Union[str, Any]          =      tokenizer.model_input_names
    UpperCamelCase__							:				str          =      {}

    if len(__UpperCAmelCase      ) == 1:
        for k in files.keys():
            UpperCamelCase__							:				Optional[int]          =      ds[k].map(
                lambda __UpperCAmelCase      : tokenizer.batch_encode_plus(
                    example[features_name[0]]		,   truncation=__UpperCAmelCase		,   max_length=__UpperCAmelCase		,   padding='''max_length'''      )		,   batched=__UpperCAmelCase		,   )
    elif len(__UpperCAmelCase      ) == 2:
        for k in files.keys():
            UpperCamelCase__							:				Dict          =      ds[k].map(
                lambda __UpperCAmelCase      : tokenizer.batch_encode_plus(
                    (example[features_name[0]], example[features_name[1]])		,   truncation=__UpperCAmelCase		,   max_length=__UpperCAmelCase		,   padding='''max_length'''		,   )		,   batched=__UpperCAmelCase		,   )

    def gen_train():
        for ex in transformed_ds[datasets.Split.TRAIN]:
            UpperCamelCase__							:				Any          =      {k: v for k, v in ex.items() if k in input_names}
            UpperCamelCase__							:				str          =      labelaid[ex[label_name]]
            yield (d, label)

    def gen_val():
        for ex in transformed_ds[datasets.Split.VALIDATION]:
            UpperCamelCase__							:				Union[str, Any]          =      {k: v for k, v in ex.items() if k in input_names}
            UpperCamelCase__							:				str          =      labelaid[ex[label_name]]
            yield (d, label)

    def gen_test():
        for ex in transformed_ds[datasets.Split.TEST]:
            UpperCamelCase__							:				Optional[Any]          =      {k: v for k, v in ex.items() if k in input_names}
            UpperCamelCase__							:				int          =      labelaid[ex[label_name]]
            yield (d, label)

    UpperCamelCase__							:				Tuple          =      (
        tf.data.Dataset.from_generator(
            __UpperCAmelCase		,   ({k: tf.intaa for k in input_names}, tf.intaa)		,   ({k: tf.TensorShape([None]      ) for k in input_names}, tf.TensorShape([]      ))		,   )
        if datasets.Split.TRAIN in transformed_ds
        else None
    )

    if train_ds is not None:
        UpperCamelCase__							:				Optional[Any]          =      train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]      )      )      )

    UpperCamelCase__							:				int          =      (
        tf.data.Dataset.from_generator(
            __UpperCAmelCase		,   ({k: tf.intaa for k in input_names}, tf.intaa)		,   ({k: tf.TensorShape([None]      ) for k in input_names}, tf.TensorShape([]      ))		,   )
        if datasets.Split.VALIDATION in transformed_ds
        else None
    )

    if val_ds is not None:
        UpperCamelCase__							:				Dict          =      val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]      )      )      )

    UpperCamelCase__							:				Optional[Any]          =      (
        tf.data.Dataset.from_generator(
            __UpperCAmelCase		,   ({k: tf.intaa for k in input_names}, tf.intaa)		,   ({k: tf.TensorShape([None]      ) for k in input_names}, tf.TensorShape([]      ))		,   )
        if datasets.Split.TEST in transformed_ds
        else None
    )

    if test_ds is not None:
        UpperCamelCase__							:				Union[str, Any]          =      test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]      )      )      )

    return train_ds, val_ds, test_ds, labelaid


UpperCAmelCase_     							= logging.getLogger(__name__)






@dataclass
class     lowercase__       :

   '''simple docstring'''


   a						:							int   		=		field(metadata={"help": "Which column contains the label"}				)
   a						:							str   		=		field(default=__lowerCamelCase			,				metadata={"help": "The path of the training file"}				)
   a						:							Optional[str]   		=		field(default=__lowerCamelCase			,				metadata={"help": "The path of the development file"}				)
   a						:							Optional[str]   		=		field(default=__lowerCamelCase			,				metadata={"help": "The path of the test file"}				)
   a						:							int   		=		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."
           )
       }			,				)
   a						:							bool   		=		field(
       default=__lowerCamelCase			,				metadata={"help": "Overwrite the cached training and evaluation sets"}				)






@dataclass
class     lowercase__       :

   '''simple docstring'''


   a						:							str   		=		field(
       metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}				)
   a						:							Optional[str]   		=		field(
       default=__lowerCamelCase			,				metadata={"help": "Pretrained config name or path if not the same as model_name"}				)
   a						:							Optional[str]   		=		field(
       default=__lowerCamelCase			,				metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}				)
   a						:							bool   		=		field(default=__lowerCamelCase			,				metadata={"help": "Set this flag to use fast tokenization."}				)
   # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
   # or just modify its tokenizer_config.json.
   a						:							Optional[str]   		=		field(
       default=__lowerCamelCase			,				metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}			,				)




def 		lowerCAmelCase_    (  )      ->	int:
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.
    UpperCamelCase__							:				Tuple          =      HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)      )
    UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				Any          =      parser.parse_args_into_dataclasses()

    if (
        os.path.exists(training_args.output_dir      )
        and os.listdir(training_args.output_dir      )
        and training_args.do_train
        and not training_args.overwrite_output_dir
    ):
        raise ValueError(
            f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
            ''' --overwrite_output_dir to overcome.'''      )

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''		,   datefmt='''%m/%d/%Y %H:%M:%S'''		,   level=logging.INFO		,   )
    logger.info(
        f"n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1      )}, "
        f"16-bits training: {training_args.fpaa}"      )
    logger.info(f"Training/evaluation parameters {training_args}"      )

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    UpperCamelCase__							:				List[str]          =      AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path		,   cache_dir=model_args.cache_dir		,   )

    UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__   ,UpperCamelCase__							:				Optional[int]          =      get_tfds(
        train_file=data_args.train_file		,   eval_file=data_args.dev_file		,   test_file=data_args.test_file		,   tokenizer=__UpperCAmelCase		,   label_column_id=data_args.label_column_id		,   max_seq_length=data_args.max_seq_length		,   )

    UpperCamelCase__							:				int          =      AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path		,   num_labels=len(__UpperCAmelCase      )		,   labelaid=__UpperCAmelCase		,   idalabel={id: label for label, id in labelaid.items()}		,   finetuning_task='''text-classification'''		,   cache_dir=model_args.cache_dir		,   )

    with training_args.strategy.scope():
        UpperCamelCase__							:				str          =      TFAutoModelForSequenceClassification.from_pretrained(
            model_args.model_name_or_path		,   from_pt=bool('''.bin''' in model_args.model_name_or_path      )		,   config=__UpperCAmelCase		,   cache_dir=model_args.cache_dir		,   )

    def compute_metrics(__UpperCAmelCase:			EvalPrediction      ) -> Dict:
        UpperCamelCase__							:				Optional[Any]          =      np.argmax(p.predictions		,   axis=1      )

        return {"acc": (preds == p.label_ids).mean()}

    # Initialize our Trainer
    UpperCamelCase__							:				Union[str, Any]          =      TFTrainer(
        model=__UpperCAmelCase		,   args=__UpperCAmelCase		,   train_dataset=__UpperCAmelCase		,   eval_dataset=__UpperCAmelCase		,   compute_metrics=__UpperCAmelCase		,   )

    # Training
    if training_args.do_train:
        trainer.train()
        trainer.save_model()
        tokenizer.save_pretrained(training_args.output_dir      )

    # Evaluation
    UpperCamelCase__							:				List[str]          =      {}
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''      )
        UpperCamelCase__							:				Tuple          =      trainer.evaluate()
        UpperCamelCase__							:				Optional[int]          =      os.path.join(training_args.output_dir		,   '''eval_results.txt'''      )

        with open(__UpperCAmelCase		,   '''w'''      ) as writer:
            logger.info('''***** Eval results *****'''      )

            for key, value in result.items():
                logger.info(f"  {key} = {value}"      )
                writer.write(f"{key} = {value}\n"      )

            results.update(__UpperCAmelCase      )

    return results


if __name__ == "__main__":
  main()

