


'''simple docstring'''




import os
from pathlib import Path
from unittest.mock import patch

import pytest
import zstandard as zstd

from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
    OfflineModeIsEnabled,
    cached_path,
    fsspec_get,
    fsspec_head,
    ftp_get,
    ftp_head,
    get_from_cache,
    http_get,
    http_head,
)


_lowerCAmelCase  :		List[str]		     =	'\\n    Text data.\n    Second line of data.'

_lowerCAmelCase  :		Any		     =	'file'

@pytest.fixture(scope='session'				)
def 			__UpperCamelCase    (    _A    :				List[Any]				)    ->      Union[str, Any]:




	"""simple docstring"""





	lowerCAmelCase					:    List[str]      							= tmp_path_factory.mktemp('data'				) / (FILE_PATH + '.zstd')
	lowerCAmelCase					:    Tuple      							= bytes(_A					,   'utf-8'				)
	with zstd.open(_A					,   'wb'				) as f:
		f.write(_A				)
	return path

@pytest.fixture
def 			__UpperCamelCase    (    _A    :				List[str]				)    ->      Union[str, Any]:




	"""simple docstring"""





	with open(os.path.join(tmpfs.local_root_dir					,   _A				)					,   'w'				) as f:
		f.write(_A				)
	return FILE_PATH

@pytest.mark.parametrize('compression_format'					,   ['gzip', 'xz', 'zstd']				)
def 			__UpperCamelCase    (    _A    :				str					,   _A    :				Tuple					,   _A    :				List[str]					,   _A    :				Dict					,   _A    :				int					,   _A    :				Optional[Any]				)    ->      Tuple:




	"""simple docstring"""





	lowerCAmelCase					:    str      							= {'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_path}
	lowerCAmelCase					:    Union[str, Any]      							= input_paths[compression_format]
	lowerCAmelCase					:    Optional[Any]      							= tmp_path / 'cache'
	lowerCAmelCase					:    int      							= DownloadConfig(cache_dir=_A					,   extract_compressed_file=_A				)
	lowerCAmelCase					:    Optional[int]      							= cached_path(_A					,   download_config=_A				)
	with open(_A				) as f:
		lowerCAmelCase					:    Any      							= f.read()
	with open(_A				) as f:
		lowerCAmelCase					:    List[str]      							= f.read()
	assert extracted_file_content == expected_file_content

@pytest.mark.parametrize('default_extracted'					,   [True, False]				)
@pytest.mark.parametrize('default_cache_dir'					,   [True, False]				)
def 			__UpperCamelCase    (    _A    :				int					,   _A    :				Any					,   _A    :				Tuple					,   _A    :				Any					,   _A    :				List[Any]				)    ->      Optional[int]:




	"""simple docstring"""





	lowerCAmelCase					:    Union[str, Any]      							= 'custom_cache'
	lowerCAmelCase					:    Any      							= 'custom_extracted_dir'
	lowerCAmelCase					:    int      							= tmp_path / 'custom_extracted_path'
	if default_extracted:
		lowerCAmelCase					:    Tuple      							= ('downloads' if default_cache_dir else custom_cache_dir, 'extracted')
	else:
		monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_DIR'					,   _A				)
		monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH'					,   str(_A				)				)
		lowerCAmelCase					:    Any      							= custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)

	lowerCAmelCase					:    List[Any]      							= xz_file
	lowerCAmelCase					:    List[Any]      							= (
	    DownloadConfig(extract_compressed_file=_A				)
	    if default_cache_dir
	    else DownloadConfig(cache_dir=tmp_path / custom_cache_dir					,   extract_compressed_file=_A				)
	)
	lowerCAmelCase					:    Dict      							= cached_path(_A					,   download_config=_A				)
	assert Path(_A				).parent.parts[-2:] == expected

def 			__UpperCamelCase    (    _A    :				Optional[int]				)    ->      List[str]:




	"""simple docstring"""





	lowerCAmelCase					:    Optional[int]      							= str(Path(_A				).resolve()				)
	assert cached_path(_A				) == text_file
	# relative path
	lowerCAmelCase					:    Optional[Any]      							= str(Path(_A				).resolve().relative_to(Path(os.getcwd()				)				)				)
	assert cached_path(_A				) == text_file

def 			__UpperCamelCase    (    _A    :				str				)    ->      Union[str, Any]:




	"""simple docstring"""





	lowerCAmelCase					:    int      							= str(tmp_path.resolve() / '__missing_file__.txt'				)
	with pytest.raises(_A				):
		cached_path(_A				)
	# relative path
	lowerCAmelCase					:    Union[str, Any]      							= './__missing_file__.txt'
	with pytest.raises(_A				):
		cached_path(_A				)

def 			__UpperCamelCase    (    _A    :				Optional[Any]				)    ->      Optional[int]:




	"""simple docstring"""





	lowerCAmelCase					:    str      							= get_from_cache(F"tmp://{tmpfs_file}"				)
	with open(_A				) as f:
		lowerCAmelCase					:    Tuple      							= f.read()
	assert output_file_content == FILE_CONTENT

@patch('datasets.config.HF_DATASETS_OFFLINE'					,   _A				)
def 			__UpperCamelCase    (    )    ->      List[str]:




	"""simple docstring"""





	with pytest.raises(_A				):
		cached_path('https://huggingface.co'				)

@patch('datasets.config.HF_DATASETS_OFFLINE'					,   _A				)
def 			__UpperCamelCase    (    _A    :				Tuple				)    ->      Any:




	"""simple docstring"""





	lowerCAmelCase					:    Union[str, Any]      							= tmp_path_factory.mktemp('data'				) / 'file.html'
	with pytest.raises(_A				):
		http_get('https://huggingface.co'					,   temp_file=_A				)
	with pytest.raises(_A				):
		http_head('https://huggingface.co'				)

@patch('datasets.config.HF_DATASETS_OFFLINE'					,   _A				)
def 			__UpperCamelCase    (    _A    :				List[str]				)    ->      Optional[int]:




	"""simple docstring"""





	lowerCAmelCase					:    Tuple      							= tmp_path_factory.mktemp('data'				) / 'file.html'
	with pytest.raises(_A				):
		ftp_get('ftp://huggingface.co'					,   temp_file=_A				)
	with pytest.raises(_A				):
		ftp_head('ftp://huggingface.co'				)






@patch('datasets.config.HF_DATASETS_OFFLINE'					,   _A				)
def 			__UpperCamelCase    (    _A    :				Dict				)    ->      List[str]:




	"""simple docstring"""





	lowerCAmelCase					:    Dict      							= tmp_path_factory.mktemp('data'				) / 'file.html'
	with pytest.raises(_A				):
		fsspec_get('s3://huggingface.co'					,   temp_file=_A				)
	with pytest.raises(_A				):
		fsspec_head('s3://huggingface.co'				)




'''simple docstring'''




import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


_lowerCAmelCase  :		List[Any]		     =	logging.getLogger(__name__)

def 			__UpperCamelCase    (    )    ->      Any:




	"""simple docstring"""





	lowerCAmelCase					:    str      							= 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=10_00					,   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=5_12					,   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.'					,   )

	lowerCAmelCase					:    Any      							= parser.parse_args()
	return args

def 			__UpperCamelCase    (    _A    :				Optional[int]				)    ->      int:




	"""simple docstring"""





	def fn(_A    :				Tuple				):
		return tokenizer(examples['text']				)

	return fn

def 			__UpperCamelCase    (    _A    :				int				)    ->      int:




	"""simple docstring"""





	lowerCAmelCase					:    Tuple      							= []
	for i in range(len(tokenized_data['input_ids']				)				):
		lowerCAmelCase					:    Optional[Any]      							= {
		    '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]				)				),
		}
		lowerCAmelCase					:    Any      							= tf.train.Features(feature=_A				)
		lowerCAmelCase					:    List[str]      							= tf.train.Example(features=_A				)
		lowerCAmelCase					:    Tuple      							= example.SerializeToString()
		records.append(_A				)
	return records

def 			__UpperCamelCase    (    _A    :				int				)    ->      Union[str, Any]:




	"""simple docstring"""





	lowerCAmelCase					:    Union[str, Any]      							= datasets.load_dataset(args.dataset_name					,   args.dataset_config					,   split=args.split				)

	if args.limit is not None:
		lowerCAmelCase					:    Optional[Any]      							= min(len(_A				)					,   args.limit				)
		lowerCAmelCase					:    Dict      							= dataset.select(range(_A				)				)
		print(F"Limiting the dataset to {args.limit} entries."				)

	lowerCAmelCase					:    str      							= 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				)
		lowerCAmelCase					:    Any      							= os.path.join(args.output_dir					,   args.split				)
		if not os.path.exists(_A				):
			os.makedirs(_A				)
	else:
		lowerCAmelCase					:    List[Any]      							= os.path.join(args.output_dir					,   args.split				)

	# Tokenize the whole dataset at once.
	lowerCAmelCase					:    Any      							= tokenize_function(_A				)
	lowerCAmelCase					:    Optional[int]      							= 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    :				str				):
		# Concatenate all texts.
		lowerCAmelCase					:    Optional[int]      							= {k: sum(examples[k]					,   []				) for k in examples.keys()}
		lowerCAmelCase					:    str      							= 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 🫀
		lowerCAmelCase					:    List[Any]      							= (total_length // args.max_length) * args.max_length
		# Split by chunks of max_len.
		lowerCAmelCase					:    str      							= {
		    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

	lowerCAmelCase					:    List[Any]      							= dataset_tokenized.map(_A					,   batched=_A					,   batch_size=10_00					,   num_proc=4				)

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

		with tf.io.TFRecordWriter(_A				) as out_file:
			for i in range(len(_A				)				):
				lowerCAmelCase					:    Union[str, Any]      							= 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__":
				_lowerCAmelCase  :		List[Any]		     =	parse_args()
				main(args)
