



"""simple docstring"""




import unittest

from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


_lowerCAmelCase    : Optional[int]							=							get_tests_dir("fixtures/spiece.model")






@require_sentencepiece
@require_tokenizers
class      UpperCAmelCase_  (    _UpperCamelCase	,      unittest.TestCase						):
      __SCREAMING_SNAKE_CASE						:       Optional[int]								=			DebertaVaTokenizer
      __SCREAMING_SNAKE_CASE						:       int								=			DebertaVaTokenizerFast
      __SCREAMING_SNAKE_CASE						:       Dict								=			True
      __SCREAMING_SNAKE_CASE						:       int								=			True



      def 						snake_case_ (					self					:     Dict						):
           super().setUp()

           # We have a SentencePiece fixture for testing
           _UpperCAmelCase      :     Union[str, Any]        =   DebertaVaTokenizer(A					,     unk_token="<unk>"						)
           tokenizer.save_pretrained(self.tmpdirname						)



      def 						snake_case_ (					self					:     Dict					,     A					:     Optional[int]						):
           _UpperCAmelCase      :     List[Any]        =   "this is a test"
           _UpperCAmelCase      :     Dict        =   "this is a test"
           return input_text, output_text



      def 						snake_case_ (					self					:     Dict						):
           _UpperCAmelCase      :     str        =   "<pad>"
           _UpperCAmelCase      :     List[str]        =   0

           self.assertEqual(self.get_tokenizer()._convert_token_to_id(A						)					,     A						)
           self.assertEqual(self.get_tokenizer()._convert_id_to_token(A						)					,     A						)



      def 						snake_case_ (					self					:     List[Any]						):
           _UpperCAmelCase      :     Union[str, Any]        =   list(self.get_tokenizer().get_vocab().keys()						)
           self.assertEqual(vocab_keys[0]					,     "<pad>"						)
           self.assertEqual(vocab_keys[1]					,     "<unk>"						)
           self.assertEqual(vocab_keys[-1]					,     "[PAD]"						)
           self.assertEqual(len(A						)					,     3_0_0_0_1						)



      def 						snake_case_ (					self					:     Tuple						):
           self.assertEqual(self.get_tokenizer().vocab_size					,     3_0_0_0_0						)



      def 						snake_case_ (					self					:     Optional[int]						):
           # fmt: off
           _UpperCAmelCase      :     Union[str, Any]        =   " \tHeLLo!how  \n Are yoU?  "
           _UpperCAmelCase      :     int        =   ["▁hello", "!", "how", "▁are", "▁you", "?"]
           # fmt: on

           _UpperCAmelCase      :     str        =   DebertaVaTokenizer(A					,     do_lower_case=A						)
           _UpperCAmelCase      :     Optional[int]        =   tokenizer.convert_ids_to_tokens(tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     int        =   DebertaVaTokenizerFast(A					,     do_lower_case=A						)
           _UpperCAmelCase      :     Any        =   rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)



      @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one."						)
      def 						snake_case_ (					self					:     List[Any]						):
           pass



      @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one."						)
      def 						snake_case_ (					self					:     int						):
           pass



      def 						snake_case_ (					self					:     Union[str, Any]						):
           # fmt: off
           _UpperCAmelCase      :     Optional[int]        =   "I was born in 92000, and this is falsé."
           _UpperCAmelCase      :     str        =   ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ]
           # fmt: on

           _UpperCAmelCase      :     Dict        =   DebertaVaTokenizer(A					,     split_by_punct=A						)
           _UpperCAmelCase      :     Union[str, Any]        =   tokenizer.convert_ids_to_tokens(tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     int        =   DebertaVaTokenizerFast(A					,     split_by_punct=A						)
           _UpperCAmelCase      :     Optional[int]        =   rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)



      def 						snake_case_ (					self					:     List[str]						):
           # fmt: off
           _UpperCAmelCase      :     List[Any]        =   "I was born in 92000, and this is falsé."
           _UpperCAmelCase      :     List[Any]        =   ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ]
           # fmt: on

           _UpperCAmelCase      :     Dict        =   DebertaVaTokenizer(A					,     do_lower_case=A					,     split_by_punct=A						)
           _UpperCAmelCase      :     Dict        =   tokenizer.convert_ids_to_tokens(tokenizer.encode(A					,     add_special_tokens=A						)						)
           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     List[str]        =   DebertaVaTokenizerFast(A					,     do_lower_case=A					,     split_by_punct=A						)
           _UpperCAmelCase      :     Dict        =   rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A					,     add_special_tokens=A						)						)
           self.assertListEqual(A					,     A						)



      def 						snake_case_ (					self					:     Tuple						):
           # fmt: off
           _UpperCAmelCase      :     str        =   "I was born in 92000, and this is falsé."
           _UpperCAmelCase      :     List[str]        =   ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ]
           # fmt: on

           _UpperCAmelCase      :     int        =   DebertaVaTokenizer(A					,     do_lower_case=A					,     split_by_punct=A						)
           _UpperCAmelCase      :     str        =   tokenizer.convert_ids_to_tokens(tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     Optional[int]        =   DebertaVaTokenizerFast(A					,     do_lower_case=A					,     split_by_punct=A						)
           _UpperCAmelCase      :     Optional[Any]        =   rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)



      def 						snake_case_ (					self					:     Union[str, Any]						):
           # fmt: off
           _UpperCAmelCase      :     Tuple        =   "I was born in 92000, and this is falsé."
           _UpperCAmelCase      :     str        =   ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ]
           # fmt: on

           _UpperCAmelCase      :     List[Any]        =   DebertaVaTokenizer(A					,     do_lower_case=A					,     split_by_punct=A						)
           _UpperCAmelCase      :     Optional[int]        =   tokenizer.convert_ids_to_tokens(tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     Dict        =   DebertaVaTokenizerFast(A					,     do_lower_case=A					,     split_by_punct=A						)
           _UpperCAmelCase      :     List[Any]        =   rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)



      def 						snake_case_ (					self					:     str						):
           # fmt: off
           _UpperCAmelCase      :     Optional[Any]        =   " \tHeLLo!how  \n Are yoU?  "
           _UpperCAmelCase      :     Optional[Any]        =   ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"]
           # fmt: on

           _UpperCAmelCase      :     Union[str, Any]        =   DebertaVaTokenizer(A					,     do_lower_case=A					,     split_by_punct=A						)
           _UpperCAmelCase      :     str        =   tokenizer.convert_ids_to_tokens(tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     List[str]        =   DebertaVaTokenizerFast(A					,     do_lower_case=A					,     split_by_punct=A						)
           _UpperCAmelCase      :     int        =   rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A					,     add_special_tokens=A						)						)

           self.assertListEqual(A					,     A						)



      def 						snake_case_ (					self					:     List[str]						):
           _UpperCAmelCase      :     Optional[Any]        =   self.get_tokenizer()
           _UpperCAmelCase      :     Tuple        =   self.get_rust_tokenizer()

           _UpperCAmelCase      :     int        =   "I was born in 92000, and this is falsé."

           _UpperCAmelCase      :     Union[str, Any]        =   tokenizer.convert_ids_to_tokens(tokenizer.encode(A					,     add_special_tokens=A						)						)
           _UpperCAmelCase      :     Tuple        =   rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A					,     add_special_tokens=A						)						)
           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     List[str]        =   tokenizer.encode(A					,     add_special_tokens=A						)
           _UpperCAmelCase      :     Tuple        =   rust_tokenizer.encode(A					,     add_special_tokens=A						)
           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     List[str]        =   self.get_rust_tokenizer()
           _UpperCAmelCase      :     List[Any]        =   tokenizer.encode(A						)
           _UpperCAmelCase      :     Any        =   rust_tokenizer.encode(A						)
           self.assertListEqual(A					,     A						)



      def 						snake_case_ (					self					:     str						):
           _UpperCAmelCase      :     List[str]        =   "This is a test"
           _UpperCAmelCase      :     Optional[Any]        =   [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9]
           _UpperCAmelCase      :     int        =   ["▁", "T", "his", "▁is", "▁a", "▁test"]
           _UpperCAmelCase      :     Optional[Any]        =   ["▁", "<unk>", "his", "▁is", "▁a", "▁test"]

           _UpperCAmelCase      :     Dict        =   DebertaVaTokenizer(A					,     keep_accents=A						)
           _UpperCAmelCase      :     Dict        =   DebertaVaTokenizerFast(A					,     keep_accents=A						)

           _UpperCAmelCase      :     Optional[int]        =   tokenizer.encode(A					,     add_special_tokens=A						)
           self.assertListEqual(A					,     A						)
           _UpperCAmelCase      :     List[str]        =   tokenizer.tokenize(A						)
           self.assertListEqual(A					,     A						)
           _UpperCAmelCase      :     List[str]        =   tokenizer.convert_ids_to_tokens(A						)
           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     Any        =   rust_tokenizer.encode(A					,     add_special_tokens=A						)
           self.assertListEqual(A					,     A						)
           _UpperCAmelCase      :     Union[str, Any]        =   rust_tokenizer.tokenize(A						)
           self.assertListEqual(A					,     A						)
           _UpperCAmelCase      :     List[str]        =   rust_tokenizer.convert_ids_to_tokens(A						)
           self.assertListEqual(A					,     A						)

           # fmt: off
           _UpperCAmelCase      :     int        =   "I was born in 92000, and this is falsé."
           _UpperCAmelCase      :     Tuple        =   [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9]
           _UpperCAmelCase      :     Union[str, Any]        =   ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ]
           _UpperCAmelCase      :     Optional[int]        =   ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ]
           # fmt: on

           _UpperCAmelCase      :     Union[str, Any]        =   tokenizer.encode(A					,     add_special_tokens=A						)
           self.assertListEqual(A					,     A						)
           _UpperCAmelCase      :     int        =   tokenizer.tokenize(A						)
           self.assertListEqual(A					,     A						)
           _UpperCAmelCase      :     Union[str, Any]        =   tokenizer.convert_ids_to_tokens(A						)
           self.assertListEqual(A					,     A						)

           _UpperCAmelCase      :     List[Any]        =   rust_tokenizer.encode(A					,     add_special_tokens=A						)
           self.assertListEqual(A					,     A						)
           _UpperCAmelCase      :     Any        =   rust_tokenizer.tokenize(A						)
           self.assertListEqual(A					,     A						)
           _UpperCAmelCase      :     str        =   rust_tokenizer.convert_ids_to_tokens(A						)
           self.assertListEqual(A					,     A						)



      def 						snake_case_ (					self					:     List[str]						):
           _UpperCAmelCase      :     int        =   DebertaVaTokenizer(A						)

           _UpperCAmelCase      :     List[Any]        =   tokenizer.encode("sequence builders"						)
           _UpperCAmelCase      :     Optional[int]        =   tokenizer.encode("multi-sequence build"						)

           _UpperCAmelCase      :     Union[str, Any]        =   tokenizer.build_inputs_with_special_tokens(A						)
           _UpperCAmelCase      :     Union[str, Any]        =   tokenizer.build_inputs_with_special_tokens(A					,     A						)

           self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]					,     A						)
           self.assertEqual(
               [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id]					,     A					,     )



      @slow
      def 						snake_case_ (					self					:     Optional[Any]						):
           # fmt: off
           _UpperC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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
           # fmt: on

           self.tokenizer_integration_test_util(
               expected_encoding=A					,     model_name="microsoft/deberta-v2-xlarge"					,     revision="ad6e42c1532ddf3a15c39246b63f5559d558b670"					,     )





"""simple docstring"""




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


_lowerCAmelCase    : Any							=							logging.getLogger(__name__)






@dataclass
class      UpperCAmelCase_  :
      __SCREAMING_SNAKE_CASE						:       str
      __SCREAMING_SNAKE_CASE						:       List[str]
      __SCREAMING_SNAKE_CASE						:       Optional[List[str]]







@dataclass
class      UpperCAmelCase_  :
      __SCREAMING_SNAKE_CASE						:       List[int]
      __SCREAMING_SNAKE_CASE						:       List[int]
      __SCREAMING_SNAKE_CASE						:       Optional[List[int]]								=			None
      __SCREAMING_SNAKE_CASE						:       Optional[List[int]]								=			None







class      UpperCAmelCase_  (    _UpperCamelCase						):
      __SCREAMING_SNAKE_CASE						:       Union[str, Any]								=			'train'
      __SCREAMING_SNAKE_CASE						:       Tuple								=			'dev'
      __SCREAMING_SNAKE_CASE						:       Optional[int]								=			'test'







class      UpperCAmelCase_  :



      @staticmethod
      def 						snake_case_ (					A					:     Union[str, Any]					,     A					:     Union[Split, str]						):
           raise NotImplementedError



      @staticmethod
      def 						snake_case_ (					A					:     str						):
           raise NotImplementedError



      @staticmethod
      def 						snake_case_ (					A					:     List[InputExample]					,     A					:     List[str]					,     A					:     int					,     A					:     PreTrainedTokenizer					,     A					:     Optional[int]=False					,     A					:     List[str]="[CLS]"					,     A					:     List[Any]=1					,     A					:     str="[SEP]"					,     A					:     int=False					,     A					:     int=False					,     A					:     Any=0					,     A					:     List[str]=0					,     A					:     Dict=-1_0_0					,     A					:     str=0					,     A					:     Optional[Any]=True					,     ):
           _UpperCAmelCase      :     Dict        =   {label: i for i, label in enumerate(A						)}

           _UpperCAmelCase      :     str        =   []
           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						)						)

                _UpperCAmelCase      :     int        =   []
                _UpperCAmelCase      :     List[str]        =   []
                for word, label in zip(example.words					,     example.labels						):
                     _UpperCAmelCase      :     str        =   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.
                _UpperCAmelCase      :     List[str]        =   tokenizer.num_special_tokens_to_add()
                if len(A						) > max_seq_length - special_tokens_count:
                     _UpperCAmelCase      :     List[Any]        =   tokens[: (max_seq_length - special_tokens_count)]
                     _UpperCAmelCase      :     List[Any]        =   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]
                _UpperCAmelCase      :     Dict        =   [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:
                     _UpperCAmelCase      :     str        =   [cls_token] + tokens
                     _UpperCAmelCase      :     Dict        =   [pad_token_label_id] + label_ids
                     _UpperCAmelCase      :     Any        =   [cls_token_segment_id] + segment_ids

                _UpperCAmelCase      :     int        =   tokenizer.convert_tokens_to_ids(A						)

                # The mask has 1 for real tokens and 0 for padding tokens. Only real
                # tokens are attended to.
                _UpperCAmelCase      :     List[Any]        =   [1 if mask_padding_with_zero else 0] * len(A						)

                # Zero-pad up to the sequence length.
                _UpperCAmelCase      :     List[str]        =   max_seq_length - len(A						)
                if pad_on_left:
                     _UpperCAmelCase      :     str        =   ([pad_token] * padding_length) + input_ids
                     _UpperCAmelCase      :     str        =   ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
                     _UpperCAmelCase      :     Any        =   ([pad_token_segment_id] * padding_length) + segment_ids
                     _UpperCAmelCase      :     Dict        =   ([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:
                     _UpperCAmelCase      :     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_  (    _UpperCamelCase						):
       __SCREAMING_SNAKE_CASE						:       List[InputFeatures]
       __SCREAMING_SNAKE_CASE						:       int								=			nn.CrossEntropyLoss().ignore_index



       def __init__(					self					:     Dict					,     A					:     TokenClassificationTask					,     A					:     str					,     A					:     PreTrainedTokenizer					,     A					:     List[str]					,     A					:     str					,     A					:     Optional[int] = None					,     A					:     List[str]=False					,     A					:     Split = Split.train					,     ):
            # Load data features from cache or dataset file
            _UpperCAmelCase      :     int        =   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.
            _UpperCAmelCase      :     List[str]        =   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}'						)
                      _UpperCAmelCase      :     Tuple        =   torch.load(A						)
                 else:
                      logger.info(f'Creating features from dataset file at {data_dir}'						)
                      _UpperCAmelCase      :     List[str]        =   token_classification_task.read_examples_from_file(A					,     A						)
                      # TODO clean up all this to leverage built-in features of tokenizers
                      _UpperCAmelCase      :     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					:     Dict						):
            return len(self.features						)



       def __getitem__(					self					:     List[str]					,     A					:     Optional[Any]						):
            return self.features[i]


if is_tf_available():
 import tensorflow as tf






 class      UpperCAmelCase_  :
       __SCREAMING_SNAKE_CASE						:       List[InputFeatures]
       __SCREAMING_SNAKE_CASE						:       int								=			-1_0_0



       def __init__(					self					:     Tuple					,     A					:     TokenClassificationTask					,     A					:     str					,     A					:     PreTrainedTokenizer					,     A					:     List[str]					,     A					:     str					,     A					:     Optional[int] = None					,     A					:     Optional[Any]=False					,     A					:     Split = Split.train					,     ):
            _UpperCAmelCase      :     Union[str, Any]        =   token_classification_task.read_examples_from_file(A					,     A						)
            # TODO clean up all this to leverage built-in features of tokenizers
            _UpperCAmelCase      :     List[str]        =   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:
                 _UpperCAmelCase      :     List[str]        =   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:
                 _UpperCAmelCase      :     List[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 						snake_case_ (					self					:     str						):
            _UpperCAmelCase      :     Dict        =   self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features						)						)						)

            return self.dataset



       def __len__(					self					:     List[Any]						):
            return len(self.features						)



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