
'''simple docstring'''

from __future__ import annotations

import unittest

import numpy as np

from transformers import LayoutLMConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers.models.layoutlm.modeling_tf_layoutlm import (
         TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
         TFLayoutLMForMaskedLM,
         TFLayoutLMForQuestionAnswering,
         TFLayoutLMForSequenceClassification,
         TFLayoutLMForTokenClassification,
         TFLayoutLMModel,
     )


class      a_     :




       def __init__(   self      ,      snake_case_      ,      snake_case_=1_3      ,      snake_case_=7      ,      snake_case_=True      ,      snake_case_=True      ,      snake_case_=True      ,      snake_case_=True      ,      snake_case_=9_9      ,      snake_case_=3_2      ,      snake_case_=2      ,      snake_case_=4      ,      snake_case_=3_7      ,      snake_case_="gelu"      ,      snake_case_=0.1      ,      snake_case_=0.1      ,      snake_case_=5_1_2      ,      snake_case_=1_6      ,      snake_case_=2      ,      snake_case_=0.02      ,      snake_case_=3      ,      snake_case_=4      ,      snake_case_=None      ,      snake_case_=1_0_0_0      ,      ):
         _lowerCAmelCase				:     List[str]       =    parent
         _lowerCAmelCase				:     Dict       =    batch_size
         _lowerCAmelCase				:     List[str]       =    seq_length
         _lowerCAmelCase				:     Dict       =    is_training
         _lowerCAmelCase				:     str       =    use_input_mask
         _lowerCAmelCase				:     List[str]       =    use_token_type_ids
         _lowerCAmelCase				:     List[str]       =    use_labels
         _lowerCAmelCase				:     Union[str, Any]       =    vocab_size
         _lowerCAmelCase				:     Any       =    hidden_size
         _lowerCAmelCase				:     List[Any]       =    num_hidden_layers
         _lowerCAmelCase				:     Optional[Any]       =    num_attention_heads
         _lowerCAmelCase				:     Optional[int]       =    intermediate_size
         _lowerCAmelCase				:     List[str]       =    hidden_act
         _lowerCAmelCase				:     Optional[Any]       =    hidden_dropout_prob
         _lowerCAmelCase				:     Optional[int]       =    attention_probs_dropout_prob
         _lowerCAmelCase				:     int       =    max_position_embeddings
         _lowerCAmelCase				:     str       =    type_vocab_size
         _lowerCAmelCase				:     str       =    type_sequence_label_size
         _lowerCAmelCase				:     Optional[Any]       =    initializer_range
         _lowerCAmelCase				:     str       =    num_labels
         _lowerCAmelCase				:     Union[str, Any]       =    num_choices
         _lowerCAmelCase				:     Any       =    scope
         _lowerCAmelCase				:     Optional[int]       =    range_bbox




       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     Tuple       =    ids_tensor([self.batch_size, self.seq_length]      ,      self.vocab_size     )

         # convert bbox to numpy since TF does not support item assignment
         _lowerCAmelCase				:     Optional[int]       =    ids_tensor([self.batch_size, self.seq_length, 4]      ,      self.range_bbox     ).numpy()
         # Ensure that bbox is legal
         for i in range(bbox.shape[0]     ):
           for j in range(bbox.shape[1]     ):
             if bbox[i, j, 3] < bbox[i, j, 1]:
               _lowerCAmelCase				:     List[str]       =    bbox[i, j, 3]
               _lowerCAmelCase				:     str       =    bbox[i, j, 1]
               _lowerCAmelCase				:     Tuple       =    t
             if bbox[i, j, 2] < bbox[i, j, 0]:
               _lowerCAmelCase				:     Tuple       =    bbox[i, j, 2]
               _lowerCAmelCase				:     Optional[Any]       =    bbox[i, j, 0]
               _lowerCAmelCase				:     Any       =    t
         _lowerCAmelCase				:     Dict       =    tf.convert_to_tensor(__lowerCamelCase     )

         _lowerCAmelCase				:     Dict       =    None
         if self.use_input_mask:
           _lowerCAmelCase				:     int       =    random_attention_mask([self.batch_size, self.seq_length]     )

         _lowerCAmelCase				:     Dict       =    None
         if self.use_token_type_ids:
           _lowerCAmelCase				:     int       =    ids_tensor([self.batch_size, self.seq_length]      ,      self.type_vocab_size     )

         _lowerCAmelCase				:     Dict       =    None
         _lowerCAmelCase				:     Any       =    None
         _lowerCAmelCase				:     str       =    None
         if self.use_labels:
           _lowerCAmelCase				:     Tuple       =    ids_tensor([self.batch_size]      ,      self.type_sequence_label_size     )
           _lowerCAmelCase				:     int       =    ids_tensor([self.batch_size, self.seq_length]      ,      self.num_labels     )
           _lowerCAmelCase				:     Dict       =    ids_tensor([self.batch_size]      ,      self.num_choices     )

         _lowerCAmelCase				:     Union[str, Any]       =    LayoutLMConfig(
             vocab_size=self.vocab_size      ,      hidden_size=self.hidden_size      ,      num_hidden_layers=self.num_hidden_layers      ,      num_attention_heads=self.num_attention_heads      ,      intermediate_size=self.intermediate_size      ,      hidden_act=self.hidden_act      ,      hidden_dropout_prob=self.hidden_dropout_prob      ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,      max_position_embeddings=self.max_position_embeddings      ,      type_vocab_size=self.type_vocab_size      ,      initializer_range=self.initializer_range      ,      )

         return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_     ):
         _lowerCAmelCase				:     Tuple       =    TFLayoutLMModel(config=__lowerCamelCase     )

         _lowerCAmelCase				:     Tuple       =    model(__lowerCamelCase      ,      __lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase     )
         _lowerCAmelCase				:     Optional[int]       =    model(__lowerCamelCase      ,      __lowerCamelCase      ,      token_type_ids=__lowerCamelCase     )
         _lowerCAmelCase				:     Dict       =    model(__lowerCamelCase      ,      __lowerCamelCase     )
         self.parent.assertEqual(result.last_hidden_state.shape      ,      (self.batch_size, self.seq_length, self.hidden_size)     )
         self.parent.assertEqual(result.pooler_output.shape      ,      (self.batch_size, self.hidden_size)     )




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_     ):
         _lowerCAmelCase				:     Optional[int]       =    TFLayoutLMForMaskedLM(config=__lowerCamelCase     )

         _lowerCAmelCase				:     List[Any]       =    model(__lowerCamelCase      ,      __lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase      ,      labels=__lowerCamelCase     )
         self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.seq_length, self.vocab_size)     )




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_     ):
         _lowerCAmelCase				:     Optional[int]       =    self.num_labels
         _lowerCAmelCase				:     Union[str, Any]       =    TFLayoutLMForSequenceClassification(config=__lowerCamelCase     )

         _lowerCAmelCase				:     Tuple       =    model(__lowerCamelCase      ,      __lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase     )
         self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.num_labels)     )




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_     ):
         _lowerCAmelCase				:     Dict       =    self.num_labels
         _lowerCAmelCase				:     int       =    TFLayoutLMForTokenClassification(config=__lowerCamelCase     )

         _lowerCAmelCase				:     Any       =    model(__lowerCamelCase      ,      __lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase      ,      labels=__lowerCamelCase     )
         self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.seq_length, self.num_labels)     )




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_      ,      snake_case_     ):
         _lowerCAmelCase				:     str       =    TFLayoutLMForQuestionAnswering(config=__lowerCamelCase     )

         _lowerCAmelCase				:     Optional[Any]       =    model(__lowerCamelCase      ,      __lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase     )
         self.parent.assertEqual(result.start_logits.shape      ,      (self.batch_size, self.seq_length)     )
         self.parent.assertEqual(result.end_logits.shape      ,      (self.batch_size, self.seq_length)     )







       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     Optional[Any]       =    self.prepare_config_and_inputs()
         (
             (
             _lowerCAmelCase	
         ) ,    (
             _lowerCAmelCase	
         ) ,    (
             _lowerCAmelCase	
         ) ,    (
             _lowerCAmelCase	
         ) ,    (
             _lowerCAmelCase	
         ) ,    (
             _lowerCAmelCase	
         ) ,    (
             _lowerCAmelCase	
         ) ,    (
             _lowerCAmelCase	
         ) ,    	
         )				:     Optional[Any]       =    config_and_inputs
         _lowerCAmelCase				:     Optional[Any]       =    {
             """input_ids""": input_ids,
             """bbox""": bbox,
             """token_type_ids""": token_type_ids,
             """attention_mask""": input_mask,
         }
         return config, inputs_dict



@require_tf
class      a_     (UpperCamelCase__							,	UpperCamelCase__							,	unittest.TestCase			):
       __lowerCAmelCase			: str			=					(
           (
               TFLayoutLMModel,
               TFLayoutLMForMaskedLM,
               TFLayoutLMForTokenClassification,
               TFLayoutLMForSequenceClassification,
               TFLayoutLMForQuestionAnswering,
           )
           if is_tf_available()
           else ()
       )
       __lowerCAmelCase			: Union[str, Any]			=					(
           {
               """feature-extraction""": TFLayoutLMModel,
               """fill-mask""": TFLayoutLMForMaskedLM,
               """text-classification""": TFLayoutLMForSequenceClassification,
               """token-classification""": TFLayoutLMForTokenClassification,
               """zero-shot""": TFLayoutLMForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       __lowerCAmelCase			: str			=					False
       __lowerCAmelCase			: Any			=					True
       __lowerCAmelCase			: Tuple			=					1_0




       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     Any       =    TFLayoutLMModelTester(self     )
         _lowerCAmelCase				:     str       =    ConfigTester(self      ,      config_class=__lowerCamelCase      ,      hidden_size=3_7     )




       def 							__UpperCamelCase				(   self     ):
         self.config_tester.run_common_tests()




       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     str       =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__lowerCamelCase     )




       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     List[Any]       =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*__lowerCamelCase     )




       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     Tuple       =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(*__lowerCamelCase     )




       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     Tuple       =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*__lowerCamelCase     )




       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     List[Any]       =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_question_answering(*__lowerCamelCase     )




       @slow
       def 							__UpperCamelCase				(   self     ):
         for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _lowerCAmelCase				:     Dict       =    TFLayoutLMModel.from_pretrained(__lowerCamelCase     )
           self.assertIsNotNone(__lowerCamelCase     )







       @unittest.skip("""Onnx compliancy broke with TF 2.10"""     )
       def 							__UpperCamelCase				(   self     ):
         pass



def 		_UpperCAmelCase (     )			->  Optional[Any]:
  # Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on:
  # fmt: off
  _lowerCAmelCase				:     Optional[Any]       =    tf.convert_to_tensor([[1_01,10_19,10_14,10_16,10_37,1_28_49,47_47,10_04,1_42_46,22_78,54_39,45_24,50_02,29_30,21_93,29_30,43_41,32_08,10_05,10_55,21_71,28_48,1_13_00,35_31,1_02],[1_01,40_70,40_34,70_20,10_24,30_58,10_15,10_13,28_61,10_13,60_70,1_92_74,27_72,62_05,2_78_14,1_61_47,1_61_47,43_43,20_47,1_02_83,1_09_69,1_43_89,10_12,23_38,1_02]]						)  # noqa: E231
  _lowerCAmelCase				:     List[Any]       =    tf.convert_to_tensor([[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],]						)  # noqa: E231
  _lowerCAmelCase				:     str       =    tf.convert_to_tensor([[[0,0,0,0],[4_23,2_37,4_40,2_51],[4_27,2_72,4_41,2_87],[4_19,1_15,4_37,1_29],[9_61,8_85,9_92,9_12],[2_56,38,3_30,58],[2_56,38,3_30,58],[3_36,42,3_53,57],[3_60,39,4_01,56],[3_60,39,4_01,56],[4_11,39,4_71,59],[4_79,41,5_28,59],[5_33,39,6_30,60],[67,1_13,1_34,1_31],[1_41,1_15,2_09,1_32],[68,1_49,1_33,1_66],[1_41,1_49,1_87,1_64],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[2_95,1_48,3_49,1_65],[4_41,1_49,4_92,1_66],[4_97,1_49,5_46,1_64],[64,2_01,1_25,2_18],[10_00,10_00,10_00,10_00]],[[0,0,0,0],[6_62,1_50,7_54,1_66],[6_65,1_99,7_42,2_11],[5_19,2_13,5_54,2_28],[5_19,2_13,5_54,2_28],[1_34,4_33,1_87,4_54],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[3_14,4_69,3_76,4_82],[5_04,6_84,5_82,7_06],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[6_10,7_49,6_52,7_65],[1_30,6_59,1_68,6_72],[1_76,6_57,2_37,6_72],[2_38,6_57,3_12,6_72],[4_43,6_53,6_28,6_72],[4_43,6_53,6_28,6_72],[7_16,3_01,8_25,3_17],[10_00,10_00,10_00,10_00]]]						)  # noqa: E231
  _lowerCAmelCase				:     int       =    tf.convert_to_tensor([[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: E231
  # these are sequence labels (i.e. at the token level)
  _lowerCAmelCase				:     Tuple       =    tf.convert_to_tensor([[-1_00,10,10,10,9,1,-1_00,7,7,-1_00,7,7,4,2,5,2,8,8,-1_00,-1_00,5,0,3,2,-1_00],[-1_00,12,12,12,-1_00,12,10,-1_00,-1_00,-1_00,-1_00,10,12,9,-1_00,-1_00,-1_00,10,10,10,9,12,-1_00,10,-1_00]]						)  # noqa: E231
  # fmt: on

  return input_ids, attention_mask, bbox, token_type_ids, labels



@require_tf
class      a_     (unittest.TestCase			):




       @slow
       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     Tuple       =    TFLayoutLMModel.from_pretrained("""microsoft/layoutlm-base-uncased"""     )

         _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase				:     Tuple       =    prepare_layoutlm_batch_inputs()

         # forward pass
         _lowerCAmelCase				:     List[str]       =    model(input_ids=__lowerCamelCase      ,      bbox=__lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase     )

         # test the sequence output on [0, :3, :3]
         _lowerCAmelCase				:     Dict       =    tf.convert_to_tensor(
             [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]]      ,      )

         self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3]      ,      __lowerCamelCase      ,      atol=1E-3     )     )

         # test the pooled output on [1, :3]
         _lowerCAmelCase				:     int       =    tf.convert_to_tensor([-0.6580, -0.0214, 0.8552]     )

         self.assertTrue(np.allclose(outputs.pooler_output[1, :3]      ,      __lowerCamelCase      ,      atol=1E-3     )     )




       @slow
       def 							__UpperCamelCase				(   self     ):
         # initialize model with randomly initialized sequence classification head
         _lowerCAmelCase				:     Any       =    TFLayoutLMForSequenceClassification.from_pretrained("""microsoft/layoutlm-base-uncased"""      ,      num_labels=2     )

         _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase				:     Optional[int]       =    prepare_layoutlm_batch_inputs()

         # forward pass
         _lowerCAmelCase				:     int       =    model(
             input_ids=__lowerCamelCase      ,      bbox=__lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase      ,      labels=tf.convert_to_tensor([1, 1]     )      ,      )

         # test whether we get a loss as a scalar
         _lowerCAmelCase				:     List[Any]       =    outputs.loss
         _lowerCAmelCase				:     Tuple       =    (2,)
         self.assertEqual(loss.shape      ,      __lowerCamelCase     )

         # test the shape of the logits
         _lowerCAmelCase				:     List[str]       =    outputs.logits
         _lowerCAmelCase				:     Tuple       =    (2, 2)
         self.assertEqual(logits.shape      ,      __lowerCamelCase     )




       @slow
       def 							__UpperCamelCase				(   self     ):
         # initialize model with randomly initialized token classification head
         _lowerCAmelCase				:     Dict       =    TFLayoutLMForTokenClassification.from_pretrained("""microsoft/layoutlm-base-uncased"""      ,      num_labels=1_3     )

         _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase				:     List[str]       =    prepare_layoutlm_batch_inputs()

         # forward pass
         _lowerCAmelCase				:     Optional[int]       =    model(
             input_ids=__lowerCamelCase      ,      bbox=__lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase      ,      labels=__lowerCamelCase     )

         # test the shape of the logits
         _lowerCAmelCase				:     List[Any]       =    outputs.logits
         _lowerCAmelCase				:     int       =    tf.convert_to_tensor((2, 2_5, 1_3)     )
         self.assertEqual(logits.shape      ,      __lowerCamelCase     )







       @slow
       def 							__UpperCamelCase				(   self     ):
         # initialize model with randomly initialized token classification head
         _lowerCAmelCase				:     Optional[Any]       =    TFLayoutLMForQuestionAnswering.from_pretrained("""microsoft/layoutlm-base-uncased"""     )

         _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase				:     List[Any]       =    prepare_layoutlm_batch_inputs()

         # forward pass
         _lowerCAmelCase				:     Optional[Any]       =    model(input_ids=__lowerCamelCase      ,      bbox=__lowerCamelCase      ,      attention_mask=__lowerCamelCase      ,      token_type_ids=__lowerCamelCase     )

         # test the shape of the logits
         _lowerCAmelCase				:     List[str]       =    tf.convert_to_tensor((2, 2_5)     )
         self.assertEqual(outputs.start_logits.shape      ,      __lowerCamelCase     )
         self.assertEqual(outputs.end_logits.shape      ,      __lowerCamelCase     )









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

import sentencepiece as spm

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


a__:      Union[str, Any]									=		logging.get_logger(__name__)

a__:      Union[str, Any]									=		{'vocab_file': 'spiece.model'}

a__:      Tuple									=		{
    'vocab_file': {
        'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model',
        'google/bigbird-roberta-large': (
            'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model'
        ),
        'google/bigbird-base-trivia-itc': (
            'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model'
        ),
    }
}

a__:      Any									=		{
    'google/bigbird-roberta-base': 4_096,
    'google/bigbird-roberta-large': 4_096,
    'google/bigbird-base-trivia-itc': 4_096,
}




class     SCREAMING_SNAKE_CASE__ (						UpperCamelCase__      ):
 __SCREAMING_SNAKE_CASE							       =	VOCAB_FILES_NAMES
 __SCREAMING_SNAKE_CASE							       =	PRETRAINED_VOCAB_FILES_MAP
 __SCREAMING_SNAKE_CASE							       =	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __SCREAMING_SNAKE_CASE							       =	['''input_ids''', '''attention_mask''']
 __SCREAMING_SNAKE_CASE							       =	[]



 def __init__(							self,__lowerCamelCase,__lowerCamelCase="<unk>",__lowerCamelCase="<s>",__lowerCamelCase="</s>",__lowerCamelCase="<pad>",__lowerCamelCase="[SEP]",__lowerCamelCase="[MASK]",__lowerCamelCase="[CLS]",__lowerCamelCase = None,**__lowerCamelCase,):
        A__											=						AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else bos_token
        A__											=						AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else eos_token
        A__											=						AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else unk_token
        A__											=						AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else pad_token
        A__											=						AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else cls_token
        A__											=						AddedToken(__lowerCamelCase,lstrip=__lowerCamelCase,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase,__lowerCamelCase ) else sep_token

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

        A__											=						{} if sp_model_kwargs is None else sp_model_kwargs

        super().__init__(
            bos_token=__lowerCamelCase,eos_token=__lowerCamelCase,unk_token=__lowerCamelCase,pad_token=__lowerCamelCase,sep_token=__lowerCamelCase,mask_token=__lowerCamelCase,cls_token=__lowerCamelCase,sp_model_kwargs=self.sp_model_kwargs,**__lowerCamelCase,)

        A__											=						vocab_file

        A__											=						spm.SentencePieceProcessor(**self.sp_model_kwargs )
        self.sp_model.Load(__lowerCamelCase )



 @property
 def 				UpperCamelCase			(							self ):
        return self.sp_model.get_piece_size()



 def 				UpperCamelCase			(							self ):
        A__											=						{self.convert_ids_to_tokens(__lowerCamelCase ): i for i in range(self.vocab_size )}
        vocab.update(self.added_tokens_encoder )
        return vocab



 def __getstate__(							self ):
        A__											=						self.__dict__.copy()
        A__											=						None
        return state



 def __setstate__(							self,__lowerCamelCase ):
        A__											=						d

        # for backward compatibility
        if not hasattr(self,'''sp_model_kwargs''' ):
               A__											=						{}

        A__											=						spm.SentencePieceProcessor(**self.sp_model_kwargs )
        self.sp_model.Load(self.vocab_file )



 def 				UpperCamelCase			(							self,__lowerCamelCase ):
        return self.sp_model.encode(__lowerCamelCase,out_type=__lowerCamelCase )



 def 				UpperCamelCase			(							self,__lowerCamelCase ):
        return self.sp_model.piece_to_id(__lowerCamelCase )



 def 				UpperCamelCase			(							self,__lowerCamelCase ):
        A__											=						self.sp_model.IdToPiece(__lowerCamelCase )
        return token



 def 				UpperCamelCase			(							self,__lowerCamelCase ):
        A__											=						[]
        A__											=						''''''
        A__											=						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
                      A__											=						True
                      A__											=						[]
               else:
                      current_sub_tokens.append(__lowerCamelCase )
                      A__											=						False
        out_string += self.sp_model.decode(__lowerCamelCase )
        return out_string.strip()



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase = False,__lowerCamelCase = None,__lowerCamelCase = True,**__lowerCamelCase,):
        A__											=						kwargs.pop('''use_source_tokenizer''',__lowerCamelCase )

        A__											=						self.convert_ids_to_tokens(__lowerCamelCase,skip_special_tokens=__lowerCamelCase )

        # To avoid mixing byte-level and unicode for byte-level BPT
        # we need to build string separately for added tokens and byte-level tokens
        # cf. https://github.com/huggingface/transformers/issues/1133
        A__											=						[]
        A__											=						[]
        for token in filtered_tokens:
               if skip_special_tokens and token in self.all_special_ids:
                      continue
               if token in self.added_tokens_encoder:
                      if current_sub_text:
                             sub_texts.append(self.convert_tokens_to_string(__lowerCamelCase ) )
                             A__											=						[]
                      sub_texts.append(__lowerCamelCase )
               else:
                      current_sub_text.append(__lowerCamelCase )
        if current_sub_text:
               sub_texts.append(self.convert_tokens_to_string(__lowerCamelCase ) )

        # Mimic the behavior of the Rust tokenizer:
        # No space before [MASK] and [SEP]
        if spaces_between_special_tokens:
               A__											=						re.sub(r''' (\[(MASK|SEP)\])''',r'''\1''',''' '''.join(__lowerCamelCase ) )
        else:
               A__											=						''''''.join(__lowerCamelCase )

        A__											=						(
            clean_up_tokenization_spaces
            if clean_up_tokenization_spaces is not None
            else self.clean_up_tokenization_spaces
        )
        if clean_up_tokenization_spaces:
               A__											=						self.clean_up_tokenization(__lowerCamelCase )
               return clean_text
        else:
               return text



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase = None ):
        if not os.path.isdir(__lowerCamelCase ):
               logger.error(f"Vocabulary path ({save_directory}) should be a directory" )
               return
        A__											=						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:
                      A__											=						self.sp_model.serialized_model_proto()
                      fi.write(__lowerCamelCase )

        return (out_vocab_file,)



 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase = None ):
        if token_ids_a is None:
               return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
        A__											=						[self.cls_token_id]
        A__											=						[self.sep_token_id]
        return cls + token_ids_a + sep + token_ids_a + sep



 def 				UpperCamelCase			(							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 )

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




 def 				UpperCamelCase			(							self,__lowerCamelCase,__lowerCamelCase = None ):
        A__											=						[self.sep_token_id]
        A__											=						[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 ) * [0] + len(token_ids_a + sep ) * [1]





