



"""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  UpperCamelCase						(       _A			:				int			,							_A			:				Any=False    )->       Optional[Any]:





						"""simple docstring"""





						try:
												A__							=       os.environ[key]
						except KeyError:
												# KEY isn't set, default to `default`.
												A__							=       default
						else:
												# KEY is set, convert it to True or False.
												try:
																		A__							=       strtobool(__a    )
												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_							:      Optional[Any]      =  parse_flag_from_env("RUN_SLOW", default=False)
UpperCAmelCase_							:      str      =  parse_flag_from_env("RUN_REMOTE", default=False)
UpperCAmelCase_							:      Optional[Any]      =  parse_flag_from_env("RUN_LOCAL", default=True)
UpperCAmelCase_							:      Union[str, Any]      =  parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
UpperCAmelCase_							:      Union[str, Any]      =  pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
UpperCAmelCase_							:      str      =  pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
UpperCAmelCase_							:      List[str]      =  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_							:      List[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_							:      List[str]      =  pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
UpperCAmelCase_							:      Optional[int]      =  pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)
def  UpperCamelCase						(       _A			:				List[str]    )->       Dict:





						"""simple docstring"""





						try:
												import faiss  # noqa
						except ImportError:
												A__							=       unittest.skip("test requires faiss"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				Optional[int]    )->       str:





						"""simple docstring"""





						try:
												import regex  # noqa
						except ImportError:
												A__							=       unittest.skip("test requires regex"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				Optional[Any]    )->       int:





						"""simple docstring"""





						try:
												import elasticsearch  # noqa
						except ImportError:
												A__							=       unittest.skip("test requires elasticsearch"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				Optional[Any]    )->       str:





						"""simple docstring"""





						try:
												import sqlalchemy  # noqa
						except ImportError:
												A__							=       unittest.skip("test requires sqlalchemy"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				Tuple    )->       str:





						"""simple docstring"""





						if not config.TORCH_AVAILABLE:
												A__							=       unittest.skip("test requires PyTorch"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				str    )->       Optional[Any]:





						"""simple docstring"""





						if not config.TF_AVAILABLE:
												A__							=       unittest.skip("test requires TensorFlow"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				Optional[int]    )->       List[Any]:





						"""simple docstring"""





						if not config.JAX_AVAILABLE:
												A__							=       unittest.skip("test requires JAX"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				str    )->       str:





						"""simple docstring"""





						if not config.PIL_AVAILABLE:
												A__							=       unittest.skip("test requires Pillow"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				List[str]    )->       Any:





						"""simple docstring"""





						try:
												import transformers  # noqa F401
						except ImportError:
												return unittest.skip("test requires transformers"    )(__a    )
						else:
												return test_case
def  UpperCamelCase						(       _A			:				str    )->       List[str]:





						"""simple docstring"""





						try:
												import tiktoken  # noqa F401
						except ImportError:
												return unittest.skip("test requires tiktoken"    )(__a    )
						else:
												return test_case
def  UpperCamelCase						(       _A			:				Any    )->       Tuple:





						"""simple docstring"""





						try:
												import spacy  # noqa F401
						except ImportError:
												return unittest.skip("test requires spacy"    )(__a    )
						else:
												return test_case
def  UpperCamelCase						(       _A			:				str    )->       Any:





						"""simple docstring"""





						def _require_spacy_model(_A			:				str    ):
												try:
																		import spacy  # noqa F401

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

						return _require_spacy_model
def  UpperCamelCase						(       _A			:				Dict    )->       List[Any]:





						"""simple docstring"""





						try:
												import pyspark  # noqa F401
						except ImportError:
												return unittest.skip("test requires pyspark"    )(__a    )
						else:
												return test_case
def  UpperCamelCase						(       _A			:				str    )->       Any:





						"""simple docstring"""





						try:
												import joblibspark  # noqa F401
						except ImportError:
												return unittest.skip("test requires joblibspark"    )(__a    )
						else:
												return test_case
def  UpperCamelCase						(       _A			:				Any    )->       Optional[Any]:





						"""simple docstring"""





						if not _run_slow_tests or _run_slow_tests == 0:
												A__							=       unittest.skip("test is slow"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				List[str]    )->       Any:





						"""simple docstring"""





						if not _run_local_tests or _run_local_tests == 0:
												A__							=       unittest.skip("test is local"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				Any    )->       int:





						"""simple docstring"""





						if not _run_packaged_tests or _run_packaged_tests == 0:
												A__							=       unittest.skip("test is packaged"    )(__a    )
						return test_case
def  UpperCamelCase						(       _A			:				Any    )->       Any:





						"""simple docstring"""





						if not _run_remote_tests or _run_remote_tests == 0:
												A__							=       unittest.skip("test requires remote"    )(__a    )
						return test_case
def  UpperCamelCase						(       *_A			:				Tuple    )->       List[Any]:





						"""simple docstring"""





						def decorate(cls			:				List[Any]    ):
												for name, fn in cls.__dict__.items():
																		if callable(__a    ) and name.startswith("test"    ):
																								for decorator in decorators:
																														A__							=       decorator(__a    )
																								setattr(cls			,							__a			,							__a    )
												return cls

						return decorate






class      UpperCamelCase    (						snake_case_     ):
	pass






class      UpperCamelCase    (						snake_case_     ):
	lowerCAmelCase	:   Optional[int]				=	0
	lowerCAmelCase	:   str				=	1
	lowerCAmelCase	:   Optional[int]				=	2





@contextmanager
def  UpperCamelCase						(       _A			:				Optional[Any]=OfflineSimulationMode.CONNECTION_FAILS			,							_A			:				str=1E-16    )->       Optional[int]:





						"""simple docstring"""





						A__							=       requests.Session().request

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

						def raise_connection_error(_A			:				int			,							_A			:				Optional[Any]			,							**_A			:				List[str]    ):
												raise requests.ConnectionError("Offline mode is enabled."			,							request=__a    )

						if mode is OfflineSimulationMode.CONNECTION_FAILS:
												with patch("requests.Session.send"			,							__a    ):
																		yield
						elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
												# inspired from https://stackoverflow.com/a/904609
												with patch("requests.Session.request"			,							__a    ):
																		yield
						elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
												with patch("datasets.config.HF_DATASETS_OFFLINE"			,							__a    ):
																		yield
						else:
												raise ValueError("Please use a value from the OfflineSimulationMode enum."    )
@contextmanager
def  UpperCamelCase						(       *_A			:				Dict			,							**_A			:				Dict    )->       List[Any]:





						"""simple docstring"""





						A__							=       str(Path().resolve()    )
						with tempfile.TemporaryDirectory(*__a			,							**__a    ) as tmp_dir:
												try:
																		os.chdir(__a    )
																		yield
												finally:
																		os.chdir(__a    )
@contextmanager
def  UpperCamelCase						(       )->       Dict:





						"""simple docstring"""





						import gc

						gc.collect()
						A__							=       pa.total_allocated_bytes()
						yield
						assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."
@contextmanager
def  UpperCamelCase						(       )->       Union[str, Any]:





						"""simple docstring"""





						import gc

						gc.collect()
						A__							=       pa.total_allocated_bytes()
						yield
						assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."
def  UpperCamelCase						(       _A			:				List[Any]			,							_A			:				Union[str, Any]    )->       Union[str, Any]:





						"""simple docstring"""





						return deepcopy(__a    ).integers(0			,							100			,							10    ).tolist() == deepcopy(__a    ).integers(0			,							100			,							10    ).tolist()
def  UpperCamelCase						(       _A			:				List[Any]    )->       str:





						"""simple docstring"""





						import decorator
						from requests.exceptions import HTTPError

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

						return decorator.decorator(_wrapper			,							__a    )






class      UpperCamelCase    :



	def __init__(       self			,	UpperCAmelCase__			,	UpperCAmelCase__			,	UpperCAmelCase__		):
							A__							=       returncode
							A__							=       stdout
							A__							=       stderr





async def  UpperCamelCase						(       _A			:				Dict			,							_A			:				int    )->       str:





						"""simple docstring"""





						while True:
												A__							=       await stream.readline()
												if line:
																		callback(__a    )
												else:
																		break
async def  UpperCamelCase						(       _A			:				Any			,							_A			:				Tuple=None			,							_A			:				Tuple=None			,							_A			:				str=None			,							_A			:				int=False			,							_A			:				List[Any]=False    )->       Tuple:





						"""simple docstring"""





						if echo:
												print("\nRunning: "			,							" ".join(__a    )    )

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

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

						A__							=       []
						A__							=       []

						def tee(_A			:				Union[str, Any]			,							_A			:				int			,							_A			:				Any			,							_A			:				Dict=""    ):
												A__							=       line.decode("utf-8"    ).rstrip()
												sink.append(__a    )
												if not quiet:
																		print(__a			,							__a			,							file=__a    )

    # XXX: the timeout doesn't seem to make any difference here
						await asyncio.wait(
						    [
						        _read_stream(p.stdout			,							lambda _A    : tee(__a			,							__a			,							sys.stdout			,							label="stdout:"    )    ),
						        _read_stream(p.stderr			,							lambda _A    : tee(__a			,							__a			,							sys.stderr			,							label="stderr:"    )    ),
						    ]			,							timeout=__a			,							)
						return _RunOutput(await p.wait()			,							__a			,							__a    )
def  UpperCamelCase						(       _A			:				Union[str, Any]			,							_A			:				Optional[int]=None			,							_A			:				Dict=None			,							_A			:				Dict=180			,							_A			:				Optional[Any]=False			,							_A			:				List[Any]=True    )->       List[str]:





						"""simple docstring"""





						A__							=       asyncio.get_event_loop()
						A__							=       loop.run_until_complete(
						    _stream_subprocess(__a			,							env=__a			,							stdin=__a			,							timeout=__a			,							quiet=__a			,							echo=__a    )    )

						A__							=       ' '.join(__a    )
						if result.returncode > 0:
												A__							=       '\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						(       )->       Tuple:





						"""simple docstring"""





						A__							=       os.environ.get("PYTEST_XDIST_WORKER"			,							"gw0"    )
						A__							=       re.sub(R"^gw"			,							""			,							__a			,							0			,							re.M    )
						return int(__a    )
def  UpperCamelCase						(       )->       Optional[int]:





						"""simple docstring"""





						A__							=       29500
						A__							=       pytest_xdist_worker_id()
						return port + uniq_delta










from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core


# define which module versions we always want to check at run time
# (usually the ones defined in `install_requires` in setup.py)
#
# order specific notes:
# - tqdm must be checked before tokenizers

UpperCAmelCase_							:      List[Any]      =  [
    "python",
    "tqdm",
    "regex",
    "requests",
    "packaging",
    "filelock",
    "numpy",
    "tokenizers",
    "huggingface-hub",
    "safetensors",
    "accelerate",
    "pyyaml",
]

for pkg in pkgs_to_check_at_runtime:
						if pkg in deps:
												if pkg == "tokenizers":
																		# must be loaded here, or else tqdm check may fail
																		from .utils import is_tokenizers_available

																		if not is_tokenizers_available():
																								continue  # not required, check version only if installed
												elif pkg == "accelerate":
																		# must be loaded here, or else tqdm check may fail
																		from .utils import is_accelerate_available

																		# Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of
																		# Transformers with PyTorch
																		if not is_accelerate_available():
																								continue  # not required, check version only if installed

												require_version_core(deps[pkg])
						else:
												raise ValueError(F'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''')
def  UpperCamelCase						(       _A			:				List[Any]			,							_A			:				int=None    )->       Optional[int]:





						"""simple docstring"""





						require_version(deps[pkg]			,							_A    )





