





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 				=     logging.get_logger(__name__)

@dataclass
class    _UpperCAmelCase							:
      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=128			,       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=_lowerCamelCase			,       metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}     )
      def 		_lowerCamelCase      (		self       ):
         A_     :				List[Any]			      =	self.task_name.lower()






class    _UpperCAmelCase							(		_lowerCamelCase     ):
      a						       =							'''train'''
      a						       =							'''dev'''
      a						       =							'''test'''






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

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






      def 		_lowerCamelCase      (		self       ):
         return self.label_list













import datasets

from .evaluate import evaluate


_lowerCAmelCase 				=     """\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
"""

_lowerCAmelCase 				=     """
This metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.
"""

_lowerCAmelCase 				=     """
Computes SQuAD scores (F1 and EM).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair as given in the references (see below)
        - 'prediction_text': the text of the answer
    references: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair (see above),
        - 'answers': a Dict in the SQuAD dataset format
            {
                'text': list of possible texts for the answer, as a list of strings
                'answer_start': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    'exact_match': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
Examples:

    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]
    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]
    >>> squad_metric = datasets.load_metric(\"squad\")
    >>> results = squad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 100.0, 'f1': 100.0}
"""

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,       _KWARGS_DESCRIPTION     )
class    _UpperCAmelCase							(		datasets.Metric     ):
      def 		_lowerCamelCase      (		self       ):
         return datasets.MetricInfo(
             description=_DESCRIPTION      ,       citation=_CITATION      ,       inputs_description=_KWARGS_DESCRIPTION      ,       features=datasets.Features(
                 {
                     """predictions""": {"""id""": datasets.Value("""string"""       ), """prediction_text""": datasets.Value("""string"""       )},
                     """references""": {
                         """id""": datasets.Value("""string"""       ),
                         """answers""": datasets.features.Sequence(
                             {
                                 """text""": datasets.Value("""string"""       ),
                                 """answer_start""": datasets.Value("""int32"""       ),
                             }       ),
                     },
                 }       )      ,       codebase_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""]      ,       reference_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""]      ,       )






      def 		_lowerCamelCase      (		self      ,       a__      ,       a__       ):
         A_     :				Union[str, Any]			      =	{prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions}
         A_     :				Optional[Any]			      =	[
             {
                 """paragraphs""": [
                     {
                         """qas""": [
                             {
                                 """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]],
                                 """id""": ref["""id"""],
                             }
                             for ref in references
                         ]
                     }
                 ]
             }
         ]
         A_     :				Union[str, Any]			      =	evaluate(dataset=a__      ,       predictions=a__       )
         return score






