
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


__lowerCAmelCase			:     str           =   logging.get_logger(__name__)




@dataclass
class        UpperCAmelCase_			:


  '''simple docstring'''







  a__           =		field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()     )}     )
  a__           =		field(
      metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}     )
  a__           =		field(
      default=1_28  ,       metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }  ,       )
  a__           =		field(
      default=_A  ,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}     )
  def 							_lowercase							( self			: Optional[Any]    )			->	List[str]:







    """simple docstring"""






    __magic_name__				     =       self.task_name.lower()







class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







  a__           =		"""train"""
  a__           =		"""dev"""
  a__           =		"""test"""







class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







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

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







    """simple docstring"""






    return len(self.features    )
  def __getitem__( self			: Tuple			,							UpperCamelCase__			: Dict    )			->	InputFeatures:







    """simple docstring"""






    return self.features[i]





  def 							_lowercase							( self			: Optional[Any]    )			->	int:







    """simple docstring"""






    return self.label_list



import re
import string

import numpy as np

import datasets


__lowerCAmelCase			:     Optional[int]           =   '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

__lowerCAmelCase			:     Optional[int]           =   '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

__lowerCAmelCase			:     Optional[int]           =   '\n'




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


  '''simple docstring'''







  def 							_lowercase							( self			: str    )			->	Optional[int]:







    """simple docstring"""






    return datasets.MetricInfo(
        description=_DESCRIPTION			,							citation=_CITATION			,							inputs_description=_KWARGS_DESCRIPTION			,							features=datasets.Features(
            {
                """predictions""": datasets.Value("""string"""			,							id="""sequence"""    ),
                """references""": datasets.Value("""string"""			,							id="""sequence"""    ),
            }    )			,							reference_urls=[]			,							)





  def 							_lowercase							( self			: Optional[int]			,							UpperCamelCase__			: Optional[Any]			,							UpperCamelCase__			: Tuple			,							UpperCamelCase__			: Optional[Any]=None			,							UpperCamelCase__			: Optional[Any]=False			,							UpperCamelCase__			: int=False			,							UpperCamelCase__			: Tuple=False			,							)			->	Dict:







    """simple docstring"""






    if regexes_to_ignore is not None:
      for s in regexes_to_ignore:
        __magic_name__				     =       np.array([re.sub(UpperCamelCase__			,							""""""			,							UpperCamelCase__    ) for x in predictions]    )
        __magic_name__				     =       np.array([re.sub(UpperCamelCase__			,							""""""			,							UpperCamelCase__    ) for x in references]    )
    else:
      __magic_name__				     =       np.asarray(UpperCamelCase__    )
      __magic_name__				     =       np.asarray(UpperCamelCase__    )

    if ignore_case:
      __magic_name__				     =       np.char.lower(UpperCamelCase__    )
      __magic_name__				     =       np.char.lower(UpperCamelCase__    )

    if ignore_punctuation:
      __magic_name__				     =       string.punctuation.maketrans(""""""			,							""""""			,							string.punctuation    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )

    if ignore_numbers:
      __magic_name__				     =       string.digits.maketrans(""""""			,							""""""			,							string.digits    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )
      __magic_name__				     =       np.char.translate(UpperCamelCase__			,							table=UpperCamelCase__    )

    __magic_name__				     =       predictions == references

    return {"exact_match": np.mean(UpperCamelCase__    ) * 100}

