import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("""3.8"""):
		import importlib_metadata
else:
		import importlib.metadata as importlib_metadata





def 				UpperCAmelCase						(    lowercase							,			lowercase=False							):







				"""simple docstring"""



				try:
								__lowercase 			=							os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								__lowercase 			=							default
				else:
								# KEY is set, convert it to True or False.
								try:
												__lowercase 			=							strtobool(lowercase							)
								except ValueError:
												# More values are supported, but let's keep the message simple.
												raise ValueError(F"If set, {key} must be yes or no."							)
				return _value


__a  :     Dict       =  parse_flag_from_env("""RUN_SLOW""", default=False)
__a  :     List[Any]       =  parse_flag_from_env("""RUN_REMOTE""", default=False)
__a  :     Optional[int]       =  parse_flag_from_env("""RUN_LOCAL""", default=True)
__a  :     Optional[int]       =  parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
__a  :     str       =  pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
__a  :     Union[str, Any]       =  pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
__a  :     Tuple       =  pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

# Audio
__a  :     str       =  pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("""soundfile""") is None or version.parse(importlib_metadata.version("""soundfile""")) < version.parse("""0.12.0"""),
    reason="""test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; """,
)

# Beam
__a  :     Optional[Any]       =  pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("""0.3.2"""),
    reason="""test requires apache-beam and a compatible dill version""",
)

# Dill-cloudpickle compatibility
__a  :     Any       =  pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("""0.3.2"""),
    reason="""test requires dill>0.3.2 for cloudpickle compatibility""",
)

# Windows
__a  :     List[Any]       =  pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import faiss  # noqa
				except ImportError:
								__lowercase 			=							unittest.skip('''test requires faiss'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import regex  # noqa
				except ImportError:
								__lowercase 			=							unittest.skip('''test requires regex'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import elasticsearch  # noqa
				except ImportError:
								__lowercase 			=							unittest.skip('''test requires elasticsearch'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import sqlalchemy  # noqa
				except ImportError:
								__lowercase 			=							unittest.skip('''test requires sqlalchemy'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				if not config.TORCH_AVAILABLE:
								__lowercase 			=							unittest.skip('''test requires PyTorch'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				if not config.TF_AVAILABLE:
								__lowercase 			=							unittest.skip('''test requires TensorFlow'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				if not config.JAX_AVAILABLE:
								__lowercase 			=							unittest.skip('''test requires JAX'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				if not config.PIL_AVAILABLE:
								__lowercase 			=							unittest.skip('''test requires Pillow'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import transformers  # noqa F401
				except ImportError:
								return unittest.skip('''test requires transformers'''							)(lowercase							)
				else:
								return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import tiktoken  # noqa F401
				except ImportError:
								return unittest.skip('''test requires tiktoken'''							)(lowercase							)
				else:
								return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import spacy  # noqa F401
				except ImportError:
								return unittest.skip('''test requires spacy'''							)(lowercase							)
				else:
								return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				def _require_spacy_model(lowercase							):
								try:
												import spacy  # noqa F401

												spacy.load(lowercase							)
								except ImportError:
												return unittest.skip('''test requires spacy'''							)(lowercase							)
								except OSError:
												return unittest.skip('''test requires spacy model \'{}\''''.format(lowercase							)							)(lowercase							)
								else:
												return test_case

				return _require_spacy_model





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import pyspark  # noqa F401
				except ImportError:
								return unittest.skip('''test requires pyspark'''							)(lowercase							)
				else:
								return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				try:
								import joblibspark  # noqa F401
				except ImportError:
								return unittest.skip('''test requires joblibspark'''							)(lowercase							)
				else:
								return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				if not _run_slow_tests or _run_slow_tests == 0:
								__lowercase 			=							unittest.skip('''test is slow'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				if not _run_local_tests or _run_local_tests == 0:
								__lowercase 			=							unittest.skip('''test is local'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				if not _run_packaged_tests or _run_packaged_tests == 0:
								__lowercase 			=							unittest.skip('''test is packaged'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				if not _run_remote_tests or _run_remote_tests == 0:
								__lowercase 			=							unittest.skip('''test requires remote'''							)(lowercase							)
				return test_case





def 				UpperCAmelCase						(    *lowercase							):







				"""simple docstring"""



				def decorate(cls							):
								for name, fn in cls.__dict__.items():
												if callable(lowercase							) and name.startswith('''test'''							):
																for decorator in decorators:
																				__lowercase 			=							decorator(lowercase							)
																setattr(cls							,			lowercase							,			lowercase							)
								return cls

				return decorate




class    _UpperCamelCase      (						_UpperCAmelCase ):


			"""simple docstring"""






			pass




class    _UpperCamelCase      (						_UpperCAmelCase ):


			"""simple docstring"""






			__a  : Tuple			 =						0
			__a  : Optional[int]			 =						1
			__a  : Any			 =						2





@contextmanager
def 				UpperCAmelCase						(    lowercase=OfflineSimulationMode.CONNECTION_FAILS							,			lowercase=1E-16							):







				"""simple docstring"""



				__lowercase 			=							requests.Session().request

				def timeout_request(lowercase							,			lowercase							,			lowercase							,			**lowercase							):
								# Change the url to an invalid url so that the connection hangs
								__lowercase 			=							'''https://10.255.255.1'''
								if kwargs.get('''timeout'''							) is None:
												raise RequestWouldHangIndefinitelyError(
												    F"Tried a call to {url} in offline mode with no timeout set. Please set a timeout."							)
								__lowercase 			=							timeout
								try:
												return online_request(lowercase							,			lowercase							,			**lowercase							)
								except Exception as e:
												# The following changes in the error are just here to make the offline timeout error prettier
												__lowercase 			=							url
												__lowercase 			=							e.args[0]
												__lowercase 			=							(max_retry_error.args[0].replace('''10.255.255.1'''							,			F"OfflineMock[{url}]"							),)
												__lowercase 			=							(max_retry_error,)
												raise

				def raise_connection_error(lowercase							,			lowercase							,			**lowercase							):
								raise requests.ConnectionError('''Offline mode is enabled.'''							,			request=lowercase							)

				if mode is OfflineSimulationMode.CONNECTION_FAILS:
								with patch('''requests.Session.send'''							,			lowercase							):
												yield
				elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
								# inspired from https://stackoverflow.com/a/904609
								with patch('''requests.Session.request'''							,			lowercase							):
												yield
				elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
								with patch('''datasets.config.HF_DATASETS_OFFLINE'''							,			lowercase							):
												yield
				else:
								raise ValueError('''Please use a value from the OfflineSimulationMode enum.'''							)





@contextmanager
def 				UpperCAmelCase						(    *lowercase							,			**lowercase							):







				"""simple docstring"""



				__lowercase 			=							str(Path().resolve()							)
				with tempfile.TemporaryDirectory(*lowercase							,			**lowercase							) as tmp_dir:
								try:
												os.chdir(lowercase							)
												yield
								finally:
												os.chdir(lowercase							)





@contextmanager
def 				UpperCAmelCase						(    ):







				"""simple docstring"""



				import gc

				gc.collect()
				__lowercase 			=							pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."





@contextmanager
def 				UpperCAmelCase						(    ):







				"""simple docstring"""



				import gc

				gc.collect()
				__lowercase 			=							pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."





def 				UpperCAmelCase						(    lowercase							,			lowercase							):







				"""simple docstring"""



				return deepcopy(lowercase							).integers(0							,			100							,			10							).tolist() == deepcopy(lowercase							).integers(0							,			100							,			10							).tolist()





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				import decorator
				from requests.exceptions import HTTPError

				def _wrapper(lowercase							,			*lowercase							,			**lowercase							):
								try:
												return func(*lowercase							,			**lowercase							)
								except HTTPError as err:
												if str(lowercase							).startswith('''500'''							) or str(lowercase							).startswith('''502'''							):
																pytest.xfail(str(lowercase							)							)
												raise err

				return decorator.decorator(_wrapper							,			lowercase							)




class    _UpperCamelCase      :


			"""simple docstring"""






			def __init__(   self      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__						)     ->					Union[str, Any]:

							'''simple docstring'''


							__lowercase 			=							returncode
							__lowercase 			=							stdout
							__lowercase 			=							stderr





async def 				UpperCAmelCase						(    lowercase							,			lowercase							):







				"""simple docstring"""



				while True:
								__lowercase 			=							await stream.readline()
								if line:
												callback(lowercase							)
								else:
												break





async def 				UpperCAmelCase						(    lowercase							,			lowercase=None							,			lowercase=None							,			lowercase=None							,			lowercase=False							,			lowercase=False							):







				"""simple docstring"""



				if echo:
								print('''\nRunning: '''							,			''' '''.join(lowercase							)							)

				__lowercase 			=							await asyncio.create_subprocess_exec(
				    cmd[0]							,			*cmd[1:]							,			stdin=lowercase							,			stdout=asyncio.subprocess.PIPE							,			stderr=asyncio.subprocess.PIPE							,			env=lowercase							,			)

				# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
				# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
				#
				# If it starts hanging, will need to switch to the following code. The problem is that no data
				# will be seen until it's done and if it hangs for example there will be no debug info.
				# out, err = await p.communicate()
				# return _RunOutput(p.returncode, out, err)

				__lowercase 			=							[]
				__lowercase 			=							[]

				def tee(lowercase							,			lowercase							,			lowercase							,			lowercase=""							):
								__lowercase 			=							line.decode('''utf-8'''							).rstrip()
								sink.append(lowercase							)
								if not quiet:
												print(lowercase							,			lowercase							,			file=lowercase							)

    # XXX: the timeout doesn't seem to make any difference here
				await asyncio.wait(
				    [
				        _read_stream(p.stdout							,			lambda lowercase							: tee(lowercase							,			lowercase							,			sys.stdout							,			label='''stdout:'''							)							),
				        _read_stream(p.stderr							,			lambda lowercase							: tee(lowercase							,			lowercase							,			sys.stderr							,			label='''stderr:'''							)							),
				    ]							,			timeout=lowercase							,			)
				return _RunOutput(await p.wait()							,			lowercase							,			lowercase							)





def 				UpperCAmelCase						(    lowercase							,			lowercase=None							,			lowercase=None							,			lowercase=180							,			lowercase=False							,			lowercase=True							):







				"""simple docstring"""



				__lowercase 			=							asyncio.get_event_loop()
				__lowercase 			=							loop.run_until_complete(
				    _stream_subprocess(lowercase							,			env=lowercase							,			stdin=lowercase							,			timeout=lowercase							,			quiet=lowercase							,			echo=lowercase							)							)

				__lowercase 			=							''' '''.join(lowercase							)
				if result.returncode > 0:
								__lowercase 			=							'''\n'''.join(result.stderr							)
								raise RuntimeError(
								    F"'{cmd_str}' failed with returncode {result.returncode}\n\n"
								    F"The combined stderr from workers follows:\n{stderr}"							)

				# check that the subprocess actually did run and produced some output, should the test rely on
				# the remote side to do the testing
				if not result.stdout and not result.stderr:
								raise RuntimeError(F"'{cmd_str}' produced no output."							)

				return result





def 				UpperCAmelCase						(    ):







				"""simple docstring"""



				__lowercase 			=							os.environ.get('''PYTEST_XDIST_WORKER'''							,			'''gw0'''							)
				__lowercase 			=							re.sub(r'''^gw'''							,			''''''							,			lowercase							,			0							,			re.M							)
				return int(lowercase							)





def 				UpperCAmelCase						(    ):







				"""simple docstring"""



				__lowercase 			=							29500
				__lowercase 			=							pytest_xdist_worker_id()
				return port + uniq_delta
import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


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





def 				UpperCAmelCase						(    ):







				"""simple docstring"""



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





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



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

				return fn





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				__lowercase 			=							[]
				for i in range(len(tokenized_data['''input_ids''']							)							):
								__lowercase 			=							{
								    '''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 			=							tf.train.Features(feature=lowercase							)
								__lowercase 			=							tf.train.Example(features=lowercase							)
								__lowercase 			=							example.SerializeToString()
								records.append(lowercase							)
				return records





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				__lowercase 			=							datasets.load_dataset(args.dataset_name							,			args.dataset_config							,			split=args.split							)

				if args.limit is not None:
								__lowercase 			=							min(len(lowercase							)							,			args.limit							)
								__lowercase 			=							dataset.select(range(lowercase							)							)
								print(F"Limiting the dataset to {args.limit} entries."							)

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

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

				__lowercase 			=							dataset_tokenized.map(lowercase							,			batched=lowercase							,			batch_size=1000							,			num_proc=4							)

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

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

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


if __name__ == "__main__":
		__a  :     Optional[Any]       =  parse_args()
		main(args)