



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__       (					__lowercase							,     __lowercase=False       )		->		Optional[int]:







						"""simple docstring"""

						try:
												A__	:							Any						    = os.environ[key]
						except KeyError:
												# KEY isn't set, default to `default`.
												A__	:							Dict						    = default
						else:
												# KEY is set, convert it to True or False.
												try:
																		A__	:							Any						    = strtobool(__lowercase       )
												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


snake_case    :						int  =						parse_flag_from_env('RUN_SLOW', default=False)
snake_case    :						int  =						parse_flag_from_env('RUN_REMOTE', default=False)
snake_case    :						str  =						parse_flag_from_env('RUN_LOCAL', default=True)
snake_case    :						str  =						parse_flag_from_env('RUN_PACKAGED', default=True)

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

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

# Windows
snake_case    :						Optional[Any]  =						pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)
def 	snake_case__       (					__lowercase       )		->		Dict:







						"""simple docstring"""

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







						"""simple docstring"""

						try:
												import regex  # noqa
						except ImportError:
												A__	:							Dict						    = unittest.skip("test requires regex"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		Dict:







						"""simple docstring"""

						try:
												import elasticsearch  # noqa
						except ImportError:
												A__	:							int						    = unittest.skip("test requires elasticsearch"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		int:







						"""simple docstring"""

						try:
												import sqlalchemy  # noqa
						except ImportError:
												A__	:							int						    = unittest.skip("test requires sqlalchemy"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		Union[str, Any]:







						"""simple docstring"""

						if not config.TORCH_AVAILABLE:
												A__	:							Optional[Any]						    = unittest.skip("test requires PyTorch"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		Optional[int]:







						"""simple docstring"""

						if not config.TF_AVAILABLE:
												A__	:							Dict						    = unittest.skip("test requires TensorFlow"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		Any:







						"""simple docstring"""

						if not config.JAX_AVAILABLE:
												A__	:							int						    = unittest.skip("test requires JAX"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		Optional[int]:







						"""simple docstring"""

						if not config.PIL_AVAILABLE:
												A__	:							Dict						    = unittest.skip("test requires Pillow"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		List[str]:







						"""simple docstring"""

						try:
												import transformers  # noqa F401
						except ImportError:
												return unittest.skip("test requires transformers"       )(__lowercase       )
						else:
												return test_case
def 	snake_case__       (					__lowercase       )		->		Tuple:







						"""simple docstring"""

						try:
												import tiktoken  # noqa F401
						except ImportError:
												return unittest.skip("test requires tiktoken"       )(__lowercase       )
						else:
												return test_case
def 	snake_case__       (					__lowercase       )		->		Dict:







						"""simple docstring"""

						try:
												import spacy  # noqa F401
						except ImportError:
												return unittest.skip("test requires spacy"       )(__lowercase       )
						else:
												return test_case
def 	snake_case__       (					__lowercase       )		->		Tuple:







						"""simple docstring"""

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

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

						return _require_spacy_model
def 	snake_case__       (					__lowercase       )		->		int:







						"""simple docstring"""

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







						"""simple docstring"""

						try:
												import joblibspark  # noqa F401
						except ImportError:
												return unittest.skip("test requires joblibspark"       )(__lowercase       )
						else:
												return test_case
def 	snake_case__       (					__lowercase       )		->		Tuple:







						"""simple docstring"""

						if not _run_slow_tests or _run_slow_tests == 0:
												A__	:							Tuple						    = unittest.skip("test is slow"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		Tuple:







						"""simple docstring"""

						if not _run_local_tests or _run_local_tests == 0:
												A__	:							Any						    = unittest.skip("test is local"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		str:







						"""simple docstring"""

						if not _run_packaged_tests or _run_packaged_tests == 0:
												A__	:							str						    = unittest.skip("test is packaged"       )(__lowercase       )
						return test_case
def 	snake_case__       (					__lowercase       )		->		Tuple:







						"""simple docstring"""

						if not _run_remote_tests or _run_remote_tests == 0:
												A__	:							Any						    = unittest.skip("test requires remote"       )(__lowercase       )
						return test_case
def 	snake_case__       (					*__lowercase       )		->		str:







						"""simple docstring"""

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

						return decorate




class 							lowerCAmelCase__  (	UpperCamelCase						):
					pass




class 							lowerCAmelCase__  (	UpperCamelCase						):
					__A     :    List[str]           =						0
					__A     :    Union[str, Any]           =						1
					__A     :    Union[str, Any]           =						2




@contextmanager
def 	snake_case__       (					__lowercase=OfflineSimulationMode.CONNECTION_FAILS							,     __lowercase=1E-16       )		->		List[Any]:







						"""simple docstring"""

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

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

						def raise_connection_error(__lowercase							,     __lowercase							,     **__lowercase       ):
												raise requests.ConnectionError("Offline mode is enabled."							,     request=__lowercase       )

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







						"""simple docstring"""

						A__	:							List[str]						    = str(Path().resolve()       )
						with tempfile.TemporaryDirectory(*__lowercase							,     **__lowercase       ) as tmp_dir:
												try:
																		os.chdir(__lowercase       )
																		yield
												finally:
																		os.chdir(__lowercase       )
@contextmanager
def 	snake_case__       (					)		->		Dict:







						"""simple docstring"""

						import gc

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







						"""simple docstring"""

						import gc

						gc.collect()
						A__	:							str						    = pa.total_allocated_bytes()
						yield
						assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."
def 	snake_case__       (					__lowercase							,     __lowercase       )		->		str:







						"""simple docstring"""

						return deepcopy(__lowercase       ).integers(0							,     1_0_0							,     1_0       ).tolist() == deepcopy(__lowercase       ).integers(0							,     1_0_0							,     1_0       ).tolist()
def 	snake_case__       (					__lowercase       )		->		str:







						"""simple docstring"""

						import decorator
						from requests.exceptions import HTTPError

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

						return decorator.decorator(_wrapper							,     __lowercase       )




class 							lowerCAmelCase__  :







					def __init__(       self      :     Dict			,		_A      :     Optional[Any]			,		_A      :     Tuple			,		_A      :     Optional[Any]):
											A__	:							int						    = returncode
											A__	:							Dict						    = stdout
											A__	:							Dict						    = stderr




async def 	snake_case__       (					__lowercase							,     __lowercase       )		->		str:







						"""simple docstring"""

						while True:
												A__	:							Any						    = await stream.readline()
												if line:
																		callback(__lowercase       )
												else:
																		break
async def 	snake_case__       (					__lowercase							,     __lowercase=None							,     __lowercase=None							,     __lowercase=None							,     __lowercase=False							,     __lowercase=False       )		->		_RunOutput:







						"""simple docstring"""

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

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

						# 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__	:							Optional[int]						    = []
						A__	:							Dict						    = []

						def tee(__lowercase							,     __lowercase							,     __lowercase							,     __lowercase=""       ):
												A__	:							Optional[int]						    = line.decode("utf-8"       ).rstrip()
												sink.append(__lowercase       )
												if not quiet:
																		print(__lowercase							,     __lowercase							,     file=__lowercase       )

    # XXX: the timeout doesn't seem to make any difference here
						await asyncio.wait(
						    [
						        _read_stream(p.stdout							,     lambda __lowercase       : tee(__lowercase							,     __lowercase							,     sys.stdout							,     label="stdout:"       )       ),
						        _read_stream(p.stderr							,     lambda __lowercase       : tee(__lowercase							,     __lowercase							,     sys.stderr							,     label="stderr:"       )       ),
						    ]							,     timeout=__lowercase							,     )
						return _RunOutput(await p.wait()							,     __lowercase							,     __lowercase       )
def 	snake_case__       (					__lowercase							,     __lowercase=None							,     __lowercase=None							,     __lowercase=1_8_0							,     __lowercase=False							,     __lowercase=True       )		->		_RunOutput:







						"""simple docstring"""

						A__	:							Dict						    = asyncio.get_event_loop()
						A__	:							List[str]						    = loop.run_until_complete(
						    _stream_subprocess(__lowercase							,     env=__lowercase							,     stdin=__lowercase							,     timeout=__lowercase							,     quiet=__lowercase							,     echo=__lowercase       )       )

						A__	:							Optional[Any]						    = " ".join(__lowercase       )
						if result.returncode > 0:
												A__	:							List[str]						    = "\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__       (					)		->		Optional[Any]:







						"""simple docstring"""

						A__	:							Optional[Any]						    = os.environ.get("PYTEST_XDIST_WORKER"							,     "gw0"       )
						A__	:							Union[str, Any]						    = re.sub(r"^gw"							,     ""							,     __lowercase							,     0							,     re.M       )
						return int(__lowercase       )




def 	snake_case__       (					)		->		str:







						"""simple docstring"""

						A__	:							Optional[Any]						    = 2_9_5_0_0
						A__	:							Optional[int]						    = pytest_xdist_worker_id()
						return port + uniq_delta





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


snake_case    :						str  =						{
    'configuration_albert': ['ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AlbertConfig', 'AlbertOnnxConfig'],
}

try:
		if not is_sentencepiece_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		snake_case    :						Any  =						['AlbertTokenizer']

try:
		if not is_tokenizers_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		snake_case    :						List[str]  =						['AlbertTokenizerFast']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		snake_case    :						List[str]  =						[
		    'ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'AlbertForMaskedLM',
		    'AlbertForMultipleChoice',
		    'AlbertForPreTraining',
		    'AlbertForQuestionAnswering',
		    'AlbertForSequenceClassification',
		    'AlbertForTokenClassification',
		    'AlbertModel',
		    'AlbertPreTrainedModel',
		    'load_tf_weights_in_albert',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		snake_case    :						Union[str, Any]  =						[
		    'TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'TFAlbertForMaskedLM',
		    'TFAlbertForMultipleChoice',
		    'TFAlbertForPreTraining',
		    'TFAlbertForQuestionAnswering',
		    'TFAlbertForSequenceClassification',
		    'TFAlbertForTokenClassification',
		    'TFAlbertMainLayer',
		    'TFAlbertModel',
		    'TFAlbertPreTrainedModel',
		]

try:
		if not is_flax_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		snake_case    :						Any  =						[
		    'FlaxAlbertForMaskedLM',
		    'FlaxAlbertForMultipleChoice',
		    'FlaxAlbertForPreTraining',
		    'FlaxAlbertForQuestionAnswering',
		    'FlaxAlbertForSequenceClassification',
		    'FlaxAlbertForTokenClassification',
		    'FlaxAlbertModel',
		    'FlaxAlbertPreTrainedModel',
		]

if TYPE_CHECKING:
		from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig

		try:
				if not is_sentencepiece_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .tokenization_albert import AlbertTokenizer

		try:
				if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .tokenization_albert_fast import AlbertTokenizerFast

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_albert import (
				    ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    AlbertForMaskedLM,
				    AlbertForMultipleChoice,
				    AlbertForPreTraining,
				    AlbertForQuestionAnswering,
				    AlbertForSequenceClassification,
				    AlbertForTokenClassification,
				    AlbertModel,
				    AlbertPreTrainedModel,
				    load_tf_weights_in_albert,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_albert import (
				    TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFAlbertForMaskedLM,
				    TFAlbertForMultipleChoice,
				    TFAlbertForPreTraining,
				    TFAlbertForQuestionAnswering,
				    TFAlbertForSequenceClassification,
				    TFAlbertForTokenClassification,
				    TFAlbertMainLayer,
				    TFAlbertModel,
				    TFAlbertPreTrainedModel,
				)

		try:
				if not is_flax_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_flax_albert import (
				    FlaxAlbertForMaskedLM,
				    FlaxAlbertForMultipleChoice,
				    FlaxAlbertForPreTraining,
				    FlaxAlbertForQuestionAnswering,
				    FlaxAlbertForSequenceClassification,
				    FlaxAlbertForTokenClassification,
				    FlaxAlbertModel,
				    FlaxAlbertPreTrainedModel,
				)
else:
		import sys

		snake_case    :						Any  =						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)