


'''simple docstring'''




import unittest

from transformers import PegasusTokenizer, PegasusTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


_lowerCAmelCase  :		Union[str, Any]		     =	get_tests_dir('fixtures/test_sentencepiece_no_bos.model')



@require_sentencepiece
@require_tokenizers
class  lowerCAmelCase				(				a      ,				unittest.TestCase							):
	_lowerCamelCase   :					str			      = PegasusTokenizer
	_lowerCamelCase   :					Union[str, Any]			      = PegasusTokenizerFast
	_lowerCamelCase   :					Optional[Any]			      = True
	_lowerCamelCase   :					Optional[Any]			      = True



	def 				lowercase     (					self    ):
		super().setUp()

		# We have a SentencePiece fixture for testing
		lowerCAmelCase					:    List[Any]      							= PegasusTokenizer(snake_case__    )
		tokenizer.save_pretrained(self.tmpdirname    )



	@cached_property
	def 				lowercase     (					self    ):
		return PegasusTokenizer.from_pretrained('google/pegasus-large'    )



	def 				lowercase     (					self ,					**snake_case__    ):
		return PegasusTokenizer.from_pretrained(self.tmpdirname ,					**snake_case__    )



	def 				lowercase     (					self ,					snake_case__    ):
		return ("This is a test", "This is a test")



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[int]      							= '</s>'
		lowerCAmelCase					:    int      							= 1

		self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case__    ) ,					snake_case__    )
		self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case__    ) ,					snake_case__    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Union[str, Any]      							= list(self.get_tokenizer().get_vocab().keys()    )

		self.assertEqual(vocab_keys[0] ,					'<pad>'    )
		self.assertEqual(vocab_keys[1] ,					'</s>'    )
		self.assertEqual(vocab_keys[-1] ,					'v'    )
		self.assertEqual(len(snake_case__    ) ,					1103    )



	def 				lowercase     (					self    ):
		self.assertEqual(self.get_tokenizer().vocab_size ,					1103    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[Any]      							= self.rust_tokenizer_class.from_pretrained(self.tmpdirname    )
		lowerCAmelCase					:    List[Any]      							= self.tokenizer_class.from_pretrained(self.tmpdirname    )
		lowerCAmelCase					:    Optional[Any]      							= (
		    'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important'
		    ' </s> <pad> <pad> <pad>'
		)
		lowerCAmelCase					:    Optional[Any]      							= rust_tokenizer([raw_input_str] ,					return_tensors=snake_case__ ,					add_special_tokens=snake_case__    ).input_ids[0]
		lowerCAmelCase					:    Optional[int]      							= py_tokenizer([raw_input_str] ,					return_tensors=snake_case__ ,					add_special_tokens=snake_case__    ).input_ids[0]
		self.assertListEqual(snake_case__ ,					snake_case__    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Any      							= self._large_tokenizer
		# <mask_1> masks whole sentence while <mask_2> masks single word
		lowerCAmelCase					:    List[str]      							= '<mask_1> To ensure a <mask_2> flow of bank resolutions.'
		lowerCAmelCase					:    Optional[Any]      							= [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1]
		lowerCAmelCase					:    Optional[Any]      							= tokenizer([raw_input_str] ,					return_tensors=snake_case__    ).input_ids[0]
		self.assertListEqual(snake_case__ ,					snake_case__    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[Any]      							= self._large_tokenizer
		# The tracebacks for the following asserts are **better** without messages or self.assertEqual
		assert tokenizer.vocab_size == 9_6103
		assert tokenizer.pad_token_id == 0
		assert tokenizer.eos_token_id == 1
		assert tokenizer.offset == 103
		assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105
		assert tokenizer.unk_token == "<unk>"
		assert tokenizer.model_max_length == 1024
		lowerCAmelCase					:    List[Any]      							= 'To ensure a smooth flow of bank resolutions.'
		lowerCAmelCase					:    Optional[int]      							= [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1]
		lowerCAmelCase					:    Any      							= tokenizer([raw_input_str] ,					return_tensors=snake_case__    ).input_ids[0]
		self.assertListEqual(snake_case__ ,					snake_case__    )
		assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3]    ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"]



	@require_torch
	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Union[str, Any]      							= ['This is going to be way too long.' * 150, 'short example']
		lowerCAmelCase					:    int      							= ['not super long but more than 5 tokens', 'tiny']
		lowerCAmelCase					:    Dict      							= self._large_tokenizer(snake_case__ ,					padding=snake_case__ ,					truncation=snake_case__ ,					return_tensors='pt'    )
		lowerCAmelCase					:    Dict      							= self._large_tokenizer(
		    text_target=snake_case__ ,					max_length=5 ,					padding=snake_case__ ,					truncation=snake_case__ ,					return_tensors='pt'    )

		assert batch.input_ids.shape == (2, 1024)
		assert batch.attention_mask.shape == (2, 1024)
		assert targets["input_ids"].shape == (2, 5)
		assert len(snake_case__    ) == 2  # input_ids, attention_mask.



	@slow
	def 				lowercase     (					self    ):
		# fmt: off
		lowerCAmelCase					:    Tuple      							= {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
		# fmt: on

		self.tokenizer_integration_test_util(
		    expected_encoding=snake_case__ ,					model_name='google/bigbird-pegasus-large-arxiv' ,					revision='ba85d0851d708441f91440d509690f1ab6353415' ,					)



@require_sentencepiece
@require_tokenizers
class  lowerCAmelCase				(				a      ,				unittest.TestCase							):
	_lowerCamelCase   :					Optional[Any]			      = PegasusTokenizer
	_lowerCamelCase   :					str			      = PegasusTokenizerFast
	_lowerCamelCase   :					Tuple			      = True
	_lowerCamelCase   :					int			      = True



	def 				lowercase     (					self    ):
		super().setUp()

		# We have a SentencePiece fixture for testing
		lowerCAmelCase					:    int      							= PegasusTokenizer(snake_case__ ,					offset=0 ,					mask_token_sent=snake_case__ ,					mask_token='[MASK]'    )
		tokenizer.save_pretrained(self.tmpdirname    )



	@cached_property
	def 				lowercase     (					self    ):
		return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv'    )



	def 				lowercase     (					self ,					**snake_case__    ):
		return PegasusTokenizer.from_pretrained(self.tmpdirname ,					**snake_case__    )



	def 				lowercase     (					self ,					snake_case__    ):
		return ("This is a test", "This is a test")



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Tuple      							= self.rust_tokenizer_class.from_pretrained(self.tmpdirname    )
		lowerCAmelCase					:    Union[str, Any]      							= self.tokenizer_class.from_pretrained(self.tmpdirname    )
		lowerCAmelCase					:    List[str]      							= (
		    'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>'
		    ' <pad> <pad> <pad>'
		)
		lowerCAmelCase					:    Dict      							= rust_tokenizer([raw_input_str] ,					return_tensors=snake_case__ ,					add_special_tokens=snake_case__    ).input_ids[0]
		lowerCAmelCase					:    Union[str, Any]      							= py_tokenizer([raw_input_str] ,					return_tensors=snake_case__ ,					add_special_tokens=snake_case__    ).input_ids[0]
		self.assertListEqual(snake_case__ ,					snake_case__    )



	@require_torch
	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[int]      							= ['This is going to be way too long.' * 1000, 'short example']
		lowerCAmelCase					:    Union[str, Any]      							= ['not super long but more than 5 tokens', 'tiny']
		lowerCAmelCase					:    List[str]      							= self._large_tokenizer(snake_case__ ,					padding=snake_case__ ,					truncation=snake_case__ ,					return_tensors='pt'    )
		lowerCAmelCase					:    List[str]      							= self._large_tokenizer(
		    text_target=snake_case__ ,					max_length=5 ,					padding=snake_case__ ,					truncation=snake_case__ ,					return_tensors='pt'    )

		assert batch.input_ids.shape == (2, 4096)
		assert batch.attention_mask.shape == (2, 4096)
		assert targets["input_ids"].shape == (2, 5)
		assert len(snake_case__    ) == 2  # input_ids, attention_mask.



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[str]      							= (
		    'This is an example string that is used to test the original TF implementation against the HF'
		    ' implementation'
		)

		lowerCAmelCase					:    Tuple      							= self._large_tokenizer(snake_case__    ).input_ids

		self.assertListEqual(
		    snake_case__ ,					[182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] ,					)




'''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)
