


"""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


UpperCAmelCase       :	int  		=						logging.get_logger(__name__)





@dataclass
class 	lowerCamelCase__  :







					"""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=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=__UpperCAmelCase	,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}							)






					def lowerCamelCase__				(			self       :					Optional[int]    ):
												'''simple docstring'''






												__UpperCAmelCase  :		str 				=   self.task_name.lower()






class 	lowerCamelCase__  (	__UpperCAmelCase							):







					"""simple docstring"""


					__a      			=				'train'
					__a      			=				'dev'
					__a      			=				'test'






class 	lowerCamelCase__  (	__UpperCAmelCase							):







					"""simple docstring"""


					__a      			=				42
					__a      			=				42
					__a      			=				42






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

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






												return len(self.features    )






					def __getitem__(			self       :					Any					,			UpperCamelCase       :					Optional[Any]    ):
												'''simple docstring'''






												return self.features[i]






					def lowerCamelCase__				(			self       :					Tuple    ):
												'''simple docstring'''






												return self.label_list








"""simple docstring"""
import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


lowerCAmelCase__    						=			threading.Lock()
lowerCAmelCase__    						=			None

lowerCAmelCase__    						=			{
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

lowerCAmelCase__    						=			logging.WARNING

lowerCAmelCase__    						=			True





def 				lowercase__		(					):
				_SCREAMING_SNAKE_CASE   :		int       		=    os.getenv('TRANSFORMERS_VERBOSITY',						lowerCamelCase       )
				if env_level_str:
								if env_level_str in log_levels:
												return log_levels[env_level_str]
								else:
												logging.getLogger().warning(
												    f"""Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, """
												    f"""has to be one of: { ", ".join(log_levels.keys()       ) }"""       )
				return _default_log_level





def 				lowercase__		(					):
				return __name__.split('.'       )[0]





def 				lowercase__		(					):
				return logging.getLogger(_get_library_name()       )





def 				lowercase__		(					):
				global _default_handler

				with _lock:
								if _default_handler:
												# This library has already configured the library root logger.
												return
								_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    logging.StreamHandler()  # Set sys.stderr as stream.
								_SCREAMING_SNAKE_CASE   :		Tuple       		=    sys.stderr.flush

								# Apply our default configuration to the library root logger.
								_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    _get_library_root_logger()
								library_root_logger.addHandler(_default_handler       )
								library_root_logger.setLevel(_get_default_logging_level()       )
								_SCREAMING_SNAKE_CASE   :		int       		=    False





def 				lowercase__		(					):
				global _default_handler

				with _lock:
								if not _default_handler:
												return

								_SCREAMING_SNAKE_CASE   :		Any       		=    _get_library_root_logger()
								library_root_logger.removeHandler(_default_handler       )
								library_root_logger.setLevel(logging.NOTSET       )
								_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    None





def 				lowercase__		(					):
				return log_levels





def 				lowercase__		(					lowerCamelCase = None       ):

				if name is None:
								_SCREAMING_SNAKE_CASE   :		Tuple       		=    _get_library_name()

				_configure_library_root_logger()
				return logging.getLogger(lowerCamelCase       )





def 				lowercase__		(					):
				_configure_library_root_logger()
				return _get_library_root_logger().getEffectiveLevel()





def 				lowercase__		(					lowerCamelCase       ):
				_configure_library_root_logger()
				_get_library_root_logger().setLevel(lowerCamelCase       )





def 				lowercase__		(					):
				return set_verbosity(lowerCamelCase       )





def 				lowercase__		(					):
				return set_verbosity(lowerCamelCase       )





def 				lowercase__		(					):
				return set_verbosity(lowerCamelCase       )





def 				lowercase__		(					):
				return set_verbosity(lowerCamelCase       )





def 				lowercase__		(					):
				_configure_library_root_logger()

				assert _default_handler is not None
				_get_library_root_logger().removeHandler(_default_handler       )





def 				lowercase__		(					):
				_configure_library_root_logger()

				assert _default_handler is not None
				_get_library_root_logger().addHandler(_default_handler       )





def 				lowercase__		(					lowerCamelCase       ):
				_configure_library_root_logger()

				assert handler is not None
				_get_library_root_logger().addHandler(lowerCamelCase       )





def 				lowercase__		(					lowerCamelCase       ):
				_configure_library_root_logger()

				assert handler is not None and handler not in _get_library_root_logger().handlers
				_get_library_root_logger().removeHandler(lowerCamelCase       )





def 				lowercase__		(					):
				_configure_library_root_logger()
				_SCREAMING_SNAKE_CASE   :		List[str]       		=    False





def 				lowercase__		(					):
				_configure_library_root_logger()
				_SCREAMING_SNAKE_CASE   :		int       		=    True





def 				lowercase__		(					):
				_SCREAMING_SNAKE_CASE   :		Any       		=    _get_library_root_logger().handlers

				for handler in handlers:
								_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'       )
								handler.setFormatter(lowerCamelCase       )





def 				lowercase__		(					):
				_SCREAMING_SNAKE_CASE   :		List[str]       		=    _get_library_root_logger().handlers

				for handler in handlers:
								handler.setFormatter(lowerCamelCase       )





def 				lowercase__		(					self,						*lowerCamelCase,						**lowerCamelCase       ):
				_SCREAMING_SNAKE_CASE   :		str       		=    os.getenv('TRANSFORMERS_NO_ADVISORY_WARNINGS',						lowerCamelCase       )
				if no_advisory_warnings:
								return
				self.warning(*lowerCamelCase,						**lowerCamelCase       )


lowerCAmelCase__    						=			warning_advice





@functools.lru_cache(lowerCamelCase       )
def 				lowercase__		(					self,						*lowerCamelCase,						**lowerCamelCase       ):
				self.warning(*lowerCamelCase,						**lowerCamelCase       )


lowerCAmelCase__    						=			warning_once


class _lowerCAmelCase						:







						def __init__(    self   ,				*lowerCAmelCase_   ,				**lowerCAmelCase_							)		->							Optional[int]:  # pylint: disable=unused-argument
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    args[0] if args else None







						def __iter__(    self							)		->							Dict:
										return iter(self._iterator							)







						def __getattr__(    self   ,				lowerCAmelCase_							)		->							Tuple:

										def empty_fn(*lowerCAmelCase_   ,				**lowerCAmelCase_							):  # pylint: disable=unused-argument
														return

										return empty_fn







						def __enter__(    self							)		->							List[Any]:
										return self







						def __exit__(    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							Optional[Any]:
										return







class _lowerCAmelCase						:







						def __call__(    self   ,				*lowerCAmelCase_   ,				**lowerCAmelCase_							)		->							Optional[Any]:
										if _tqdm_active:
														return tqdm_lib.tqdm(*lowerCAmelCase_   ,				**lowerCAmelCase_							)
										else:
														return EmptyTqdm(*lowerCAmelCase_   ,				**lowerCAmelCase_							)







						def 			A      (    self   ,				*lowerCAmelCase_   ,				**lowerCAmelCase_							)		->							List[str]:
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    None
										if _tqdm_active:
														return tqdm_lib.tqdm.set_lock(*lowerCAmelCase_   ,				**lowerCAmelCase_							)







						def 			A      (    self							)		->							Any:
										if _tqdm_active:
														return tqdm_lib.tqdm.get_lock()







lowerCAmelCase__    						=			_tqdm_cls()





def 				lowercase__		(					):
				global _tqdm_active
				return bool(_tqdm_active       )





def 				lowercase__		(					):
				global _tqdm_active
				_SCREAMING_SNAKE_CASE   :		int       		=    True
				hf_hub_utils.enable_progress_bars()






def 				lowercase__		(					):
				global _tqdm_active
				_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    False
				hf_hub_utils.disable_progress_bars()

