import unittest

import numpy as np

from transformers import is_flax_available
from transformers.testing_utils import require_flax

from ..test_modeling_flax_common import ids_tensor


if is_flax_available():
 import jax
 import jax.numpy as jnp

 from transformers.generation import (
     FlaxForcedBOSTokenLogitsProcessor,
     FlaxForcedEOSTokenLogitsProcessor,
     FlaxLogitsProcessorList,
     FlaxMinLengthLogitsProcessor,
     FlaxTemperatureLogitsWarper,
     FlaxTopKLogitsWarper,
     FlaxTopPLogitsWarper,
 )
@require_flax
class 						_A (  unittest.TestCase				):






  def  __a      (  self		:     List[str]				,						_A		:     int				,						_A		:     int				)		->   Any:






       """simple docstring"""







       lowercase :       Tuple       =			jnp.ones((batch_size, length)				) / length
       return scores






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






       """simple docstring"""







       lowercase :       Optional[int]       =			None
       lowercase :       Any       =			20

       lowercase :       str       =			self._get_uniform_logits(batch_size=2				,						length=lowerCAmelCase__				)

       # tweak scores to not be uniform anymore
       lowercase :       str       =			scores.at[1, 5].set((1 / length) + 0.1				)  # peak, 1st batch
       lowercase :       Optional[Any]       =			scores.at[1, 10].set((1 / length) - 0.4				)  # valley, 1st batch

       # compute softmax
       lowercase :       Union[str, Any]       =			jax.nn.softmax(lowerCAmelCase__				,						axis=-1				)

       lowercase :       List[Any]       =			FlaxTemperatureLogitsWarper(temperature=0.5				)
       lowercase :       Any       =			FlaxTemperatureLogitsWarper(temperature=1.3				)

       lowercase :       Union[str, Any]       =			jax.nn.softmax(temp_dist_warper_sharper(lowerCAmelCase__				,						scores.copy()				,						cur_len=lowerCAmelCase__				)				,						axis=-1				)
       lowercase :       Dict       =			jax.nn.softmax(temp_dist_warper_smoother(lowerCAmelCase__				,						scores.copy()				,						cur_len=lowerCAmelCase__				)				,						axis=-1				)

       # uniform distribution stays uniform
       self.assertTrue(jnp.allclose(probs[0, :]				,						warped_prob_sharp[0, :]				,						atol=1E-3				)				)
       self.assertTrue(jnp.allclose(probs[0, :]				,						warped_prob_smooth[0, :]				,						atol=1E-3				)				)

       # sharp peaks get higher, valleys get lower
       self.assertLess(probs[1, :].max()				,						warped_prob_sharp[1, :].max()				)
       self.assertGreater(probs[1, :].min()				,						warped_prob_sharp[1, :].min()				)

       # smooth peaks get lower, valleys get higher
       self.assertGreater(probs[1, :].max()				,						warped_prob_smooth[1, :].max()				)
       self.assertLess(probs[1, :].min()				,						warped_prob_smooth[1, :].min()				)






  def  __a      (  self		:     Union[str, Any]				)		->   Tuple:






       """simple docstring"""







       lowercase :       List[str]       =			None
       lowercase :       Optional[int]       =			10
       lowercase :       int       =			2

       # create ramp distribution
       lowercase :       str       =			np.broadcast_to(np.arange(lowerCAmelCase__				)[None, :]				,						(batch_size, vocab_size)				).copy()
       lowercase :       List[Any]       =			ramp_logits[1:, : vocab_size // 2] + vocab_size

       lowercase :       Optional[int]       =			FlaxTopKLogitsWarper(3				)

       lowercase :       Union[str, Any]       =			top_k_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)

       # check that correct tokens are filtered
       self.assertListEqual(jnp.isinf(scores[0]				).tolist()				,						7 * [True] + 3 * [False]				)
       self.assertListEqual(jnp.isinf(scores[1]				).tolist()				,						2 * [True] + 3 * [False] + 5 * [True]				)

       # check special case
       lowercase :       Optional[int]       =			5
       lowercase :       Union[str, Any]       =			FlaxTopKLogitsWarper(top_k=1				,						filter_value=0.0				,						min_tokens_to_keep=3				)

       lowercase :       Optional[Any]       =			np.broadcast_to(np.arange(lowerCAmelCase__				)[None, :]				,						(batch_size, length)				).copy()
       lowercase :       List[str]       =			top_k_warp_safety_check(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)

       # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
       self.assertListEqual((scores == 0.0).sum(axis=-1				).tolist()				,						[2, 2]				)






  def  __a      (  self		:     List[str]				)		->   Tuple:






       """simple docstring"""







       lowercase :       Optional[int]       =			None
       lowercase :       Any       =			10
       lowercase :       Union[str, Any]       =			2

       # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
       lowercase :       List[Any]       =			np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]]				)				)

       lowercase :       Optional[int]       =			FlaxTopPLogitsWarper(0.8				)
       lowercase :       Optional[Any]       =			np.exp(top_p_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)				)

       # dist should be filtered to keep min num values so that sum is >= top_p
       # exp (-inf) => 0
       lowercase :       Optional[Any]       =			np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]]				)
       self.assertTrue(np.allclose(lowerCAmelCase__				,						lowerCAmelCase__				,						atol=1E-3				)				)

       # check edge cases with negative and extreme logits
       lowercase :       List[str]       =			np.broadcast_to(np.arange(lowerCAmelCase__				)[None, :]				,						(batch_size, vocab_size)				).copy() - (
           vocab_size // 2
       )

       # make ramp_logits more extreme
       lowercase :       int       =			ramp_logits[1] * 100.0

       # make sure at least 2 tokens are kept
       lowercase :       Union[str, Any]       =			FlaxTopPLogitsWarper(0.9				,						min_tokens_to_keep=2				,						filter_value=0.0				)
       lowercase :       List[str]       =			top_p_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)

       # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
       self.assertListEqual((filtered_dist != 0.0).sum(axis=-1				).tolist()				,						[3, 2]				)






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






       """simple docstring"""







       lowercase :       int       =			20
       lowercase :       List[str]       =			4
       lowercase :       Dict       =			0

       lowercase :       Any       =			FlaxMinLengthLogitsProcessor(min_length=10				,						eos_token_id=lowerCAmelCase__				)

       # check that min length is applied at length 5
       lowercase :       Optional[Any]       =			ids_tensor((batch_size, 20)				,						vocab_size=20				)
       lowercase :       List[str]       =			5
       lowercase :       Tuple       =			self._get_uniform_logits(lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       List[Any]       =			min_dist_processor(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()				,						4 * [-float('''inf'''				)]				)

       # check that min length is not applied anymore at length 15
       lowercase :       int       =			self._get_uniform_logits(lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       List[Any]       =			15
       lowercase :       int       =			min_dist_processor(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       self.assertFalse(jnp.isinf(lowerCAmelCase__				).any()				)






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






       """simple docstring"""







       lowercase :       Optional[Any]       =			20
       lowercase :       int       =			4
       lowercase :       Tuple       =			0

       lowercase :       Optional[int]       =			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__				)

       # check that all scores are -inf except the bos_token_id score
       lowercase :       Any       =			ids_tensor((batch_size, 1)				,						vocab_size=20				)
       lowercase :       Union[str, Any]       =			1
       lowercase :       Any       =			self._get_uniform_logits(lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       Optional[Any]       =			logits_processor(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]				).all()				)
       self.assertListEqual(scores[:, bos_token_id].tolist()				,						4 * [0]				)  # score for bos_token_id shold be zero

       # check that bos_token_id is not forced if current length is greater than 1
       lowercase :       Any       =			3
       lowercase :       Optional[int]       =			self._get_uniform_logits(lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       str       =			logits_processor(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       self.assertFalse(jnp.isinf(lowerCAmelCase__				).any()				)






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






       """simple docstring"""







       lowercase :       str       =			20
       lowercase :       List[Any]       =			4
       lowercase :       int       =			0
       lowercase :       Optional[int]       =			5

       lowercase :       int       =			FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__				,						eos_token_id=lowerCAmelCase__				)

       # check that all scores are -inf except the eos_token_id when max_length is reached
       lowercase :       Optional[int]       =			ids_tensor((batch_size, 4)				,						vocab_size=20				)
       lowercase :       Optional[int]       =			4
       lowercase :       str       =			self._get_uniform_logits(lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       Optional[Any]       =			logits_processor(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]				).all()				)
       self.assertListEqual(scores[:, eos_token_id].tolist()				,						4 * [0]				)  # score for eos_token_id should be zero

       # check that eos_token_id is not forced if max_length is not reached
       lowercase :       Dict       =			3
       lowercase :       Dict       =			self._get_uniform_logits(lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       Any       =			logits_processor(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       self.assertFalse(jnp.isinf(lowerCAmelCase__				).any()				)






  def  __a      (  self		:     Dict				)		->   Any:






       """simple docstring"""







       lowercase :       int       =			4
       lowercase :       Optional[int]       =			10
       lowercase :       List[Any]       =			15
       lowercase :       Optional[Any]       =			2
       lowercase :       Union[str, Any]       =			1
       lowercase :       Any       =			15

       # dummy input_ids and scores
       lowercase :       Optional[int]       =			ids_tensor((batch_size, sequence_length)				,						lowerCAmelCase__				)
       lowercase :       Optional[int]       =			input_ids.copy()

       lowercase :       str       =			self._get_uniform_logits(lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       Union[str, Any]       =			scores.copy()

       # instantiate all dist processors
       lowercase :       str       =			FlaxTemperatureLogitsWarper(temperature=0.5				)
       lowercase :       str       =			FlaxTopKLogitsWarper(3				)
       lowercase :       Optional[int]       =			FlaxTopPLogitsWarper(0.8				)

       # instantiate all logits processors
       lowercase :       Optional[Any]       =			FlaxMinLengthLogitsProcessor(min_length=10				,						eos_token_id=lowerCAmelCase__				)
       lowercase :       Dict       =			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__				)
       lowercase :       List[Any]       =			FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__				,						eos_token_id=lowerCAmelCase__				)

       lowercase :       str       =			10

       # no processor list
       lowercase :       Optional[int]       =			temp_dist_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       lowercase :       List[str]       =			top_k_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       lowercase :       str       =			top_p_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       lowercase :       Tuple       =			min_dist_proc(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       lowercase :       Optional[Any]       =			bos_dist_proc(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
       lowercase :       Union[str, Any]       =			eos_dist_proc(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)

       # with processor list
       lowercase :       List[str]       =			FlaxLogitsProcessorList(
           [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]				)
       lowercase :       Tuple       =			processor(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)

       # scores should be equal
       self.assertTrue(jnp.allclose(lowerCAmelCase__				,						lowerCAmelCase__				,						atol=1E-3				)				)

       # input_ids should never be changed
       self.assertListEqual(input_ids.tolist()				,						input_ids_comp.tolist()				)






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






       """simple docstring"""







       lowercase :       Dict       =			4
       lowercase :       int       =			10
       lowercase :       Any       =			15
       lowercase :       List[Any]       =			2
       lowercase :       Any       =			1
       lowercase :       Optional[int]       =			15

       # dummy input_ids and scores
       lowercase :       List[Any]       =			ids_tensor((batch_size, sequence_length)				,						lowerCAmelCase__				)
       lowercase :       List[str]       =			input_ids.copy()

       lowercase :       Tuple       =			self._get_uniform_logits(lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       List[Any]       =			scores.copy()

       # instantiate all dist processors
       lowercase :       Any       =			FlaxTemperatureLogitsWarper(temperature=0.5				)
       lowercase :       Dict       =			FlaxTopKLogitsWarper(3				)
       lowercase :       List[str]       =			FlaxTopPLogitsWarper(0.8				)

       # instantiate all logits processors
       lowercase :       str       =			FlaxMinLengthLogitsProcessor(min_length=10				,						eos_token_id=lowerCAmelCase__				)
       lowercase :       int       =			FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowerCAmelCase__				)
       lowercase :       Union[str, Any]       =			FlaxForcedEOSTokenLogitsProcessor(max_length=lowerCAmelCase__				,						eos_token_id=lowerCAmelCase__				)

       lowercase :       Dict       =			10

       # no processor list
       def run_no_processor_list(_A		:     Dict				,						_A		:     int				,						_A		:     Optional[int]				):
            lowercase :       List[str]       =			temp_dist_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
            lowercase :       Dict       =			top_k_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
            lowercase :       List[Any]       =			top_p_warp(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
            lowercase :       Union[str, Any]       =			min_dist_proc(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
            lowercase :       List[str]       =			bos_dist_proc(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
            lowercase :       int       =			eos_dist_proc(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
            return scores

       # with processor list
       def run_processor_list(_A		:     str				,						_A		:     str				,						_A		:     List[str]				):
            lowercase :       Union[str, Any]       =			FlaxLogitsProcessorList(
                [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]				)
            lowercase :       Dict       =			processor(lowerCAmelCase__				,						lowerCAmelCase__				,						cur_len=lowerCAmelCase__				)
            return scores

       lowercase :       Any       =			jax.jit(lowerCAmelCase__				)
       lowercase :       List[str]       =			jax.jit(lowerCAmelCase__				)

       lowercase :       Tuple       =			jitted_run_no_processor_list(lowerCAmelCase__				,						lowerCAmelCase__				,						lowerCAmelCase__				)
       lowercase :       Dict       =			jitted_run_processor_list(lowerCAmelCase__				,						lowerCAmelCase__				,						lowerCAmelCase__				)

       # scores should be equal
       self.assertTrue(jnp.allclose(lowerCAmelCase__				,						lowerCAmelCase__				,						atol=1E-3				)				)

       # input_ids should never be changed
       self.assertListEqual(input_ids.tolist()				,						input_ids_comp.tolist()				)





import os
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


lowerCAmelCase_						=			logging.get_logger(__name__)

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

lowerCAmelCase_						=			{
    'vocab_file': {
        'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model',
        'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model',
        'moussaKam/barthez-orangesum-title': (
            'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model'
        ),
    },
}

lowerCAmelCase_						=			{
    'moussaKam/mbarthez': 10_24,
    'moussaKam/barthez': 10_24,
    'moussaKam/barthez-orangesum-title': 10_24,
}

lowerCAmelCase_						=			'▁'
class 						_A (  _lowerCamelCase				):
  _UpperCamelCase       :      Optional[Any]			=      VOCAB_FILES_NAMES
  _UpperCamelCase       :      Union[str, Any]			=      PRETRAINED_VOCAB_FILES_MAP
  _UpperCamelCase       :      Optional[Any]			=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  _UpperCamelCase       :      List[Any]			=      ['''input_ids''', '''attention_mask''']






  def __init__(  self		:     Any				,						_A		:     Optional[int]				,						_A		:     List[str]="<s>"				,						_A		:     Tuple="</s>"				,						_A		:     Dict="</s>"				,						_A		:     Dict="<s>"				,						_A		:     List[str]="<unk>"				,						_A		:     str="<pad>"				,						_A		:     Any="<mask>"				,						_A		:     Optional[Dict[str, Any]] = None				,						**_A		:     Union[str, Any]				,						)		->   None:






       """simple docstring"""







       lowercase :       List[str]       =			AddedToken(_A				,						lstrip=_A				,						rstrip=_A				) if isinstance(_A				,						_A				) else mask_token

       lowercase :       List[Any]       =			{} if sp_model_kwargs is None else sp_model_kwargs

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

       lowercase :       Any       =			vocab_file
       lowercase :       Any       =			spm.SentencePieceProcessor(**self.sp_model_kwargs				)
       self.sp_model.Load(str(_A				)				)

       lowercase :       Optional[Any]       =			{'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

       lowercase :       Tuple       =			len(self.sp_model				) - 1
       lowercase :       Any       =			{v: k for k, v in self.fairseq_tokens_to_ids.items()}






  def  __a      (  self		:     Tuple				,						_A		:     List[int]				,						_A		:     Optional[List[int]] = None				)		->   List[int]:






       """simple docstring"""







       if token_ids_a is None:
            return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
       lowercase :       Any       =			[self.cls_token_id]
       lowercase :       int       =			[self.sep_token_id]
       return cls + token_ids_a + sep + sep + token_ids_a + sep






  def  __a      (  self		:     Optional[int]				,						_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				)

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






  def  __a      (  self		:     Optional[int]				,						_A		:     List[int]				,						_A		:     Optional[List[int]] = None				)		->   List[int]:






       """simple docstring"""







       lowercase :       List[str]       =			[self.sep_token_id]
       lowercase :       List[str]       =			[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 + sep + token_ids_a + sep				) * [0]






  @property
  def  __a      (  self		:     List[Any]				)		->   Optional[Any]:






       """simple docstring"""







       return len(self.sp_model				)






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






       """simple docstring"""







       lowercase :       int       =			{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		:     Union[str, Any]				,						_A		:     str				)		->   List[str]:






       """simple docstring"""







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






  def  __a      (  self		:     Optional[int]				,						_A		:     str				)		->   Dict:






       """simple docstring"""







       if token in self.fairseq_tokens_to_ids:
            return self.fairseq_tokens_to_ids[token]
       lowercase :       Optional[int]       =			self.sp_model.PieceToId(_A				)

       return spm_id if spm_id else self.unk_token_id






  def  __a      (  self		:     Any				,						_A		:     List[str]				)		->   List[str]:






       """simple docstring"""







       if index in self.fairseq_ids_to_tokens:
            return self.fairseq_ids_to_tokens[index]
       return self.sp_model.IdToPiece(_A				)






  def  __a      (  self		:     Any				,						_A		:     Tuple				)		->   Tuple:






       """simple docstring"""







       lowercase :       Dict       =			[]
       lowercase :       Any       =			''''''
       lowercase :       str       =			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
                 lowercase :       int       =			True
                 lowercase :       Optional[Any]       =			[]
            else:
                 current_sub_tokens.append(_A				)
                 lowercase :       List[str]       =			False
       out_string += self.sp_model.decode(_A				)
       return out_string.strip()






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






       """simple docstring"""







       lowercase :       str       =			self.__dict__.copy()
       lowercase :       Any       =			None
       return state






  def __setstate__(  self		:     Optional[int]				,						_A		:     Tuple				)		->   str:






       """simple docstring"""







       lowercase :       List[str]       =			d

       # for backward compatibility
       if not hasattr(self				,						'''sp_model_kwargs'''				):
            lowercase :       Union[str, Any]       =			{}

       lowercase :       List[Any]       =			spm.SentencePieceProcessor(**self.sp_model_kwargs				)
       self.sp_model.Load(self.vocab_file				)






  def  __a      (  self		:     str				,						_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
       lowercase :       Any       =			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:
                 lowercase :       Optional[Any]       =			self.sp_model.serialized_model_proto()
                 fi.write(_A				)

       return (out_vocab_file,)