

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							(				lowerCAmelCase:  Tuple  ,      lowerCAmelCase:  List[str]=False )   ->       List[Any]:


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


SCREAMING_SNAKE_CASE_     :   List[Any]        =      parse_flag_from_env('RUN_SLOW', default=False)
SCREAMING_SNAKE_CASE_     :   Optional[int]        =      parse_flag_from_env('RUN_REMOTE', default=False)
SCREAMING_SNAKE_CASE_     :   Dict        =      parse_flag_from_env('RUN_LOCAL', default=True)
SCREAMING_SNAKE_CASE_     :   int        =      parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
SCREAMING_SNAKE_CASE_     :   List[Any]        =      pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
SCREAMING_SNAKE_CASE_     :   int        =      pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
SCREAMING_SNAKE_CASE_     :   str        =      pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

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

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Optional[Any] )   ->       str:


				try:
								import faiss  # noqa
				except ImportError:
								_UpperCAmelCase       :		List[Any] 		=    unittest.skip("test requires faiss" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  List[Any] )   ->       str:


				try:
								import regex  # noqa
				except ImportError:
								_UpperCAmelCase       :		str 		=    unittest.skip("test requires regex" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  List[str] )   ->       List[str]:


				try:
								import elasticsearch  # noqa
				except ImportError:
								_UpperCAmelCase       :		List[Any] 		=    unittest.skip("test requires elasticsearch" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Optional[int] )   ->       List[Any]:


				try:
								import sqlalchemy  # noqa
				except ImportError:
								_UpperCAmelCase       :		Any 		=    unittest.skip("test requires sqlalchemy" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  str )   ->       List[Any]:


				if not config.TORCH_AVAILABLE:
								_UpperCAmelCase       :		Dict 		=    unittest.skip("test requires PyTorch" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Tuple )   ->       List[Any]:


				if not config.TF_AVAILABLE:
								_UpperCAmelCase       :		int 		=    unittest.skip("test requires TensorFlow" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Optional[Any] )   ->       str:


				if not config.JAX_AVAILABLE:
								_UpperCAmelCase       :		Dict 		=    unittest.skip("test requires JAX" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  str )   ->       Union[str, Any]:


				if not config.PIL_AVAILABLE:
								_UpperCAmelCase       :		int 		=    unittest.skip("test requires Pillow" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Union[str, Any] )   ->       List[Any]:


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

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Optional[int] )   ->       List[Any]:


				try:
								import tiktoken  # noqa F401
				except ImportError:
								return unittest.skip("test requires tiktoken" )(lowerCAmelCase )
				else:
								return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Any )   ->       List[Any]:


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

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Any )   ->       Union[str, Any]:


				def _require_spacy_model(lowerCAmelCase:  Dict ):
								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 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  str )   ->       Optional[Any]:


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

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Optional[int] )   ->       List[str]:


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

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  List[str] )   ->       Union[str, Any]:


				if not _run_slow_tests or _run_slow_tests == 0:
								_UpperCAmelCase       :		Tuple 		=    unittest.skip("test is slow" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  List[Any] )   ->       Tuple:


				if not _run_local_tests or _run_local_tests == 0:
								_UpperCAmelCase       :		Optional[Any] 		=    unittest.skip("test is local" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Dict )   ->       str:


				if not _run_packaged_tests or _run_packaged_tests == 0:
								_UpperCAmelCase       :		Union[str, Any] 		=    unittest.skip("test is packaged" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  List[Any] )   ->       List[Any]:


				if not _run_remote_tests or _run_remote_tests == 0:
								_UpperCAmelCase       :		List[Any] 		=    unittest.skip("test requires remote" )(lowerCAmelCase )
				return test_case

def 							__SCREAMING_SNAKE_CASE							(				*lowerCAmelCase:  List[Any] )   ->       Optional[Any]:


				def decorate(cls:  Tuple ):
								for name, fn in cls.__dict__.items():
												if callable(lowerCAmelCase ) and name.startswith("test" ):
																for decorator in decorators:
																				_UpperCAmelCase       :		Tuple 		=    decorator(lowerCAmelCase )
																setattr(cls  ,      lowerCAmelCase  ,      lowerCAmelCase )
								return cls

				return decorate

class 				a  (	UpperCAmelCase				):
						pass







class 				a  (	UpperCAmelCase				):
						_lowercase    						=			0
						_lowercase    						=			1
						_lowercase    						=			2







@contextmanager
def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Optional[Any]=OfflineSimulationMode.CONNECTION_FAILS  ,      lowerCAmelCase:  Optional[int]=1E-16 )   ->       Tuple:
				_UpperCAmelCase       :		Dict 		=    requests.Session().request

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

				def raise_connection_error(lowerCAmelCase:  Dict  ,      lowerCAmelCase:  int  ,      **lowerCAmelCase:  Optional[int] ):
								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 							__SCREAMING_SNAKE_CASE							(				*lowerCAmelCase:  List[str]  ,      **lowerCAmelCase:  Optional[Any] )   ->       Dict:
				_UpperCAmelCase       :		Any 		=    str(Path().resolve() )
				with tempfile.TemporaryDirectory(*lowerCAmelCase  ,      **lowerCAmelCase ) as tmp_dir:
								try:
												os.chdir(lowerCAmelCase )
												yield
								finally:
												os.chdir(lowerCAmelCase )

@contextmanager
def 							__SCREAMING_SNAKE_CASE							(				)   ->       Optional[Any]:
				import gc

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

@contextmanager
def 							__SCREAMING_SNAKE_CASE							(				)   ->       Union[str, Any]:
				import gc

				gc.collect()
				_UpperCAmelCase       :		List[Any] 		=    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							(				lowerCAmelCase:  Optional[Any]  ,      lowerCAmelCase:  str )   ->       Optional[Any]:
				return deepcopy(lowerCAmelCase ).integers(0  ,      100  ,      10 ).tolist() == deepcopy(lowerCAmelCase ).integers(0  ,      100  ,      10 ).tolist()

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  int )   ->       str:
				import decorator
				from requests.exceptions import HTTPError

				def _wrapper(lowerCAmelCase:  str  ,      *lowerCAmelCase:  Dict  ,      **lowerCAmelCase:  List[str] ):
								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 				a  :


						def __init__(       self						,					A_						,					A_						,					A_	):







										'''simple docstring'''


										_UpperCAmelCase       :		Union[str, Any] 		=    returncode
										_UpperCAmelCase       :		Any 		=    stdout
										_UpperCAmelCase       :		Dict 		=    stderr







async def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  List[str]  ,      lowerCAmelCase:  int )   ->       Union[str, Any]:


				while True:
								_UpperCAmelCase       :		int 		=    await stream.readline()
								if line:
												callback(lowerCAmelCase )
								else:
												break

async def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  str  ,      lowerCAmelCase:  Tuple=None  ,      lowerCAmelCase:  List[str]=None  ,      lowerCAmelCase:  Dict=None  ,      lowerCAmelCase:  int=False  ,      lowerCAmelCase:  Dict=False )   ->       Dict:


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

				_UpperCAmelCase       :		List[str] 		=    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       :		Any 		=    []
				_UpperCAmelCase       :		Dict 		=    []

				def tee(lowerCAmelCase:  Optional[int]  ,      lowerCAmelCase:  Optional[Any]  ,      lowerCAmelCase:  Optional[int]  ,      lowerCAmelCase:  Optional[Any]="" ):
								_UpperCAmelCase       :		List[str] 		=    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 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  Tuple  ,      lowerCAmelCase:  Any=None  ,      lowerCAmelCase:  Dict=None  ,      lowerCAmelCase:  Optional[int]=180  ,      lowerCAmelCase:  str=False  ,      lowerCAmelCase:  Dict=True )   ->       int:
				_UpperCAmelCase       :		int 		=    asyncio.get_event_loop()
				_UpperCAmelCase       :		Optional[int] 		=    loop.run_until_complete(
				    _stream_subprocess(lowerCAmelCase  ,      env=lowerCAmelCase  ,      stdin=lowerCAmelCase  ,      timeout=lowerCAmelCase  ,      quiet=lowerCAmelCase  ,      echo=lowerCAmelCase ) )

				_UpperCAmelCase       :		Any 		=    " ".join(lowerCAmelCase )
				if result.returncode > 0:
								_UpperCAmelCase       :		Dict 		=    "\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							(				)   ->       int:
				_UpperCAmelCase       :		Optional[int] 		=    os.environ.get("PYTEST_XDIST_WORKER"  ,      "gw0" )
				_UpperCAmelCase       :		Dict 		=    re.sub(R"^gw"  ,      ""  ,      lowerCAmelCase  ,      0  ,      re.M )
				return int(lowerCAmelCase )





def 							__SCREAMING_SNAKE_CASE							(				)   ->       Optional[Any]:
				_UpperCAmelCase       :		Union[str, Any] 		=    2_9500
				_UpperCAmelCase       :		Optional[int] 		=    pytest_xdist_worker_id()
				return port + uniq_delta





from ...configuration_utils import PretrainedConfig
from ...utils import logging


SCREAMING_SNAKE_CASE_        =      logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_        =      {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/config.json'}

class 				a  (	UpperCAmelCase				):
						_lowercase    						=			"openai-gpt"
						_lowercase    						=			{
						    "max_position_embeddings": "n_positions",
						    "hidden_size": "n_embd",
						    "num_attention_heads": "n_head",
						    "num_hidden_layers": "n_layer",
						}


						def __init__(       self						,					A_=40478						,					A_=512						,					A_=768						,					A_=12						,					A_=12						,					A_="gelu"						,					A_=0.1						,					A_=0.1						,					A_=0.1						,					A_=1e-5						,					A_=0.02						,					A_="cls_index"						,					A_=True						,					A_=None						,					A_=True						,					A_=0.1						,					**A_						,					):







										'''simple docstring'''


										_UpperCAmelCase       :		Any 		=    vocab_size
										_UpperCAmelCase       :		str 		=    n_positions
										_UpperCAmelCase       :		List[Any] 		=    n_embd
										_UpperCAmelCase       :		Dict 		=    n_layer
										_UpperCAmelCase       :		Any 		=    n_head
										_UpperCAmelCase       :		int 		=    afn
										_UpperCAmelCase       :		int 		=    resid_pdrop
										_UpperCAmelCase       :		Tuple 		=    embd_pdrop
										_UpperCAmelCase       :		Optional[Any] 		=    attn_pdrop
										_UpperCAmelCase       :		Any 		=    layer_norm_epsilon
										_UpperCAmelCase       :		List[str] 		=    initializer_range
										_UpperCAmelCase       :		Union[str, Any] 		=    summary_type
										_UpperCAmelCase       :		List[Any] 		=    summary_use_proj
										_UpperCAmelCase       :		Optional[Any] 		=    summary_activation
										_UpperCAmelCase       :		int 		=    summary_first_dropout
										_UpperCAmelCase       :		List[str] 		=    summary_proj_to_labels
										super().__init__(**A_	)


