


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       ,		_a=False		)					->							Optional[int]:
     '''simple docstring'''





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

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

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




def     UpperCamelCase    (      _a		)					->							Tuple:
     '''simple docstring'''





     try:
          import faiss  # noqa
     except ImportError:
          lowercase_       :List[Any]     =       unittest.skip('''test requires faiss'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Optional[Any]:
     '''simple docstring'''





     try:
          import regex  # noqa
     except ImportError:
          lowercase_       :Optional[Any]     =       unittest.skip('''test requires regex'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Union[str, Any]:
     '''simple docstring'''





     try:
          import elasticsearch  # noqa
     except ImportError:
          lowercase_       :Optional[int]     =       unittest.skip('''test requires elasticsearch'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Any:
     '''simple docstring'''





     try:
          import sqlalchemy  # noqa
     except ImportError:
          lowercase_       :Optional[Any]     =       unittest.skip('''test requires sqlalchemy'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							List[str]:
     '''simple docstring'''





     if not config.TORCH_AVAILABLE:
          lowercase_       :List[Any]     =       unittest.skip('''test requires PyTorch'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Tuple:
     '''simple docstring'''





     if not config.TF_AVAILABLE:
          lowercase_       :int     =       unittest.skip('''test requires TensorFlow'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Any:
     '''simple docstring'''





     if not config.JAX_AVAILABLE:
          lowercase_       :str     =       unittest.skip('''test requires JAX'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							str:
     '''simple docstring'''





     if not config.PIL_AVAILABLE:
          lowercase_       :Tuple     =       unittest.skip('''test requires Pillow'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Optional[Any]:
     '''simple docstring'''





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




def     UpperCamelCase    (      _a		)					->							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		)					->							str:
     '''simple docstring'''





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




def     UpperCamelCase    (      _a		)					->							Optional[Any]:
     '''simple docstring'''





     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     UpperCamelCase    (      _a		)					->							Optional[int]:
     '''simple docstring'''





     try:
          import pyspark  # noqa F401
     except ImportError:
          return unittest.skip('''test requires pyspark'''		)(_a		)
     else:
          return test_case




def     UpperCamelCase    (      _a		)					->							int:
     '''simple docstring'''





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




def     UpperCamelCase    (      _a		)					->							str:
     '''simple docstring'''





     if not _run_slow_tests or _run_slow_tests == 0:
          lowercase_       :Dict     =       unittest.skip('''test is slow'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Optional[Any]:
     '''simple docstring'''





     if not _run_local_tests or _run_local_tests == 0:
          lowercase_       :Optional[Any]     =       unittest.skip('''test is local'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Any:
     '''simple docstring'''





     if not _run_packaged_tests or _run_packaged_tests == 0:
          lowercase_       :List[str]     =       unittest.skip('''test is packaged'''		)(_a		)
     return test_case




def     UpperCamelCase    (      _a		)					->							Optional[Any]:
     '''simple docstring'''





     if not _run_remote_tests or _run_remote_tests == 0:
          lowercase_       :List[str]     =       unittest.skip('''test requires remote'''		)(_a		)
     return test_case




def     UpperCamelCase    (      *_a		)					->							List[Any]:
     '''simple docstring'''





     def decorate(cls		):
          for name, fn in cls.__dict__.items():
               if callable(_a		) and name.startswith('''test'''		):
                    for decorator in decorators:
                         lowercase_       :List[str]     =       decorator(_a		)
                    setattr(cls       ,		_a       ,		_a		)
          return cls

     return decorate






class      UpperCamelCase					(		lowercase__     ):


   '''simple docstring'''







   pass






class      UpperCamelCase					(		lowercase__     ):


   '''simple docstring'''







   lowercase					:	List[str]									=0
   lowercase					:	Tuple									=1
   lowercase					:	int									=2




@contextmanager
def     UpperCamelCase    (      _a=OfflineSimulationMode.CONNECTION_FAILS       ,		_a=1E-16		)					->							Any:
     '''simple docstring'''





     lowercase_       :Optional[int]     =       requests.Session().request

     def timeout_request(_a       ,		_a       ,		_a       ,		**_a		):
          # Change the url to an invalid url so that the connection hangs
          lowercase_       :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."		)
          lowercase_       :Union[str, 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
               lowercase_       :Optional[Any]     =       url
               lowercase_       :str     =       e.args[0]
               lowercase_       :Dict     =       (max_retry_error.args[0].replace('''10.255.255.1'''       ,		f"OfflineMock[{url}]"		),)
               lowercase_       :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     UpperCamelCase    (      *_a       ,		**_a		)					->							Tuple:
     '''simple docstring'''





     lowercase_       :Tuple     =       str(Path().resolve()		)
     with tempfile.TemporaryDirectory(*_a       ,		**_a		) as tmp_dir:
          try:
               os.chdir(_a		)
               yield
          finally:
               os.chdir(_a		)




@contextmanager
def     UpperCamelCase    (      )					->							Union[str, Any]:
     '''simple docstring'''





     import gc

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




@contextmanager
def     UpperCamelCase    (      )					->							Any:
     '''simple docstring'''





     import gc

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




def     UpperCamelCase    (      _a       ,		_a		)					->							Tuple:
     '''simple docstring'''





     return deepcopy(_a		).integers(0       ,		1_0_0       ,		1_0		).tolist() == deepcopy(_a		).integers(0       ,		1_0_0       ,		1_0		).tolist()




def     UpperCamelCase    (      _a		)					->							Dict:
     '''simple docstring'''





     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      UpperCamelCase					:


   '''simple docstring'''







   def __init__(     self   ,							UpperCamelCase_   ,							UpperCamelCase_   ,							UpperCamelCase_		):
        lowercase_       :str     =       returncode
        lowercase_       :Dict     =       stdout
        lowercase_       :int     =       stderr




async def     UpperCamelCase    (      _a       ,		_a		)					->							str:
     '''simple docstring'''





     while True:
          lowercase_       :Optional[Any]     =       await stream.readline()
          if line:
               callback(_a		)
          else:
               break




async def     UpperCamelCase    (      _a       ,		_a=None       ,		_a=None       ,		_a=None       ,		_a=False       ,		_a=False		)					->							_RunOutput:
     '''simple docstring'''





     if echo:
          print('''\nRunning: '''       ,		''' '''.join(_a		)		)

     lowercase_       :Union[str, 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)

     lowercase_       :Tuple     =       []
     lowercase_       :Dict     =       []

     def tee(_a       ,		_a       ,		_a       ,		_a=""		):
          lowercase_       :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     UpperCamelCase    (      _a       ,		_a=None       ,		_a=None       ,		_a=1_8_0       ,		_a=False       ,		_a=True		)					->							_RunOutput:
     '''simple docstring'''





     lowercase_       :Optional[int]     =       asyncio.get_event_loop()
     lowercase_       :Optional[int]     =       loop.run_until_complete(
         _stream_subprocess(_a       ,		env=_a       ,		stdin=_a       ,		timeout=_a       ,		quiet=_a       ,		echo=_a		)		)

     lowercase_       :str     =       ''' '''.join(_a		)
     if result.returncode > 0:
          lowercase_       :Tuple     =       '''\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    (      )					->							List[str]:
     '''simple docstring'''





     lowercase_       :str     =       os.environ.get('''PYTEST_XDIST_WORKER'''       ,		'''gw0'''		)
     lowercase_       :Any     =       re.sub(R'''^gw'''       ,		''''''       ,		_a       ,		0       ,		re.M		)
     return int(_a		)




def     UpperCamelCase    (      )					->							Tuple:
     '''simple docstring'''





     lowercase_       :List[str]     =       2_9_5_0_0
     lowercase_       :List[str]     =       pytest_xdist_worker_id()
     return port + uniq_delta





def     UpperCamelCase    (      _a		)					->							int:
     '''simple docstring'''





     assert isinstance(_a       ,		_a		), f"The input value of [n={number}] is not an integer"

     if number == 1:
          return 2
     elif number < 1:
          lowercase_       :str     =       f"The input value of [n={number}] has to be > 0"
          raise ValueError(_a		)
     else:
          lowercase_       :List[str]     =       sylvester(number - 1		)
          lowercase_       :Union[str, Any]     =       num - 1
          lowercase_       :List[str]     =       num
          return lower * upper + 1


if __name__ == "__main__":
   print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")

