






'''simple docstring'''



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,
)


__A		=logging.getLogger(__name__)


@dataclass(frozen=a__		)
class 						_snake_case   :
					lowerCAmelCase :str
					lowerCAmelCase :str
					lowerCAmelCase :Optional[str]						=   None
					lowerCAmelCase :Optional[str]						=   None
					lowerCAmelCase :Optional[str]						=   None


@dataclass(frozen=a__		)
class 						_snake_case   :
					lowerCAmelCase :List[int]
					lowerCAmelCase :Optional[List[int]]						=   None
					lowerCAmelCase :Optional[List[int]]						=   None
					lowerCAmelCase :Optional[Union[int, float]]						=   None
					lowerCAmelCase :Optional[int]						=   None


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


		class 						_snake_case   (       a__		):
							lowerCAmelCase :List[InputFeatures]




							def __init__( self							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase = None							,							_lowerCamelCase=False							,							_lowerCamelCase = False							,							):
										UpperCAmelCase__					:   Optional[Any]       				=       hans_processors[task]()

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

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

																UpperCAmelCase__					:   Dict       				=       (
																    processor.get_dev_examples(_lowerCamelCase) if evaluate else processor.get_train_examples(_lowerCamelCase)
																)

																logger.info("""Training examples: %s"""							,							len(_lowerCamelCase))
																UpperCAmelCase__					:   Dict       				=       hans_convert_examples_to_features(_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase)
																logger.info("""Saving features into cached file %s"""							,							_lowerCamelCase)
																torch.save(self.features							,							_lowerCamelCase)




							def __len__( self):
										return len(self.features)




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




							def 			snake_case__  ( self):
										return self.label_list


if is_tf_available():
		import tensorflow as tf


		class 						_snake_case   :
							lowerCAmelCase :List[InputFeatures]




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

										UpperCAmelCase__					:   List[Any]       				=       processor.get_dev_examples(_lowerCamelCase) if evaluate else processor.get_train_examples(_lowerCamelCase)
										UpperCAmelCase__					:   Any       				=       hans_convert_examples_to_features(_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase)

										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(_lowerCamelCase)))

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

										UpperCAmelCase__					:   List[Any]       				=       tf.data.Dataset.from_generator(
										    _lowerCamelCase							,							(
										        {
										            """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 			snake_case__  ( self):
										return self.dataset




							def __len__( self):
										return len(self.features)




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




							def 			snake_case__  ( self):
										return self.label_list


class 						_snake_case   (       a__		):




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self._create_examples(self._read_tsv(os.path.join(_lowerCamelCase							,							"""heuristics_train_set.txt"""))							,							"""train""")




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self._create_examples(self._read_tsv(os.path.join(_lowerCamelCase							,							"""heuristics_evaluation_set.txt"""))							,							"""dev""")




					def 			snake_case__  ( self):
								return ["contradiction", "entailment", "neutral"]




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







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__	, UpperCamelCase__	, UpperCamelCase__	, ):
			UpperCAmelCase__					:   Tuple       				=       {label: i for i, label in enumerate(UpperCamelCase__   )}

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

						UpperCAmelCase__					:   List[Any]       				=       tokenizer(
						    example.text_a	, example.text_b	, add_special_tokens=UpperCamelCase__	, max_length=UpperCamelCase__	, padding="""max_length"""	, truncation=UpperCamelCase__	, return_overflowing_tokens=UpperCamelCase__	, )

						UpperCAmelCase__					:   Optional[Any]       				=       label_map[example.label] if example.label in label_map else 0

						UpperCAmelCase__					:   List[Any]       				=       int(example.pairID   )

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

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

			return features


__A		={
    'hans': 3,
}


__A		={
    'hans': HansProcessor,
}



'''simple docstring'''



import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


__A		=logging.get_logger(__name__)

__A		='▁'

__A		={'vocab_file': 'sentencepiece.bpe.model'}

__A		={
    'vocab_file': {
        'facebook/mbart-large-50-one-to-many-mmt': (
            'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model'
        ),
    }
}

__A		={
    'facebook/mbart-large-50-one-to-many-mmt': 10_24,
}

# fmt: off
__A		=['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN', 'af_ZA', 'az_AZ', 'bn_IN', 'fa_IR', 'he_IL', 'hr_HR', 'id_ID', 'ka_GE', 'km_KH', 'mk_MK', 'ml_IN', 'mn_MN', 'mr_IN', 'pl_PL', 'ps_AF', 'pt_XX', 'sv_SE', 'sw_KE', 'ta_IN', 'te_IN', 'th_TH', 'tl_XX', 'uk_UA', 'ur_PK', 'xh_ZA', 'gl_ES', 'sl_SI']


class 						_snake_case   (       a__		):
					lowerCAmelCase :int						=   VOCAB_FILES_NAMES
					lowerCAmelCase :Dict						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowerCAmelCase :str						=   PRETRAINED_VOCAB_FILES_MAP
					lowerCAmelCase :List[str]						=   ['''input_ids''', '''attention_mask''']

					lowerCAmelCase :List[int]						=   []
					lowerCAmelCase :List[int]						=   []




					def __init__( self							,							_lowerCamelCase							,							_lowerCamelCase=None							,							_lowerCamelCase=None							,							_lowerCamelCase="</s>"							,							_lowerCamelCase="</s>"							,							_lowerCamelCase="<s>"							,							_lowerCamelCase="<unk>"							,							_lowerCamelCase="<pad>"							,							_lowerCamelCase="<mask>"							,							_lowerCamelCase = None							,							**_lowerCamelCase							,							):
								# Mask token behave like a normal word, i.e. include the space before it
								UpperCAmelCase__					:   List[str]       				=       AddedToken(_lowerCamelCase							,							lstrip=_lowerCamelCase							,							rstrip=_lowerCamelCase) if isinstance(_lowerCamelCase							,							_lowerCamelCase) else mask_token

								UpperCAmelCase__					:   Dict       				=       {} if sp_model_kwargs is None else sp_model_kwargs

								UpperCAmelCase__					:   Dict       				=       kwargs.get("""additional_special_tokens"""							,							[])
								kwargs["additional_special_tokens"] += [
								    code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
								]

								super().__init__(
								    src_lang=_lowerCamelCase							,							tgt_lang=_lowerCamelCase							,							eos_token=_lowerCamelCase							,							unk_token=_lowerCamelCase							,							sep_token=_lowerCamelCase							,							cls_token=_lowerCamelCase							,							pad_token=_lowerCamelCase							,							mask_token=_lowerCamelCase							,							sp_model_kwargs=self.sp_model_kwargs							,							**_lowerCamelCase							,							)

								UpperCAmelCase__					:   str       				=       spm.SentencePieceProcessor(**self.sp_model_kwargs)
								self.sp_model.Load(str(_lowerCamelCase))
								UpperCAmelCase__					:   int       				=       vocab_file

								# Original fairseq vocab and spm vocab must be "aligned":
								# Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
								# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
								# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
								# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

								# Mimic fairseq token-to-id alignment for the first 4 token
								UpperCAmelCase__					:   Union[str, Any]       				=       {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}

								# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
								UpperCAmelCase__					:   List[str]       				=       1

								UpperCAmelCase__					:   Optional[int]       				=       len(self.sp_model)
								UpperCAmelCase__					:   List[str]       				=       {
								    code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_lowerCamelCase)
								}
								UpperCAmelCase__					:   Optional[int]       				=       {v: k for k, v in self.lang_code_to_id.items()}
								UpperCAmelCase__					:   Optional[int]       				=       len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset

								self.fairseq_tokens_to_ids.update(self.lang_code_to_id)
								UpperCAmelCase__					:   Union[str, Any]       				=       {v: k for k, v in self.fairseq_tokens_to_ids.items()}

								UpperCAmelCase__					:   Dict       				=       src_lang if src_lang is not None else """en_XX"""
								UpperCAmelCase__					:   str       				=       self.lang_code_to_id[self._src_lang]
								UpperCAmelCase__					:   Tuple       				=       tgt_lang
								self.set_src_lang_special_tokens(self._src_lang)




					@property
					def 			snake_case__  ( self):
								return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1  # Plus 1 for the mask token




					@property
					def 			snake_case__  ( self):
								return self._src_lang




					@src_lang.setter
					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   str       				=       new_src_lang
								self.set_src_lang_special_tokens(self._src_lang)




					def __getstate__( self):
								UpperCAmelCase__					:   int       				=       self.__dict__.copy()
								UpperCAmelCase__					:   Tuple       				=       None
								return state




					def __setstate__( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Union[str, Any]       				=       d

								# for backward compatibility
								if not hasattr(self							,							"""sp_model_kwargs"""):
											UpperCAmelCase__					:   Optional[Any]       				=       {}

								UpperCAmelCase__					:   Any       				=       spm.SentencePieceProcessor(**self.sp_model_kwargs)
								self.sp_model.Load(self.vocab_file)




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   Dict       				=       {self.convert_ids_to_tokens(_lowerCamelCase): i for i in range(self.vocab_size)}
								vocab.update(self.added_tokens_encoder)
								return vocab




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self.sp_model.encode(_lowerCamelCase							,							out_type=_lowerCamelCase)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								if token in self.fairseq_tokens_to_ids:
											return self.fairseq_tokens_to_ids[token]
								UpperCAmelCase__					:   Dict       				=       self.sp_model.PieceToId(_lowerCamelCase)

								# Need to return unknown token if the SP model returned 0
								return spm_id + self.fairseq_offset if spm_id else self.unk_token_id




					def 			snake_case__  ( self							,							_lowerCamelCase):
								if index in self.fairseq_ids_to_tokens:
											return self.fairseq_ids_to_tokens[index]
								return self.sp_model.IdToPiece(index - self.fairseq_offset)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Optional[Any]       				=       []
								UpperCAmelCase__					:   List[Any]       				=       """"""
								UpperCAmelCase__					:   Optional[int]       				=       False
								for token in tokens:
											# make sure that special tokens are not decoded using sentencepiece model
											if token in self.all_special_tokens:
														if not prev_is_special:
																	out_string += " "
														out_string += self.sp_model.decode(_lowerCamelCase) + token
														UpperCAmelCase__					:   Tuple       				=       True
														UpperCAmelCase__					:   List[str]       				=       []
											else:
														current_sub_tokens.append(_lowerCamelCase)
														UpperCAmelCase__					:   Dict       				=       False
								out_string += self.sp_model.decode(_lowerCamelCase)
								return out_string.strip()




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

								if os.path.abspath(self.vocab_file) != os.path.abspath(_lowerCamelCase) and os.path.isfile(self.vocab_file):
											copyfile(self.vocab_file							,							_lowerCamelCase)
								elif not os.path.isfile(self.vocab_file):
											with open(_lowerCamelCase							,							"""wb""") as fi:
														UpperCAmelCase__					:   List[str]       				=       self.sp_model.serialized_model_proto()
														fi.write(_lowerCamelCase)

								return (out_vocab_file,)




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None							,							_lowerCamelCase = False):

								if already_has_special_tokens:
											return super().get_special_tokens_mask(
											    token_ids_a=_lowerCamelCase							,							token_ids_a=_lowerCamelCase							,							already_has_special_tokens=_lowerCamelCase)

								UpperCAmelCase__					:   Tuple       				=       [1] * len(self.prefix_tokens)
								UpperCAmelCase__					:   Dict       				=       [1] * len(self.suffix_tokens)
								if token_ids_a is None:
											return prefix_ones + ([0] * len(_lowerCamelCase)) + suffix_ones
								return prefix_ones + ([0] * len(_lowerCamelCase)) + ([0] * len(_lowerCamelCase)) + suffix_ones




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = None):
								if token_ids_a is None:
											return self.prefix_tokens + token_ids_a + self.suffix_tokens
								# We don't expect to process pairs, but leave the pair logic for API consistency
								return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							**_lowerCamelCase):
								if src_lang is None or tgt_lang is None:
											raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""")
								UpperCAmelCase__					:   Any       				=       src_lang
								UpperCAmelCase__					:   Dict       				=       self(_lowerCamelCase							,							add_special_tokens=_lowerCamelCase							,							return_tensors=_lowerCamelCase							,							**_lowerCamelCase)
								UpperCAmelCase__					:   List[Any]       				=       self.convert_tokens_to_ids(_lowerCamelCase)
								UpperCAmelCase__					:   List[str]       				=       tgt_lang_id
								return inputs




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = "en_XX"							,							_lowerCamelCase = None							,							_lowerCamelCase = "ro_RO"							,							**_lowerCamelCase							,							):
								UpperCAmelCase__					:   Tuple       				=       src_lang
								UpperCAmelCase__					:   Optional[Any]       				=       tgt_lang
								return super().prepare_seqaseq_batch(_lowerCamelCase							,							_lowerCamelCase							,							**_lowerCamelCase)




					def 			snake_case__  ( self):
								return self.set_src_lang_special_tokens(self.src_lang)




					def 			snake_case__  ( self):
								return self.set_tgt_lang_special_tokens(self.tgt_lang)




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   Tuple       				=       self.lang_code_to_id[src_lang]
								UpperCAmelCase__					:   Optional[int]       				=       [self.cur_lang_code_id]
								UpperCAmelCase__					:   Optional[int]       				=       [self.eos_token_id]




					def 			snake_case__  ( self							,							_lowerCamelCase):
								UpperCAmelCase__					:   List[Any]       				=       self.lang_code_to_id[tgt_lang]
								UpperCAmelCase__					:   Dict       				=       [self.cur_lang_code_id]
								UpperCAmelCase__					:   Optional[int]       				=       [self.eos_token_id]