





'''simple docstring'''





import json
import os
from typing import Optional, Tuple

import regex as re

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_a						=   logging.get_logger(__name__)

_a						=   {
    "vocab_file": "vocab.json",
    "merges_file": "merges.txt",
}

_a						=   {
    "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"},
    "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"},
}

_a						=   {
    "ctrl": 256,
}

_a						=   {
    "Pregnancy": 168_629,
    "Christianity": 7_675,
    "Explain": 106_423,
    "Fitness": 63_440,
    "Saving": 63_163,
    "Ask": 27_171,
    "Ass": 95_985,
    "Joke": 163_509,
    "Questions": 45_622,
    "Thoughts": 49_605,
    "Retail": 52_342,
    "Feminism": 164_338,
    "Writing": 11_992,
    "Atheism": 192_263,
    "Netflix": 48_616,
    "Computing": 39_639,
    "Opinion": 43_213,
    "Alone": 44_967,
    "Funny": 58_917,
    "Gaming": 40_358,
    "Human": 4_088,
    "India": 1_331,
    "Joker": 77_138,
    "Diet": 36_206,
    "Legal": 11_859,
    "Norman": 4_939,
    "Tip": 72_689,
    "Weight": 52_343,
    "Movies": 46_273,
    "Running": 23_425,
    "Science": 2_090,
    "Horror": 37_793,
    "Confession": 60_572,
    "Finance": 12_250,
    "Politics": 16_360,
    "Scary": 191_985,
    "Support": 12_654,
    "Technologies": 32_516,
    "Teenage": 66_160,
    "Event": 32_769,
    "Learned": 67_460,
    "Notion": 182_770,
    "Wikipedia": 37_583,
    "Books": 6_665,
    "Extract": 76_050,
    "Confessions": 102_701,
    "Conspiracy": 75_932,
    "Links": 63_674,
    "Narcissus": 150_425,
    "Relationship": 54_766,
    "Relationships": 134_796,
    "Reviews": 41_671,
    "News": 4_256,
    "Translation": 26_820,
    "multilingual": 128_406,
}





def lowerCAmelCase__(__snake_case							)       ->   Any:







	'''simple docstring'''







	lowerCamelCase__              =	set()
	lowerCamelCase__              =	word[0]
	for char in word[1:]:
		pairs.add((prev_char, char)							)
		lowerCamelCase__              =	char

	lowerCamelCase__              =	set(__snake_case							)
	return pairs






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		VOCAB_FILES_NAMES
			lowerCAmelCase_							  =		PRETRAINED_VOCAB_FILES_MAP
			lowerCAmelCase_							  =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			lowerCAmelCase_							  =		CONTROL_CODES





			def __init__(					self ,						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase="<unk>" ,						**__lowerCAmelCase							):



				'''simple docstring'''







				super().__init__(unk_token=__lowerCAmelCase ,						**__lowerCAmelCase							)

				with open(__lowerCAmelCase ,						encoding='''utf-8'''							) as vocab_handle:
					lowerCamelCase__              =	json.load(__lowerCAmelCase							)
				lowerCamelCase__              =	{v: k for k, v in self.encoder.items()}
				with open(__lowerCAmelCase ,						encoding='''utf-8'''							) as merges_handle:
					lowerCamelCase__              =	merges_handle.read().split('''\n'''							)[1:-1]
				lowerCamelCase__              =	[tuple(merge.split()							) for merge in merges]
				lowerCamelCase__              =	dict(zip(__lowerCAmelCase ,						range(len(__lowerCAmelCase							)							)							)							)
				lowerCamelCase__              =	{}





			@property
			def 	__lowerCamelCase       (					self							):



				'''simple docstring'''







				return len(self.encoder							)





			def 	__lowerCamelCase       (					self							):



				'''simple docstring'''







				return dict(self.encoder ,						**self.added_tokens_encoder							)





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				if token in self.cache:
					return self.cache[token]
				lowerCamelCase__              =	tuple(__lowerCAmelCase							)
				lowerCamelCase__              =	tuple(list(word[:-1]							) + [word[-1] + '''</w>''']							)
				lowerCamelCase__              =	get_pairs(__lowerCAmelCase							)

				if not pairs:
					return token

				while True:
					lowerCamelCase__              =	min(__lowerCAmelCase ,						key=lambda __lowerCAmelCase							: self.bpe_ranks.get(__lowerCAmelCase ,						float('''inf'''							)							)							)
					if bigram not in self.bpe_ranks:
						break
					lowerCamelCase__       ,			lowerCamelCase__              =	bigram
					lowerCamelCase__              =	[]
					lowerCamelCase__              =	0
					while i < len(__lowerCAmelCase							):
						try:
							lowerCamelCase__              =	word.index(__lowerCAmelCase ,						__lowerCAmelCase							)
						except ValueError:
							new_word.extend(word[i:]							)
							break
						else:
							new_word.extend(word[i:j]							)
							lowerCamelCase__              =	j

						if word[i] == first and i < len(__lowerCAmelCase							) - 1 and word[i + 1] == second:
							new_word.append(first + second							)
							i += 2
						else:
							new_word.append(word[i]							)
							i += 1
					lowerCamelCase__              =	tuple(__lowerCAmelCase							)
					lowerCamelCase__              =	new_word
					if len(__lowerCAmelCase							) == 1:
						break
					else:
						lowerCamelCase__              =	get_pairs(__lowerCAmelCase							)
				lowerCamelCase__              =	'''@@ '''.join(__lowerCAmelCase							)
				lowerCamelCase__              =	word[:-4]
				lowerCamelCase__              =	word
				return word





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	[]

				lowerCamelCase__              =	re.findall(r'''\S+\n?''' ,						__lowerCAmelCase							)

				for token in words:
					split_tokens.extend(list(self.bpe(__lowerCAmelCase							).split(''' '''							)							)							)
				return split_tokens





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				return self.encoder.get(__lowerCAmelCase ,						self.encoder.get(self.unk_token							)							)





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				return self.decoder.get(__lowerCAmelCase ,						self.unk_token							)





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	''' '''.join(__lowerCAmelCase							).replace('''@@ ''' ,						''''''							).strip()
				return out_string





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase ,						__lowerCAmelCase = None							):



				'''simple docstring'''







				if not os.path.isdir(__lowerCAmelCase							):
					logger.error(F'Vocabulary path ({save_directory}) should be a directory'							)
					return
				lowerCamelCase__              =	os.path.join(
				    __lowerCAmelCase ,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']							)
				lowerCamelCase__              =	os.path.join(
				    __lowerCAmelCase ,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']							)

				with open(__lowerCAmelCase ,						'''w''' ,						encoding='''utf-8'''							) as f:
					f.write(json.dumps(self.encoder ,						indent=2 ,						sort_keys=__lowerCAmelCase ,						ensure_ascii=__lowerCAmelCase							) + '''\n'''							)

				lowerCamelCase__              =	0
				with open(__lowerCAmelCase ,						'''w''' ,						encoding='''utf-8'''							) as writer:
					writer.write('''#version: 0.2\n'''							)
					for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,						key=lambda __lowerCAmelCase							: kv[1]							):
						if index != token_index:
							logger.warning(
							    F'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
							    ''' Please check that the tokenizer is not corrupted!'''							)
							lowerCamelCase__              =	token_index
						writer.write(''' '''.join(__lowerCAmelCase							) + '''\n'''							)
						index += 1

				return vocab_file, merge_file

			# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
			#     filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
			#     tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
			#     tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
			#     return ''.join(tokens_generated_so_far)










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       __A					:

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





			def 	__lowerCamelCase       (					self							):



				'''simple docstring'''







				lowerCamelCase__              =	self.task_name.lower()






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		"""train"""
			lowerCAmelCase_							  =		"""dev"""
			lowerCAmelCase_							  =		"""test"""






class       __A					(					lowerCAmelCase				):

			'''simple docstring'''







			lowerCAmelCase_							  =		42
			lowerCAmelCase_							  =		42
			lowerCAmelCase_							  =		42





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

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



				'''simple docstring'''







				return len(self.features							)





			def __getitem__(					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				return self.features[i]





			def 	__lowerCamelCase       (					self							):



				'''simple docstring'''







				return self.label_list



