

import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


a__				=		logging.getLogger(__name__)

@dataclass
class 				UpperCAmelCase_		:
							"""simple docstring"""







							UpperCAmelCase__       :						str
							UpperCAmelCase__       :						List[str]
							UpperCAmelCase__       :						Optional[List[str]]



@dataclass
class 				UpperCAmelCase_		:
							"""simple docstring"""







							UpperCAmelCase__       :						List[int]
							UpperCAmelCase__       :						List[int]
							UpperCAmelCase__       :						Optional[List[int]]	    =    None
							UpperCAmelCase__       :						Optional[List[int]]	    =    None



class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						Union[str, Any]	    =    "train"
							UpperCAmelCase__       :						Dict	    =    "dev"
							UpperCAmelCase__       :						List[Any]	    =    "test"



class 				UpperCAmelCase_		:
							"""simple docstring"""







							@staticmethod
							def 				__lowercase				(			_a       ,							_a       )    ->    List[InputExample]:
												raise NotImplementedError


							@staticmethod
							def 				__lowercase				(			_a       )    ->    List[str]:
												raise NotImplementedError




							@staticmethod
							def 				__lowercase				(			_a       ,							_a       ,							_a       ,							_a       ,							_a=False       ,							_a="[CLS]"       ,							_a=1       ,							_a="[SEP]"       ,							_a=False       ,							_a=False       ,							_a=0       ,							_a=0       ,							_a=-1_0_0       ,							_a=0       ,							_a=True       ,							)    ->    List[InputFeatures]:
												_a	:    Union[str, Any]         =		{label: i for i, label in enumerate(_a       )}

												_a	:    Optional[Any]         =		[]
												for ex_index, example in enumerate(_a       ):
																	if ex_index % 1_0_0_0_0 == 0:
																						logger.info('''Writing example %d of %d'''       ,							_a       ,							len(_a       )       )

																	_a	:    List[str]         =		[]
																	_a	:    int         =		[]
																	for word, label in zip(example.words       ,							example.labels       ):
																						_a	:    List[Any]         =		tokenizer.tokenize(_a       )

																						# bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
																						if len(_a       ) > 0:
																											tokens.extend(_a       )
																											# Use the real label id for the first token of the word, and padding ids for the remaining tokens
																											label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_a       ) - 1)       )

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
																	_a	:    Optional[int]         =		tokenizer.num_special_tokens_to_add()
																	if len(_a       ) > max_seq_length - special_tokens_count:
																						_a	:    str         =		tokens[: (max_seq_length - special_tokens_count)]
																						_a	:    int         =		label_ids[: (max_seq_length - special_tokens_count)]

																	# The convention in BERT is:
																	# (a) For sequence pairs:
																	#  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
																	#  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
																	# (b) For single sequences:
																	#  tokens:   [CLS] the dog is hairy . [SEP]
																	#  type_ids:   0   0   0   0  0     0   0
																	#
																	# Where "type_ids" are used to indicate whether this is the first
																	# sequence or the second sequence. The embedding vectors for `type=0` and
																	# `type=1` were learned during pre-training and are added to the wordpiece
																	# embedding vector (and position vector). This is not *strictly* necessary
																	# since the [SEP] token unambiguously separates the sequences, but it makes
																	# it easier for the model to learn the concept of sequences.
																	#
																	# For classification tasks, the first vector (corresponding to [CLS]) is
																	# used as the "sentence vector". Note that this only makes sense because
																	# the entire model is fine-tuned.
																	tokens += [sep_token]
																	label_ids += [pad_token_label_id]
																	if sep_token_extra:
																						# roberta uses an extra separator b/w pairs of sentences
																						tokens += [sep_token]
																						label_ids += [pad_token_label_id]
																	_a	:    List[str]         =		[sequence_a_segment_id] * len(_a       )

																	if cls_token_at_end:
																						tokens += [cls_token]
																						label_ids += [pad_token_label_id]
																						segment_ids += [cls_token_segment_id]
																	else:
																						_a	:    int         =		[cls_token] + tokens
																						_a	:    Optional[int]         =		[pad_token_label_id] + label_ids
																						_a	:    Dict         =		[cls_token_segment_id] + segment_ids

																	_a	:    List[Any]         =		tokenizer.convert_tokens_to_ids(_a       )

																	# The mask has 1 for real tokens and 0 for padding tokens. Only real
																	# tokens are attended to.
																	_a	:    Optional[int]         =		[1 if mask_padding_with_zero else 0] * len(_a       )

																	# Zero-pad up to the sequence length.
																	_a	:    List[str]         =		max_seq_length - len(_a       )
																	if pad_on_left:
																						_a	:    Union[str, Any]         =		([pad_token] * padding_length) + input_ids
																						_a	:    Dict         =		([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
																						_a	:    int         =		([pad_token_segment_id] * padding_length) + segment_ids
																						_a	:    Optional[int]         =		([pad_token_label_id] * padding_length) + label_ids
																	else:
																						input_ids += [pad_token] * padding_length
																						input_mask += [0 if mask_padding_with_zero else 1] * padding_length
																						segment_ids += [pad_token_segment_id] * padding_length
																						label_ids += [pad_token_label_id] * padding_length

																	assert len(_a       ) == max_seq_length
																	assert len(_a       ) == max_seq_length
																	assert len(_a       ) == max_seq_length
																	assert len(_a       ) == max_seq_length

																	if ex_index < 5:
																						logger.info('''*** Example ***'''       )
																						logger.info('''guid: %s'''       ,							example.guid       )
																						logger.info('''tokens: %s'''       ,							''' '''.join([str(_a       ) for x in tokens]       )       )
																						logger.info('''input_ids: %s'''       ,							''' '''.join([str(_a       ) for x in input_ids]       )       )
																						logger.info('''input_mask: %s'''       ,							''' '''.join([str(_a       ) for x in input_mask]       )       )
																						logger.info('''segment_ids: %s'''       ,							''' '''.join([str(_a       ) for x in segment_ids]       )       )
																						logger.info('''label_ids: %s'''       ,							''' '''.join([str(_a       ) for x in label_ids]       )       )

																	if "token_type_ids" not in tokenizer.model_input_names:
																						_a	:    Dict         =		None

																	features.append(
																	    InputFeatures(
																	        input_ids=_a       ,							attention_mask=_a       ,							token_type_ids=_a       ,							label_ids=_a       )       )
												return features


if is_torch_available():
			import torch
			from torch import nn
			from torch.utils.data import Dataset

			class 				UpperCAmelCase_		(			__lowercase   ):
										"""simple docstring"""







										UpperCAmelCase__       :						List[InputFeatures]
										UpperCAmelCase__       :						int	    =    nn.CrossEntropyLoss().ignore_index


										def __init__(			self       ,							_a       ,							_a       ,							_a       ,							_a       ,							_a       ,							_a = None       ,							_a=False       ,							_a = Split.train       ,							)    ->    Tuple:
															# Load data features from cache or dataset file
															_a	:    List[Any]         =		os.path.join(
															    _a       ,							'''cached_{}_{}_{}'''.format(mode.value       ,							tokenizer.__class__.__name__       ,							str(_a       )       )       ,							)

															# 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 overwrite_cache:
																									logger.info(F"""Loading features from cached file {cached_features_file}"""       )
																									_a	:    Optional[Any]         =		torch.load(_a       )
																				else:
																									logger.info(F"""Creating features from dataset file at {data_dir}"""       )
																									_a	:    List[Any]         =		token_classification_task.read_examples_from_file(_a       ,							_a       )
																									# TODO clean up all this to leverage built-in features of tokenizers
																									_a	:    List[Any]         =		token_classification_task.convert_examples_to_features(
																									    _a       ,							_a       ,							_a       ,							_a       ,							cls_token_at_end=bool(model_type in ['''xlnet''']       )       ,							cls_token=tokenizer.cls_token       ,							cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0       ,							sep_token=tokenizer.sep_token       ,							sep_token_extra=_a       ,							pad_on_left=bool(tokenizer.padding_side == '''left'''       )       ,							pad_token=tokenizer.pad_token_id       ,							pad_token_segment_id=tokenizer.pad_token_type_id       ,							pad_token_label_id=self.pad_token_label_id       ,							)
																									logger.info(F"""Saving features into cached file {cached_features_file}"""       )
																									torch.save(self.features       ,							_a       )


										def __len__(			self       )    ->    Optional[int]:
															return len(self.features       )




										def __getitem__(			self       ,							_a       )    ->    InputFeatures:
															return self.features[i]


if is_tf_available():
			import tensorflow as tf

			class 				UpperCAmelCase_		:
										"""simple docstring"""







										UpperCAmelCase__       :						List[InputFeatures]
										UpperCAmelCase__       :						int	    =    -100


										def __init__(			self       ,							_a       ,							_a       ,							_a       ,							_a       ,							_a       ,							_a = None       ,							_a=False       ,							_a = Split.train       ,							)    ->    Dict:
															_a	:    str         =		token_classification_task.read_examples_from_file(_a       ,							_a       )
															# TODO clean up all this to leverage built-in features of tokenizers
															_a	:    Optional[int]         =		token_classification_task.convert_examples_to_features(
															    _a       ,							_a       ,							_a       ,							_a       ,							cls_token_at_end=bool(model_type in ['''xlnet''']       )       ,							cls_token=tokenizer.cls_token       ,							cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0       ,							sep_token=tokenizer.sep_token       ,							sep_token_extra=_a       ,							pad_on_left=bool(tokenizer.padding_side == '''left'''       )       ,							pad_token=tokenizer.pad_token_id       ,							pad_token_segment_id=tokenizer.pad_token_type_id       ,							pad_token_label_id=self.pad_token_label_id       ,							)

															def gen():
																				for ex in self.features:
																									if ex.token_type_ids is None:
																														yield (
																														    {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
																														    ex.label_ids,
																														)
																									else:
																														yield (
																														    {
																														        "input_ids": ex.input_ids,
																														        "attention_mask": ex.attention_mask,
																														        "token_type_ids": ex.token_type_ids,
																														    },
																														    ex.label_ids,
																														)

															if "token_type_ids" not in tokenizer.model_input_names:
																				_a	:    Union[str, Any]         =		tf.data.Dataset.from_generator(
																				    _a       ,							({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa)       ,							(
																				        {'''input_ids''': tf.TensorShape([None]       ), '''attention_mask''': tf.TensorShape([None]       )},
																				        tf.TensorShape([None]       ),
																				    )       ,							)
															else:
																				_a	:    Union[str, Any]         =		tf.data.Dataset.from_generator(
																				    _a       ,							({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa)       ,							(
																				        {
																				            '''input_ids''': tf.TensorShape([None]       ),
																				            '''attention_mask''': tf.TensorShape([None]       ),
																				            '''token_type_ids''': tf.TensorShape([None]       ),
																				        },
																				        tf.TensorShape([None]       ),
																				    )       ,							)


										def 				__lowercase				(			self       )    ->    str:
															_a	:    Dict         =		self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features       )       )       )

															return self.dataset


										def __len__(			self       )    ->    str:
															return len(self.features       )




										def __getitem__(			self       ,							_a       )    ->    InputFeatures:
															return self.features[i]






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

@dataclass
class 				UpperCAmelCase_		:
							"""simple docstring"""







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


							def 				__lowercase				(			self       )    ->    List[Any]:
												_a	:    List[Any]         =		self.task_name.lower()



class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						List[str]	    =    "train"
							UpperCAmelCase__       :						List[str]	    =    "dev"
							UpperCAmelCase__       :						Union[str, Any]	    =    "test"



class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						GlueDataTrainingArguments
							UpperCAmelCase__       :						str
							UpperCAmelCase__       :						List[InputFeatures]


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

												# Make sure only the first process in distributed training processes the dataset,
												# and the others will use the cache.
												_a	:    Optional[int]         =		cached_features_file + '''.lock'''
												with FileLock(_a       ):
																	if os.path.exists(_a       ) and not args.overwrite_cache:
																						_a	:    List[Any]         =		time.time()
																						_a	:    str         =		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	:    str         =		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	:    Union[str, Any]         =		glue_convert_examples_to_features(
																						    _a       ,							_a       ,							max_length=args.max_seq_length       ,							label_list=_a       ,							output_mode=self.output_mode       ,							)
																						_a	:    Optional[int]         =		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       )    ->    Optional[int]:
												return len(self.features       )


							def __getitem__(			self       ,							_a       )    ->    InputFeatures:
												return self.features[i]




							def 				__lowercase				(			self       )    ->    Tuple:
												return self.label_list



