





'''simple docstring'''




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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowercase__       : List[Any]         =       logging.get_logger(__name__)

lowercase__       : Tuple         =       '''▁'''

lowercase__       : Tuple         =       {'''vocab_file''': '''sentencepiece.bpe.model'''}

lowercase__       : List[str]         =       {
    '''vocab_file''': {
        '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''',
    }
}

lowercase__       : Optional[int]         =       {
    '''facebook/xglm-564M''': 20_48,
}


class 					SCREAMING_SNAKE_CASE       (UpperCamelCase_				):
     lowerCAmelCase						     =			VOCAB_FILES_NAMES
     lowerCAmelCase						     =			PRETRAINED_VOCAB_FILES_MAP
     lowerCAmelCase						     =			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowerCAmelCase						     =			['''input_ids''', '''attention_mask''']


     def __init__(		self		,      _UpperCAmelCase		,      _UpperCAmelCase="<s>"		,      _UpperCAmelCase="</s>"		,      _UpperCAmelCase="</s>"		,      _UpperCAmelCase="<s>"		,      _UpperCAmelCase="<unk>"		,      _UpperCAmelCase="<pad>"		,      _UpperCAmelCase = None		,      **_UpperCAmelCase		,      ):

          '''simple docstring'''






          __A		:					str						=			{} if sp_model_kwargs is None else sp_model_kwargs

          # Compatibility with the original tokenizer
          __A		:					Optional[Any]						=			7
          __A		:					Tuple						=			[F'<madeupword{i}>' for i in range(self.num_madeup_words)]

          __A		:					Optional[Any]						=			kwargs.get('additional_special_tokens'		,      [])
          kwargs["additional_special_tokens"] += [
              word for word in madeup_words if word not in kwargs["additional_special_tokens"]
          ]

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

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

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

          # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
          __A		:					Any						=			1

          # Mimic fairseq token-to-id alignment for the first 4 token
          __A		:					Tuple						=			{'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

          __A		:					List[Any]						=			len(self.sp_model)
          __A		:					str						=			{F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)}
          self.fairseq_tokens_to_ids.update(__SCREAMING_SNAKE_CASE)

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


     def __getstate__(		self):

          '''simple docstring'''






          __A		:					Optional[int]						=			self.__dict__.copy()
          __A		:					Union[str, Any]						=			None
          __A		:					str						=			self.sp_model.serialized_model_proto()
          return state


     def __setstate__(		self		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					Optional[int]						=			d

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

          __A		:					List[str]						=			spm.SentencePieceProcessor(**self.sp_model_kwargs)
          self.sp_model.LoadFromSerializedProto(self.sp_model_proto)


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase = None):

          '''simple docstring'''






          if token_ids_a is None:
               return [self.sep_token_id] + token_ids_a
          __A		:					List[Any]						=			[self.sep_token_id]
          return sep + token_ids_a + sep + sep + token_ids_a


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase = None		,      _UpperCAmelCase = False):

          '''simple docstring'''






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

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


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase = None):

          '''simple docstring'''






          __A		:					Tuple						=			[self.sep_token_id]

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


     @property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Tuple						=			{self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE): i for i in range(self.vocab_size)}
          vocab.update(self.added_tokens_encoder)
          return vocab


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase):

          '''simple docstring'''






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


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase):

          '''simple docstring'''






          if token in self.fairseq_tokens_to_ids:
               return self.fairseq_tokens_to_ids[token]
          __A		:					Dict						=			self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE)

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


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase):

          '''simple docstring'''






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


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					str						=			''''''.join(__SCREAMING_SNAKE_CASE).replace(__SCREAMING_SNAKE_CASE		,      ' ').strip()
          return out_string


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase = None):

          '''simple docstring'''






          if not os.path.isdir(__SCREAMING_SNAKE_CASE):
               logger.error(F'Vocabulary path ({save_directory}) should be a directory')
               return
          __A		:					Union[str, Any]						=			os.path.join(
              __SCREAMING_SNAKE_CASE		,      (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])

          if os.path.abspath(self.vocab_file) != os.path.abspath(__SCREAMING_SNAKE_CASE) and os.path.isfile(self.vocab_file):
               copyfile(self.vocab_file		,      __SCREAMING_SNAKE_CASE)
          elif not os.path.isfile(self.vocab_file):
               with open(__SCREAMING_SNAKE_CASE		,      'wb') as fi:
                    __A		:					Optional[Any]						=			self.sp_model.serialized_model_proto()
                    fi.write(__SCREAMING_SNAKE_CASE)

          return (out_vocab_file,)

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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCamelCase  =logging.get_logger(__name__)


lowerCamelCase  ="▁"

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

lowerCamelCase  ={
    "vocab_file": {
        "google/reformer-crime-and-punishment": (
            "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model"
        )
    }
}

lowerCamelCase  ={
    "google/reformer-crime-and-punishment": 5_2_4_2_8_8,
}




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     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''']






     def __init__(				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE="</s>"    ,    __SCREAMING_SNAKE_CASE="<unk>"    ,    __SCREAMING_SNAKE_CASE=[]    ,    __SCREAMING_SNAKE_CASE = None    ,    **__SCREAMING_SNAKE_CASE    ,    )	-> None:




           """simple docstring"""







           UpperCamelCase__     : int											=					{} if sp_model_kwargs is None else sp_model_kwargs

           super().__init__(
               eos_token=__SCREAMING_SNAKE_CASE    ,    unk_token=__SCREAMING_SNAKE_CASE    ,    additional_special_tokens=__SCREAMING_SNAKE_CASE    ,    sp_model_kwargs=self.sp_model_kwargs    ,    **__SCREAMING_SNAKE_CASE    ,    )

           UpperCamelCase__     : Dict											=					vocab_file
           UpperCamelCase__     : Any											=					spm.SentencePieceProcessor(**self.sp_model_kwargs	)
           self.sp_model.Load(__SCREAMING_SNAKE_CASE	)






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




           """simple docstring"""







           return self.sp_model.get_piece_size()






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Dict[str, int]:




           """simple docstring"""







           UpperCamelCase__     : Tuple											=					{self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE	): i for i in range(self.vocab_size	)}
           vocab.update(self.added_tokens_encoder	)
           return vocab






     def __getstate__(				self	)	-> Any:




           """simple docstring"""







           UpperCamelCase__     : Dict											=					self.__dict__.copy()
           UpperCamelCase__     : int											=					None
           return state






     def __setstate__(				self    ,    __SCREAMING_SNAKE_CASE	)	-> str:




           """simple docstring"""







           UpperCamelCase__     : int											=					d

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

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






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> List[str]:




           """simple docstring"""







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






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> List[str]:




           """simple docstring"""







           return self.sp_model.piece_to_id(__SCREAMING_SNAKE_CASE	)






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> List[Any]:




           """simple docstring"""







           if index < self.sp_model.get_piece_size():
                 UpperCamelCase__     : str											=					self.sp_model.IdToPiece(__SCREAMING_SNAKE_CASE	)
           return token






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> Dict:




           """simple docstring"""







           UpperCamelCase__     : List[str]											=					[]
           UpperCamelCase__     : Union[str, Any]											=					''''''
           for token in tokens:
                 # make sure that special tokens are not decoded using sentencepiece model
                 if token in self.all_special_tokens:
                       out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE	) + token
                       UpperCamelCase__     : str											=					[]
                 else:
                       current_sub_tokens.append(__SCREAMING_SNAKE_CASE	)
           out_string += self.sp_model.decode(__SCREAMING_SNAKE_CASE	)
           return out_string.strip()






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE = None	)	-> Tuple[str]:




           """simple docstring"""







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

           if os.path.abspath(self.vocab_file	) != os.path.abspath(__SCREAMING_SNAKE_CASE	) and os.path.isfile(self.vocab_file	):
                 copyfile(self.vocab_file    ,    __SCREAMING_SNAKE_CASE	)
           elif not os.path.isfile(self.vocab_file	):
                 with open(__SCREAMING_SNAKE_CASE    ,    '''wb'''	) as fi:
                       UpperCamelCase__     : int											=					self.sp_model.serialized_model_proto()
                       fi.write(__SCREAMING_SNAKE_CASE	)

           return (out_vocab_file,)


