






import argparse
import logging

import datasets
from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
from tokenizers.models import Unigram
from tokenizers.trainers import UnigramTrainer

from transformers import AlbertTokenizerFast


__lowerCamelCase						= logging.getLogger(__name__)






def    UpperCamelCase__  (   )     ->		int:







							"""simple docstring"""





							_a  :    Tuple			=						argparse.ArgumentParser(description='''Train a unigram tokenizer on the wikitext dataset.'''     )
							parser.add_argument(
							    '''--dataset_name'''    ,	type=UpperCAmelCase    ,	default='''wikitext'''    ,	help='''Name of the training. Explore datasets at: hf.co/datasets.'''    ,	)
							parser.add_argument(
							    '''--dataset_config'''    ,	type=UpperCAmelCase    ,	default='''wikitext-103-raw-v1'''    ,	help='''Configuration name of the dataset.'''     )
							parser.add_argument(
							    '''--batch_size'''    ,	type=UpperCAmelCase    ,	default=1000    ,	help='''Batch size during training.'''    ,	)
							parser.add_argument(
							    '''--vocab_size'''    ,	type=UpperCAmelCase    ,	default=10048    ,	help='''Size of the desired vocabulary.'''    ,	)
							parser.add_argument(
							    '''--limit'''    ,	default=UpperCAmelCase    ,	type=UpperCAmelCase    ,	help='''Limit the number of shards (used for debugging).'''    ,	)
							parser.add_argument(
							    '''--export_to_hub'''    ,	action='''store_true'''    ,	)

							_a  :    str			=						parser.parse_args()
							return args






def    UpperCamelCase__  (   UpperCAmelCase     )     ->		int:







							"""simple docstring"""





							_a  :    List[str]			=						datasets.load_dataset(args.dataset_name    ,	args.dataset_config    ,	split='''train'''     )

							if args.limit is not None:
														_a  :    Optional[int]			=						min(len(UpperCAmelCase     )    ,	args.limit     )
														_a  :    Optional[Any]			=						dataset.select(range(UpperCAmelCase     )     )
														logger.info(F'Limiting the dataset to {args.limit} entries.'     )

							def batch_iterator():
														for i in range(0    ,	len(UpperCAmelCase     )    ,	args.batch_size     ):
																					yield dataset[i : i + args.batch_size]["text"]

    # Prepare the tokenizer.
							_a  :    Any			=						Tokenizer(Unigram()     )
							_a  :    int			=						normalizers.Sequence([normalizers.Replace('''``'''    ,	'''"'''     ), normalizers.Replace('''\'\''''    ,	'''"'''     )]     )
							_a  :    List[str]			=						pre_tokenizers.Metaspace()

							# Prepare the trainer.
							_a  :    List[str]			=						UnigramTrainer(
							    unk_token='''<unk>'''    ,	special_tokens=['''[CLS]''', '''[SEP]''', '''<unk>''', '''<pad>''', '''[MASK]''']    ,	vocab_size=args.vocab_size    ,	)

							logger.info('''Training the tokenizer.'''     )
							tokenizer.train_from_iterator(batch_iterator()    ,	trainer=UpperCAmelCase     )
							logger.info('''Tokenizer training complete!'''     )

							_a  :    Any			=						tokenizer.token_to_id('''[CLS]'''     )
							_a  :    Optional[Any]			=						tokenizer.token_to_id('''[SEP]'''     )
							_a  :    int			=						processors.TemplateProcessing(
							    single='''[CLS]:0 $A:0 [SEP]:0'''    ,	pair='''[CLS]:0 $A:0 [SEP]:0 $B:1 [SEP]:1'''    ,	special_tokens=[
							        ('''[CLS]''', cls_token_id),
							        ('''[SEP]''', sep_token_id),
							    ]    ,	)
							_a  :    Union[str, Any]			=						decoders.Metaspace()

							if args.export_to_hub:
														logger.info('''Exporting the trained tokenzier to Hub.'''     )
														_a  :    Any			=						AlbertTokenizerFast(tokenizer_object=UpperCAmelCase     )
														new_tokenizer.push_to_hub('''unigram-tokenizer-dataset'''     )


if __name__ == "__main__":
						__lowerCamelCase						= parse_args()
						main(args)







import textwrap

import pyarrow as pa
import pytest

from datasets import Features, Image
from datasets.packaged_modules.text.text import Text

from ..utils import require_pil






@pytest.fixture
def    UpperCamelCase__  (   UpperCAmelCase     )     ->		Union[str, Any]:







							"""simple docstring"""





							_a  :    Tuple			=						tmp_path / '''text.txt'''
							_a  :    Dict			=						textwrap.dedent(
							    '''\
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        Second paragraph:
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
        Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        '''     )
							with open(UpperCAmelCase    ,	'''w'''    ,	encoding='''utf-8'''     ) as f:
														f.write(UpperCAmelCase     )
							return str(UpperCAmelCase     )






@pytest.fixture
def    UpperCamelCase__  (   UpperCAmelCase    ,	UpperCAmelCase     )     ->		Optional[int]:







							"""simple docstring"""





							_a  :    List[Any]			=						tmp_path / '''text_with_image.txt'''
							with open(UpperCAmelCase    ,	'''w'''    ,	encoding='''utf-8'''     ) as f:
														f.write(UpperCAmelCase     )
							return str(UpperCAmelCase     )






@pytest.mark.parametrize('''keep_linebreaks'''    ,	[True, False]     )
def    UpperCamelCase__  (   UpperCAmelCase    ,	UpperCAmelCase     )     ->		Any:







							"""simple docstring"""





							with open(UpperCAmelCase    ,	encoding='''utf-8'''     ) as f:
														_a  :    str			=						f.read().splitlines(keepends=UpperCAmelCase     )
							_a  :    Tuple			=						Text(keep_linebreaks=UpperCAmelCase    ,	encoding='''utf-8'''     )
							_a  :    Optional[Any]			=						text._generate_tables([[text_file]]     )
							_a  :    str			=						pa.concat_tables([table for _, table in generator]     ).to_pydict()['''text''']
							assert generated_content == expected_content






@require_pil
def    UpperCamelCase__  (   UpperCAmelCase     )     ->		List[str]:







							"""simple docstring"""





							with open(UpperCAmelCase    ,	encoding='''utf-8'''     ) as f:
														_a  :    str			=						f.read().splitlines()[0]
							_a  :    Dict			=						Text(encoding='''utf-8'''    ,	features=Features({'''image''': Image()}     )     )
							_a  :    str			=						text._generate_tables([[text_file_with_image]]     )
							_a  :    int			=						pa.concat_tables([table for _, table in generator]     )
							assert pa_table.schema.field('''image'''     ).type == Image()()
							_a  :    Optional[int]			=						pa_table.to_pydict()['''image''']
							assert generated_content == [{"path": image_file, "bytes": None}]







@pytest.mark.parametrize('''sample_by'''    ,	['''line''', '''paragraph''', '''document''']     )
def    UpperCamelCase__  (   UpperCAmelCase    ,	UpperCAmelCase     )     ->		Optional[Any]:







							"""simple docstring"""





							with open(UpperCAmelCase    ,	encoding='''utf-8'''     ) as f:
														_a  :    Any			=						f.read()
							if sample_by == "line":
														_a  :    Any			=						expected_content.splitlines()
							elif sample_by == "paragraph":
														_a  :    Tuple			=						expected_content.split('''\n\n'''     )
							elif sample_by == "document":
														_a  :    Dict			=						[expected_content]
							_a  :    Dict			=						Text(sample_by=UpperCAmelCase    ,	encoding='''utf-8'''    ,	chunksize=100     )
							_a  :    Optional[int]			=						text._generate_tables([[text_file]]     )
							_a  :    List[Any]			=						pa.concat_tables([table for _, table in generator]     ).to_pydict()['''text''']
							assert generated_content == expected_content