


"""simple docstring"""


import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TFEfficientFormerForImageClassification,
		    TFEfficientFormerForImageClassificationWithTeacher,
		    TFEfficientFormerModel,
		)
		from transformers.models.efficientformer.modeling_tf_efficientformer import (
		    TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
		)


if is_vision_available():
		from PIL import Image

		from transformers import EfficientFormerImageProcessor
class snake_case      :







		def __init__(					self      :       Optional[Any]    ,   a__      :       int    ,   a__      :       int = 13    ,   a__      :       int = 64    ,   a__      :       int = 2    ,   a__      :       int = 3    ,   a__      :       int = 3    ,   a__      :       bool = True    ,   a__      :       bool = True    ,   a__      :       int = 1_28    ,   a__      :       Dict=[16, 32, 64, 1_28]    ,   a__      :       int = 7    ,   a__      :       int = 4    ,   a__      :       int = 37    ,   a__      :       str = "gelu"    ,   a__      :       float = 0.1    ,   a__      :       float = 0.1    ,   a__      :       int = 10    ,   a__      :       float = 0.0_2    ,   a__      :       int = 2    ,   a__      :       int = 1    ,   a__      :       int = 1_28    ,   a__      :       List[int] = [2, 2, 2, 2]    ,   a__      :       int = 2    ,   a__      :       int = 2    ,   )       ->						Tuple:





						'''simple docstring'''







						_A					  =			parent
						_A					  =			batch_size
						_A					  =			image_size
						_A					  =			patch_size
						_A					  =			num_channels
						_A					  =			is_training
						_A					  =			use_labels
						_A					  =			hidden_size
						_A					  =			num_hidden_layers
						_A					  =			num_attention_heads
						_A					  =			intermediate_size
						_A					  =			hidden_act
						_A					  =			hidden_dropout_prob
						_A					  =			attention_probs_dropout_prob
						_A					  =			type_sequence_label_size
						_A					  =			initializer_range
						_A					  =			encoder_stride
						_A					  =			num_attention_outputs
						_A					  =			embed_dim
						_A					  =			embed_dim + 1
						_A					  =			resolution
						_A					  =			depths
						_A					  =			hidden_sizes
						_A					  =			dim
						_A					  =			mlp_expansion_ratio







		def  a_ (					self      :       Any		)       ->						Dict:





						'''simple docstring'''







						_A					  =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

						_A					  =			None
						if self.use_labels:
										_A					  =			ids_tensor([self.batch_size]    ,   self.type_sequence_label_size		)

						_A					  =			self.get_config()

						return config, pixel_values, labels







		def  a_ (					self      :       Union[str, Any]		)       ->						List[str]:





						'''simple docstring'''







						return EfficientFormerConfig(
						    image_size=self.image_size    ,   patch_size=self.patch_size    ,   num_channels=self.num_channels    ,   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    ,   is_decoder=a__    ,   initializer_range=self.initializer_range    ,   encoder_stride=self.encoder_stride    ,   resolution=self.resolution    ,   depths=self.depths    ,   hidden_sizes=self.hidden_sizes    ,   dim=self.dim    ,   mlp_expansion_ratio=self.mlp_expansion_ratio    ,   )







		def  a_ (					self      :       Union[str, Any]    ,   a__      :       Optional[Any]    ,   a__      :       Any    ,   a__      :       Tuple		)       ->						Tuple:





						'''simple docstring'''







						_A					  =			TFEfficientFormerModel(config=a__		)
						_A					  =			model(a__    ,   training=a__		)
						self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)		)







		def  a_ (					self      :       Tuple    ,   a__      :       int    ,   a__      :       Dict    ,   a__      :       List[str]		)       ->						List[str]:





						'''simple docstring'''







						_A					  =			self.type_sequence_label_size
						_A					  =			TFEfficientFormerForImageClassification(a__		)
						_A					  =			model(a__    ,   labels=a__    ,   training=a__		)
						self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.type_sequence_label_size)		)

						# test greyscale images
						_A					  =			1
						_A					  =			TFEfficientFormerForImageClassification(a__		)

						_A					  =			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
						_A					  =			model(a__    ,   labels=a__		)
						self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.type_sequence_label_size)		)







		def  a_ (					self      :       Union[str, Any]		)       ->						Optional[int]:





						'''simple docstring'''







						_A					  =			self.prepare_config_and_inputs()
						_A  ,		_A  ,		_A					  =			config_and_inputs
						_A					  =			{"pixel_values": pixel_values}
						return config, inputs_dict





@require_tf
class snake_case      (  _UpperCamelCase     ,				_UpperCamelCase     ,				unittest.TestCase):
		__UpperCamelCase           =			(
		    (
		        TFEfficientFormerModel,
		        TFEfficientFormerForImageClassificationWithTeacher,
		        TFEfficientFormerForImageClassification,
		    )
		    if is_tf_available()
		    else ()
		)
		__UpperCamelCase           =			(
		    {
		        'feature-extraction': TFEfficientFormerModel,
		        'image-classification': (
		            TFEfficientFormerForImageClassification,
		            TFEfficientFormerForImageClassificationWithTeacher,
		        ),
		    }
		    if is_tf_available()
		    else {}
		)

		__UpperCamelCase           =			False

		__UpperCamelCase           =			False
		__UpperCamelCase           =			False
		__UpperCamelCase           =			False
		__UpperCamelCase           =			False







		def  a_ (					self      :       Any		)       ->						Optional[Any]:





						'''simple docstring'''







						_A					  =			TFEfficientFormerModelTester(self		)
						_A					  =			ConfigTester(
						    self    ,   config_class=a__    ,   has_text_modality=a__    ,   hidden_size=37		)







		def  a_ (					self      :       int		)       ->						List[Any]:





						'''simple docstring'''







						self.config_tester.run_common_tests()







		@unittest.skip(reason="EfficientFormer does not use inputs_embeds"		)
		def  a_ (					self      :       Dict		)       ->						Any:





						'''simple docstring'''







						pass







		@unittest.skip(reason="EfficientFormer does not support input and output embeddings"		)
		def  a_ (					self      :       Optional[int]		)       ->						Optional[int]:





						'''simple docstring'''







						pass







		def  a_ (					self      :       int		)       ->						Dict:





						'''simple docstring'''







						_A  ,		_A					  =			self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										_A					  =			model_class(a__		)
										_A					  =			inspect.signature(model.call		)
										# signature.parameters is an OrderedDict => so arg_names order is deterministic
										_A					  =			[*signature.parameters.keys()]

										_A					  =			["pixel_values"]
										self.assertListEqual(arg_names[:1]    ,   a__		)







		def  a_ (					self      :       Optional[int]		)       ->						List[Any]:





						'''simple docstring'''







						def check_hidden_states_output(a__      :       Union[str, Any]    ,   a__      :       Optional[int]    ,   a__      :       int		):
										_A					  =			model_class(a__		)

										_A					  =			model(**self._prepare_for_class(a__    ,   a__		)    ,   training=a__		)
										_A					  =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										_A					  =			getattr(
										    self.model_tester    ,   "expected_num_hidden_layers"    ,   self.model_tester.num_hidden_layers + 1		)
										self.assertEqual(len(a__		)    ,   a__		)

										if hasattr(self.model_tester    ,   "encoder_seq_length"		):
														_A					  =			self.model_tester.encoder_seq_length
														if hasattr(self.model_tester    ,   "chunk_length"		) and self.model_tester.chunk_length > 1:
																		_A					  =			seq_length * self.model_tester.chunk_length
										else:
														_A					  =			self.model_tester.seq_length

										self.assertListEqual(
										    list(hidden_states[-1].shape[-2:]		)    ,   [seq_length, self.model_tester.hidden_size]    ,   )

										if config.is_encoder_decoder:
														_A					  =			outputs.decoder_hidden_states

														self.asseretIsInstance(a__    ,   (list, tuple)		)
														self.assertEqual(len(a__		)    ,   a__		)
														_A					  =			getattr(self.model_tester    ,   "seq_length"    ,   a__		)
														_A					  =			getattr(self.model_tester    ,   "decoder_seq_length"    ,   a__		)

														self.assertListEqual(
														    list(hidden_states[-1].shape[-2:]		)    ,   [decoder_seq_length, self.model_tester.hidden_size]    ,   )

						_A  ,		_A					  =			self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										_A					  =			True
										check_hidden_states_output(a__    ,   a__    ,   a__		)

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										_A					  =			True

										check_hidden_states_output(a__    ,   a__    ,   a__		)







		def  a_ (					self      :       Union[str, Any]    ,   a__      :       List[Any]    ,   a__      :       Any    ,   a__      :       Tuple=False		)       ->						int:





						'''simple docstring'''







						_A					  =			super()._prepare_for_class(a__    ,   a__    ,   return_labels=a__		)

						if return_labels:
										if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
														del inputs_dict["labels"]

						return inputs_dict







		def  a_ (					self      :       List[Any]		)       ->						List[Any]:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*a__		)







		@unittest.skip(reason="EfficientFormer does not implement masked image modeling yet"		)
		def  a_ (					self      :       Tuple		)       ->						str:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_masked_image_modeling(*a__		)







		def  a_ (					self      :       List[Any]		)       ->						int:





						'''simple docstring'''







						_A					  =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*a__		)







		@slow
		def  a_ (					self      :       Dict		)       ->						List[str]:





						'''simple docstring'''







						for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										_A					  =			TFEfficientFormerModel.from_pretrained(a__		)
										self.assertIsNotNone(a__		)







		def  a_ (					self      :       int		)       ->						str:





						'''simple docstring'''







						_A  ,		_A					  =			self.model_tester.prepare_config_and_inputs_for_common()
						_A					  =			True

						_A					  =			getattr(self.model_tester    ,   "seq_length"    ,   a__		)
						_A					  =			getattr(self.model_tester    ,   "encoder_seq_length"    ,   a__		)
						_A					  =			getattr(self.model_tester    ,   "key_length"    ,   a__		)
						_A					  =			getattr(self.model_tester    ,   "chunk_length"    ,   a__		)

						if chunk_length is not None and hasattr(self.model_tester    ,   "num_hashes"		):
										_A					  =			encoder_seq_length * self.model_tester.num_hashes

						for model_class in self.all_model_classes:
										_A					  =			True
										_A					  =			False
										_A					  =			True
										_A					  =			model_class(a__		)

										_A					  =			model(**self._prepare_for_class(a__    ,   a__		)    ,   training=a__		)
										_A					  =			outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
										self.assertEqual(len(a__		)    ,   self.model_tester.num_attention_outputs		)

										# check that output_attentions also work using config
										del inputs_dict["output_attentions"]
										_A					  =			True
										_A					  =			model_class(a__		)
										_A					  =			model(**self._prepare_for_class(a__    ,   a__		)    ,   training=a__		)

										_A					  =			outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
										self.assertEqual(len(a__		)    ,   self.model_tester.num_attention_outputs		)

										if chunk_length is not None:
														self.assertListEqual(
														    list(attentions[0].shape[-4:]		)    ,   [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]    ,   )
										else:
														self.assertListEqual(
														    list(attentions[0].shape[-3:]		)    ,   [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]    ,   )







		def  a_ (					self      :       Dict		)       ->						int:





						'''simple docstring'''







						_A  ,		_A					  =			self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										# Prepare our model
										_A					  =			model_class(a__		)
										# These are maximally general inputs for the model, with multiple None dimensions
										# Hopefully this will catch any conditionals that fail for flexible shapes
										_A					  =			{
										    key: tf.keras.Input(shape=val.shape[1:]    ,   dtype=val.dtype    ,   name=a__		)
										    for key, val in model.input_signature.items()
										    if key in model.dummy_inputs
										}
										_A					  =			model(a__		)
										self.assertTrue(outputs_dict is not None		)






def      a__ (				)	->	Optional[Any]:
				_A					  =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
				return image




@require_tf
@require_vision
class snake_case      (  unittest.TestCase):







		@cached_property
		def  a_ (					self      :       Optional[Any]		)       ->						Any:





						'''simple docstring'''







						return (
						    EfficientFormerImageProcessor.from_pretrained("snap-research/efficientformer-l1-300"		)
						    if is_vision_available()
						    else None
						)







		@slow
		def  a_ (					self      :       Optional[Any]		)       ->						int:





						'''simple docstring'''







						_A					  =			TFEfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300"		)
						_A					  =			self.default_image_processor
						_A					  =			prepare_img()
						_A					  =			image_processor(images=a__    ,   return_tensors="tf"		)
						# forward pass
						_A					  =			model(**a__    ,   training=a__		)
						# verify the logits
						_A					  =			tf.TensorShape((1, 10_00)		)
						self.assertEqual(outputs.logits.shape    ,   a__		)
						_A					  =			tf.constant([-0.0_5_5_5, 0.4_8_2_5, -0.0_8_5_2]		)
						self.assertTrue(np.allclose(outputs.logits[0, :3]    ,   a__    ,   atol=1E-4		)		)







		@slow
		def  a_ (					self      :       str		)       ->						int:





						'''simple docstring'''







						_A					  =			TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
						    "snap-research/efficientformer-l1-300"		)
						_A					  =			self.default_image_processor
						_A					  =			prepare_img()
						_A					  =			image_processor(images=a__    ,   return_tensors="tf"		)
						# forward pass
						_A					  =			model(**a__    ,   training=a__		)
						# verify the logits
						_A					  =			tf.TensorShape((1, 10_00)		)
						self.assertEqual(outputs.logits.shape    ,   a__		)
						_A					  =			tf.constant([-0.1_3_1_2, 0.4_3_5_3, -1.0_4_9_9]		)
						self.assertTrue(np.allclose(outputs.logits[0, :3]    ,   a__    ,   atol=1E-4		)		)



"""simple docstring"""


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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer


if TYPE_CHECKING:
		from ...tokenization_utils_base import TextInput
from ...utils import logging


a_       							=    logging.get_logger(__name__)

a_       							=    {"vocab_file": "spiece.model"}

a_       							=    {
    "vocab_file": {
        "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model",
        "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model",
        "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model",
        "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model",
        "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model",
    }
}


# TODO(PVP) - this should be removed in Transformers v5
a_       							=    {
    "t5-small": 5_12,
    "t5-base": 5_12,
    "t5-large": 5_12,
    "t5-3b": 5_12,
    "t5-11b": 5_12,
}

a_       							=    "▁"
class snake_case      (  _UpperCamelCase):
		__UpperCamelCase           =			VOCAB_FILES_NAMES
		__UpperCamelCase           =			PRETRAINED_VOCAB_FILES_MAP
		__UpperCamelCase           =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		__UpperCamelCase           =			['input_ids', 'attention_mask']







		def __init__(					self      :       List[str]    ,   a__      :       Optional[int]    ,   a__      :       Union[str, Any]="</s>"    ,   a__      :       Union[str, Any]="<unk>"    ,   a__      :       str="<pad>"    ,   a__      :       Optional[int]=1_00    ,   a__      :       List[Any]=None    ,   a__      :       Optional[Dict[str, Any]] = None    ,   a__      :       Any=True    ,   **a__      :       Optional[int]    ,   )       ->						None:





						'''simple docstring'''







						if extra_ids > 0 and additional_special_tokens is None:
										_A					  =			[F"""<extra_id_{i}>""" for i in range(a__		)]
						elif extra_ids > 0 and additional_special_tokens is not None:
										# Check that we have the right number of extra_id special tokens
										_A					  =			len(set(filter(lambda a__		: bool("extra_id" in str(a__		)		)    ,   a__		)		)		)
										if extra_tokens != extra_ids:
														raise ValueError(
														    F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"""
														    " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids"
														    " tokens"		)
						if legacy:
										logger.warning_once(
										    F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to"""
										    " read the related pull request available at https://github.com/huggingface/transformers/pull/24565"		)

						_A					  =			legacy
						_A					  =			{} if sp_model_kwargs is None else sp_model_kwargs

						super().__init__(
						    eos_token=a__    ,   unk_token=a__    ,   pad_token=a__    ,   extra_ids=a__    ,   additional_special_tokens=a__    ,   sp_model_kwargs=self.sp_model_kwargs    ,   legacy=a__    ,   **a__    ,   )

						_A					  =			vocab_file
						_A					  =			extra_ids

						_A					  =			spm.SentencePieceProcessor(**self.sp_model_kwargs		)
						self.sp_model.Load(a__		)







		@staticmethod
		def  a_ (					a__      :       List[str]    ,   a__      :       Optional[int]    ,   a__      :       Tuple		)       ->						Tuple:





						'''simple docstring'''







						if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
										_A					  =			TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path]
										if init_max_model_length is not None and init_max_model_length != max_model_length:
														return init_max_model_length
										elif init_max_model_length is None:
														warnings.warn(
														    "This tokenizer was incorrectly instantiated with a model max length of"
														    F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this"""
														    " behavior is kept to avoid breaking backwards compatibility when padding/encoding with"
														    " `truncation is True`.\n- Be aware that you SHOULD NOT rely on"
														    F""" {pretrained_model_name_or_path} automatically truncating your input to"""
														    F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences"""
														    F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with"""
														    " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please"
														    " instantiate this tokenizer with `model_max_length` set to your preferred value."    ,   a__    ,   )

						return max_model_length







		@property
		def  a_ (					self      :       List[Any]		)       ->						Dict:





						'''simple docstring'''







						return self.sp_model.get_piece_size() + self._extra_ids







		def  a_ (					self      :       Dict		)       ->						Optional[Any]:





						'''simple docstring'''







						_A					  =			{self.convert_ids_to_tokens(a__		): i for i in range(self.vocab_size		)}
						vocab.update(self.added_tokens_encoder		)
						return vocab







		def  a_ (					self      :       Optional[Any]    ,   a__      :       List[int]    ,   a__      :       Optional[List[int]] = None    ,   a__      :       bool = False		)       ->						List[int]:





						'''simple docstring'''







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

						# normal case: some special tokens
						if token_ids_a is None:
										return ([0] * len(a__		)) + [1]
						return ([0] * len(a__		)) + [1] + ([0] * len(a__		)) + [1]







		def  a_ (					self      :       List[str]		)       ->						List[str]:





						'''simple docstring'''







						return list(
						    set(filter(lambda a__		: bool(re.search(r"<extra_id_\d+>"    ,   a__		)		) is not None    ,   self.additional_special_tokens		)		)		)







		def  a_ (					self      :       str		)       ->						List[Any]:





						'''simple docstring'''







						return [self._convert_token_to_id(a__		) for token in self.get_sentinel_tokens()]







		def  a_ (					self      :       List[Any]    ,   a__      :       List[int]		)       ->						List[int]:





						'''simple docstring'''







						if len(a__		) > 0 and token_ids[-1] == self.eos_token_id:
										warnings.warn(
										    F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"""
										    " eos tokens being added."		)
										return token_ids
						else:
										return token_ids + [self.eos_token_id]







		def  a_ (					self      :       int    ,   a__      :       List[int]    ,   a__      :       Optional[List[int]] = None		)       ->						List[int]:





						'''simple docstring'''







						_A					  =			[self.eos_token_id]

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







		def  a_ (					self      :       Union[str, Any]    ,   a__      :       List[int]    ,   a__      :       Optional[List[int]] = None		)       ->						List[int]:





						'''simple docstring'''







						_A					  =			self._add_eos_if_not_present(a__		)
						if token_ids_a is None:
										return token_ids_a
						else:
										_A					  =			self._add_eos_if_not_present(a__		)
										return token_ids_a + token_ids_a







		def __getstate__(					self      :       Dict		)       ->						Union[str, Any]:





						'''simple docstring'''







						_A					  =			self.__dict__.copy()
						_A					  =			None
						return state







		def __setstate__(					self      :       int    ,   a__      :       Optional[int]		)       ->						Union[str, Any]:





						'''simple docstring'''







						_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  a_ (					self      :       int    ,   a__      :       "TextInput"    ,   **a__      :       List[str]		)       ->						List[str]:





						'''simple docstring'''







						if not self.legacy:
										_A					  =			SPIECE_UNDERLINE + text.replace(a__    ,   " "		)
						return super().tokenize(a__    ,   **a__		)







		def  a_ (					self      :       str    ,   a__      :       Dict    ,   **a__      :       Optional[int]		)       ->						Any:





						'''simple docstring'''







						if not self.legacy:
										_A					  =			text.startswith(a__		)
										if is_first:
														_A					  =			text[1:]

						_A					  =			self.sp_model.encode(a__    ,   out_type=a__		)

						if not self.legacy and not is_first and not text.startswith(" "		) and tokens[0].startswith(a__		):
										_A					  =			([tokens[0][1:]] if len(tokens[0]		) > 1 else []) + tokens[1:]
						return tokens







		def  a_ (					self      :       int    ,   a__      :       List[Any]		)       ->						List[str]:





						'''simple docstring'''







						if token.startswith("<extra_id_"		):
										_A					  =			re.match(r"<extra_id_(\d+)>"    ,   a__		)
										_A					  =			int(match.group(1		)		)
										return self.vocab_size - num - 1
						return self.sp_model.piece_to_id(a__		)







		def  a_ (					self      :       Dict    ,   a__      :       Union[str, Any]		)       ->						Any:





						'''simple docstring'''







						if index < self.sp_model.get_piece_size():
										_A					  =			self.sp_model.IdToPiece(a__		)
						else:
										_A					  =			F"""<extra_id_{self.vocab_size - 1 - index}>"""
						return token







		def  a_ (					self      :       Optional[int]    ,   a__      :       Tuple		)       ->						List[str]:





						'''simple docstring'''







						_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(a__		) + token
														_A					  =			True
														_A					  =			[]
										else:
														current_sub_tokens.append(a__		)
														_A					  =			False
						out_string += self.sp_model.decode(a__		)
						return out_string.strip()







		def  a_ (					self      :       Dict    ,   a__      :       str    ,   a__      :       Optional[str] = None		)       ->						Tuple[str]:





						'''simple docstring'''







						if not os.path.isdir(a__		):
										logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""		)
										return
						_A					  =			os.path.join(
						    a__    ,   (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]		)

						if os.path.abspath(self.vocab_file		) != os.path.abspath(a__		) and os.path.isfile(self.vocab_file		):
										copyfile(self.vocab_file    ,   a__		)
						elif not os.path.isfile(self.vocab_file		):
										with open(a__    ,   "wb"		) as fi:
														_A					  =			self.sp_model.serialized_model_proto()
														fi.write(a__		)

						return (out_vocab_file,)