



"""simple docstring"""







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


__lowercase    =				logging.get_logger(__name__)






@dataclass
class 						_A  :







    """simple docstring"""




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






    def      __snake_case							( self    :   int):
      a						:		Union[str, Any]											=      self.task_name.lower()






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							Union[str, Any]     =	"""train"""
    UpperCAmelCase	:							str     =	"""dev"""
    UpperCAmelCase	:							int     =	"""test"""






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							GlueDataTrainingArguments
    UpperCAmelCase	:							str
    UpperCAmelCase	:							List[InputFeatures]






    def __init__( self    :   Union[str, Any]    ,			__UpperCAmelCase    :   GlueDataTrainingArguments    ,			__UpperCAmelCase    :   PreTrainedTokenizerBase    ,			__UpperCAmelCase    :   Optional[int] = None    ,			__UpperCAmelCase    :   Union[str, Split] = Split.train    ,			__UpperCAmelCase    :   Optional[str] = None    ,			):
      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"    ,			__UpperCAmelCase    ,			)
      a						:		int											=      args
      a						:		Union[str, Any]											=      glue_processors[args.task_name]()
      a						:		int											=      glue_output_modes[args.task_name]
      if isinstance(__UpperCAmelCase    ,			__UpperCAmelCase):
        try:
          a						:		Union[str, Any]											=      Split[mode]
        except KeyError:
          raise KeyError("mode is not a valid split name")
        # Load data features from cache or dataset file
      a						:		List[Any]											=      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}'''    ,			)
      a						:		List[Any]											=      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)
        a						:		List[Any]											=      label_list[2], label_list[1]
      a						:		str											=      label_list

      # Make sure only the first process in distributed training processes the dataset,
      # and the others will use the cache.
      a						:		Any											=      cached_features_file + ".lock"
      with FileLock(__UpperCAmelCase):
        if os.path.exists(__UpperCAmelCase) and not args.overwrite_cache:
          a						:		List[Any]											=      time.time()
          a						:		List[str]											=      torch.load(__UpperCAmelCase)
          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:
            a						:		Dict											=      self.processor.get_dev_examples(args.data_dir)
          elif mode == Split.test:
            a						:		Optional[int]											=      self.processor.get_test_examples(args.data_dir)
          else:
            a						:		int											=      self.processor.get_train_examples(args.data_dir)
          if limit_length is not None:
            a						:		Tuple											=      examples[:limit_length]
          a						:		int											=      glue_convert_examples_to_features(
              __UpperCAmelCase    ,			__UpperCAmelCase    ,			max_length=args.max_seq_length    ,			label_list=__UpperCAmelCase    ,			output_mode=self.output_mode    ,			)
          a						:		Optional[Any]											=      time.time()
          torch.save(self.features    ,			__UpperCAmelCase)
          # ^ 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    :   Union[str, Any]):
      return len(self.features)






    def __getitem__( self    :   str    ,			__UpperCAmelCase    :   int):
      return self.features[i]






    def      __snake_case							( self    :   Optional[Any]):
      return self.label_list










"""simple docstring"""







import datasets


__lowercase    =				"""\
@InProceedings{conneau2018xnli,
  author = \"Conneau, Alexis
                 and Rinott, Ruty
                 and Lample, Guillaume
                 and Williams, Adina
                 and Bowman, Samuel R.
                 and Schwenk, Holger
                 and Stoyanov, Veselin\",
  title = \"XNLI: Evaluating Cross-lingual Sentence Representations\",
  booktitle = \"Proceedings of the 2018 Conference on Empirical Methods
               in Natural Language Processing\",
  year = \"2018\",
  publisher = \"Association for Computational Linguistics\",
  location = \"Brussels, Belgium\",
}
"""

__lowercase    =				"""\
XNLI is a subset of a few thousand examples from MNLI which has been translated
into a 14 different languages (some low-ish resource). As with MNLI, the goal is
to predict textual entailment (does sentence A imply/contradict/neither sentence
B) and is a classification task (given two sentences, predict one of three
labels).
"""

__lowercase    =				"""
Computes XNLI score which is just simple accuracy.
Args:
    predictions: Predicted labels.
    references: Ground truth labels.
Returns:
    'accuracy': accuracy
Examples:

    >>> predictions = [0, 1]
    >>> references = [0, 1]
    >>> xnli_metric = datasets.load_metric(\"xnli\")
    >>> results = xnli_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'accuracy': 1.0}
"""


def 					lowercase      (    A_  ,       A_	)->				List[str]:
  '''simple docstring'''







  return (preds == labels).mean()







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,_KWARGS_DESCRIPTION  )
class 						_A  (  datasets.Metric  ):







    """simple docstring"""




    def      __snake_case							( self    :   List[str]):
      return datasets.MetricInfo(
          description=_DESCRIPTION    ,			citation=_CITATION    ,			inputs_description=_KWARGS_DESCRIPTION    ,			features=datasets.Features(
              {
                  "predictions": datasets.Value("int64" if self.config_name != "sts-b" else "float32"),
                  "references": datasets.Value("int64" if self.config_name != "sts-b" else "float32"),
              })    ,			codebase_urls=[]    ,			reference_urls=[]    ,			format="numpy"    ,			)






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   List[Any]    ,			__UpperCAmelCase    :   Tuple):
      return {"accuracy": simple_accuracy(__UpperCAmelCase    ,			__UpperCAmelCase)}






