






import json
import os
from typing import Dict, List, Optional, Tuple

import regex as re

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


lowercase			  =    logging.get_logger(__name__)


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

lowercase			  =    {
    '''vocab_file''': {
        '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json'''
    },
    '''merges_file''': {
        '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt'''
    },
    '''tokenizer_config_file''': {
        '''facebook/blenderbot_small-90M''': (
            '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json'''
        )
    },
}

lowercase			  =    {'''facebook/blenderbot_small-90M''': 5_12}

def      lowerCAmelCase__	(    _a       :			Tuple    ):
		snake_case_				:							Optional[int]						 =       set()
		snake_case_				:							Any						 =       word[0]
		for char in word[1:]:
				pairs.add((prev_char, char)    )
				snake_case_				:							Union[str, Any]						 =       char

		snake_case_				:							Optional[int]						 =       set(a_    )
		return pairs




class 		UpperCAmelCase_						(	_UpperCamelCase					):


						'''simple docstring'''




						A     :   int						=					VOCAB_FILES_NAMES
						A     :   List[Any]						=					PRETRAINED_VOCAB_FILES_MAP
						A     :   Optional[int]						=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						A     :   Dict						=					['input_ids', 'attention_mask']






						def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE="__start__"		,				_SCREAMING_SNAKE_CASE="__end__"		,				_SCREAMING_SNAKE_CASE="__unk__"		,				_SCREAMING_SNAKE_CASE="__null__"		,				**_SCREAMING_SNAKE_CASE		,				) ->				Dict:
								super().__init__(unk_token=_UpperCAmelCase		,				bos_token=_UpperCAmelCase		,				eos_token=_UpperCAmelCase		,				pad_token=_UpperCAmelCase		,				**_UpperCAmelCase				)

								with open(_UpperCAmelCase		,				encoding="utf-8"				) as vocab_handle:
										snake_case_				:							Any						 =       json.load(_UpperCAmelCase				)
								snake_case_				:							Tuple						 =       {v: k for k, v in self.encoder.items()}
								with open(_UpperCAmelCase		,				encoding="utf-8"				) as merges_handle:
										snake_case_				:							Tuple						 =       merges_handle.read().split("\n"				)[1:-1]
								snake_case_				:							Optional[int]						 =       [tuple(merge.split()				) for merge in merges]
								snake_case_				:							List[str]						 =       dict(zip(_UpperCAmelCase		,				range(len(_UpperCAmelCase				)				)				)				)
								snake_case_				:							Union[str, Any]						 =       {}






						@property
						def       _lowerCAmelCase       (	self				) ->				List[Any]:
								return len(self.encoder				)






						def       _lowerCAmelCase       (	self				) ->				Tuple:
								return dict(self.encoder		,				**self.added_tokens_encoder				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[str]:
								if token in self.cache:
										return self.cache[token]
								snake_case_				:							Optional[int]						 =       re.sub("([.,!?()])"		,				r" \1"		,				_UpperCAmelCase				)
								snake_case_				:							List[Any]						 =       re.sub("(\')"		,				r" \1 "		,				_UpperCAmelCase				)
								snake_case_				:							Dict						 =       re.sub(r"\s{2,}"		,				" "		,				_UpperCAmelCase				)
								if "\n" in token:
										snake_case_				:							Union[str, Any]						 =       token.replace("\n"		,				" __newln__"				)

								snake_case_				:							List[Any]						 =       token.split(" "				)
								snake_case_				:							Tuple						 =       []
								for token in tokens:
										if not len(_UpperCAmelCase				):
												continue

										snake_case_				:							List[Any]						 =       token.lower()
										snake_case_				:							Union[str, Any]						 =       tuple(_UpperCAmelCase				)
										snake_case_				:							int						 =       tuple(list(word[:-1]				) + [word[-1] + "</w>"]				)
										snake_case_				:							List[Any]						 =       get_pairs(_UpperCAmelCase				)

										if not pairs:
												words.append(_UpperCAmelCase				)
												continue

										while True:
												snake_case_				:							Dict						 =       min(_UpperCAmelCase		,				key=lambda _SCREAMING_SNAKE_CASE				: self.bpe_ranks.get(_UpperCAmelCase		,				float("inf"				)				)				)
												if bigram not in self.bpe_ranks:
														break
												snake_case_				:							Dict						 =       bigram
												snake_case_				:							str						 =       []
												snake_case_				:							Optional[Any]						 =       0

												while i < len(_UpperCAmelCase				):
														try:
																snake_case_				:							Any						 =       word.index(_UpperCAmelCase		,				_UpperCAmelCase				)
																new_word.extend(word[i:j]				)
																snake_case_				:							Tuple						 =       j
														except ValueError:
																new_word.extend(word[i:]				)
																break

														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
												snake_case_				:							Union[str, Any]						 =       tuple(_UpperCAmelCase				)
												snake_case_				:							Tuple						 =       new_word
												if len(_UpperCAmelCase				) == 1:
														break
												else:
														snake_case_				:							Dict						 =       get_pairs(_UpperCAmelCase				)
										snake_case_				:							Union[str, Any]						 =       '''@@ '''.join(_UpperCAmelCase				)
										snake_case_				:							List[str]						 =       word[:-4]

										snake_case_				:							int						 =       word
										words.append(_UpperCAmelCase				)
								return " ".join(_UpperCAmelCase				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				Union[str, Any]:
								snake_case_				:							List[Any]						 =       []

								snake_case_				:							str						 =       re.findall(r"\S+\n?"		,				_UpperCAmelCase				)

								for token in words:
										split_tokens.extend(list(self.bpe(_UpperCAmelCase				).split(" "				)				)				)
								return split_tokens






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				int:
								snake_case_				:							Dict						 =       token.lower()
								return self.encoder.get(_UpperCAmelCase		,				self.encoder.get(self.unk_token				)				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				str:
								return self.decoder.get(_UpperCAmelCase		,				self.unk_token				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				Tuple:
								snake_case_				:							List[Any]						 =       ''' '''.join(_UpperCAmelCase				).replace("@@ "		,				""				).strip()
								return out_string






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = None				) ->				Optional[int]:
								if not os.path.isdir(_UpperCAmelCase				):
										logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''				)
										return
								snake_case_				:							int						 =       os.path.join(
								    _UpperCAmelCase		,				(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]				)
								snake_case_				:							Optional[Any]						 =       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"				)

								snake_case_				:							int						 =       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 _SCREAMING_SNAKE_CASE				: 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!"				)
														snake_case_				:							Tuple						 =       token_index
												writer.write(" ".join(_UpperCAmelCase				) + "\n"				)
												index += 1

								return vocab_file, merge_file








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

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


lowercase  :							Optional[Any]			  =    logging.getLogger(__name__)




@dataclass(frozen=SCREAMING_SNAKE_CASE__					)
class 		UpperCAmelCase_						:


						'''simple docstring'''




						A     :   str
						A     :   str
						A     :   Optional[str]						=					None
						A     :   Optional[str]						=					None
						A     :   Optional[str]						=					None




@dataclass(frozen=SCREAMING_SNAKE_CASE__					)
class 		UpperCAmelCase_						:


						'''simple docstring'''




						A     :   List[int]
						A     :   Optional[List[int]]						=					None
						A     :   Optional[List[int]]						=					None
						A     :   Optional[Union[int, float]]						=					None
						A     :   Optional[int]						=					None


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




							class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


													'''simple docstring'''




													A     :   List[InputFeatures]






													def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE=False		,				_SCREAMING_SNAKE_CASE = False		,				) ->				Union[str, Any]:
															snake_case_				:							str						 =       hans_processors[task]()

															snake_case_				:							Tuple						 =       os.path.join(
															    _SCREAMING_SNAKE_CASE		,				"cached_{}_{}_{}_{}".format(
															        "dev" if evaluate else "train"		,				tokenizer.__class__.__name__		,				str(_SCREAMING_SNAKE_CASE				)		,				_SCREAMING_SNAKE_CASE		,				)		,				)
															snake_case_				:							Dict						 =       processor.get_labels()
															if tokenizer.__class__ in (
															    RobertaTokenizer,
															    RobertaTokenizerFast,
															    XLMRobertaTokenizer,
															    BartTokenizer,
															    BartTokenizerFast,
															):
																	# HACK(label indices are swapped in RoBERTa pretrained model)
																	snake_case_ ,       snake_case_				:							Any						 =       label_list[2], label_list[1]
															snake_case_				:							Tuple						 =       label_list

															# Make sure only the first process in distributed training processes the dataset,
															# and the others will use the cache.
															snake_case_				:							Dict						 =       cached_features_file + ".lock"
															with FileLock(_SCREAMING_SNAKE_CASE				):
																	if os.path.exists(_SCREAMING_SNAKE_CASE				) and not overwrite_cache:
																			logger.info(f'''Loading features from cached file {cached_features_file}'''				)
																			snake_case_				:							Dict						 =       torch.load(_SCREAMING_SNAKE_CASE				)
																	else:
																			logger.info(f'''Creating features from dataset file at {data_dir}'''				)

																			snake_case_				:							Any						 =       (
																			    processor.get_dev_examples(_SCREAMING_SNAKE_CASE				) if evaluate else processor.get_train_examples(_SCREAMING_SNAKE_CASE				)
																			)

																			logger.info("Training examples: %s"		,				len(_SCREAMING_SNAKE_CASE				)				)
																			snake_case_				:							Union[str, Any]						 =       hans_convert_examples_to_features(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)
																			logger.info("Saving features into cached file %s"		,				_SCREAMING_SNAKE_CASE				)
																			torch.save(self.features		,				_SCREAMING_SNAKE_CASE				)






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






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






													def       _lowerCAmelCase       (	self				) ->				Dict:
															return self.label_list


if is_tf_available():
							import tensorflow as tf




							class 		UpperCAmelCase_						:


													'''simple docstring'''




													A     :   List[InputFeatures]






													def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = 128		,				_SCREAMING_SNAKE_CASE=False		,				_SCREAMING_SNAKE_CASE = False		,				) ->				Optional[int]:
															snake_case_				:							Tuple						 =       hans_processors[task]()
															snake_case_				:							Dict						 =       processor.get_labels()
															if tokenizer.__class__ in (
															    RobertaTokenizer,
															    RobertaTokenizerFast,
															    XLMRobertaTokenizer,
															    BartTokenizer,
															    BartTokenizerFast,
															):
																	# HACK(label indices are swapped in RoBERTa pretrained model)
																	snake_case_ ,       snake_case_				:							List[str]						 =       label_list[2], label_list[1]
															snake_case_				:							Dict						 =       label_list

															snake_case_				:							int						 =       processor.get_dev_examples(_SCREAMING_SNAKE_CASE				) if evaluate else processor.get_train_examples(_SCREAMING_SNAKE_CASE				)
															snake_case_				:							str						 =       hans_convert_examples_to_features(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)

															def gen():
																	for ex_index, ex in tqdm.tqdm(enumerate(self.features				)		,				desc="convert examples to features"				):
																			if ex_index % 1_0000 == 0:
																					logger.info("Writing example %d of %d" % (ex_index, len(_SCREAMING_SNAKE_CASE				))				)

																			yield (
																			    {
																			        "example_id": 0,
																			        "input_ids": ex.input_ids,
																			        "attention_mask": ex.attention_mask,
																			        "token_type_ids": ex.token_type_ids,
																			    },
																			    ex.label,
																			)

															snake_case_				:							List[Any]						 =       tf.data.Dataset.from_generator(
															    _SCREAMING_SNAKE_CASE		,				(
															        {
															            "example_id": tf.intaa,
															            "input_ids": tf.intaa,
															            "attention_mask": tf.intaa,
															            "token_type_ids": tf.intaa,
															        },
															        tf.intaa,
															    )		,				(
															        {
															            "example_id": tf.TensorShape([]				),
															            "input_ids": tf.TensorShape([None, None]				),
															            "attention_mask": tf.TensorShape([None, None]				),
															            "token_type_ids": tf.TensorShape([None, None]				),
															        },
															        tf.TensorShape([]				),
															    )		,				)






													def       _lowerCAmelCase       (	self				) ->				int:
															return self.dataset






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






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






													def       _lowerCAmelCase       (	self				) ->				Dict:
															return self.label_list




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				int:
								return self._create_examples(self._read_tsv(os.path.join(_SCREAMING_SNAKE_CASE		,				"heuristics_train_set.txt"				)				)		,				"train"				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[Any]:
								return self._create_examples(self._read_tsv(os.path.join(_SCREAMING_SNAKE_CASE		,				"heuristics_evaluation_set.txt"				)				)		,				"dev"				)






						def       _lowerCAmelCase       (	self				) ->				Dict:
								return ["contradiction", "entailment", "neutral"]






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								snake_case_				:							Optional[Any]						 =       []
								for i, line in enumerate(_SCREAMING_SNAKE_CASE				):
										if i == 0:
												continue
										snake_case_				:							List[Any]						 =       "%s-%s" % (set_type, line[0])
										snake_case_				:							int						 =       line[5]
										snake_case_				:							str						 =       line[6]
										snake_case_				:							Any						 =       line[7][2:] if line[7].startswith("ex"				) else line[7]
										snake_case_				:							Dict						 =       line[0]
										examples.append(InputExample(guid=_SCREAMING_SNAKE_CASE		,				text_a=_SCREAMING_SNAKE_CASE		,				text_b=_SCREAMING_SNAKE_CASE		,				label=_SCREAMING_SNAKE_CASE		,				pairID=_SCREAMING_SNAKE_CASE				)				)
								return examples




def      lowerCAmelCase__	(    _a       :			List[InputExample]  ,      _a       :			List[str]  ,      _a       :			int  ,      _a       :			PreTrainedTokenizer  ,      ):
		snake_case_				:							Optional[Any]						 =       {label: i for i, label in enumerate(_a    )}

		snake_case_				:							Optional[Any]						 =       []
		for ex_index, example in tqdm.tqdm(enumerate(_a    )  ,      desc="convert examples to features"    ):
				if ex_index % 1_00_00 == 0:
						logger.info("Writing example %d" % (ex_index)    )

				snake_case_				:							Optional[Any]						 =       tokenizer(
				    example.text_a  ,      example.text_b  ,      add_special_tokens=_a  ,      max_length=_a  ,      padding="max_length"  ,      truncation=_a  ,      return_overflowing_tokens=_a  ,      )

				snake_case_				:							Dict						 =       label_map[example.label] if example.label in label_map else 0

				snake_case_				:							Optional[Any]						 =       int(example.pairID    )

				features.append(InputFeatures(**_a  ,      label=_a  ,      pairID=_a    )    )

		for i, example in enumerate(examples[:5]    ):
				logger.info("*** Example ***"    )
				logger.info(F'''guid: {example}'''    )
				logger.info(F'''features: {features[i]}'''    )

		return features


lowercase  :							List[str]			  =    {
    '''hans''': 3,
}

lowercase  :							int			  =    {
    '''hans''': HansProcessor,
}
