



import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


lowerCAmelCase__	    =    logging.getLogger(__name__)


def    __lowerCamelCase   (  ):

				"""simple docstring"""


				lowercase__	:       int						=	argparse.ArgumentParser(
				    description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset."		)
				parser.add_argument(
				    "--dataset_name"	,					type=lowerCAmelCase__	,					default="wikitext"	,					help="Name of the training. Explore datasets at: hf.co/datasets."	,					)
				parser.add_argument(
				    "--dataset_config"	,					type=lowerCAmelCase__	,					default="wikitext-103-raw-v1"	,					help="Configuration name of the dataset."		)
				parser.add_argument(
				    "--tokenizer_name_or_path"	,					type=lowerCAmelCase__	,					default="sayakpaul/unigram-tokenizer-wikitext"	,					help="Tokenizer identifier. Can be a local filepath or a Hub identifier."	,					)
				parser.add_argument(
				    "--shard_size"	,					type=lowerCAmelCase__	,					default=1_000	,					help="Number of entries to go in a single shard."	,					)
				parser.add_argument("--split"	,					type=lowerCAmelCase__	,					default="train"	,					choices=["train", "test", "validation"]		)
				parser.add_argument(
				    "--limit"	,					default=lowerCAmelCase__	,					type=lowerCAmelCase__	,					help="Limit the number of shards (used for debugging)."	,					)
				parser.add_argument(
				    "--max_length"	,					type=lowerCAmelCase__	,					default=512	,					help="Maximum sequence length. For training on TPUs, it helps to have a maximum"
				    " sequence length that is a multiple of 8."	,					)
				parser.add_argument(
				    "--output_dir"	,					default="tf-tpu"	,					type=lowerCAmelCase__	,					help="Output directory where the TFRecord shards will be saved. If the"
				    " path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord"
				    " shards will be directly saved to a Google Cloud Storage bucket."	,					)

				lowercase__	:       List[Any]						=	parser.parse_args()
				return args


def    __lowerCamelCase   (  lowerCamelCase__		):

				"""simple docstring"""


				def fn(lowerCamelCase__		):
								return tokenizer(examples["text"]		)

				return fn


def    __lowerCamelCase   (  lowerCamelCase__		):

				"""simple docstring"""


				lowercase__	:       Tuple						=	[]
				for i in range(len(tokenized_data["input_ids"]		)		):
								lowercase__	:       str						=	{
								    "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i]		)		),
								    "attention_mask": tf.train.Feature(
								        intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i]		)		),
								}
								lowercase__	:       List[Any]						=	tf.train.Features(feature=lowerCAmelCase__		)
								lowercase__	:       Optional[int]						=	tf.train.Example(features=lowerCAmelCase__		)
								lowercase__	:       List[Any]						=	example.SerializeToString()
								records.append(lowerCAmelCase__		)
				return records


def    __lowerCamelCase   (  lowerCamelCase__		):

				"""simple docstring"""


				lowercase__	:       Optional[Any]						=	datasets.load_dataset(args.dataset_name	,					args.dataset_config	,					split=args.split		)

				if args.limit is not None:
								lowercase__	:       Dict						=	min(len(lowerCAmelCase__		)	,					args.limit		)
								lowercase__	:       List[str]						=	dataset.select(range(lowerCAmelCase__		)		)
								print(F"""Limiting the dataset to {args.limit} entries."""		)

				lowercase__	:       int						=	AutoTokenizer.from_pretrained(args.tokenizer_name_or_path		)

				# Handle output directory creation.
				# For serializing into a Google Cloud Storage Bucket, one needs to first
				# create a bucket.
				if "gs" not in args.output_dir:
								if not os.path.exists(args.output_dir		):
												os.makedirs(args.output_dir		)
								lowercase__	:       Tuple						=	os.path.join(args.output_dir	,					args.split		)
								if not os.path.exists(lowerCAmelCase__		):
												os.makedirs(lowerCAmelCase__		)
				else:
								lowercase__	:       int						=	os.path.join(args.output_dir	,					args.split		)

				# Tokenize the whole dataset at once.
				lowercase__	:       List[str]						=	tokenize_function(lowerCAmelCase__		)
				lowercase__	:       Optional[int]						=	dataset.map(lowerCAmelCase__	,					batched=lowerCAmelCase__	,					num_proc=4	,					remove_columns=["text"]		)

				# We need to concatenate all our texts together, and then split the result
				# into chunks of a fixed size, which we will call block_size. To do this, we
				# will use the map method again, with the option batched=True. When we use batched=True,
				# the function we pass to map() will be passed multiple inputs at once, allowing us
				# to group them into more or fewer examples than we had in the input.
				# This allows us to create our new fixed-length samples. The advantage of this
				# method is that we don't lose a whole lot of content from the dataset compared to the
				# case where we simply tokenize with a pre-defined max_length.

				def group_texts(lowerCamelCase__		):
								# Concatenate all texts.
								lowercase__	:       Dict						=	{k: sum(examples[k]	,					[]		) for k in examples.keys()}
								lowercase__	:       Dict						=	len(concatenated_examples[list(examples.keys()		)[0]]		)
								# We drop the small remainder, though you could add padding instead if the model supports it
								# In this, as in all things, we advise you to follow your heart 🫀
								lowercase__	:       Optional[int]						=	(total_length // args.max_length) * args.max_length
								# Split by chunks of max_len.
								lowercase__	:       List[str]						=	{
								    k: [t[i : i + args.max_length] for i in range(0	,					lowerCAmelCase__	,					args.max_length		)]
								    for k, t in concatenated_examples.items()
								}
								return result

				lowercase__	:       List[str]						=	dataset_tokenized.map(lowerCAmelCase__	,					batched=lowerCAmelCase__	,					batch_size=1_000	,					num_proc=4		)

				lowercase__	:       Any						=	0
				lowercase__	:       int						=	0
				for shard in range(0	,					len(lowerCAmelCase__		)	,					args.shard_size		):
								lowercase__	:       str						=	grouped_dataset[shard : shard + args.shard_size]
								lowercase__	:       int						=	len(dataset_snapshot["input_ids"]		)
								lowercase__	:       Tuple						=	os.path.join(lowerCAmelCase__	,					F"""dataset-{shard_count}-{records_containing}.tfrecord"""		)
								lowercase__	:       Any						=	get_serialized_examples(lowerCAmelCase__		)

								with tf.io.TFRecordWriter(lowerCAmelCase__		) as out_file:
												for i in range(len(lowerCAmelCase__		)		):
																lowercase__	:       List[str]						=	serialized_examples[i]
																out_file.write(lowerCAmelCase__		)
												print("Wrote file {} containing {} records".format(lowerCAmelCase__	,					lowerCAmelCase__		)		)

								shard_count += 1
								total_records += records_containing

				with open(F"""split-{args.split}-records-count.txt"""	,					"w"		) as f:
								print(F"""Total {args.split} records: {total_records}"""	,					file=lowerCAmelCase__		)


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







'''simple docstring'''

import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer


SCREAMING_SNAKE_CASE							:				int     	=			logging.get_logger(__name__)


SCREAMING_SNAKE_CASE							:				Dict     	=			{"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

# See all BART models at https://huggingface.co/models?filter=bart
SCREAMING_SNAKE_CASE							:				str     	=			{
    "vocab_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
    },
    "merges_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
    },
    "tokenizer_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json",
    },
}

SCREAMING_SNAKE_CASE							:				Union[str, Any]     	=			{
    "facebook/bart-base": 1024,
    "facebook/bart-large": 1024,
    "facebook/bart-large-mnli": 1024,
    "facebook/bart-large-cnn": 1024,
    "facebook/bart-large-xsum": 1024,
    "yjernite/bart_eli5": 1024,
}






class    snake_case     (      lowercase_		):






				"""simple docstring"""
				_a    	=     VOCAB_FILES_NAMES
				_a    	=     PRETRAINED_VOCAB_FILES_MAP
				_a    	=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				_a    	=     ["""input_ids""", """attention_mask"""]
				_a    	=     BartTokenizer



				def __init__(    self,     _lowercase=None,     _lowercase=None,     _lowercase=None,     _lowercase="replace",     _lowercase="<s>",     _lowercase="</s>",     _lowercase="</s>",     _lowercase="<s>",     _lowercase="<unk>",     _lowercase="<pad>",     _lowercase="<mask>",     _lowercase=False,     _lowercase=True,     **_lowercase,     )     ->							Dict:
											super().__init__(
											    _lowercase,     _lowercase,     tokenizer_file=_lowercase,     errors=_lowercase,     bos_token=_lowercase,     eos_token=_lowercase,     sep_token=_lowercase,     cls_token=_lowercase,     unk_token=_lowercase,     pad_token=_lowercase,     mask_token=_lowercase,     add_prefix_space=_lowercase,     trim_offsets=_lowercase,     **_lowercase,     )

											SCREAMING_SNAKE_CASE_				=				json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()       )
											if pre_tok_state.get('add_prefix_space',     _lowercase       ) != add_prefix_space:
																		SCREAMING_SNAKE_CASE_				=				getattr(_lowercase,     pre_tok_state.pop('type'       )       )
																		SCREAMING_SNAKE_CASE_				=				add_prefix_space
																		SCREAMING_SNAKE_CASE_				=				pre_tok_class(**_lowercase       )

											SCREAMING_SNAKE_CASE_				=				add_prefix_space

											# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
											SCREAMING_SNAKE_CASE_				=				'post_processor'
											SCREAMING_SNAKE_CASE_				=				getattr(self.backend_tokenizer,     _lowercase,     _lowercase       )
											if tokenizer_component_instance:
																		SCREAMING_SNAKE_CASE_				=				json.loads(tokenizer_component_instance.__getstate__()       )

																		# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
																		if "sep" in state:
																									SCREAMING_SNAKE_CASE_				=				tuple(state['sep']       )
																		if "cls" in state:
																									SCREAMING_SNAKE_CASE_				=				tuple(state['cls']       )

																		SCREAMING_SNAKE_CASE_				=				False

																		if state.get('add_prefix_space',     _lowercase       ) != add_prefix_space:
																									SCREAMING_SNAKE_CASE_				=				add_prefix_space
																									SCREAMING_SNAKE_CASE_				=				True

																		if state.get('trim_offsets',     _lowercase       ) != trim_offsets:
																									SCREAMING_SNAKE_CASE_				=				trim_offsets
																									SCREAMING_SNAKE_CASE_				=				True

																		if changes_to_apply:
																									SCREAMING_SNAKE_CASE_				=				getattr(_lowercase,     state.pop('type'       )       )
																									SCREAMING_SNAKE_CASE_				=				component_class(**_lowercase       )
																									setattr(self.backend_tokenizer,     _lowercase,     _lowercase       )



				@property
				def   a__					(    self       )     ->							str:
											if self._mask_token is None:
																		if self.verbose:
																									logger.error('Using mask_token, but it is not set yet.'       )
																		return None
											return str(self._mask_token       )



				@mask_token.setter
				def   a__					(    self,     _lowercase       )     ->							Dict:
											SCREAMING_SNAKE_CASE_				=				AddedToken(_lowercase,     lstrip=_lowercase,     rstrip=_lowercase       ) if isinstance(_lowercase,     _lowercase       ) else value
											SCREAMING_SNAKE_CASE_				=				value



				def   a__					(    self,     *_lowercase,     **_lowercase       )     ->							BatchEncoding:
											SCREAMING_SNAKE_CASE_				=				kwargs.get('is_split_into_words',     _lowercase       )

											if is_split_into_words and not self.add_prefix_space:
																		raise ValueError(
																		    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
																		    'to use it with pretokenized inputs.'       )

											return super()._batch_encode_plus(*_lowercase,     **_lowercase       )



				def   a__					(    self,     *_lowercase,     **_lowercase       )     ->							BatchEncoding:
											SCREAMING_SNAKE_CASE_				=				kwargs.get('is_split_into_words',     _lowercase       )

											if is_split_into_words and not self.add_prefix_space:
																		raise ValueError(
																		    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
																		    'to use it with pretokenized inputs.'       )

											return super()._encode_plus(*_lowercase,     **_lowercase       )



				def   a__					(    self,     _lowercase,     _lowercase = None       )     ->							Tuple[str]:
											SCREAMING_SNAKE_CASE_				=				self._tokenizer.model.save(_lowercase,     name=_lowercase       )
											return tuple(_lowercase       )



				def   a__					(    self,     _lowercase,     _lowercase=None       )     ->							Optional[Any]:
											SCREAMING_SNAKE_CASE_				=				[self.bos_token_id] + token_ids_a + [self.eos_token_id]
											if token_ids_a is None:
																		return output

											return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]





				def   a__					(    self,     _lowercase,     _lowercase = None       )     ->							List[int]:
											SCREAMING_SNAKE_CASE_				=				[self.sep_token_id]
											SCREAMING_SNAKE_CASE_				=				[self.cls_token_id]

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





