



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:
										UpperCamelCase_		  =   os.environ[key]
					except KeyError:
										# KEY isn't set, default to `default`.
										UpperCamelCase_		  =   default
					else:
										# KEY is set, convert it to True or False.
										try:
															UpperCamelCase_		  =   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   :							List[Any]							 =parse_flag_from_env("""RUN_REMOTE""", default=False)
UpperCAmelCase   :							Dict							 =parse_flag_from_env("""RUN_LOCAL""", default=True)
UpperCAmelCase   :							Tuple							 =parse_flag_from_env("""RUN_PACKAGED""", default=True)

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

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

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



def    _lowerCAmelCase    (_lowerCAmelCase):
					try:
										import faiss  # noqa
					except ImportError:
										UpperCamelCase_		  =   unittest.skip("test requires faiss")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					try:
										import regex  # noqa
					except ImportError:
										UpperCamelCase_		  =   unittest.skip("test requires regex")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					try:
										import elasticsearch  # noqa
					except ImportError:
										UpperCamelCase_		  =   unittest.skip("test requires elasticsearch")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					try:
										import sqlalchemy  # noqa
					except ImportError:
										UpperCamelCase_		  =   unittest.skip("test requires sqlalchemy")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					if not config.TORCH_AVAILABLE:
										UpperCamelCase_		  =   unittest.skip("test requires PyTorch")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					if not config.TF_AVAILABLE:
										UpperCamelCase_		  =   unittest.skip("test requires TensorFlow")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					if not config.JAX_AVAILABLE:
										UpperCamelCase_		  =   unittest.skip("test requires JAX")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					if not config.PIL_AVAILABLE:
										UpperCamelCase_		  =   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:
										UpperCamelCase_		  =   unittest.skip("test is slow")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					if not _run_local_tests or _run_local_tests == 0:
										UpperCamelCase_		  =   unittest.skip("test is local")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					if not _run_packaged_tests or _run_packaged_tests == 0:
										UpperCamelCase_		  =   unittest.skip("test is packaged")(_lowerCAmelCase)
					return test_case



def    _lowerCAmelCase    (_lowerCAmelCase):
					if not _run_remote_tests or _run_remote_tests == 0:
										UpperCamelCase_		  =   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:
																									UpperCamelCase_		  =   decorator(_lowerCAmelCase)
																				setattr(cls   ,	_lowerCAmelCase   ,	_lowerCAmelCase)
										return cls

					return decorate


class       _lowercase   (a_      ):
				'''simple docstring'''







				pass




class       _lowercase   (a_      ):
				'''simple docstring'''







				lowercase__   						=						0
				lowercase__   						=						1
				lowercase__   						=						2




@contextmanager
def    _lowerCAmelCase    (_lowerCAmelCase=OfflineSimulationMode.CONNECTION_FAILS   ,	_lowerCAmelCase=1e-16):
					UpperCamelCase_		  =   requests.Session().request

					def timeout_request(_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase   ,	**_lowerCAmelCase):
										# Change the url to an invalid url so that the connection hangs
										UpperCamelCase_		  =   "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.""")
										UpperCamelCase_		  =   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
															UpperCamelCase_		  =   url
															UpperCamelCase_		  =   e.args[0]
															UpperCamelCase_		  =   (max_retry_error.args[0].replace("10.255.255.1"   ,	f"""OfflineMock[{url}]"""),)
															UpperCamelCase_		  =   (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):
					UpperCamelCase_		  =   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()
					UpperCamelCase_		  =   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()
					UpperCamelCase_		  =   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   ,	1_00   ,	10).tolist() == deepcopy(_lowerCAmelCase).integers(0   ,	1_00   ,	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       _lowercase   :
				'''simple docstring'''







				def __init__( self     , snake_case__     , snake_case__     , snake_case__    ):

									'''simple docstring'''


									UpperCamelCase_		  =   returncode
									UpperCamelCase_		  =   stdout
									UpperCamelCase_		  =   stderr




async def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase):
					while True:
										UpperCamelCase_		  =   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))

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

					UpperCamelCase_		  =   []
					UpperCamelCase_		  =   []

					def tee(_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase=""):
										UpperCamelCase_		  =   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=1_80   ,	_lowerCAmelCase=False   ,	_lowerCAmelCase=True):
					UpperCamelCase_		  =   asyncio.get_event_loop()
					UpperCamelCase_		  =   loop.run_until_complete(
					    _stream_subprocess(_lowerCAmelCase   ,	env=_lowerCAmelCase   ,	stdin=_lowerCAmelCase   ,	timeout=_lowerCAmelCase   ,	quiet=_lowerCAmelCase   ,	echo=_lowerCAmelCase))

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






def    _lowerCAmelCase    ():
					UpperCamelCase_		  =   2_95_00
					UpperCamelCase_		  =   pytest_xdist_worker_id()
					return port + uniq_delta





import os

import pytest

from datasets import (
    get_dataset_config_info,
    get_dataset_config_names,
    get_dataset_infos,
    get_dataset_split_names,
    inspect_dataset,
    inspect_metric,
)


UpperCAmelCase   :							Optional[Any]							 =pytest.mark.integration



@pytest.mark.parametrize("path"   ,	["paws", "csv"])
def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase):
					inspect_dataset(_lowerCAmelCase   ,	_lowerCAmelCase)
					UpperCamelCase_		  =   path + ".py"
					assert script_name in os.listdir(_lowerCAmelCase)
					assert "__pycache__" not in os.listdir(_lowerCAmelCase)



@pytest.mark.filterwarnings("ignore:inspect_metric is deprecated:FutureWarning")
@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning")
@pytest.mark.parametrize("path"   ,	["accuracy"])
def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase):
					inspect_metric(_lowerCAmelCase   ,	_lowerCAmelCase)
					UpperCamelCase_		  =   path + ".py"
					assert script_name in os.listdir(_lowerCAmelCase)
					assert "__pycache__" not in os.listdir(_lowerCAmelCase)



@pytest.mark.parametrize(
    "path, config_name, expected_splits"   ,	[
        ("squad", "plain_text", ["train", "validation"]),
        ("dalle-mini/wit", "dalle-mini--wit", ["train"]),
        ("paws", "labeled_final", ["train", "test", "validation"]),
    ]   ,	)
def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase):
					UpperCamelCase_		  =   get_dataset_config_info(_lowerCAmelCase   ,	config_name=_lowerCAmelCase)
					assert info.config_name == config_name
					assert list(info.splits.keys()) == expected_splits



@pytest.mark.parametrize(
    "path, config_name, expected_exception"   ,	[
        ("paws", None, ValueError),
    ]   ,	)
def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase):
					with pytest.raises(_lowerCAmelCase):
										get_dataset_config_info(_lowerCAmelCase   ,	config_name=_lowerCAmelCase)



@pytest.mark.parametrize(
    "path, expected"   ,	[
        ("squad", "plain_text"),
        ("acronym_identification", "default"),
        ("lhoestq/squad", "plain_text"),
        ("lhoestq/test", "default"),
        ("lhoestq/demo1", "lhoestq--demo1"),
        ("dalle-mini/wit", "dalle-mini--wit"),
    ]   ,	)
def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase):
					UpperCamelCase_		  =   get_dataset_config_names(_lowerCAmelCase)
					assert expected in config_names



@pytest.mark.parametrize(
    "path, expected_configs, expected_splits_in_first_config"   ,	[
        ("squad", ["plain_text"], ["train", "validation"]),
        ("dalle-mini/wit", ["dalle-mini--wit"], ["train"]),
        ("paws", ["labeled_final", "labeled_swap", "unlabeled_final"], ["train", "test", "validation"]),
    ]   ,	)
def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase):
					UpperCamelCase_		  =   get_dataset_infos(_lowerCAmelCase)
					assert list(infos.keys()) == expected_configs
					UpperCamelCase_		  =   expected_configs[0]
					assert expected_config in infos
					UpperCamelCase_		  =   infos[expected_config]
					assert info.config_name == expected_config
					assert list(info.splits.keys()) == expected_splits_in_first_config



@pytest.mark.parametrize(
    "path, expected_config, expected_splits"   ,	[
        ("squad", "plain_text", ["train", "validation"]),
        ("dalle-mini/wit", "dalle-mini--wit", ["train"]),
        ("paws", "labeled_final", ["train", "test", "validation"]),
    ]   ,	)
def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase):
					UpperCamelCase_		  =   get_dataset_infos(_lowerCAmelCase)
					assert expected_config in infos
					UpperCamelCase_		  =   infos[expected_config]
					assert info.config_name == expected_config
					assert list(info.splits.keys()) == expected_splits






@pytest.mark.parametrize(
    "path, config_name, expected_exception"   ,	[
        ("paws", None, ValueError),
    ]   ,	)
def    _lowerCAmelCase    (_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase):
					with pytest.raises(_lowerCAmelCase):
										get_dataset_split_names(_lowerCAmelCase   ,	config_name=_lowerCAmelCase)
