






import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


__UpperCamelCase					:		Union[str, Any]	  =						logging.getLogger(__name__)
def      a_ (      )			->			Union[str, Any]:







				"""simple docstring"""
				snake_case__									=     argparse.ArgumentParser(
				    description='Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.'  )
				parser.add_argument(
				    '--dataset_name'      ,   type=_A      ,   default='wikitext'      ,   help='Name of the training. Explore datasets at: hf.co/datasets.'      ,   )
				parser.add_argument(
				    '--dataset_config'      ,   type=_A      ,   default='wikitext-103-raw-v1'      ,   help='Configuration name of the dataset.'  )
				parser.add_argument(
				    '--tokenizer_name_or_path'      ,   type=_A      ,   default='sayakpaul/unigram-tokenizer-wikitext'      ,   help='Tokenizer identifier. Can be a local filepath or a Hub identifier.'      ,   )
				parser.add_argument(
				    '--shard_size'      ,   type=_A      ,   default=1000      ,   help='Number of entries to go in a single shard.'      ,   )
				parser.add_argument('--split'      ,   type=_A      ,   default='train'      ,   choices=['train', 'test', 'validation']  )
				parser.add_argument(
				    '--limit'      ,   default=_A      ,   type=_A      ,   help='Limit the number of shards (used for debugging).'      ,   )
				parser.add_argument(
				    '--max_length'      ,   type=_A      ,   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=_A      ,   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.'      ,   )

				snake_case__									=     parser.parse_args()
				return args
def      a_ (      _A  )			->			Optional[Any]:







				"""simple docstring"""
				def fn(_A  ):
								return tokenizer(examples['text']  )

				return fn
def      a_ (      _A  )			->			List[Any]:







				"""simple docstring"""
				snake_case__									=     []
				for i in range(len(tokenized_data['input_ids']  )  ):
								snake_case__									=     {
								    '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]  )  ),
								}
								snake_case__									=     tf.train.Features(feature=_A  )
								snake_case__									=     tf.train.Example(features=_A  )
								snake_case__									=     example.SerializeToString()
								records.append(_A  )
				return records
def      a_ (      _A  )			->			str:







				"""simple docstring"""
				snake_case__									=     datasets.load_dataset(args.dataset_name      ,   args.dataset_config      ,   split=args.split  )

				if args.limit is not None:
								snake_case__									=     min(len(_A  )      ,   args.limit  )
								snake_case__									=     dataset.select(range(_A  )  )
								print(f'''Limiting the dataset to {args.limit} entries.'''  )

				snake_case__									=     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  )
								snake_case__									=     os.path.join(args.output_dir      ,   args.split  )
								if not os.path.exists(_A  ):
												os.makedirs(_A  )
				else:
								snake_case__									=     os.path.join(args.output_dir      ,   args.split  )

				# Tokenize the whole dataset at once.
				snake_case__									=     tokenize_function(_A  )
				snake_case__									=     dataset.map(_A      ,   batched=_A      ,   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(_A  ):
								# Concatenate all texts.
								snake_case__									=     {k: sum(examples[k]      ,   []  ) for k in examples.keys()}
								snake_case__									=     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 🫀
								snake_case__									=     (total_length // args.max_length) * args.max_length
								# Split by chunks of max_len.
								snake_case__									=     {
								    k: [t[i : i + args.max_length] for i in range(0      ,   _A      ,   args.max_length  )]
								    for k, t in concatenated_examples.items()
								}
								return result

				snake_case__									=     dataset_tokenized.map(_A      ,   batched=_A      ,   batch_size=1000      ,   num_proc=4  )

				snake_case__									=     0
				snake_case__									=     0
				for shard in range(0      ,   len(_A  )      ,   args.shard_size  ):
								snake_case__									=     grouped_dataset[shard : shard + args.shard_size]
								snake_case__									=     len(dataset_snapshot['input_ids']  )
								snake_case__									=     os.path.join(_A      ,   f'''dataset-{shard_count}-{records_containing}.tfrecord'''  )
								snake_case__									=     get_serialized_examples(_A  )

								with tf.io.TFRecordWriter(_A  ) as out_file:
												for i in range(len(_A  )  ):
																snake_case__									=     serialized_examples[i]
																out_file.write(_A  )
												print('Wrote file {} containing {} records'.format(_A      ,   _A  )  )

								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=_A  )


if __name__ == "__main__":
							__UpperCamelCase					:		Optional[int]	  =						parse_args()
							main(args)












import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


__UpperCamelCase					:		Any	  =						datasets.utils.logging.get_logger(__name__)

__UpperCamelCase					:		Union[str, Any]	  =						["""names""", """prefix"""]
__UpperCamelCase					:		List[str]	  =						["""warn_bad_lines""", """error_bad_lines""", """mangle_dupe_cols"""]
__UpperCamelCase					:		Dict	  =						["""encoding_errors""", """on_bad_lines"""]
__UpperCamelCase					:		Any	  =						["""date_format"""]


@dataclass
class   __SCREAMING_SNAKE_CASE(	datasets.BuilderConfig	):
							_UpperCAmelCase     =       ","
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       "infer"
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       "."
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       '"'
							_UpperCAmelCase     =       0
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       0
							_UpperCAmelCase     =       True
							_UpperCAmelCase     =       False
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       1_0_0_0_0
							_UpperCAmelCase     =       None
							_UpperCAmelCase     =       "strict"
							_UpperCAmelCase     =       "error"
							_UpperCAmelCase     =       None
							def lowerCAmelCase_ (     self:      Tuple						)		->		int:
											if self.delimiter is not None:
															snake_case__									=     self.delimiter
											if self.column_names is not None:
															snake_case__									=     self.column_names


							@property
							def lowerCAmelCase_ (     self:      Optional[int]						)		->		List[str]:
											snake_case__									=     {
											    'sep': self.sep,
											    'header': self.header,
											    'names': self.names,
											    'index_col': self.index_col,
											    'usecols': self.usecols,
											    'prefix': self.prefix,
											    'mangle_dupe_cols': self.mangle_dupe_cols,
											    'engine': self.engine,
											    'converters': self.converters,
											    'true_values': self.true_values,
											    'false_values': self.false_values,
											    'skipinitialspace': self.skipinitialspace,
											    'skiprows': self.skiprows,
											    'nrows': self.nrows,
											    'na_values': self.na_values,
											    'keep_default_na': self.keep_default_na,
											    'na_filter': self.na_filter,
											    'verbose': self.verbose,
											    'skip_blank_lines': self.skip_blank_lines,
											    'thousands': self.thousands,
											    'decimal': self.decimal,
											    'lineterminator': self.lineterminator,
											    'quotechar': self.quotechar,
											    'quoting': self.quoting,
											    'escapechar': self.escapechar,
											    'comment': self.comment,
											    'encoding': self.encoding,
											    'dialect': self.dialect,
											    'error_bad_lines': self.error_bad_lines,
											    'warn_bad_lines': self.warn_bad_lines,
											    'skipfooter': self.skipfooter,
											    'doublequote': self.doublequote,
											    'memory_map': self.memory_map,
											    'float_precision': self.float_precision,
											    'chunksize': self.chunksize,
											    'encoding_errors': self.encoding_errors,
											    'on_bad_lines': self.on_bad_lines,
											    'date_format': self.date_format,
											}

											# some kwargs must not be passed if they don't have a default value
											# some others are deprecated and we can also not pass them if they are the default value
											for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
															if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()       ,	UpperCamelCase						):
																			del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
											if not (datasets.config.PANDAS_VERSION.major >= 2):
															for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
																			del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
											if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
															for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
																			del pd_read_csv_kwargs[pd_read_csv_parameter]

											return pd_read_csv_kwargs


class   __SCREAMING_SNAKE_CASE(	datasets.ArrowBasedBuilder	):
							_UpperCAmelCase     =       CsvConfig
							def lowerCAmelCase_ (     self:      str						)		->		int:
											return datasets.DatasetInfo(features=self.config.features						)
							def lowerCAmelCase_ (     self:      Tuple       ,	UpperCamelCase:      Dict						)		->		int:
											if not self.config.data_files:
															raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}'''						)
											snake_case__									=     dl_manager.download_and_extract(self.config.data_files						)
											if isinstance(UpperCamelCase       ,	(str, list, tuple)						):
															snake_case__									=     data_files
															if isinstance(UpperCamelCase       ,	UpperCamelCase						):
																			snake_case__									=     [files]
															snake_case__									=     [dl_manager.iter_files(UpperCamelCase						) for file in files]
															return [datasets.SplitGenerator(name=datasets.Split.TRAIN       ,	gen_kwargs={'files': files}						)]
											snake_case__									=     []
											for split_name, files in data_files.items():
															if isinstance(UpperCamelCase       ,	UpperCamelCase						):
																			snake_case__									=     [files]
															snake_case__									=     [dl_manager.iter_files(UpperCamelCase						) for file in files]
															splits.append(datasets.SplitGenerator(name=UpperCamelCase       ,	gen_kwargs={'files': files}						)						)
											return splits
							def lowerCAmelCase_ (     self:      int       ,	UpperCamelCase:      pa.Table						)		->		pa.Table:
											if self.config.features is not None:
															snake_case__									=     self.config.features.arrow_schema
															if all(not require_storage_cast(UpperCamelCase						) for feature in self.config.features.values()						):
																			# cheaper cast
																			snake_case__									=     pa.Table.from_arrays([pa_table[field.name] for field in schema]       ,	schema=UpperCamelCase						)
															else:
																			# more expensive cast; allows str <-> int/float or str to Audio for example
																			snake_case__									=     table_cast(UpperCamelCase       ,	UpperCamelCase						)
											return pa_table


							def lowerCAmelCase_ (     self:      str       ,	UpperCamelCase:      Tuple						)		->		Tuple:
											snake_case__									=     self.config.features.arrow_schema if self.config.features else None
											# dtype allows reading an int column as str
											snake_case__									=     (
											    {
											        name: dtype.to_pandas_dtype() if not require_storage_cast(UpperCamelCase						) else object
											        for name, dtype, feature in zip(schema.names       ,	schema.types       ,	self.config.features.values()						)
											    }
											    if schema is not None
											    else None
											)
											for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCamelCase						)						):
															snake_case__									=     pd.read_csv(UpperCamelCase       ,	iterator=UpperCamelCase       ,	dtype=UpperCamelCase       ,	**self.config.pd_read_csv_kwargs						)
															try:
																			for batch_idx, df in enumerate(UpperCamelCase						):
																							snake_case__									=     pa.Table.from_pandas(UpperCamelCase						)
																							# Uncomment for debugging (will print the Arrow table size and elements)
																							# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																							# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																							yield (file_idx, batch_idx), self._cast_table(UpperCamelCase						)
															except ValueError as e:
																			logger.error(F'''Failed to read file \'{file}\' with error {type(UpperCamelCase						)}: {e}'''						)
																			raise




