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


A   :     Any       =				logging.get_logger(__name__)


@dataclass
class      lowerCamelCase    :
  """simple docstring"""







  lowerCamelCase__   =  field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(glue_processors.keys()    )}    )
  lowerCamelCase__   =  field(
      metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''}    )
  lowerCamelCase__   =  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.'''
          )
      }     ,					)
  lowerCamelCase__   =  field(
      default=SCREAMING_SNAKE_CASE__     ,					metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}    )







  def       __A   (							self       :				int      )     ->		Dict:
        SCREAMING_SNAKE_CASE_      =     self.task_name.lower()



class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
  """simple docstring"""







  lowerCamelCase__   =  '''train'''
  lowerCamelCase__   =  '''dev'''
  lowerCamelCase__   =  '''test'''



class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
  """simple docstring"""







  lowerCamelCase__   =  42
  lowerCamelCase__   =  42
  lowerCamelCase__   =  42







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

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







  def __getitem__(							self       :				Tuple     ,   __magic_name__       :				Optional[int]      )     ->		InputFeatures:
        return self.features[i]







  def       __A   (							self       :				Tuple      )     ->		Optional[int]:
        return self.label_list



import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
      from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
      from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
      from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


A   :     Tuple       =				DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

A   :     Dict       =				"main"
# Default branch name
A   :     List[str]       =				"f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
A   :     Tuple       =				"aaaaaaa"
# This commit does not exist, so we should 404.

A   :     int       =				"d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
A   :     Tuple       =				"4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"


@contextlib.contextmanager
def    a__       (						):
      print("Welcome!" )
      yield
      print("Bye!" )


@contextlib.contextmanager
def    a__       (						):
      print("Bonjour!" )
      yield
      print("Au revoir!" )


class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  def       __A   (							self       :				Union[str, Any]      )     ->		Any:
        # If the spec is missing, importlib would not be able to import the module dynamically.
        assert transformers.__spec__ is not None
        assert importlib.util.find_spec("transformers"      ) is not None



class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Union[str, Any]      )     ->		Union[str, Any]:
        with ContextManagers([]      ):
              print("Transformers are awesome!"      )
        # The print statement adds a new line at the end of the output
        self.assertEqual(mock_stdout.getvalue()     ,   "Transformers are awesome!\n"      )







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Dict     ,   __magic_name__       :				Union[str, Any]      )     ->		int:
        with ContextManagers([context_en()]      ):
              print("Transformers are awesome!"      )
        # The output should be wrapped with an English welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()     ,   "Welcome!\nTransformers are awesome!\nBye!\n"      )







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				str      )     ->		Union[str, Any]:
        with ContextManagers([context_fr(), context_en()]      ):
              print("Transformers are awesome!"      )
        # The output should be wrapped with an English and French welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()     ,   "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"      )







  @require_torch
  def       __A   (							self       :				List[str]      )     ->		Union[str, Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )







  @require_tf
  def       __A   (							self       :				List[str]      )     ->		Optional[Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )







  @require_flax
  def       __A   (							self       :				int      )     ->		Tuple:
        # Flax models don't have labels
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


