


"""simple docstring"""






import json
import os
from functools import lru_cache
from typing import TYPE_CHECKING, List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
	from transformers.pipelines.conversational import Conversation

_lowerCamelCase     =  logging.get_logger(__name__)


_lowerCamelCase     =  {
    'vocab_file': 'vocab.json',
    'merges_file': 'merges.txt',
    'tokenizer_config_file': 'tokenizer_config.json',
}

_lowerCamelCase     =  {
    'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'},
    'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'},
    'tokenizer_config_file': {
        'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json'
    },
}

_lowerCamelCase     =  {'facebook/blenderbot-3B': 128}


@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def __lowercase     (      ):
				SCREAMING_SNAKE_CASE__     							=				(
				    list(range(ord("!"  )						,					ord("~"  ) + 1  )  ) + list(range(ord("¡"  )						,					ord("¬"  ) + 1  )  ) + list(range(ord("®"  )						,					ord("ÿ"  ) + 1  )  )
				)
				SCREAMING_SNAKE_CASE__     							=				bs[:]
				SCREAMING_SNAKE_CASE__     							=				0
				for b in range(2**8  ):
								if b not in bs:
												bs.append(lowerCamelCase_  )
												cs.append(2**8 + n  )
												n += 1
				SCREAMING_SNAKE_CASE__     							=				[chr(lowerCamelCase_  ) for n in cs]
				return dict(zip(lowerCamelCase_						,					lowerCamelCase_  )  )


def __lowercase     (      lowerCamelCase_  :      Union[str, Any]  ):
				SCREAMING_SNAKE_CASE__     							=				set()
				SCREAMING_SNAKE_CASE__     							=				word[0]
				for char in word[1:]:
								pairs.add((prev_char, char)  )
								SCREAMING_SNAKE_CASE__     							=				char
				return pairs


class 			lowerCamelCase_		(			lowercase   ):





				"""simple docstring"""







				_lowerCAmelCase      :      List[str]      							=					VOCAB_FILES_NAMES
				_lowerCAmelCase      :      List[str]      							=					PRETRAINED_VOCAB_FILES_MAP
				_lowerCAmelCase      :      Optional[Any]      							=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				_lowerCAmelCase      :      Optional[int]      							=					["input_ids", "attention_mask"]



				def __init__(						self       ,		UpperCAmelCase__       ,		UpperCAmelCase__       ,		UpperCAmelCase__="replace"       ,		UpperCAmelCase__="<s>"       ,		UpperCAmelCase__="</s>"       ,		UpperCAmelCase__="</s>"       ,		UpperCAmelCase__="<s>"       ,		UpperCAmelCase__="<unk>"       ,		UpperCAmelCase__="<pad>"       ,		UpperCAmelCase__="<mask>"       ,		UpperCAmelCase__=False       ,		**UpperCAmelCase__       ,		):
								SCREAMING_SNAKE_CASE__     							=				AddedToken(UpperCAmelCase__       ,		lstrip=UpperCAmelCase__       ,		rstrip=UpperCAmelCase__     ) if isinstance(UpperCAmelCase__       ,		UpperCAmelCase__     ) else bos_token
								SCREAMING_SNAKE_CASE__     							=				AddedToken(UpperCAmelCase__       ,		lstrip=UpperCAmelCase__       ,		rstrip=UpperCAmelCase__     ) if isinstance(UpperCAmelCase__       ,		UpperCAmelCase__     ) else eos_token
								SCREAMING_SNAKE_CASE__     							=				AddedToken(UpperCAmelCase__       ,		lstrip=UpperCAmelCase__       ,		rstrip=UpperCAmelCase__     ) if isinstance(UpperCAmelCase__       ,		UpperCAmelCase__     ) else sep_token
								SCREAMING_SNAKE_CASE__     							=				AddedToken(UpperCAmelCase__       ,		lstrip=UpperCAmelCase__       ,		rstrip=UpperCAmelCase__     ) if isinstance(UpperCAmelCase__       ,		UpperCAmelCase__     ) else cls_token
								SCREAMING_SNAKE_CASE__     							=				AddedToken(UpperCAmelCase__       ,		lstrip=UpperCAmelCase__       ,		rstrip=UpperCAmelCase__     ) if isinstance(UpperCAmelCase__       ,		UpperCAmelCase__     ) else unk_token
								SCREAMING_SNAKE_CASE__     							=				AddedToken(UpperCAmelCase__       ,		lstrip=UpperCAmelCase__       ,		rstrip=UpperCAmelCase__     ) if isinstance(UpperCAmelCase__       ,		UpperCAmelCase__     ) else pad_token

								# Mask token behave like a normal word, i.e. include the space before it
								SCREAMING_SNAKE_CASE__     							=				AddedToken(UpperCAmelCase__       ,		lstrip=UpperCAmelCase__       ,		rstrip=UpperCAmelCase__     ) if isinstance(UpperCAmelCase__       ,		UpperCAmelCase__     ) else mask_token

								super().__init__(
								    errors=UpperCAmelCase__       ,		bos_token=UpperCAmelCase__       ,		eos_token=UpperCAmelCase__       ,		unk_token=UpperCAmelCase__       ,		sep_token=UpperCAmelCase__       ,		cls_token=UpperCAmelCase__       ,		pad_token=UpperCAmelCase__       ,		mask_token=UpperCAmelCase__       ,		add_prefix_space=UpperCAmelCase__       ,		**UpperCAmelCase__       ,		)

								with open(UpperCAmelCase__       ,		encoding="utf-8"     ) as vocab_handle:
												SCREAMING_SNAKE_CASE__     							=				json.load(UpperCAmelCase__     )
								SCREAMING_SNAKE_CASE__     							=				{v: k for k, v in self.encoder.items()}
								SCREAMING_SNAKE_CASE__     							=				errors  # how to handle errors in decoding
								SCREAMING_SNAKE_CASE__     							=				bytes_to_unicode()
								SCREAMING_SNAKE_CASE__     							=				{v: k for k, v in self.byte_encoder.items()}
								with open(UpperCAmelCase__       ,		encoding="utf-8"     ) as merges_handle:
												SCREAMING_SNAKE_CASE__     							=				merges_handle.read().split("\n"     )[1:-1]
								SCREAMING_SNAKE_CASE__     							=				[tuple(merge.split()     ) for merge in bpe_merges]
								SCREAMING_SNAKE_CASE__     							=				dict(zip(UpperCAmelCase__       ,		range(len(UpperCAmelCase__     )     )     )     )
								SCREAMING_SNAKE_CASE__     							=				{}
								SCREAMING_SNAKE_CASE__     							=				add_prefix_space

								# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
								SCREAMING_SNAKE_CASE__     							=				re.compile(R"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"     )



				@property
				# Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot
				def   lowerCAmelCase__		(						self     ):
								return len(self.encoder     )



				def   lowerCAmelCase__		(						self     ):
								return dict(self.encoder       ,		**self.added_tokens_encoder     )



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__     ):
								if token in self.cache:
												return self.cache[token]
								SCREAMING_SNAKE_CASE__     							=				tuple(UpperCAmelCase__     )
								SCREAMING_SNAKE_CASE__     							=				get_pairs(UpperCAmelCase__     )

								if not pairs:
												return token

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

																if word[i] == first and i < len(UpperCAmelCase__     ) - 1 and word[i + 1] == second:
																				new_word.append(first + second     )
																				i += 2
																else:
																				new_word.append(word[i]     )
																				i += 1
												SCREAMING_SNAKE_CASE__     							=				tuple(UpperCAmelCase__     )
												SCREAMING_SNAKE_CASE__     							=				new_word
												if len(UpperCAmelCase__     ) == 1:
																break
												else:
																SCREAMING_SNAKE_CASE__     							=				get_pairs(UpperCAmelCase__     )
								SCREAMING_SNAKE_CASE__     							=				" ".join(UpperCAmelCase__     )
								SCREAMING_SNAKE_CASE__     							=				word
								return word



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__     ):
								SCREAMING_SNAKE_CASE__     							=				[]
								for token in re.findall(self.pat       ,		UpperCAmelCase__     ):
												SCREAMING_SNAKE_CASE__     							=				"".join(
												    self.byte_encoder[b] for b in token.encode("utf-8"     )     )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
												bpe_tokens.extend(bpe_token for bpe_token in self.bpe(UpperCAmelCase__     ).split(" "     )     )
								return bpe_tokens



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__     ):
								return self.encoder.get(UpperCAmelCase__       ,		self.encoder.get(self.unk_token     )     )



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__     ):
								return self.decoder.get(UpperCAmelCase__     )



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__     ):
								SCREAMING_SNAKE_CASE__     							=				"".join(UpperCAmelCase__     )
								SCREAMING_SNAKE_CASE__     							=				bytearray([self.byte_decoder[c] for c in text]     ).decode("utf-8"       ,		errors=self.errors     )
								return text



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__       ,		UpperCAmelCase__ = None     ):
								if not os.path.isdir(UpperCAmelCase__     ):
												logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''     )
												return
								SCREAMING_SNAKE_CASE__     							=				os.path.join(
								    UpperCAmelCase__       ,		(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]     )
								SCREAMING_SNAKE_CASE__     							=				os.path.join(
								    UpperCAmelCase__       ,		(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]     )

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

								SCREAMING_SNAKE_CASE__     							=				0
								with open(UpperCAmelCase__       ,		"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 UpperCAmelCase__     : 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!"     )
																				SCREAMING_SNAKE_CASE__     							=				token_index
																writer.write(" ".join(UpperCAmelCase__     ) + "\n"     )
																index += 1

								return vocab_file, merge_file



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__       ,		UpperCAmelCase__ = None       ,		UpperCAmelCase__ = False     ):
								if already_has_special_tokens:
												return super().get_special_tokens_mask(
												    token_ids_a=UpperCAmelCase__       ,		token_ids_a=UpperCAmelCase__       ,		already_has_special_tokens=UpperCAmelCase__     )

								if token_ids_a is None:
												return [1] + ([0] * len(UpperCAmelCase__     )) + [1]
								return [1] + ([0] * len(UpperCAmelCase__     )) + [1, 1] + ([0] * len(UpperCAmelCase__     )) + [1]



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__       ,		UpperCAmelCase__ = None     ):
								SCREAMING_SNAKE_CASE__     							=				[self.sep_token_id]
								SCREAMING_SNAKE_CASE__     							=				[self.cls_token_id]

								if token_ids_a is None:
												return len(cls + token_ids_a + sep     ) * [0]
								return len(cls + token_ids_a + sep + sep + token_ids_a + sep     ) * [0]



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__       ,		UpperCAmelCase__=False       ,		**UpperCAmelCase__     ):
								SCREAMING_SNAKE_CASE__     							=				kwargs.pop("add_prefix_space"       ,		self.add_prefix_space     )
								if (is_split_into_words or add_prefix_space) and (len(UpperCAmelCase__     ) > 0 and not text[0].isspace()):
												SCREAMING_SNAKE_CASE__     							=				" " + text
								return (text, kwargs)



				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__       ,		UpperCAmelCase__ = None     ):
								return token_ids_a + [self.eos_token_id]






				def   lowerCAmelCase__		(						self       ,		UpperCAmelCase__     ):
								SCREAMING_SNAKE_CASE__     							=				[]
								for is_user, text in conversation.iter_texts():
												if is_user:
																# We need to space prefix as it's being done within blenderbot
																inputs.append(" " + text     )
												else:
																# Generated responses should contain them already.
																inputs.append(UpperCAmelCase__     )

								SCREAMING_SNAKE_CASE__     							=				"  ".join(UpperCAmelCase__     )
								SCREAMING_SNAKE_CASE__     							=				self.encode(UpperCAmelCase__     )
								if len(UpperCAmelCase__     ) > self.model_max_length:
												SCREAMING_SNAKE_CASE__     							=				input_ids[-self.model_max_length :]
												logger.warning(f'''Trimmed input from conversation as it was longer than {self.model_max_length} tokens.'''     )
								return input_ids




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


_lowerCamelCase     =  logging.get_logger(__name__)


@dataclass
class 			lowerCamelCase_		:





				"""simple docstring"""







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



				def   lowerCAmelCase__		(						self     ):
								SCREAMING_SNAKE_CASE__     							=				self.task_name.lower()


class 			lowerCamelCase_		(			lowercase   ):





				"""simple docstring"""







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


class 			lowerCamelCase_		(			lowercase   ):





				"""simple docstring"""







				_lowerCAmelCase      :      GlueDataTrainingArguments
				_lowerCAmelCase      :      str
				_lowerCAmelCase      :      List[InputFeatures]



				def __init__(						self       ,		UpperCAmelCase__       ,		UpperCAmelCase__       ,		UpperCAmelCase__ = None       ,		UpperCAmelCase__ = Split.train       ,		UpperCAmelCase__ = None       ,		):
								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"       ,		UpperCAmelCase__       ,		)
								SCREAMING_SNAKE_CASE__     							=				args
								SCREAMING_SNAKE_CASE__     							=				glue_processors[args.task_name]()
								SCREAMING_SNAKE_CASE__     							=				glue_output_modes[args.task_name]
								if isinstance(UpperCAmelCase__       ,		UpperCAmelCase__     ):
												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(UpperCAmelCase__     ):
												if os.path.exists(UpperCAmelCase__     ) and not args.overwrite_cache:
																SCREAMING_SNAKE_CASE__     							=				time.time()
																SCREAMING_SNAKE_CASE__     							=				torch.load(UpperCAmelCase__     )
																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(
																    UpperCAmelCase__       ,		UpperCAmelCase__       ,		max_length=args.max_seq_length       ,		label_list=UpperCAmelCase__       ,		output_mode=self.output_mode       ,		)
																SCREAMING_SNAKE_CASE__     							=				time.time()
																torch.save(self.features       ,		UpperCAmelCase__     )
																# ^ 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     ):
								return len(self.features     )



				def __getitem__(						self       ,		UpperCAmelCase__     ):
								return self.features[i]






				def   lowerCAmelCase__		(						self     ):
								return self.label_list
