
import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


_UpperCAmelCase      :				List[str]          = datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
							import pyspark


@dataclass
class        lowercase      (	datasets.BuilderConfig     ):
		__lowercase : List[str]			  =       None






def    A (      lowercase					, lowercase					, )     ->						Union[str, Any]:
		'''simple docstring'''

		import pyspark

		def generate_fn():
				UpperCamelCase						=  df.select('*'					, pyspark.sql.functions.spark_partition_id().alias('part_id'				)				)
				for partition_id in partition_order:
						UpperCamelCase						=  df_with_partition_id.select('*'				).where(f'''part_id = {partition_id}'''				).drop('part_id'				)
						UpperCamelCase						=  partition_df.collect()
						UpperCamelCase						=  0
						for row in rows:
								yield f'''{partition_id}_{row_id}''', row.asDict()
								row_id += 1

		return generate_fn


class        lowercase      (	_BaseExamplesIterable     ):



		def __init__(				self       ,   A_       ,   A_=None       ,   )						->      List[str]:
				"""simple docstring"""
				UpperCamelCase						=  df
				UpperCamelCase						=  partition_order or range(self.df.rdd.getNumPartitions() )
				UpperCamelCase						=  _generate_iterable_examples(self.df       ,   self.partition_order )



		def __iter__(				self )						->      List[Any]:
				"""simple docstring"""
				yield from self.generate_examples_fn()



		def __UpperCamelCase				(				self       ,   A_ )						->      int:
				"""simple docstring"""
				UpperCamelCase						=  list(range(self.df.rdd.getNumPartitions() ) )
				generator.shuffle(_lowerCAmelCase )
				return SparkExamplesIterable(self.df       ,   partition_order=_lowerCAmelCase )



		def __UpperCamelCase				(				self       ,   A_       ,   A_ )						->      Union[str, Any]:
				"""simple docstring"""
				UpperCamelCase						=  self.split_shard_indices_by_worker(_lowerCAmelCase       ,   _lowerCAmelCase )
				return SparkExamplesIterable(self.df       ,   partition_order=_lowerCAmelCase )



		@property
		def __UpperCamelCase				(				self )						->      int:
				"""simple docstring"""
				return len(self.partition_order )






class        lowercase      (	datasets.DatasetBuilder     ):
		__lowercase : Union[str, Any]			  =       SparkConfig



		def __init__(				self       ,   A_       ,   A_ = None       ,   A_ = None       ,   **A_       ,   )						->      List[str]:
				"""simple docstring"""
				import pyspark

				UpperCamelCase						=  pyspark.sql.SparkSession.builder.getOrCreate()
				UpperCamelCase						=  df
				UpperCamelCase						=  working_dir

				super().__init__(
				    cache_dir=_lowerCAmelCase       ,   config_name=str(self.df.semanticHash() )       ,   **_lowerCAmelCase       ,   )



		def __UpperCamelCase				(				self )						->      Optional[int]:
				"""simple docstring"""
				# Returns the path of the created file.
				def create_cache_and_write_probe(A_ ):
						# makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
						# already exist.
						os.makedirs(self._cache_dir       ,   exist_ok=_lowerCAmelCase )
						UpperCamelCase						=  os.path.join(self._cache_dir       ,   'fs_test' + uuid.uuida().hex )
						# Opening the file in append mode will create a new file unless it already exists, in which case it will not
						# change the file contents.
						open(_lowerCAmelCase       ,   'a' )
						return [probe_file]

				if self._spark.conf.get('spark.master'       ,   '' ).startswith('local' ):
						return

				# If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
				# accessible to the driver.
				# TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
				if self._cache_dir:
						UpperCamelCase						=  (
						    self._spark.sparkContext.parallelize(range(1 )       ,   1 ).mapPartitions(_lowerCAmelCase ).collect()
						)
						if os.path.isfile(probe[0] ):
								return

				raise ValueError(
				    'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' )



		def __UpperCamelCase				(				self )						->      int:
				"""simple docstring"""
				return datasets.DatasetInfo(features=self.config.features )



		def __UpperCamelCase				(				self       ,   A_ )						->      Tuple:
				"""simple docstring"""
				return [datasets.SplitGenerator(name=datasets.Split.TRAIN )]



		def __UpperCamelCase				(				self       ,   A_ )						->      int:
				"""simple docstring"""
				import pyspark

				def get_arrow_batch_size(A_ ):
						for batch in it:
								yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} )

				UpperCamelCase						=  self.df.count()
				UpperCamelCase						=  df_num_rows if df_num_rows <= 100 else 100
				# Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
				UpperCamelCase						=  (
				    self.df.limit(_lowerCAmelCase )
				    .repartition(1 )
				    .mapInArrow(_lowerCAmelCase       ,   'batch_bytes: long' )
				    .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) )
				    .collect()[0]
				    .sample_bytes
				    / sample_num_rows
				)
				UpperCamelCase						=  approx_bytes_per_row * df_num_rows
				if approx_total_size > max_shard_size:
						# Make sure there is at least one row per partition.
						UpperCamelCase						=  min(_lowerCAmelCase       ,   int(approx_total_size / max_shard_size ) )
						UpperCamelCase						=  self.df.repartition(_lowerCAmelCase )



		def __UpperCamelCase				(				self       ,   A_       ,   A_       ,   A_       ,   )						->      Optional[int]:
				"""simple docstring"""
				import pyspark

				UpperCamelCase						=  ParquetWriter if file_format == 'parquet' else ArrowWriter
				UpperCamelCase						=  os.path.join(self._working_dir       ,   os.path.basename(_lowerCAmelCase ) ) if self._working_dir else fpath
				UpperCamelCase						=  file_format == 'parquet'

				# Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
				# pickling the SparkContext.
				UpperCamelCase						=  self.config.features
				UpperCamelCase						=  self._writer_batch_size
				UpperCamelCase						=  self._fs.storage_options

				def write_arrow(A_ ):
						# Within the same SparkContext, no two task attempts will share the same attempt ID.
						UpperCamelCase						=  pyspark.TaskContext().taskAttemptId()
						UpperCamelCase						=  next(_lowerCAmelCase       ,   _lowerCAmelCase )
						if first_batch is None:
								# Some partitions might not receive any data.
								return pa.RecordBatch.from_arrays(
								    [[task_id], [0], [0]]       ,   names=['task_id', 'num_examples', 'num_bytes']       ,   )
						UpperCamelCase						=  0
						UpperCamelCase						=  writer_class(
						    features=_lowerCAmelCase       ,   path=working_fpath.replace('SSSSS'       ,   F'''{shard_id:05d}''' ).replace('TTTTT'       ,   F'''{task_id:05d}''' )       ,   writer_batch_size=_lowerCAmelCase       ,   storage_options=_lowerCAmelCase       ,   embed_local_files=_lowerCAmelCase       ,   )
						UpperCamelCase						=  pa.Table.from_batches([first_batch] )
						writer.write_table(_lowerCAmelCase )
						for batch in it:
								if max_shard_size is not None and writer._num_bytes >= max_shard_size:
										UpperCamelCase			,						UpperCamelCase						=  writer.finalize()
										writer.close()
										yield pa.RecordBatch.from_arrays(
										    [[task_id], [num_examples], [num_bytes]]       ,   names=['task_id', 'num_examples', 'num_bytes']       ,   )
										shard_id += 1
										UpperCamelCase						=  writer_class(
										    features=writer._features       ,   path=working_fpath.replace('SSSSS'       ,   F'''{shard_id:05d}''' ).replace('TTTTT'       ,   F'''{task_id:05d}''' )       ,   writer_batch_size=_lowerCAmelCase       ,   storage_options=_lowerCAmelCase       ,   embed_local_files=_lowerCAmelCase       ,   )
								UpperCamelCase						=  pa.Table.from_batches([batch] )
								writer.write_table(_lowerCAmelCase )

						if writer._num_bytes > 0:
								UpperCamelCase			,						UpperCamelCase						=  writer.finalize()
								writer.close()
								yield pa.RecordBatch.from_arrays(
								    [[task_id], [num_examples], [num_bytes]]       ,   names=['task_id', 'num_examples', 'num_bytes']       ,   )

						if working_fpath != fpath:
								for file in os.listdir(os.path.dirname(_lowerCAmelCase ) ):
										UpperCamelCase						=  os.path.join(os.path.dirname(_lowerCAmelCase )       ,   os.path.basename(_lowerCAmelCase ) )
										shutil.move(_lowerCAmelCase       ,   _lowerCAmelCase )

				UpperCamelCase						=  (
				    self.df.mapInArrow(_lowerCAmelCase       ,   'task_id: long, num_examples: long, num_bytes: long' )
				    .groupBy('task_id' )
				    .agg(
				        pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' )       ,   pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' )       ,   pyspark.sql.functions.count('num_bytes' ).alias('num_shards' )       ,   pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' )       ,   )
				    .collect()
				)
				for row in stats:
						yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)



		def __UpperCamelCase				(				self       ,   A_       ,   A_ = "arrow"       ,   A_ = None       ,   A_ = None       ,   **A_       ,   )						->      Union[str, Any]:
				"""simple docstring"""
				self._validate_cache_dir()

				UpperCamelCase						=  convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE )
				self._repartition_df_if_needed(_lowerCAmelCase )
				UpperCamelCase						=  not is_remote_filesystem(self._fs )
				UpperCamelCase						=  os.path.join if is_local else posixpath.join

				UpperCamelCase						=  '-TTTTT-SSSSS-of-NNNNN'
				UpperCamelCase						=  F'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}'''
				UpperCamelCase						=  path_join(self._output_dir       ,   _lowerCAmelCase )

				UpperCamelCase						=  0
				UpperCamelCase						=  0
				UpperCamelCase						=  0
				UpperCamelCase						=  []
				UpperCamelCase						=  []

				for task_id, content in self._prepare_split_single(_lowerCAmelCase       ,   _lowerCAmelCase       ,   _lowerCAmelCase ):
						(
						    (
						    UpperCamelCase			
						)			,						(
						    UpperCamelCase			
						)			,						(
						    UpperCamelCase			
						)			,						(
						    UpperCamelCase			
						)			,									
						)						=  content
						if num_bytes > 0:
								total_num_examples += num_examples
								total_num_bytes += num_bytes
								total_shards += num_shards
								task_id_and_num_shards.append((task_id, num_shards) )
								all_shard_lengths.extend(_lowerCAmelCase )

				UpperCamelCase						=  total_num_examples
				UpperCamelCase						=  total_num_bytes

				# should rename everything at the end
				logger.debug(F'''Renaming {total_shards} shards.''' )
				if total_shards > 1:
						UpperCamelCase						=  all_shard_lengths

						# Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
						# pickling error due to pickling the SparkContext.
						UpperCamelCase						=  self._fs

						# use the -SSSSS-of-NNNNN pattern
						def _rename_shard(
						    A_       ,   A_       ,   A_       ,   ):
								rename(
								    _lowerCAmelCase       ,   fpath.replace('SSSSS'       ,   F'''{shard_id:05d}''' ).replace('TTTTT'       ,   F'''{task_id:05d}''' )       ,   fpath.replace('TTTTT-SSSSS'       ,   F'''{global_shard_id:05d}''' ).replace('NNNNN'       ,   F'''{total_shards:05d}''' )       ,   )

						UpperCamelCase						=  []
						UpperCamelCase						=  0
						for i in range(len(_lowerCAmelCase ) ):
								UpperCamelCase			,						UpperCamelCase						=  task_id_and_num_shards[i]
								for shard_id in range(_lowerCAmelCase ):
										args.append([task_id, shard_id, global_shard_id] )
										global_shard_id += 1
						self._spark.sparkContext.parallelize(_lowerCAmelCase       ,   len(_lowerCAmelCase ) ).map(lambda A_ : _rename_shard(*_lowerCAmelCase ) ).collect()
				else:
						# don't use any pattern
						UpperCamelCase						=  0
						UpperCamelCase						=  task_id_and_num_shards[0][0]
						self._rename(
						    fpath.replace('SSSSS'       ,   F'''{shard_id:05d}''' ).replace('TTTTT'       ,   F'''{task_id:05d}''' )       ,   fpath.replace(_lowerCAmelCase       ,   '' )       ,   )



		def __UpperCamelCase				(				self       ,   A_       ,   )						->      str:
				"""simple docstring"""
				return SparkExamplesIterable(self.df )


import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
					from test_module.custom_tokenization_fast import CustomTokenizerFast


class        lowercase      (	unittest.TestCase     ):



		def __UpperCamelCase				(				self )						->      Tuple:
				"""simple docstring"""
				# A mock response for an HTTP head request to emulate server down
				UpperCamelCase						=  mock.Mock()
				UpperCamelCase						=  500
				UpperCamelCase						=  {}
				UpperCamelCase						=  HTTPError
				UpperCamelCase						=  {}

				# Download this model to make sure it's in the cache.
				UpperCamelCase						=  BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' )

				# Under the mock environment we get a 500 error when trying to reach the tokenizer.
				with mock.patch('requests.Session.request'       ,   return_value=A_ ) as mock_head:
						UpperCamelCase						=  BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' )
						# This check we did call the fake head request
						mock_head.assert_called()



		@require_tokenizers
		def __UpperCamelCase				(				self )						->      Dict:
				"""simple docstring"""
				# A mock response for an HTTP head request to emulate server down
				UpperCamelCase						=  mock.Mock()
				UpperCamelCase						=  500
				UpperCamelCase						=  {}
				UpperCamelCase						=  HTTPError
				UpperCamelCase						=  {}

				# Download this model to make sure it's in the cache.
				UpperCamelCase						=  GPTaTokenizerFast.from_pretrained('gpt2' )

				# Under the mock environment we get a 500 error when trying to reach the tokenizer.
				with mock.patch('requests.Session.request'       ,   return_value=A_ ) as mock_head:
						UpperCamelCase						=  GPTaTokenizerFast.from_pretrained('gpt2' )
						# This check we did call the fake head request
						mock_head.assert_called()



		def __UpperCamelCase				(				self )						->      Optional[Any]:
				"""simple docstring"""
				# This test is for deprecated behavior and can be removed in v5
				try:
						UpperCamelCase						=  tempfile.mktemp()
						with open(A_       ,   'wb' ) as f:
								http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'       ,   A_ )

						UpperCamelCase						=  AlbertTokenizer.from_pretrained(A_ )
				finally:
						os.remove(A_ )

				# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
				# the current folder and have the right name.
				if os.path.isfile('tokenizer.json' ):
						# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
						return
				try:
						with open('tokenizer.json'       ,   'wb' ) as f:
								http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json'       ,   A_ )
						UpperCamelCase						=  AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' )
						# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
						self.assertEqual(tokenizer.vocab_size       ,   1_000 )
						# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

				finally:
						os.remove('tokenizer.json' )



		def __UpperCamelCase				(				self )						->      Dict:
				"""simple docstring"""
				# This test is for deprecated behavior and can be removed in v5
				UpperCamelCase						=  AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' )






@is_staging_test
class        lowercase      (	unittest.TestCase     ):
		__lowercase : int			  =       ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]



		@classmethod
		def __UpperCamelCase				(				cls )						->      Tuple:
				"""simple docstring"""
				UpperCamelCase						=  TOKEN
				HfFolder.save_token(A_ )



		@classmethod
		def __UpperCamelCase				(				cls )						->      Optional[int]:
				"""simple docstring"""
				try:
						delete_repo(token=cls._token       ,   repo_id='test-tokenizer' )
				except HTTPError:
						pass

				try:
						delete_repo(token=cls._token       ,   repo_id='valid_org/test-tokenizer-org' )
				except HTTPError:
						pass

				try:
						delete_repo(token=cls._token       ,   repo_id='test-dynamic-tokenizer' )
				except HTTPError:
						pass



		def __UpperCamelCase				(				self )						->      Any:
				"""simple docstring"""
				with tempfile.TemporaryDirectory() as tmp_dir:
						UpperCamelCase						=  os.path.join(A_       ,   'vocab.txt' )
						with open(A_       ,   'w'       ,   encoding='utf-8' ) as vocab_writer:
								vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) )
						UpperCamelCase						=  BertTokenizer(A_ )

				tokenizer.push_to_hub('test-tokenizer'       ,   use_auth_token=self._token )
				UpperCamelCase						=  BertTokenizer.from_pretrained(F'''{USER}/test-tokenizer''' )
				self.assertDictEqual(new_tokenizer.vocab       ,   tokenizer.vocab )

				# Reset repo
				delete_repo(token=self._token       ,   repo_id='test-tokenizer' )

				# Push to hub via save_pretrained
				with tempfile.TemporaryDirectory() as tmp_dir:
						tokenizer.save_pretrained(A_       ,   repo_id='test-tokenizer'       ,   push_to_hub=A_       ,   use_auth_token=self._token )

				UpperCamelCase						=  BertTokenizer.from_pretrained(F'''{USER}/test-tokenizer''' )
				self.assertDictEqual(new_tokenizer.vocab       ,   tokenizer.vocab )



		def __UpperCamelCase				(				self )						->      int:
				"""simple docstring"""
				with tempfile.TemporaryDirectory() as tmp_dir:
						UpperCamelCase						=  os.path.join(A_       ,   'vocab.txt' )
						with open(A_       ,   'w'       ,   encoding='utf-8' ) as vocab_writer:
								vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) )
						UpperCamelCase						=  BertTokenizer(A_ )

				tokenizer.push_to_hub('valid_org/test-tokenizer-org'       ,   use_auth_token=self._token )
				UpperCamelCase						=  BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' )
				self.assertDictEqual(new_tokenizer.vocab       ,   tokenizer.vocab )

				# Reset repo
				delete_repo(token=self._token       ,   repo_id='valid_org/test-tokenizer-org' )

				# Push to hub via save_pretrained
				with tempfile.TemporaryDirectory() as tmp_dir:
						tokenizer.save_pretrained(
						    A_       ,   repo_id='valid_org/test-tokenizer-org'       ,   push_to_hub=A_       ,   use_auth_token=self._token )

				UpperCamelCase						=  BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' )
				self.assertDictEqual(new_tokenizer.vocab       ,   tokenizer.vocab )



		@require_tokenizers
		def __UpperCamelCase				(				self )						->      Dict:
				"""simple docstring"""
				CustomTokenizer.register_for_auto_class()
				with tempfile.TemporaryDirectory() as tmp_dir:
						UpperCamelCase						=  os.path.join(A_       ,   'vocab.txt' )
						with open(A_       ,   'w'       ,   encoding='utf-8' ) as vocab_writer:
								vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) )
						UpperCamelCase						=  CustomTokenizer(A_ )

				# No fast custom tokenizer
				tokenizer.push_to_hub('test-dynamic-tokenizer'       ,   use_auth_token=self._token )

				UpperCamelCase						=  AutoTokenizer.from_pretrained(F'''{USER}/test-dynamic-tokenizer'''       ,   trust_remote_code=A_ )
				# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
				self.assertEqual(tokenizer.__class__.__name__       ,   'CustomTokenizer' )

				# Fast and slow custom tokenizer
				CustomTokenizerFast.register_for_auto_class()
				with tempfile.TemporaryDirectory() as tmp_dir:
						UpperCamelCase						=  os.path.join(A_       ,   'vocab.txt' )
						with open(A_       ,   'w'       ,   encoding='utf-8' ) as vocab_writer:
								vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) )

						UpperCamelCase						=  BertTokenizerFast.from_pretrained(A_ )
						bert_tokenizer.save_pretrained(A_ )
						UpperCamelCase						=  CustomTokenizerFast.from_pretrained(A_ )

				tokenizer.push_to_hub('test-dynamic-tokenizer'       ,   use_auth_token=self._token )

				UpperCamelCase						=  AutoTokenizer.from_pretrained(F'''{USER}/test-dynamic-tokenizer'''       ,   trust_remote_code=A_ )
				# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
				self.assertEqual(tokenizer.__class__.__name__       ,   'CustomTokenizerFast' )
				UpperCamelCase						=  AutoTokenizer.from_pretrained(
				    F'''{USER}/test-dynamic-tokenizer'''       ,   use_fast=A_       ,   trust_remote_code=A_ )
				# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
				self.assertEqual(tokenizer.__class__.__name__       ,   'CustomTokenizer' )






class        lowercase      (	unittest.TestCase     ):



		def __UpperCamelCase				(				self )						->      Optional[int]:
				"""simple docstring"""
				UpperCamelCase						=  Trie()
				trie.add('Hello 友達' )
				self.assertEqual(trie.data       ,   {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} )
				trie.add('Hello' )
				trie.data
				self.assertEqual(trie.data       ,   {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} )



		def __UpperCamelCase				(				self )						->      str:
				"""simple docstring"""
				UpperCamelCase						=  Trie()
				self.assertEqual(trie.split('[CLS] This is a extra_id_100' )       ,   ['[CLS] This is a extra_id_100'] )
				trie.add('[CLS]' )
				trie.add('extra_id_1' )
				trie.add('extra_id_100' )
				self.assertEqual(trie.split('[CLS] This is a extra_id_100' )       ,   ['[CLS]', ' This is a ', 'extra_id_100'] )



		def __UpperCamelCase				(				self )						->      List[Any]:
				"""simple docstring"""
				UpperCamelCase						=  Trie()
				trie.add('A' )
				self.assertEqual(trie.split('ABC' )       ,   ['A', 'BC'] )
				self.assertEqual(trie.split('BCA' )       ,   ['BC', 'A'] )



		def __UpperCamelCase				(				self )						->      Tuple:
				"""simple docstring"""
				UpperCamelCase						=  Trie()
				trie.add('TOKEN]' )
				trie.add('[SPECIAL_TOKEN]' )
				self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' )       ,   ['This is something ', '[SPECIAL_TOKEN]'] )



		def __UpperCamelCase				(				self )						->      Dict:
				"""simple docstring"""
				UpperCamelCase						=  Trie()
				trie.add('A' )
				trie.add('P' )
				trie.add('[SPECIAL_TOKEN]' )
				self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' )       ,   ['This is something ', '[SPECIAL_TOKEN]'] )



		def __UpperCamelCase				(				self )						->      Optional[Any]:
				"""simple docstring"""
				UpperCamelCase						=  Trie()
				trie.add('AB' )
				trie.add('B' )
				trie.add('C' )
				self.assertEqual(trie.split('ABC' )       ,   ['AB', 'C'] )



		def __UpperCamelCase				(				self )						->      Tuple:
				"""simple docstring"""
				UpperCamelCase						=  Trie()
				trie.add('ABC' )
				trie.add('B' )
				trie.add('CD' )
				self.assertEqual(trie.split('ABCD' )       ,   ['ABC', 'D'] )



		def __UpperCamelCase				(				self )						->      int:
				"""simple docstring"""
				# Even if the offsets are wrong, we necessarily output correct string
				# parts.
				UpperCamelCase						=  Trie()
				UpperCamelCase						=  trie.cut_text('ABC'       ,   [0, 0, 2, 1, 2, 3] )
				self.assertEqual(A_       ,   ['AB', 'C'] )
