






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


__UpperCamelCase      :      int     						=						DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

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

__UpperCamelCase      :      List[Any]     						=						"""d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"""
# Sha-1 of config.json on the top of `main`, for checking purposes
__UpperCamelCase      :      str     						=						"""4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"""





@contextlib.contextmanager
def 				snake_case  (     ):




	'''simple docstring'''







	print("""Welcome!"""					)
	yield
	print("""Bye!"""					)





@contextlib.contextmanager
def 				snake_case  (     ):




	'''simple docstring'''







	print("""Bonjour!"""					)
	yield
	print("""Au revoir!"""					)


class        __UpperCamelCase    (     unittest.TestCase   ):







	def  _a   (  self      :							Optional[int]			)		-> Optional[int]:
		"""simple docstring"""







		assert transformers.__spec__ is not None
		assert importlib.util.find_spec("""transformers"""			) is not None


class        __UpperCamelCase    (     unittest.TestCase   ):







	@unittest.mock.patch("""sys.stdout"""       ,				new_callable=io.StringIO			)
	def  _a   (  self      :							Any       ,				_lowerCAmelCase      :							int			)		-> Dict:
		"""simple docstring"""







		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       ,				_lowerCAmelCase      :							Dict			)		-> Optional[Any]:
		"""simple docstring"""







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







		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      :							Any			)		-> Optional[int]:
		"""simple docstring"""







		self.assertEqual(find_labels(__a			)       ,				["""labels"""]			)
		self.assertEqual(find_labels(__a			)       ,				["""labels""", """next_sentence_label"""]			)
		self.assertEqual(find_labels(__a			)       ,				["""start_positions""", """end_positions"""]			)


		class        __UpperCamelCase    (     _lowerCAmelCase   ):
			pass

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







	@require_tf
	def  _a   (  self      :							List[str]			)		-> List[Any]:
		"""simple docstring"""







		self.assertEqual(find_labels(__a			)       ,				["""labels"""]			)
		self.assertEqual(find_labels(__a			)       ,				["""labels""", """next_sentence_label"""]			)
		self.assertEqual(find_labels(__a			)       ,				["""start_positions""", """end_positions"""]			)


		class        __UpperCamelCase    (     _lowerCAmelCase   ):
			pass

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







	@require_flax
	def  _a   (  self      :							str			)		-> str:
		"""simple docstring"""







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


		class        __UpperCamelCase    (     _lowerCAmelCase   ):
			pass

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









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


__UpperCamelCase      :      Any     						=						logging.get_logger(__name__)


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







	def  _a   (  self      :							Dict			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.task_name.lower()


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Optional[int]   =       'train'
	__snake_case	:int   =       'dev'
	__snake_case	:Any   =       'test'


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:GlueDataTrainingArguments
	__snake_case	:str
	__snake_case	:List[InputFeatures]







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

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







		return len(self.features			)







	def __getitem__(  self      :							Tuple       ,				_lowerCAmelCase      :							Optional[int]			)		-> InputFeatures:
		"""simple docstring"""







		return self.features[i]







	def  _a   (  self      :							str			)		-> int:
		"""simple docstring"""







		return self.label_list

