





'''simple docstring'''







import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch





def        lowerCamelCase_      (  SCREAMING_SNAKE_CASE__      :			str   ) ->	List[Any]:  # picklable for multiprocessing
						return x.sum()





def        lowerCamelCase_      (  SCREAMING_SNAKE_CASE__      :			Any   ) ->	List[Any]:  # picklable for multiprocessing
						return i + 1


@dataclass
class 					__a      :
							__a					:   int
							__a					:   str





class 					__a      (lowerCamelCase     ):

							def     UpperCAmelCase__	(							self							:     Tuple   )					->       int:







													"""simple docstring"""
													UpperCAmelCase_			:      List[str]     						=  {}
													UpperCAmelCase_			:      List[Any]     						=  []
													UpperCAmelCase_			:      str     						=  1
													UpperCAmelCase_			:      int     						=  [1, 2]
													UpperCAmelCase_			:      str     						=  {'''a''': 1, '''b''': 2}
													UpperCAmelCase_			:      str     						=  {'''a''': [1, 2], '''b''': [3, 4]}
													UpperCAmelCase_			:      str     						=  {'''a''': {'''1''': 1}, '''b''': 2}
													UpperCAmelCase_			:      List[str]     						=  {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4}
													UpperCAmelCase_			:      Dict     						=  {}
													UpperCAmelCase_			:      Optional[int]     						=  []
													UpperCAmelCase_			:      Optional[int]     						=  2
													UpperCAmelCase_			:      Optional[Any]     						=  [2, 3]
													UpperCAmelCase_			:      List[str]     						=  {'''a''': 2, '''b''': 3}
													UpperCAmelCase_			:      int     						=  {'''a''': [2, 3], '''b''': [4, 5]}
													UpperCAmelCase_			:      List[str]     						=  {'''a''': {'''1''': 2}, '''b''': 3}
													UpperCAmelCase_			:      Optional[int]     						=  {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5}
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__   )       ,     __magic_name__   )

													UpperCAmelCase_			:      Dict     						=  2
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )

													UpperCAmelCase_			:      Optional[int]     						=  {'''a''': np.eye(2   ), '''b''': np.zeros(3   ), '''c''': np.ones(2   )}
													UpperCAmelCase_			:      str     						=  {'''a''': 2, '''b''': 0, '''c''': 2}
													UpperCAmelCase_			:      int     						=  {
													    '''a''': np.eye(2   ).astype(__magic_name__   ),
													    '''b''': np.zeros(3   ).astype(__magic_name__   ),
													    '''c''': np.ones(2   ).astype(__magic_name__   ),
													}
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     map_numpy=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(
													    {k: v.tolist() for k, v in map_nested(__magic_name__       ,     __magic_name__       ,     map_numpy=__magic_name__   ).items()}       ,     {k: v.tolist() for k, v in expected_map_nested_sna_int.items()}       ,     )
													self.assertEqual(map_nested(__magic_name__       ,     __magic_name__       ,     map_numpy=__magic_name__       ,     num_proc=__magic_name__   )       ,     __magic_name__   )
													self.assertEqual(
													    {k: v.tolist() for k, v in map_nested(__magic_name__       ,     __magic_name__       ,     map_numpy=__magic_name__       ,     num_proc=__magic_name__   ).items()}       ,     {k: v.tolist() for k, v in expected_map_nested_sna_int.items()}       ,     )
													with self.assertRaises(__magic_name__   ):  # can't pickle a local lambda
																			map_nested(lambda __magic_name__   : x + 1       ,     __magic_name__       ,     num_proc=__magic_name__   )

							def     UpperCAmelCase__	(							self							:     Dict   )					->       int:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  {'''a''': 1, '''b''': 2}
													UpperCAmelCase_			:      Optional[int]     						=  {'''a''': 3, '''b''': 4}
													UpperCAmelCase_			:      Optional[int]     						=  {'''a''': 5, '''b''': 6}
													UpperCAmelCase_			:      Optional[int]     						=  sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))]   )
													self.assertEqual(sorted(zip_dict(__magic_name__       ,     __magic_name__       ,     __magic_name__   )   )       ,     __magic_name__   )



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







													"""simple docstring"""


													class 					__a      :
																				__a					:   List[str]									=       "bar"





													UpperCAmelCase_			:      Union[str, Any]     						=  Foo()
													self.assertEqual(foo.my_attr       ,     '''bar'''   )
													with temporary_assignment(__magic_name__       ,     '''my_attr'''       ,     '''BAR'''   ):
																			self.assertEqual(foo.my_attr       ,     '''BAR'''   )
													self.assertEqual(foo.my_attr       ,     '''bar'''   )





@pytest.mark.parametrize(
    '''iterable_length, num_proc, expected_num_proc''',			[
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ],			)
def        lowerCamelCase_      (  SCREAMING_SNAKE_CASE__      :			str,			SCREAMING_SNAKE_CASE__      :			Dict,			SCREAMING_SNAKE_CASE__      :			Union[str, Any]   ) ->	Optional[Any]:
						with patch('''datasets.utils.py_utils._single_map_nested'''   ) as mock_single_map_nested, patch(
						    '''datasets.parallel.parallel.Pool'''   ) as mock_multiprocessing_pool:
												UpperCAmelCase_			:      List[str]     						=  {F"""{i}""": i for i in range(SCREAMING_SNAKE_CASE__   )}
												UpperCAmelCase_			:      int     						=  map_nested(lambda SCREAMING_SNAKE_CASE__   : x + 10,			SCREAMING_SNAKE_CASE__,			num_proc=SCREAMING_SNAKE_CASE__,			parallel_min_length=16   )
												if expected_num_proc == 1:
																		assert mock_single_map_nested.called
																		assert not mock_multiprocessing_pool.called
												else:
																		assert not mock_single_map_nested.called
																		assert mock_multiprocessing_pool.called
																		assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc


class 					__a      (lowerCamelCase     ):

							@require_tf
							def     UpperCAmelCase__	(							self							:     str   )					->       List[str]:







													"""simple docstring"""
													import tensorflow as tf
													from tensorflow.keras import layers

													UpperCAmelCase_			:      int     						=  layers.Dense(2   )

													def gen_random_output():
																			UpperCAmelCase_			:      int     						=  tf.random.uniform((1, 3)   )
																			return model(__magic_name__   ).numpy()

													with temp_seed(42       ,     set_tensorflow=__magic_name__   ):
																			UpperCAmelCase_			:      int     						=  gen_random_output()
													with temp_seed(42       ,     set_tensorflow=__magic_name__   ):
																			UpperCAmelCase_			:      List[Any]     						=  gen_random_output()
													UpperCAmelCase_			:      Optional[int]     						=  gen_random_output()

													np.testing.assert_equal(__magic_name__       ,     __magic_name__   )
													self.assertGreater(np.abs(outa - outa   ).sum()       ,     0   )

							@require_torch
							def     UpperCAmelCase__	(							self							:     Optional[int]   )					->       str:







													"""simple docstring"""
													import torch

													def gen_random_output():
																			UpperCAmelCase_			:      Optional[Any]     						=  torch.nn.Linear(3       ,     2   )
																			UpperCAmelCase_			:      Tuple     						=  torch.rand(1       ,     3   )
																			return model(__magic_name__   ).detach().numpy()

													with temp_seed(42       ,     set_pytorch=__magic_name__   ):
																			UpperCAmelCase_			:      Union[str, Any]     						=  gen_random_output()
													with temp_seed(42       ,     set_pytorch=__magic_name__   ):
																			UpperCAmelCase_			:      List[Any]     						=  gen_random_output()
													UpperCAmelCase_			:      List[Any]     						=  gen_random_output()

													np.testing.assert_equal(__magic_name__       ,     __magic_name__   )
													self.assertGreater(np.abs(outa - outa   ).sum()       ,     0   )



							def     UpperCAmelCase__	(							self							:     str   )					->       Optional[Any]:







													"""simple docstring"""
													def gen_random_output():
																			return np.random.rand(1       ,     3   )

													with temp_seed(42   ):
																			UpperCAmelCase_			:      List[str]     						=  gen_random_output()
													with temp_seed(42   ):
																			UpperCAmelCase_			:      List[str]     						=  gen_random_output()
													UpperCAmelCase_			:      str     						=  gen_random_output()

													np.testing.assert_equal(__magic_name__       ,     __magic_name__   )
													self.assertGreater(np.abs(outa - outa   ).sum()       ,     0   )





@pytest.mark.parametrize('''input_data''',			[{}]   )
def        lowerCamelCase_      (  SCREAMING_SNAKE_CASE__      :			Any   ) ->	str:
						UpperCAmelCase_			:      List[str]     						=  NestedDataStructure(SCREAMING_SNAKE_CASE__   ).data
						assert output_data == input_data





@pytest.mark.parametrize(
    '''data, expected_output''',			[
        ({}, []),
        ([], []),
        ('''foo''', ['''foo''']),
        (['''foo''', '''bar'''], ['''foo''', '''bar''']),
        ([['''foo''', '''bar''']], ['''foo''', '''bar''']),
        ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']),
        ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']),
        ({'''a''': 1, '''b''': 2}, [1, 2]),
        ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]),
        ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]),
        ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]),
        ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]),
        ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]),
    ],			)
def        lowerCamelCase_      (  SCREAMING_SNAKE_CASE__      :			int,			SCREAMING_SNAKE_CASE__      :			str   ) ->	Optional[Any]:
						UpperCAmelCase_			:      List[str]     						=  NestedDataStructure(SCREAMING_SNAKE_CASE__   ).flatten()
						assert output == expected_output





def        lowerCamelCase_      (  ) ->	Dict:
						UpperCAmelCase_			:      Union[str, Any]     						=  A(x=1,			y='''foobar'''   )
						UpperCAmelCase_			:      int     						=  {'''x''': 1, '''y''': '''foobar'''}
						assert asdict(SCREAMING_SNAKE_CASE__   ) == expected_output

						UpperCAmelCase_			:      Tuple     						=  {'''a''': {'''b''': A(x=10,			y='''foo'''   )}, '''c''': [A(x=20,			y='''bar'''   )]}
						UpperCAmelCase_			:      List[Any]     						=  {'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]}
						assert asdict(SCREAMING_SNAKE_CASE__   ) == expected_output

						with pytest.raises(SCREAMING_SNAKE_CASE__   ):
												asdict([1, A(x=10,			y='''foo'''   )]   )





def        lowerCamelCase_      (  SCREAMING_SNAKE_CASE__      :			str   ) ->	Optional[int]:
						return text.split()





def        lowerCamelCase_      (  SCREAMING_SNAKE_CASE__      :			str   ) ->	Optional[int]:
						yield (time.time(), content)
						time.sleep(2   )
						yield (time.time(), content)





def        lowerCamelCase_      (  ) ->	Optional[int]:
						with Pool(2   ) as pool:
												UpperCAmelCase_			:      List[Any]     						=  list(iflatmap_unordered(SCREAMING_SNAKE_CASE__,			_split_text,			kwargs_iterable=[{'''text''': '''hello there'''}] * 10   )   )
												assert out.count('''hello'''   ) == 10
												assert out.count('''there'''   ) == 10
												assert len(SCREAMING_SNAKE_CASE__   ) == 20

						# check multiprocess from pathos (uses dill for pickling)
						with multiprocess.Pool(2   ) as pool:
												UpperCAmelCase_			:      Optional[int]     						=  list(iflatmap_unordered(SCREAMING_SNAKE_CASE__,			_split_text,			kwargs_iterable=[{'''text''': '''hello there'''}] * 10   )   )
												assert out.count('''hello'''   ) == 10
												assert out.count('''there'''   ) == 10
												assert len(SCREAMING_SNAKE_CASE__   ) == 20

						# check that we get items as fast as possible
						with Pool(2   ) as pool:
												UpperCAmelCase_			:      str     						=  []
												for yield_time, content in iflatmap_unordered(
												    SCREAMING_SNAKE_CASE__,			_aseconds_generator_of_aitems_with_timing,			kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}]   ):
																		assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
																		out.append(SCREAMING_SNAKE_CASE__   )
												assert out.count('''a'''   ) == 2
												assert out.count('''b'''   ) == 2
												assert len(SCREAMING_SNAKE_CASE__   ) == 4












'''simple docstring'''







import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


snake_case_     :       str						=  logging.get_logger(__name__)

snake_case_     :       int						=  "▁"

snake_case_     :       str						=  {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"}

snake_case_     :       int						=  {
    "sentencepiece_model_file": "sentencepiece.bpe.model",
    "vocab_file": "vocab.txt",
}

snake_case_     :       Optional[Any]						=  {
    "vocab_file": {
        "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt",
        "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt",
    },
    "sentencepiece_model_file": {
        "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model",
        "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model",
    },
}

snake_case_     :       Dict						=  {
    "ernie-m-base": 5_14,
    "ernie-m-large": 5_14,
}

snake_case_     :       Any						=  {
    "ernie-m-base": {"do_lower_case": False},
    "ernie-m-large": {"do_lower_case": False},
}


class 					__a      (lowerCamelCase     ):
							__a					:   List[str]									=       ["input_ids"]

							__a					:   Union[str, Any]									=       VOCAB_FILES_NAMES
							__a					:   Tuple									=       PRETRAINED_INIT_CONFIGURATION
							__a					:   Dict									=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							__a					:   Optional[int]									=       PRETRAINED_VOCAB_FILES_MAP
							__a					:   Union[str, Any]									=       RESOURCE_FILES_NAMES

							def __init__(							self							:     Union[str, Any]       ,     __magic_name__							:     Dict       ,     __magic_name__							:     int=None       ,     __magic_name__							:     str=False       ,     __magic_name__							:     int="utf8"       ,     __magic_name__							:     Optional[int]="[UNK]"       ,     __magic_name__							:     Dict="[SEP]"       ,     __magic_name__							:     List[Any]="[PAD]"       ,     __magic_name__							:     str="[CLS]"       ,     __magic_name__							:     Optional[int]="[MASK]"       ,     __magic_name__							:     Optional[Dict[str, Any]] = None       ,     **__magic_name__							:     Union[str, Any]       ,     )					->       None:







													"""simple docstring"""
													# Mask token behave like a normal word, i.e. include the space before it and
													# is included in the raw text, there should be a match in a non-normalized sentence.

													UpperCAmelCase_			:      List[Any]     						=  {} if sp_model_kwargs is None else sp_model_kwargs
													super().__init__(
													    do_lower_case=__magic_name__       ,     unk_token=__magic_name__       ,     sep_token=__magic_name__       ,     pad_token=__magic_name__       ,     cls_token=__magic_name__       ,     mask_token=__magic_name__       ,     vocab_file=__magic_name__       ,     encoding=__magic_name__       ,     sp_model_kwargs=self.sp_model_kwargs       ,     **__magic_name__       ,     )
													UpperCAmelCase_			:      Optional[Any]     						=  do_lower_case
													UpperCAmelCase_			:      List[str]     						=  sentencepiece_model_ckpt
													UpperCAmelCase_			:      Tuple     						=  spm.SentencePieceProcessor(**self.sp_model_kwargs   )
													self.sp_model.Load(__magic_name__   )

													# to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
													if vocab_file is not None:
																			UpperCAmelCase_			:      List[Any]     						=  self.load_vocab(filepath=__magic_name__   )
													else:
																			UpperCAmelCase_			:      str     						=  {self.sp_model.id_to_piece(__magic_name__   ): id for id in range(self.sp_model.get_piece_size()   )}
													UpperCAmelCase_			:      int     						=  {v: k for k, v in self.vocab.items()}

							def     UpperCAmelCase__	(							self							:     List[str]       ,     __magic_name__							:     Any   )					->       Any:







													"""simple docstring"""
													if text is None:
																			return None

													UpperCAmelCase_			:      str     						=  self.tokenize(__magic_name__   )
													UpperCAmelCase_						,       UpperCAmelCase_			:      str     						=  '''''', []

													for i, ch in enumerate(__magic_name__   ):
																			if ch in self.SP_CHAR_MAPPING:
																									UpperCAmelCase_			:      Optional[int]     						=  self.SP_CHAR_MAPPING.get(__magic_name__   )
																			else:
																									UpperCAmelCase_			:      Union[str, Any]     						=  unicodedata.normalize('''NFKC'''       ,     __magic_name__   )
																			if self.is_whitespace(__magic_name__   ):
																									continue
																			normalized_text += ch
																			char_mapping.extend([i] * len(__magic_name__   )   )

													UpperCAmelCase_						,       UpperCAmelCase_						,       UpperCAmelCase_			:      Union[str, Any]     						=  normalized_text, [], 0

													if self.do_lower_case:
																			UpperCAmelCase_			:      Optional[int]     						=  text.lower()

													for token in split_tokens:
																			if token[:1] == "▁":
																									UpperCAmelCase_			:      Tuple     						=  token[1:]
																			UpperCAmelCase_			:      int     						=  text[offset:].index(__magic_name__   ) + offset
																			UpperCAmelCase_			:      Optional[int]     						=  start + len(__magic_name__   )

																			token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)   )
																			UpperCAmelCase_			:      int     						=  end
													return token_mapping

							@property
							def     UpperCAmelCase__	(							self							:     Any   )					->       Any:







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

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







													"""simple docstring"""
													return dict(self.vocab       ,     **self.added_tokens_encoder   )

							def __getstate__(							self							:     str   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  self.__dict__.copy()
													UpperCAmelCase_			:      Optional[Any]     						=  None
													return state

							def __setstate__(							self							:     str       ,     __magic_name__							:     Any   )					->       Dict:







													"""simple docstring"""
													UpperCAmelCase_			:      Dict     						=  d

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

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

							def     UpperCAmelCase__	(							self							:     Optional[int]       ,     __magic_name__							:     Any   )					->       List[str]:







													"""simple docstring"""
													return "".join((self.SP_CHAR_MAPPING.get(__magic_name__       ,     __magic_name__   ) for c in text)   )

							def     UpperCAmelCase__	(							self							:     List[str]       ,     __magic_name__							:     Tuple       ,     __magic_name__							:     Any=False       ,     __magic_name__							:     List[str]=64       ,     __magic_name__							:     List[str]=0.1   )					->       List[str]:







													"""simple docstring"""

													if self.sp_model_kwargs.get('''enable_sampling'''   ) is True:
																			UpperCAmelCase_			:      Dict     						=  True
													if self.sp_model_kwargs.get('''alpha'''   ) is not None:
																			UpperCAmelCase_			:      Union[str, Any]     						=  self.sp_model_kwargs.get('''alpha'''   )
													if self.sp_model_kwargs.get('''nbest_size'''   ) is not None:
																			UpperCAmelCase_			:      Any     						=  self.sp_model_kwargs.get('''nbest_size'''   )

													if not enable_sampling:
																			UpperCAmelCase_			:      Dict     						=  self.sp_model.EncodeAsPieces(__magic_name__   )
													else:
																			UpperCAmelCase_			:      Dict     						=  self.sp_model.SampleEncodeAsPieces(__magic_name__       ,     __magic_name__       ,     __magic_name__   )
													UpperCAmelCase_			:      List[Any]     						=  []
													for pi, piece in enumerate(__magic_name__   ):
																			if piece == SPIECE_UNDERLINE:
																									if not pieces[pi + 1].startswith(__magic_name__   ) and pi != 0:
																															new_pieces.append(__magic_name__   )
																															continue
																									else:
																															continue
																			UpperCAmelCase_			:      List[str]     						=  0
																			for i, chunk in enumerate(__magic_name__   ):
																									if chunk == SPIECE_UNDERLINE:
																															continue
																									if self.is_ch_char(__magic_name__   ) or self.is_punct(__magic_name__   ):
																															if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
																																					new_pieces.append(piece[lst_i:i]   )
																															new_pieces.append(__magic_name__   )
																															UpperCAmelCase_			:      List[Any]     						=  i + 1
																									elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
																															if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
																																					new_pieces.append(piece[lst_i:i]   )
																															UpperCAmelCase_			:      List[str]     						=  i
																									elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
																															if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
																																					new_pieces.append(piece[lst_i:i]   )
																															UpperCAmelCase_			:      str     						=  i
																			if len(__magic_name__   ) > lst_i:
																									new_pieces.append(piece[lst_i:]   )
													return new_pieces

							def     UpperCAmelCase__	(							self							:     List[Any]       ,     __magic_name__							:     Optional[int]   )					->       List[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  ''''''.join(__magic_name__   ).replace(__magic_name__       ,     ''' '''   ).strip()
													return out_string

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







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  self.convert_ids_to_tokens(__magic_name__   )
													UpperCAmelCase_			:      Optional[Any]     						=  ''''''.join(__magic_name__   ).replace(__magic_name__       ,     ''' '''   ).strip()
													return out_string

							def     UpperCAmelCase__	(							self							:     str       ,     __magic_name__							:     Optional[Any]   )					->       List[Any]:







													"""simple docstring"""
													return self.vocab.get(__magic_name__       ,     self.vocab.get(self.unk_token   )   )

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







													"""simple docstring"""
													return self.reverse_vocab.get(__magic_name__       ,     self.unk_token   )

							def     UpperCAmelCase__	(							self							:     Tuple       ,     __magic_name__							:     Any       ,     __magic_name__							:     Union[str, Any]=None   )					->       Any:







													"""simple docstring"""
													if token_ids_a is None:
																			return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
													UpperCAmelCase_			:      Union[str, Any]     						=  [self.cls_token_id]
													UpperCAmelCase_			:      List[Any]     						=  [self.sep_token_id]
													return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep

							def     UpperCAmelCase__	(							self							:     Any       ,     __magic_name__							:     Optional[Any]       ,     __magic_name__							:     List[str]=None   )					->       int:







													"""simple docstring"""
													if offset_mapping_a is None:
																			return [(0, 0)] + offset_mapping_a + [(0, 0)]

													return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     Optional[Any]       ,     __magic_name__							:     List[str]=None       ,     __magic_name__							:     Optional[Any]=False   )					->       Optional[int]:







													"""simple docstring"""

													if already_has_special_tokens:
																			if token_ids_a is not None:
																									raise ValueError(
																									    '''You should not supply a second sequence if the provided sequence of '''
																									    '''ids is already formatted with special tokens for the model.'''   )
																			return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

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

							def     UpperCAmelCase__	(							self							:     List[str]       ,     __magic_name__							:     List[int]       ,     __magic_name__							:     Optional[List[int]] = None   )					->       List[int]:







													"""simple docstring"""
													# called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
													if token_ids_a is None:
																			# [CLS] X [SEP]
																			return (len(__magic_name__   ) + 2) * [0]

													# [CLS] A [SEP] [SEP] B [SEP]
													return [0] * (len(__magic_name__   ) + 1) + [1] * (len(__magic_name__   ) + 3)

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     str   )					->       Tuple:







													"""simple docstring"""
													if "\u4e00" <= char <= "\u9fff":
																			return True
													return False

							def     UpperCAmelCase__	(							self							:     int       ,     __magic_name__							:     Optional[int]   )					->       str:







													"""simple docstring"""
													if ("a" <= char <= "z") or ("A" <= char <= "Z"):
																			return True
													return False

							def     UpperCAmelCase__	(							self							:     int       ,     __magic_name__							:     Optional[Any]   )					->       Dict:







													"""simple docstring"""
													if char in ",;:.?!~，；：。？！《》【】":
																			return True
													return False

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







													"""simple docstring"""
													if char == " " or char == "\t" or char == "\n" or char == "\r":
																			return True
													if len(__magic_name__   ) == 1:
																			UpperCAmelCase_			:      Optional[Any]     						=  unicodedata.category(__magic_name__   )
																			if cat == "Zs":
																									return True
													return False

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







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  {}
													with io.open(__magic_name__       ,     '''r'''       ,     encoding='''utf-8'''   ) as f:
																			for index, line in enumerate(__magic_name__   ):
																									UpperCAmelCase_			:      List[Any]     						=  line.rstrip('''\n'''   )
																									UpperCAmelCase_			:      Dict     						=  int(__magic_name__   )

													return token_to_idx



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







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  0
													if os.path.isdir(__magic_name__   ):
																			UpperCAmelCase_			:      Any     						=  os.path.join(
																			    __magic_name__       ,     (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']   )
													else:
																			UpperCAmelCase_			:      List[str]     						=  (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory
													with open(__magic_name__       ,     '''w'''       ,     encoding='''utf-8'''   ) as writer:
																			for token, token_index in sorted(self.vocab.items()       ,     key=lambda __magic_name__   : kv[1]   ):
																									if index != token_index:
																															logger.warning(
																															    F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."""
																															    ''' Please check that the vocabulary is not corrupted!'''   )
																															UpperCAmelCase_			:      Dict     						=  token_index
																									writer.write(token + '''\n'''   )
																									index += 1

													UpperCAmelCase_			:      Union[str, Any]     						=  os.path.join(__magic_name__       ,     '''sentencepiece.bpe.model'''   )
													with open(__magic_name__       ,     '''wb'''   ) as fi:
																			UpperCAmelCase_			:      Optional[int]     						=  self.sp_model.serialized_model_proto()
																			fi.write(__magic_name__   )

													return (vocab_file,)





