



'''simple docstring'''

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 				a  (     UpperCamelCase_    :    Dict      ,					UpperCamelCase_    :    str=False			)       ->	Any:


		try:
				snake_case__	     =os.environ[key]
		except KeyError:
				# KEY isn't set, default to `default`.
				snake_case__	     =default
		else:
				# KEY is set, convert it to True or False.
				try:
						snake_case__	     =strtobool(UpperCamelCase_			)
				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


SCREAMING_SNAKE_CASE__     :						List[str]	=  parse_flag_from_env('''RUN_SLOW''', default=False)
SCREAMING_SNAKE_CASE__     :						Optional[int]	=  parse_flag_from_env('''RUN_REMOTE''', default=False)
SCREAMING_SNAKE_CASE__     :						str	=  parse_flag_from_env('''RUN_LOCAL''', default=True)
SCREAMING_SNAKE_CASE__     :						List[Any]	=  parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
SCREAMING_SNAKE_CASE__     :						str	=  pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
SCREAMING_SNAKE_CASE__     :						Optional[int]	=  pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
SCREAMING_SNAKE_CASE__     :						Optional[Any]	=  pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
SCREAMING_SNAKE_CASE__     :						List[Any]	=  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
SCREAMING_SNAKE_CASE__     :						List[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
SCREAMING_SNAKE_CASE__     :						List[Any]	=  pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
SCREAMING_SNAKE_CASE__     :						int	=  pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)






def 				a  (     UpperCamelCase_    :    List[Any]			)       ->	List[Any]:


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






def 				a  (     UpperCamelCase_    :    Optional[int]			)       ->	Tuple:


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






def 				a  (     UpperCamelCase_    :    List[Any]			)       ->	Tuple:


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






def 				a  (     UpperCamelCase_    :    Union[str, Any]			)       ->	Any:


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






def 				a  (     UpperCamelCase_    :    Any			)       ->	Optional[int]:


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






def 				a  (     UpperCamelCase_    :    str			)       ->	Optional[int]:


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






def 				a  (     UpperCamelCase_    :    int			)       ->	List[str]:


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






def 				a  (     UpperCamelCase_    :    List[str]			)       ->	Optional[Any]:


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






def 				a  (     UpperCamelCase_    :    Optional[int]			)       ->	str:


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






def 				a  (     UpperCamelCase_    :    List[Any]			)       ->	Optional[int]:


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






def 				a  (     UpperCamelCase_    :    Optional[int]			)       ->	Tuple:


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






def 				a  (     UpperCamelCase_    :    int			)       ->	Optional[Any]:


		def _require_spacy_model(UpperCamelCase_    :    Optional[int]			):
				try:
						import spacy  # noqa F401

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

		return _require_spacy_model






def 				a  (     UpperCamelCase_    :    List[str]			)       ->	str:


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






def 				a  (     UpperCamelCase_    :    str			)       ->	List[str]:


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






def 				a  (     UpperCamelCase_    :    Tuple			)       ->	Tuple:


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






def 				a  (     UpperCamelCase_    :    List[Any]			)       ->	Union[str, Any]:


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






def 				a  (     UpperCamelCase_    :    Optional[int]			)       ->	Optional[Any]:


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






def 				a  (     UpperCamelCase_    :    Tuple			)       ->	Optional[Any]:


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






def 				a  (     *UpperCamelCase_    :    str			)       ->	Dict:


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

		return decorate

class 							a__( snake_case_     ):
			pass





class 							a__( snake_case_     ):
			a_	: Any									=      0
			a_	: Tuple									=      1
			a_	: List[str]									=      2






@contextmanager
def 				a  (     UpperCamelCase_    :    Optional[int]=OfflineSimulationMode.CONNECTION_FAILS      ,					UpperCamelCase_    :    List[Any]=1e-16			)       ->	Any:
		snake_case__	     =requests.Session().request

		def timeout_request(UpperCamelCase_    :    List[Any]      ,					UpperCamelCase_    :    Optional[Any]      ,					UpperCamelCase_    :    List[str]      ,					**UpperCamelCase_    :    Any			):
				# Change the url to an invalid url so that the connection hangs
				snake_case__	     ='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."""			)
				snake_case__	     =timeout
				try:
						return online_request(UpperCamelCase_      ,					UpperCamelCase_      ,					**UpperCamelCase_			)
				except Exception as e:
						# The following changes in the error are just here to make the offline timeout error prettier
						snake_case__	     =url
						snake_case__	     =e.args[0]
						snake_case__	     =(max_retry_error.args[0].replace('10.255.255.1'      ,					f"""OfflineMock[{url}]"""			),)
						snake_case__	     =(max_retry_error,)
						raise

		def raise_connection_error(UpperCamelCase_    :    Dict      ,					UpperCamelCase_    :    Tuple      ,					**UpperCamelCase_    :    List[Any]			):
				raise requests.ConnectionError('Offline mode is enabled.'      ,					request=UpperCamelCase_			)

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






@contextmanager
def 				a  (     *UpperCamelCase_    :    Optional[int]      ,					**UpperCamelCase_    :    Dict			)       ->	int:
		snake_case__	     =str(Path().resolve()			)
		with tempfile.TemporaryDirectory(*UpperCamelCase_      ,					**UpperCamelCase_			) as tmp_dir:
				try:
						os.chdir(UpperCamelCase_			)
						yield
				finally:
						os.chdir(UpperCamelCase_			)






@contextmanager
def 				a  (     )       ->	Any:
		import gc

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






@contextmanager
def 				a  (     )       ->	List[Any]:
		import gc

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






def 				a  (     UpperCamelCase_    :    Tuple      ,					UpperCamelCase_    :    Optional[int]			)       ->	Optional[Any]:
		return deepcopy(UpperCamelCase_			).integers(0      ,					100      ,					10			).tolist() == deepcopy(UpperCamelCase_			).integers(0      ,					100      ,					10			).tolist()






def 				a  (     UpperCamelCase_    :    List[Any]			)       ->	Tuple:
		import decorator
		from requests.exceptions import HTTPError

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

		return decorator.decorator(_wrapper      ,					UpperCamelCase_			)

class 							a__:






			def __init__(     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Optional[Any]:
					snake_case__	     =returncode
					snake_case__	     =stdout
					snake_case__	     =stderr






async def 				a  (     UpperCamelCase_    :    List[str]      ,					UpperCamelCase_    :    Dict			)       ->	Dict:


		while True:
				snake_case__	     =await stream.readline()
				if line:
						callback(UpperCamelCase_			)
				else:
						break






async def 				a  (     UpperCamelCase_    :    Dict      ,					UpperCamelCase_    :    Optional[int]=None      ,					UpperCamelCase_    :    Optional[int]=None      ,					UpperCamelCase_    :    Dict=None      ,					UpperCamelCase_    :    Optional[Any]=False      ,					UpperCamelCase_    :    Optional[Any]=False			)       ->	str:


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

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

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

		snake_case__	     =[]
		snake_case__	     =[]

		def tee(UpperCamelCase_    :    int      ,					UpperCamelCase_    :    Tuple      ,					UpperCamelCase_    :    Any      ,					UpperCamelCase_    :    int=""			):
				snake_case__	     =line.decode('utf-8'			).rstrip()
				sink.append(UpperCamelCase_			)
				if not quiet:
						print(UpperCamelCase_      ,					UpperCamelCase_      ,					file=UpperCamelCase_			)

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






def 				a  (     UpperCamelCase_    :    Tuple      ,					UpperCamelCase_    :    Dict=None      ,					UpperCamelCase_    :    Dict=None      ,					UpperCamelCase_    :    List[str]=180      ,					UpperCamelCase_    :    List[str]=False      ,					UpperCamelCase_    :    Optional[Any]=True			)       ->	int:
		snake_case__	     =asyncio.get_event_loop()
		snake_case__	     =loop.run_until_complete(
		    _stream_subprocess(UpperCamelCase_      ,					env=UpperCamelCase_      ,					stdin=UpperCamelCase_      ,					timeout=UpperCamelCase_      ,					quiet=UpperCamelCase_      ,					echo=UpperCamelCase_			)			)

		snake_case__	     =' '.join(UpperCamelCase_			)
		if result.returncode > 0:
				snake_case__	     ='\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 				a  (     )       ->	str:
		snake_case__	     =os.environ.get('PYTEST_XDIST_WORKER'      ,					'gw0'			)
		snake_case__	     =re.sub(r'^gw'      ,					''      ,					UpperCamelCase_      ,					0      ,					re.M			)
		return int(UpperCamelCase_			)






def 				a  (     )       ->	List[str]:
		snake_case__	     =29500
		snake_case__	     =pytest_xdist_worker_id()
		return port + uniq_delta











'''simple docstring'''






import argparse
import logging
import pickle
import random
import time

import numpy as np

from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
A__							:  List[str]    =logging.getLogger(__name__)
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				argparse.ArgumentParser(
          description="""Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids)."""    )
      parser.add_argument("""--file_path"""				,      type=lowerCAmelCase				,      default="""data/dump.txt"""				,      help="""The path to the data."""    )
      parser.add_argument("""--tokenizer_type"""				,      type=lowerCAmelCase				,      default="""bert"""				,      choices=["""bert""", """roberta""", """gpt2"""]    )
      parser.add_argument("""--tokenizer_name"""				,      type=lowerCAmelCase				,      default="""bert-base-uncased"""				,      help="""The tokenizer to use."""    )
      parser.add_argument("""--dump_file"""				,      type=lowerCAmelCase				,      default="""data/dump"""				,      help="""The dump file prefix."""    )
      _lowerCAmelCase					=				parser.parse_args()

      logger.info(f"Loading Tokenizer ({args.tokenizer_name})"    )
      if args.tokenizer_type == "bert":
            _lowerCAmelCase					=				BertTokenizer.from_pretrained(args.tokenizer_name    )
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""cls_token"""]  # `[CLS]`
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""sep_token"""]  # `[SEP]`
      elif args.tokenizer_type == "roberta":
            _lowerCAmelCase					=				RobertaTokenizer.from_pretrained(args.tokenizer_name    )
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""cls_token"""]  # `<s>`
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""sep_token"""]  # `</s>`
      elif args.tokenizer_type == "gpt2":
            _lowerCAmelCase					=				GPTaTokenizer.from_pretrained(args.tokenizer_name    )
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""bos_token"""]  # `<|endoftext|>`
            _lowerCAmelCase					=				tokenizer.special_tokens_map["""eos_token"""]  # `<|endoftext|>`

      logger.info(f"Loading text from {args.file_path}"    )
      with open(args.file_path				,      """r"""				,      encoding="""utf8"""    ) as fp:
            _lowerCAmelCase					=				fp.readlines()

      logger.info("""Start encoding"""    )
      logger.info(f"{len(lowerCAmelCase    )} examples to process."    )

      _lowerCAmelCase					=				[]
      _lowerCAmelCase					=				0
      _lowerCAmelCase					=				1_00_00
      _lowerCAmelCase					=				time.time()
      for text in data:
            _lowerCAmelCase					=				f"{bos} {text.strip()} {sep}"
            _lowerCAmelCase					=				tokenizer.encode(lowerCAmelCase				,      add_special_tokens=lowerCAmelCase    )
            rslt.append(lowerCAmelCase    )

            iter += 1
            if iter % interval == 0:
                  _lowerCAmelCase					=				time.time()
                  logger.info(f"{iter} examples processed. - {(end-start):.2f}s/{interval}expl"    )
                  _lowerCAmelCase					=				time.time()
      logger.info("""Finished binarization"""    )
      logger.info(f"{len(lowerCAmelCase    )} examples processed."    )

      _lowerCAmelCase					=				f"{args.dump_file}.{args.tokenizer_name}.pickle"
      _lowerCAmelCase					=				tokenizer.vocab_size
      if vocab_size < (1 << 16):
            _lowerCAmelCase					=				[np.uintaa(lowerCAmelCase    ) for d in rslt]
      else:
            _lowerCAmelCase					=				[np.intaa(lowerCAmelCase    ) for d in rslt]
      random.shuffle(rslt_    )
      logger.info(f"Dump to {dp_file}"    )
      with open(lowerCAmelCase				,      """wb"""    ) as handle:
            pickle.dump(rslt_				,      lowerCAmelCase				,      protocol=pickle.HIGHEST_PROTOCOL    )


if __name__ == "__main__":
      main()






