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 					_snake_case	(  __snake_case  ,     __snake_case=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(__snake_case						)
										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


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

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

# Audio
_lowerCAmelCase       =		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
_lowerCAmelCase       =		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
_lowerCAmelCase       =		pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
_lowerCAmelCase       =		pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)
def 					_snake_case	(  __snake_case						):
					try:
										import faiss  # noqa
					except ImportError:
										_UpperCamelCase			     =     unittest.skip('''test requires faiss'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					try:
										import regex  # noqa
					except ImportError:
										_UpperCamelCase			     =     unittest.skip('''test requires regex'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					try:
										import elasticsearch  # noqa
					except ImportError:
										_UpperCamelCase			     =     unittest.skip('''test requires elasticsearch'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					try:
										import sqlalchemy  # noqa
					except ImportError:
										_UpperCamelCase			     =     unittest.skip('''test requires sqlalchemy'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					if not config.TORCH_AVAILABLE:
										_UpperCamelCase			     =     unittest.skip('''test requires PyTorch'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					if not config.TF_AVAILABLE:
										_UpperCamelCase			     =     unittest.skip('''test requires TensorFlow'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					if not config.JAX_AVAILABLE:
										_UpperCamelCase			     =     unittest.skip('''test requires JAX'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					if not config.PIL_AVAILABLE:
										_UpperCamelCase			     =     unittest.skip('''test requires Pillow'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					try:
										import transformers  # noqa F401
					except ImportError:
										return unittest.skip('''test requires transformers'''						)(__snake_case						)
					else:
										return test_case
def 					_snake_case	(  __snake_case						):
					try:
										import tiktoken  # noqa F401
					except ImportError:
										return unittest.skip('''test requires tiktoken'''						)(__snake_case						)
					else:
										return test_case
def 					_snake_case	(  __snake_case						):
					try:
										import spacy  # noqa F401
					except ImportError:
										return unittest.skip('''test requires spacy'''						)(__snake_case						)
					else:
										return test_case
def 					_snake_case	(  __snake_case						):

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

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

					return _require_spacy_model
def 					_snake_case	(  __snake_case						):
					try:
										import pyspark  # noqa F401
					except ImportError:
										return unittest.skip('''test requires pyspark'''						)(__snake_case						)
					else:
										return test_case
def 					_snake_case	(  __snake_case						):
					try:
										import joblibspark  # noqa F401
					except ImportError:
										return unittest.skip('''test requires joblibspark'''						)(__snake_case						)
					else:
										return test_case
def 					_snake_case	(  __snake_case						):
					if not _run_slow_tests or _run_slow_tests == 0:
										_UpperCamelCase			     =     unittest.skip('''test is slow'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					if not _run_local_tests or _run_local_tests == 0:
										_UpperCamelCase			     =     unittest.skip('''test is local'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					if not _run_packaged_tests or _run_packaged_tests == 0:
										_UpperCamelCase			     =     unittest.skip('''test is packaged'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  __snake_case						):
					if not _run_remote_tests or _run_remote_tests == 0:
										_UpperCamelCase			     =     unittest.skip('''test requires remote'''						)(__snake_case						)
					return test_case
def 					_snake_case	(  *__snake_case						):
					def decorate(cls						):
										for name, fn in cls.__dict__.items():
															if callable(__snake_case						) and name.startswith('''test'''						):
																				for decorator in decorators:
																									_UpperCamelCase			     =     decorator(__snake_case						)
																				setattr(cls  ,     __snake_case  ,     __snake_case						)
										return cls

					return decorate
class     lowerCAmelCase_     (       __lowercase ):
							pass




class     lowerCAmelCase_     (       __lowercase ):
							UpperCAmelCase				   =     0
							UpperCAmelCase				   =     1
							UpperCAmelCase				   =     2




@contextmanager
def 					_snake_case	(  __snake_case=OfflineSimulationMode.CONNECTION_FAILS  ,     __snake_case=1E-16						):
					_UpperCamelCase			     =     requests.Session().request

					def timeout_request(__snake_case  ,     __snake_case  ,     __snake_case  ,     **__snake_case						):
										# 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(__snake_case  ,     __snake_case  ,     **__snake_case						)
										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(__snake_case  ,     __snake_case  ,     **__snake_case						):
										raise requests.ConnectionError('''Offline mode is enabled.'''  ,     request=__snake_case						)

					if mode is OfflineSimulationMode.CONNECTION_FAILS:
										with patch('''requests.Session.send'''  ,     __snake_case						):
															yield
					elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
										# inspired from https://stackoverflow.com/a/904609
										with patch('''requests.Session.request'''  ,     __snake_case						):
															yield
					elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
										with patch('''datasets.config.HF_DATASETS_OFFLINE'''  ,     __snake_case						):
															yield
					else:
										raise ValueError('''Please use a value from the OfflineSimulationMode enum.'''						)
@contextmanager
def 					_snake_case	(  *__snake_case  ,     **__snake_case						):
					_UpperCamelCase			     =     str(Path().resolve()						)
					with tempfile.TemporaryDirectory(*__snake_case  ,     **__snake_case						) as tmp_dir:
										try:
															os.chdir(__snake_case						)
															yield
										finally:
															os.chdir(__snake_case						)
@contextmanager
def 					_snake_case	(  ):
					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 					_snake_case	(  ):
					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 					_snake_case	(  __snake_case  ,     __snake_case						):
					return deepcopy(__snake_case						).integers(0  ,     100  ,     10						).tolist() == deepcopy(__snake_case						).integers(0  ,     100  ,     10						).tolist()
def 					_snake_case	(  __snake_case						):
					import decorator
					from requests.exceptions import HTTPError

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

					return decorator.decorator(_wrapper  ,     __snake_case						)
class     lowerCAmelCase_     :







							def __init__(   self      :     Any ,			_A      :     Dict ,			_A      :     str ,			_A      :     Any		):
												_UpperCamelCase			     =     returncode
												_UpperCamelCase			     =     stdout
												_UpperCamelCase			     =     stderr




async def 					_snake_case	(  __snake_case  ,     __snake_case						):
					while True:
										_UpperCamelCase			     =     await stream.readline()
										if line:
															callback(__snake_case						)
										else:
															break
async def 					_snake_case	(  __snake_case  ,     __snake_case=None  ,     __snake_case=None  ,     __snake_case=None  ,     __snake_case=False  ,     __snake_case=False						):
					if echo:
										print('''\nRunning: '''  ,     ''' '''.join(__snake_case						)						)

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

					# 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(__snake_case  ,     __snake_case  ,     __snake_case  ,     __snake_case=""						):
										_UpperCamelCase			     =     line.decode('''utf-8'''						).rstrip()
										sink.append(__snake_case						)
										if not quiet:
															print(__snake_case  ,     __snake_case  ,     file=__snake_case						)

    # XXX: the timeout doesn't seem to make any difference here
					await asyncio.wait(
					    [
					        _read_stream(p.stdout  ,     lambda __snake_case						: tee(__snake_case  ,     __snake_case  ,     sys.stdout  ,     label='''stdout:'''						)						),
					        _read_stream(p.stderr  ,     lambda __snake_case						: tee(__snake_case  ,     __snake_case  ,     sys.stderr  ,     label='''stderr:'''						)						),
					    ]  ,     timeout=__snake_case  ,     )
					return _RunOutput(await p.wait()  ,     __snake_case  ,     __snake_case						)
def 					_snake_case	(  __snake_case  ,     __snake_case=None  ,     __snake_case=None  ,     __snake_case=180  ,     __snake_case=False  ,     __snake_case=True						):
					_UpperCamelCase			     =     asyncio.get_event_loop()
					_UpperCamelCase			     =     loop.run_until_complete(
					    _stream_subprocess(__snake_case  ,     env=__snake_case  ,     stdin=__snake_case  ,     timeout=__snake_case  ,     quiet=__snake_case  ,     echo=__snake_case						)						)

					_UpperCamelCase			     =     ''' '''.join(__snake_case						)
					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 					_snake_case	(  ):
					_UpperCamelCase			     =     os.environ.get('''PYTEST_XDIST_WORKER'''  ,     '''gw0'''						)
					_UpperCamelCase			     =     re.sub(R'''^gw'''  ,     ''''''  ,     __snake_case  ,     0  ,     re.M						)
					return int(__snake_case						)







def 					_snake_case	(  ):
					_UpperCamelCase			     =     29500
					_UpperCamelCase			     =     pytest_xdist_worker_id()
					return port + uniq_delta

import os
import re
import shutil
import sys
import tempfile
import unittest

import black


_lowerCAmelCase       =		os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated.
_lowerCAmelCase       =		"    \"\"\"\n    Output class for the scheduler's step function output.\n\n    Args:\n        prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n            Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n            denoising loop.\n        pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n            The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n            `pred_original_sample` can be used to preview progress or for guidance.\n    \"\"\"\n\n    prev_sample: torch.FloatTensor\n    pred_original_sample: Optional[torch.FloatTensor] = None\n"
class     lowerCAmelCase_     (       unittest.TestCase ):







							def  UpperCamelCase_						(   self      :     List[Any]		):
												_UpperCamelCase			     =     tempfile.mkdtemp()
												os.makedirs(os.path.join(self.diffusers_dir ,			'''schedulers/'''		)		)
												_UpperCamelCase			     =     self.diffusers_dir
												shutil.copy(
												    os.path.join(_A ,			'''src/diffusers/schedulers/scheduling_ddpm.py'''		) ,			os.path.join(self.diffusers_dir ,			'''schedulers/scheduling_ddpm.py'''		) ,			)







							def  UpperCamelCase_						(   self      :     List[str]		):
												_UpperCamelCase			     =     '''src/diffusers'''
												shutil.rmtree(self.diffusers_dir		)







							def  UpperCamelCase_						(   self      :     str ,			_A      :     List[str] ,			_A      :     Optional[Any] ,			_A      :     List[str] ,			_A      :     Optional[int]=None		):
												_UpperCamelCase			     =     comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code
												if overwrite_result is not None:
																	_UpperCamelCase			     =     comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result
												_UpperCamelCase			     =     black.Mode(target_versions={black.TargetVersion.PYaa} ,			line_length=119		)
												_UpperCamelCase			     =     black.format_str(_A ,			mode=_A		)
												_UpperCamelCase			     =     os.path.join(self.diffusers_dir ,			'''new_code.py'''		)
												with open(_A ,			'''w''' ,			newline='''\n'''		) as f:
																	f.write(_A		)
												if overwrite_result is None:
																	self.assertTrue(len(check_copies.is_copy_consistent(_A		)		) == 0		)
												else:
																	check_copies.is_copy_consistent(f.name ,			overwrite=_A		)
																	with open(_A ,			'''r'''		) as f:
																						self.assertTrue(f.read() ,			_A		)







							def  UpperCamelCase_						(   self      :     Any		):
												_UpperCamelCase			     =     check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput'''		)
												self.assertEqual(_A ,			_A		)







							def  UpperCamelCase_						(   self      :     List[str]		):
												# Base copy consistency
												self.check_copy_consistency(
												    '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ,			'''DDPMSchedulerOutput''' ,			REFERENCE_CODE + '''\n''' ,			)

												# With no empty line at the end
												self.check_copy_consistency(
												    '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ,			'''DDPMSchedulerOutput''' ,			_A ,			)

												# Copy consistency with rename
												self.check_copy_consistency(
												    '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' ,			'''TestSchedulerOutput''' ,			re.sub('''DDPM''' ,			'''Test''' ,			_A		) ,			)

												# Copy consistency with a really long name
												_UpperCamelCase			     =     '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason'''
												self.check_copy_consistency(
												    F"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""" ,			F"""{long_class_name}SchedulerOutput""" ,			re.sub('''Bert''' ,			_A ,			_A		) ,			)

												# Copy consistency with overwrite
												self.check_copy_consistency(
												    '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' ,			'''TestSchedulerOutput''' ,			_A ,			overwrite_result=re.sub('''DDPM''' ,			'''Test''' ,			_A		) ,			)
