




"""simple docstring"""




import os
import unicodedata
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 SPIECE_UNDERLINE, logging


lowerCAmelCase							:			Dict     							=							logging.get_logger(__name__)

lowerCAmelCase							:			Any     							=							{"""vocab_file""": """spiece.model"""}

lowerCAmelCase							:			int     							=							{
    """vocab_file""": {
        """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model""",
        """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model""",
    }
}

lowerCAmelCase							:			Union[str, Any]     							=							{
    """xlnet-base-cased""": None,
    """xlnet-large-cased""": None,
}

# Segments (not really needed)
lowerCAmelCase							:			List[str]     							=							0
lowerCAmelCase							:			Tuple     							=							1
lowerCAmelCase							:			List[Any]     							=							2
lowerCAmelCase							:			Optional[int]     							=							3
lowerCAmelCase							:			Tuple     							=							4






class     __magic_name__							(       _UpperCAmelCase				):






				'''simple docstring'''
				__UpperCamelCase			  =						VOCAB_FILES_NAMES
				__UpperCamelCase			  =						PRETRAINED_VOCAB_FILES_MAP
				__UpperCamelCase			  =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				__UpperCamelCase			  =						"left"





				def __init__(       self		, _a		, _a=False		, _a=True		, _a=False		, _a="<s>"		, _a="</s>"		, _a="<unk>"		, _a="<sep>"		, _a="<pad>"		, _a="<cls>"		, _a="<mask>"		, _a=["<eop>", "<eod>"]		, _a = None		, **_a		, ):





							"""simple docstring"""
							lowerCamelCase			      =					AddedToken(lowercase_		, lstrip=lowercase_		, rstrip=lowercase_ ) if isinstance(lowercase_		, lowercase_ ) else mask_token

							lowerCamelCase			      =					{} if sp_model_kwargs is None else sp_model_kwargs

							super().__init__(
							    do_lower_case=lowercase_		, remove_space=lowercase_		, keep_accents=lowercase_		, bos_token=lowercase_		, eos_token=lowercase_		, unk_token=lowercase_		, sep_token=lowercase_		, pad_token=lowercase_		, cls_token=lowercase_		, mask_token=lowercase_		, additional_special_tokens=lowercase_		, sp_model_kwargs=self.sp_model_kwargs		, **lowercase_		, )

							lowerCamelCase			      =					3

							lowerCamelCase			      =					do_lower_case
							lowerCamelCase			      =					remove_space
							lowerCamelCase			      =					keep_accents
							lowerCamelCase			      =					vocab_file

							lowerCamelCase			      =					spm.SentencePieceProcessor(**self.sp_model_kwargs )
							self.sp_model.Load(lowercase_ )





				@property
				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							return len(self.sp_model )





				def    _lowerCAmelCase				(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					{self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )}
							vocab.update(self.added_tokens_encoder )
							return vocab





				def __getstate__(       self ):





							"""simple docstring"""
							lowerCamelCase			      =					self.__dict__.copy()
							lowerCamelCase			      =					None
							return state





				def __setstate__(       self		, _a ):





							"""simple docstring"""
							lowerCamelCase			      =					d

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

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





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""







							if self.remove_space:
										lowerCamelCase			      =					""" """.join(inputs.strip().split() )
							else:
										lowerCamelCase			      =					inputs
							lowerCamelCase			      =					outputs.replace("""``"""		, """\"""" ).replace("""\'\'"""		, """\"""" )

							if not self.keep_accents:
										lowerCamelCase			      =					unicodedata.normalize("""NFKD"""		, lowercase_ )
										lowerCamelCase			      =					"""""".join([c for c in outputs if not unicodedata.combining(lowercase_ )] )
							if self.do_lower_case:
										lowerCamelCase			      =					outputs.lower()

							return outputs





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							lowerCamelCase			      =					self.preprocess_text(lowercase_ )
							lowerCamelCase			      =					self.sp_model.encode(lowercase_		, out_type=lowercase_ )
							lowerCamelCase			      =					[]
							for piece in pieces:
										if len(lowercase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit():
													lowerCamelCase			      =					self.sp_model.EncodeAsPieces(piece[:-1].replace(lowercase_		, """""" ) )
													if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
																if len(cur_pieces[0] ) == 1:
																			lowerCamelCase			      =					cur_pieces[1:]
																else:
																			lowerCamelCase			      =					cur_pieces[0][1:]
													cur_pieces.append(piece[-1] )
													new_pieces.extend(lowercase_ )
										else:
													new_pieces.append(lowercase_ )

							return new_pieces





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							return self.sp_model.PieceToId(lowercase_ )





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							return self.sp_model.IdToPiece(lowercase_ )





				def    _lowerCAmelCase				(       self		, _a ):





							"""simple docstring"""
							lowerCamelCase			      =					"""""".join(lowercase_ ).replace(lowercase_		, """ """ ).strip()
							return out_string





				def    _lowerCAmelCase				(       self		, _a		, _a = False		, _a = None		, _a = True		, **_a		, ):





							"""simple docstring"""
							lowerCamelCase			      =					kwargs.pop("""use_source_tokenizer"""		, lowercase_ )

							lowerCamelCase			      =					self.convert_ids_to_tokens(lowercase_		, skip_special_tokens=lowercase_ )

							# 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
							lowerCamelCase			      =					[]
							lowerCamelCase			      =					[]
							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(lowercase_ ) )
																lowerCamelCase			      =					[]
													sub_texts.append(lowercase_ )
										else:
													current_sub_text.append(lowercase_ )
							if current_sub_text:
										sub_texts.append(self.convert_tokens_to_string(lowercase_ ) )

							# Mimic the behavior of the Rust tokenizer:
							# By default, there are no spaces between special tokens
							lowerCamelCase			      =					"""""".join(lowercase_ )

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





				def    _lowerCAmelCase				(       self		, _a		, _a = None ):





							"""simple docstring"""
							lowerCamelCase			      =					[self.sep_token_id]
							lowerCamelCase			      =					[self.cls_token_id]
							if token_ids_a is None:
										return token_ids_a + sep + cls
							return token_ids_a + sep + token_ids_a + sep + cls





				def    _lowerCAmelCase				(       self		, _a		, _a = None		, _a = False ):





							"""simple docstring"""







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

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





				def    _lowerCAmelCase				(       self		, _a		, _a = None ):





							"""simple docstring"""
							lowerCamelCase			      =					[self.sep_token_id]
							lowerCamelCase			      =					[2]

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





				def    _lowerCAmelCase				(       self		, _a		, _a = None ):





							"""simple docstring"""







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

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

							return (out_vocab_file,)






from timeit import timeit
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	int      )							->      int:





    '''simple docstring'''






    if number < 0:
        raise ValueError('the value of input must not be negative'      )
    A__          =   0
    while number:
        number &= number - 1
        result += 1
    return result
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	int      )							->      int:





    '''simple docstring'''






    if number < 0:
        raise ValueError('the value of input must not be negative'      )
    A__          =   0
    while number:
        if number % 2 == 1:
            result += 1
        number >>= 1
    return result
def 						_snake_case(    )							->      None:





    '''simple docstring'''






    def do_benchmark(SCREAMING_SNAKE_CASE__			:	int      ) -> None:
        A__          =   'import __main__ as z'
        print(f'Benchmark when {number = }:'      )
        print(f'{get_set_bits_count_using_modulo_operator(SCREAMING_SNAKE_CASE__      ) = }'      )
        A__          =   timeit('z.get_set_bits_count_using_modulo_operator(25)'    ,			setup=SCREAMING_SNAKE_CASE__      )
        print(f'timeit() runs in {timing} seconds'      )
        print(f'{get_set_bits_count_using_brian_kernighans_algorithm(SCREAMING_SNAKE_CASE__      ) = }'      )
        A__          =   timeit(
            'z.get_set_bits_count_using_brian_kernighans_algorithm(25)'    ,			setup=SCREAMING_SNAKE_CASE__    ,			)
        print(f'timeit() runs in {timing} seconds'      )

    for number in (25, 37, 58, 0):
        do_benchmark(SCREAMING_SNAKE_CASE__      )
        print()


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     benchmark()

