





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


_SCREAMING_SNAKE_CASE 		=						parse_flag_from_env("""RUN_SLOW""", default=False)
_SCREAMING_SNAKE_CASE 		=						parse_flag_from_env("""RUN_REMOTE""", default=False)
_SCREAMING_SNAKE_CASE 		=						parse_flag_from_env("""RUN_LOCAL""", default=True)
_SCREAMING_SNAKE_CASE 		=						parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
_SCREAMING_SNAKE_CASE 		=						pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
_SCREAMING_SNAKE_CASE 		=						pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
_SCREAMING_SNAKE_CASE 		=						pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

# Audio
_SCREAMING_SNAKE_CASE 		=						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 		=						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 		=						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 		=						pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	try:
		import faiss  # noqa
	except ImportError:
		snake_case_						:     List[str]     =		unittest.skip('test requires faiss'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	try:
		import regex  # noqa
	except ImportError:
		snake_case_						:     Dict     =		unittest.skip('test requires regex'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	try:
		import elasticsearch  # noqa
	except ImportError:
		snake_case_						:     int     =		unittest.skip('test requires elasticsearch'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	try:
		import sqlalchemy  # noqa
	except ImportError:
		snake_case_						:     Union[str, Any]     =		unittest.skip('test requires sqlalchemy'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	if not config.TORCH_AVAILABLE:
		snake_case_						:     Union[str, Any]     =		unittest.skip('test requires PyTorch'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	if not config.TF_AVAILABLE:
		snake_case_						:     Union[str, Any]     =		unittest.skip('test requires TensorFlow'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	if not config.JAX_AVAILABLE:
		snake_case_						:     Optional[Any]     =		unittest.skip('test requires JAX'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	if not config.PIL_AVAILABLE:
		snake_case_						:     List[str]     =		unittest.skip('test requires Pillow'				)(__a				)
	return test_case


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


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


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


def 							SCREAMING_SNAKE_CASE__  (      __a				):

	def _require_spacy_model(__a				):
		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 							SCREAMING_SNAKE_CASE__  (      __a				):
	try:
		import pyspark  # noqa F401
	except ImportError:
		return unittest.skip('test requires pyspark'				)(__a				)
	else:
		return test_case


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


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	if not _run_slow_tests or _run_slow_tests == 0:
		snake_case_						:     Optional[Any]     =		unittest.skip('test is slow'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	if not _run_local_tests or _run_local_tests == 0:
		snake_case_						:     Dict     =		unittest.skip('test is local'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	if not _run_packaged_tests or _run_packaged_tests == 0:
		snake_case_						:     int     =		unittest.skip('test is packaged'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	if not _run_remote_tests or _run_remote_tests == 0:
		snake_case_						:     str     =		unittest.skip('test requires remote'				)(__a				)
	return test_case


def 							SCREAMING_SNAKE_CASE__  (      *__a				):
	def decorate(cls				):
		for name, fn in cls.__dict__.items():
			if callable(__a				) and name.startswith('test'				):
				for decorator in decorators:
					snake_case_						:     Tuple     =		decorator(__a				)
				setattr(cls				,	__a				,	__a				)
		return cls

	return decorate
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						pass
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     Optional[int]	 =    0
						__magic_name__:     str	 =    1
						__magic_name__:     Optional[int]	 =    2


@contextmanager
def 							SCREAMING_SNAKE_CASE__  (      __a=OfflineSimulationMode.CONNECTION_FAILS				,	__a=1E-16				):
	snake_case_						:     List[str]     =		requests.Session().request

	def timeout_request(__a				,	__a				,	__a				,	**__a				):
		# Change the url to an invalid url so that the connection hangs
		snake_case_						:     Optional[int]     =		'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_						:     List[Any]     =		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
			snake_case_						:     List[str]     =		url
			snake_case_						:     Tuple     =		e.args[0]
			snake_case_						:     str     =		(max_retry_error.args[0].replace('10.255.255.1'				,	f"""OfflineMock[{url}]"""				),)
			snake_case_						:     int     =		(max_retry_error,)
			raise

	def raise_connection_error(__a				,	__a				,	**__a				):
		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 							SCREAMING_SNAKE_CASE__  (      *__a				,	**__a				):
	snake_case_						:     Dict     =		str(Path().resolve()				)
	with tempfile.TemporaryDirectory(*__a				,	**__a				) as tmp_dir:
		try:
			os.chdir(__a				)
			yield
		finally:
			os.chdir(__a				)


@contextmanager
def 							SCREAMING_SNAKE_CASE__  (      ):
	import gc

	gc.collect()
	snake_case_						:     List[Any]     =		pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."


@contextmanager
def 							SCREAMING_SNAKE_CASE__  (      ):
	import gc

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


def 							SCREAMING_SNAKE_CASE__  (      __a				,	__a				):
	return deepcopy(__a				).integers(0				,	1_00				,	10				).tolist() == deepcopy(__a				).integers(0				,	1_00				,	10				).tolist()


def 							SCREAMING_SNAKE_CASE__  (      __a				):
	import decorator
	from requests.exceptions import HTTPError

	def _wrapper(__a				,	*__a				,	**__a				):
		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 SCREAMING_SNAKE_CASE_  :






						def __init__( self : Tuple						,				_A : Any						,				_A : Tuple						,				_A : List[str]		)							->      Union[str, Any]:







							"""simple docstring"""


							snake_case_						:     Optional[Any]     =		returncode
							snake_case_						:     str     =		stdout
							snake_case_						:     int     =		stderr


async def 							SCREAMING_SNAKE_CASE__  (      __a				,	__a				):
	while True:
		snake_case_						:     Dict     =		await stream.readline()
		if line:
			callback(__a				)
		else:
			break


async def 							SCREAMING_SNAKE_CASE__  (      __a				,	__a=None				,	__a=None				,	__a=None				,	__a=False				,	__a=False				):
	if echo:
		print('\nRunning: '				,	' '.join(__a				)				)

	snake_case_						:     List[Any]     =		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)

	snake_case_						:     Tuple     =		[]
	snake_case_						:     Any     =		[]

	def tee(__a				,	__a				,	__a				,	__a=""				):
		snake_case_						:     Union[str, Any]     =		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 							SCREAMING_SNAKE_CASE__  (      __a				,	__a=None				,	__a=None				,	__a=1_80				,	__a=False				,	__a=True				):
	snake_case_						:     Union[str, Any]     =		asyncio.get_event_loop()
	snake_case_						:     List[Any]     =		loop.run_until_complete(
	    _stream_subprocess(__a				,	env=__a				,	stdin=__a				,	timeout=__a				,	quiet=__a				,	echo=__a				)				)

	snake_case_						:     Optional[Any]     =		' '.join(__a				)
	if result.returncode > 0:
		snake_case_						:     Any     =		'\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 							SCREAMING_SNAKE_CASE__  (      ):
	snake_case_						:     Any     =		os.environ.get('PYTEST_XDIST_WORKER'				,	'gw0'				)
	snake_case_						:     List[Any]     =		re.sub(r'^gw'				,	''				,	__a				,	0				,	re.M				)
	return int(__a				)


def 							SCREAMING_SNAKE_CASE__  (      ):
	snake_case_						:     str     =		2_95_00
	snake_case_						:     Any     =		pytest_xdist_worker_id()
	return port + uniq_delta








_SCREAMING_SNAKE_CASE 		=						{
    """Pillow""": """Pillow""",
    """accelerate""": """accelerate>=0.11.0""",
    """compel""": """compel==0.1.8""",
    """black""": """black~=23.1""",
    """datasets""": """datasets""",
    """filelock""": """filelock""",
    """flax""": """flax>=0.4.1""",
    """hf-doc-builder""": """hf-doc-builder>=0.3.0""",
    """huggingface-hub""": """huggingface-hub>=0.13.2""",
    """requests-mock""": """requests-mock==1.10.0""",
    """importlib_metadata""": """importlib_metadata""",
    """invisible-watermark""": """invisible-watermark""",
    """isort""": """isort>=5.5.4""",
    """jax""": """jax>=0.2.8,!=0.3.2""",
    """jaxlib""": """jaxlib>=0.1.65""",
    """Jinja2""": """Jinja2""",
    """k-diffusion""": """k-diffusion>=0.0.12""",
    """torchsde""": """torchsde""",
    """note_seq""": """note_seq""",
    """librosa""": """librosa""",
    """numpy""": """numpy""",
    """omegaconf""": """omegaconf""",
    """parameterized""": """parameterized""",
    """protobuf""": """protobuf>=3.20.3,<4""",
    """pytest""": """pytest""",
    """pytest-timeout""": """pytest-timeout""",
    """pytest-xdist""": """pytest-xdist""",
    """ruff""": """ruff>=0.0.241""",
    """safetensors""": """safetensors""",
    """sentencepiece""": """sentencepiece>=0.1.91,!=0.1.92""",
    """scipy""": """scipy""",
    """onnx""": """onnx""",
    """regex""": """regex!=2019.12.17""",
    """requests""": """requests""",
    """tensorboard""": """tensorboard""",
    """torch""": """torch>=1.4""",
    """torchvision""": """torchvision""",
    """transformers""": """transformers>=4.25.1""",
    """urllib3""": """urllib3<=2.0.0""",
}

