




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 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase=False ):
				try:
								__magic_name__						:						Union[str, Any]										=os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								__magic_name__						:						List[str]										=default
				else:
								# KEY is set, convert it to True or False.
								try:
												__magic_name__						:						int										=strtobool(lowerCamelCase )
								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


UpperCAmelCase_		:					Dict          =  parse_flag_from_env("RUN_SLOW", default=False)
UpperCAmelCase_		:					str          =  parse_flag_from_env("RUN_REMOTE", default=False)
UpperCAmelCase_		:					int          =  parse_flag_from_env("RUN_LOCAL", default=True)
UpperCAmelCase_		:					Any          =  parse_flag_from_env("RUN_PACKAGED", default=True)

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

# Audio
UpperCAmelCase_		:					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
UpperCAmelCase_		:					str          =  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
UpperCAmelCase_		:					Optional[int]          =  pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
UpperCAmelCase_		:					Tuple          =  pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import faiss  # noqa
				except ImportError:
								__magic_name__						:						List[str]										=unittest.skip("""test requires faiss""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import regex  # noqa
				except ImportError:
								__magic_name__						:						Union[str, Any]										=unittest.skip("""test requires regex""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import elasticsearch  # noqa
				except ImportError:
								__magic_name__						:						Any										=unittest.skip("""test requires elasticsearch""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import sqlalchemy  # noqa
				except ImportError:
								__magic_name__						:						Tuple										=unittest.skip("""test requires sqlalchemy""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if not config.TORCH_AVAILABLE:
								__magic_name__						:						List[Any]										=unittest.skip("""test requires PyTorch""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if not config.TF_AVAILABLE:
								__magic_name__						:						List[str]										=unittest.skip("""test requires TensorFlow""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if not config.JAX_AVAILABLE:
								__magic_name__						:						Union[str, Any]										=unittest.skip("""test requires JAX""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if not config.PIL_AVAILABLE:
								__magic_name__						:						Optional[Any]										=unittest.skip("""test requires Pillow""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import transformers  # noqa F401
				except ImportError:
								return unittest.skip("""test requires transformers""" )(lowerCamelCase )
				else:
								return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import tiktoken  # noqa F401
				except ImportError:
								return unittest.skip("""test requires tiktoken""" )(lowerCamelCase )
				else:
								return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import spacy  # noqa F401
				except ImportError:
								return unittest.skip("""test requires spacy""" )(lowerCamelCase )
				else:
								return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):

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

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

				return _require_spacy_model




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import pyspark  # noqa F401
				except ImportError:
								return unittest.skip("""test requires pyspark""" )(lowerCamelCase )
				else:
								return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				try:
								import joblibspark  # noqa F401
				except ImportError:
								return unittest.skip("""test requires joblibspark""" )(lowerCamelCase )
				else:
								return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if not _run_slow_tests or _run_slow_tests == 0:
								__magic_name__						:						List[str]										=unittest.skip("""test is slow""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if not _run_local_tests or _run_local_tests == 0:
								__magic_name__						:						Any										=unittest.skip("""test is local""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if not _run_packaged_tests or _run_packaged_tests == 0:
								__magic_name__						:						Dict										=unittest.skip("""test is packaged""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						lowerCamelCase ):
				if not _run_remote_tests or _run_remote_tests == 0:
								__magic_name__						:						Optional[Any]										=unittest.skip("""test requires remote""" )(lowerCamelCase )
				return test_case




def 		lowerCAmelCase_ (						*lowerCamelCase ):
				def decorate(cls ):
								for name, fn in cls.__dict__.items():
												if callable(lowerCamelCase ) and name.startswith("""test""" ):
																for decorator in decorators:
																				__magic_name__						:						Optional[Any]										=decorator(lowerCamelCase )
																setattr(cls						,  lowerCamelCase						,  lowerCamelCase )
								return cls

				return decorate




class 		__A   (      UpperCamelCase__      ):
						pass




class 		__A   (      UpperCamelCase__      ):
						UpperCamelCase      =       0
						UpperCamelCase      =       1
						UpperCamelCase      =       2




@contextmanager
def 		lowerCAmelCase_ (						lowerCamelCase=OfflineSimulationMode.CONNECTION_FAILS						,  lowerCamelCase=1E-16 ):
				__magic_name__						:						Union[str, Any]										=requests.Session().request

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

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

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




@contextmanager
def 		lowerCAmelCase_ (						*lowerCamelCase						,  **lowerCamelCase ):
				__magic_name__						:						Any										=str(Path().resolve() )
				with tempfile.TemporaryDirectory(*lowerCamelCase						,  **lowerCamelCase ) as tmp_dir:
								try:
												os.chdir(lowerCamelCase )
												yield
								finally:
												os.chdir(lowerCamelCase )




@contextmanager
def 		lowerCAmelCase_ (						):
				import gc

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




@contextmanager
def 		lowerCAmelCase_ (						):
				import gc

				gc.collect()
				__magic_name__						:						List[str]										=pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."




def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase ):
				return deepcopy(lowerCamelCase ).integers(0						,  100						,  10 ).tolist() == deepcopy(lowerCamelCase ).integers(0						,  100						,  10 ).tolist()




def 		lowerCAmelCase_ (						lowerCamelCase ):
				import decorator
				from requests.exceptions import HTTPError

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

				return decorator.decorator(_wrapper						,  lowerCamelCase )




class 		__A   :

						def __init__(		self :Any     ,			__snake_case :List[str]     ,			__snake_case :List[Any]     ,			__snake_case :str			):
										'''simple docstring'''

										__magic_name__						:						Optional[Any]										=returncode
										__magic_name__						:						Any										=stdout
										__magic_name__						:						Any										=stderr




async def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase ):
				while True:
								__magic_name__						:						Any										=await stream.readline()
								if line:
												callback(lowerCamelCase )
								else:
												break




async def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase=None						,  lowerCamelCase=None						,  lowerCamelCase=None						,  lowerCamelCase=False						,  lowerCamelCase=False ):
				if echo:
								print("""\nRunning: """						,  """ """.join(lowerCamelCase ) )

				__magic_name__						:						Optional[int]										=await asyncio.create_subprocess_exec(
				    cmd[0]						,  *cmd[1:]						,  stdin=lowerCamelCase						,  stdout=asyncio.subprocess.PIPE						,  stderr=asyncio.subprocess.PIPE						,  env=lowerCamelCase						,  )

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

				__magic_name__						:						Tuple										=[]
				__magic_name__						:						int										=[]

				def tee(lowerCamelCase						,  lowerCamelCase						,  lowerCamelCase						,  lowerCamelCase="" ):
								__magic_name__						:						Tuple										=line.decode("""utf-8""" ).rstrip()
								sink.append(lowerCamelCase )
								if not quiet:
												print(lowerCamelCase						,  lowerCamelCase						,  file=lowerCamelCase )

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




def 		lowerCAmelCase_ (						lowerCamelCase						,  lowerCamelCase=None						,  lowerCamelCase=None						,  lowerCamelCase=180						,  lowerCamelCase=False						,  lowerCamelCase=True ):
				__magic_name__						:						Tuple										=asyncio.get_event_loop()
				__magic_name__						:						Any										=loop.run_until_complete(
				    _stream_subprocess(lowerCamelCase						,  env=lowerCamelCase						,  stdin=lowerCamelCase						,  timeout=lowerCamelCase						,  quiet=lowerCamelCase						,  echo=lowerCamelCase ) )

				__magic_name__						:						Optional[int]										=""" """.join(lowerCamelCase )
				if result.returncode > 0:
								__magic_name__						:						List[str]										="""\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 		lowerCAmelCase_ (						):
				__magic_name__						:						Dict										=os.environ.get("""PYTEST_XDIST_WORKER"""						,  """gw0""" )
				__magic_name__						:						str										=re.sub(R"""^gw"""						,  """"""						,  lowerCamelCase						,  0						,  re.M )
				return int(lowerCamelCase )




def 		lowerCAmelCase_ (						):
				__magic_name__						:						Optional[int]										=29500
				__magic_name__						:						int										=pytest_xdist_worker_id()
				return port + uniq_delta









'''simple docstring'''





import os
from tempfile import TemporaryDirectory
from unittest import TestCase

import pytest
from absl.testing import parameterized

from datasets import config
from datasets.arrow_reader import HF_GCP_BASE_URL
from datasets.builder import DatasetBuilder
from datasets.dataset_dict import IterableDatasetDict
from datasets.iterable_dataset import IterableDataset
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.file_utils import cached_path


__a  			=						[
    {"dataset": "wikipedia", "config_name": "20220301.de"},
    {"dataset": "wikipedia", "config_name": "20220301.en"},
    {"dataset": "wikipedia", "config_name": "20220301.fr"},
    {"dataset": "wikipedia", "config_name": "20220301.frr"},
    {"dataset": "wikipedia", "config_name": "20220301.it"},
    {"dataset": "wikipedia", "config_name": "20220301.simple"},
    {"dataset": "snli", "config_name": "plain_text"},
    {"dataset": "eli5", "config_name": "LFQA_reddit"},
    {"dataset": "wiki40b", "config_name": "en"},
    {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.compressed"},
    {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.no_index"},
    {"dataset": "wiki_dpr", "config_name": "psgs_w100.multiset.no_index"},
    {"dataset": "natural_questions", "config_name": "default"},
]





def 		__snake_case(							_lowerCAmelCase=True						)						->					Dict:
      if with_config:
            return [
                {
                    "testcase_name": d["dataset"] + "/" + d["config_name"],
                    "dataset": d["dataset"],
                    "config_name": d["config_name"],
                }
                for d in DATASETS_ON_HF_GCP
            ]
      else:
            return [
                {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP}
            ]







@parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=_a      )      )
class        UpperCAmelCase_			(			_a      ):
    """simple docstring"""







    lowercase   =						None
    lowercase   =						None




    def lowerCamelCase			(       self   :	List[Any]					,	snake_case_   :	Union[str, Any]					,	snake_case_   :	Optional[int]		):
          with TemporaryDirectory() as tmp_dir:
                snake_case__    :       Dict       		= dataset_module_factory(snake_case_					,	cache_dir=snake_case_		)

                snake_case__    :       Optional[int]       		= import_main_class(dataset_module.module_path					,	dataset=snake_case_		)

                snake_case__    :       DatasetBuilder       		= builder_cls(
                    cache_dir=snake_case_					,	config_name=snake_case_					,	hash=dataset_module.hash					,	)

                snake_case__    :       Dict       		= """/""".join(
                    [
                        HF_GCP_BASE_URL,
                        builder_instance._relative_data_dir(with_hash=snake_case_		).replace(os.sep					,	"""/"""		),
                        config.DATASET_INFO_FILENAME,
                    ]		)
                snake_case__    :       List[str]       		= cached_path(snake_case_					,	cache_dir=snake_case_		)
                self.assertTrue(os.path.exists(snake_case_		)		)





@pytest.mark.integration
def 		__snake_case(							_lowerCAmelCase						)						->					Tuple:
      snake_case__    :       Optional[int]       		= tmp_path_factory.mktemp("""test_hf_gcp"""						) / """test_wikipedia_simple"""
      snake_case__    :       Dict       		= dataset_module_factory("""wikipedia"""	,  cache_dir=_lowerCAmelCase						)
      snake_case__    :       Dict       		= import_main_class(dataset_module.module_path						)
      snake_case__    :       DatasetBuilder       		= builder_cls(
          cache_dir=_lowerCAmelCase	,  config_name="""20220301.frr"""	,  hash=dataset_module.hash	,  )
      # use the HF cloud storage, not the original download_and_prepare that uses apache-beam
      snake_case__    :       Any       		= None
      builder_instance.download_and_prepare()
      snake_case__    :       Union[str, Any]       		= builder_instance.as_dataset()
      assert ds





@pytest.mark.integration
def 		__snake_case(							_lowerCAmelCase						)						->					List[str]:
      snake_case__    :       Optional[int]       		= dataset_module_factory("""wikipedia"""	,  cache_dir=_lowerCAmelCase						)
      snake_case__    :       List[str]       		= import_main_class(dataset_module.module_path	,  dataset=_lowerCAmelCase						)
      snake_case__    :       DatasetBuilder       		= builder_cls(
          cache_dir=_lowerCAmelCase	,  config_name="""20220301.frr"""	,  hash=dataset_module.hash	,  )
      snake_case__    :       Any       		= builder_instance.as_streaming_dataset()
      assert ds
      assert isinstance(_lowerCAmelCase	,  _lowerCAmelCase						)
      assert "train" in ds
      assert isinstance(ds["""train"""]	,  _lowerCAmelCase						)
      assert next(iter(ds["""train"""]						)						)
