



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


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

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

# Audio
lowerCAmelCase__		:					int							=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__		:					Union[str, 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
lowerCAmelCase__		:					List[str]							=pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
lowerCAmelCase__		:					Optional[Any]							=pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)






def      __lowercase       (			a__       )    ->			Tuple:
							try:
														import faiss  # noqa
							except ImportError:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test requires faiss'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			Tuple:
							try:
														import regex  # noqa
							except ImportError:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test requires regex'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			Optional[int]:
							try:
														import elasticsearch  # noqa
							except ImportError:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test requires elasticsearch'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			Optional[int]:
							try:
														import sqlalchemy  # noqa
							except ImportError:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test requires sqlalchemy'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			Optional[int]:
							if not config.TORCH_AVAILABLE:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test requires PyTorch'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			Dict:
							if not config.TF_AVAILABLE:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test requires TensorFlow'       )(a__       )
							return test_case






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






def      __lowercase       (			a__       )    ->			Dict:
							if not config.PIL_AVAILABLE:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test requires Pillow'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			Dict:
							try:
														import transformers  # noqa F401
							except ImportError:
														return unittest.skip('test requires transformers'       )(a__       )
							else:
														return test_case






def      __lowercase       (			a__       )    ->			List[Any]:
							try:
														import tiktoken  # noqa F401
							except ImportError:
														return unittest.skip('test requires tiktoken'       )(a__       )
							else:
														return test_case






def      __lowercase       (			a__       )    ->			List[Any]:
							try:
														import spacy  # noqa F401
							except ImportError:
														return unittest.skip('test requires spacy'       )(a__       )
							else:
														return test_case






def      __lowercase       (			a__       )    ->			int:

							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      __lowercase       (			a__       )    ->			List[Any]:
							try:
														import pyspark  # noqa F401
							except ImportError:
														return unittest.skip('test requires pyspark'       )(a__       )
							else:
														return test_case






def      __lowercase       (			a__       )    ->			Dict:
							try:
														import joblibspark  # noqa F401
							except ImportError:
														return unittest.skip('test requires joblibspark'       )(a__       )
							else:
														return test_case






def      __lowercase       (			a__       )    ->			Union[str, Any]:
							if not _run_slow_tests or _run_slow_tests == 0:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test is slow'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			Dict:
							if not _run_local_tests or _run_local_tests == 0:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test is local'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			int:
							if not _run_packaged_tests or _run_packaged_tests == 0:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test is packaged'       )(a__       )
							return test_case






def      __lowercase       (			a__       )    ->			Any:
							if not _run_remote_tests or _run_remote_tests == 0:
														__SCREAMING_SNAKE_CASE									= unittest.skip('test requires remote'       )(a__       )
							return test_case






def      __lowercase       (			*a__       )    ->			Optional[int]:
							def decorate(cls       ):
														for name, fn in cls.__dict__.items():
																					if callable(a__       ) and name.startswith('test'       ):
																												for decorator in decorators:
																																			__SCREAMING_SNAKE_CASE									= decorator(a__       )
																												setattr(cls							,       a__							,       a__       )
														return cls

							return decorate

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						pass







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Optional[int]      =  0
						UpperCamelCase__      :			Any      =  1
						UpperCamelCase__      :			Tuple      =  2







@contextmanager
def      __lowercase       (			a__=OfflineSimulationMode.CONNECTION_FAILS							,       a__=1E-16       )    ->			Tuple:
							__SCREAMING_SNAKE_CASE									= requests.Session().request

							def timeout_request(a__							,       a__							,       a__							,       **a__       ):
														# Change the url to an invalid url so that the connection hangs
														__SCREAMING_SNAKE_CASE									= '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."""       )
														__SCREAMING_SNAKE_CASE									= 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
																					__SCREAMING_SNAKE_CASE									= url
																					__SCREAMING_SNAKE_CASE									= e.args[0]
																					__SCREAMING_SNAKE_CASE									= (max_retry_error.args[0].replace('10.255.255.1'							,       f"""OfflineMock[{url}]"""       ),)
																					__SCREAMING_SNAKE_CASE									= (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      __lowercase       (			*a__							,       **a__       )    ->			List[Any]:
							__SCREAMING_SNAKE_CASE									= str(Path().resolve()       )
							with tempfile.TemporaryDirectory(*a__							,       **a__       ) as tmp_dir:
														try:
																					os.chdir(a__       )
																					yield
														finally:
																					os.chdir(a__       )






@contextmanager
def      __lowercase       (			)    ->			List[Any]:
							import gc

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






@contextmanager
def      __lowercase       (			)    ->			List[str]:
							import gc

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






def      __lowercase       (			a__							,       a__       )    ->			int:
							return deepcopy(a__       ).integers(0							,       1_00							,       10       ).tolist() == deepcopy(a__       ).integers(0							,       1_00							,       10       ).tolist()






def      __lowercase       (			a__       )    ->			Any:
							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				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= returncode
													__SCREAMING_SNAKE_CASE									= stdout
													__SCREAMING_SNAKE_CASE									= stderr







async def      __lowercase       (			a__							,       a__       )    ->			Optional[int]:
							while True:
														__SCREAMING_SNAKE_CASE									= await stream.readline()
														if line:
																					callback(a__       )
														else:
																					break






async def      __lowercase       (			a__							,       a__=None							,       a__=None							,       a__=None							,       a__=False							,       a__=False       )    ->			_RunOutput:
							if echo:
														print('\nRunning: '							,       ' '.join(a__       )       )

							__SCREAMING_SNAKE_CASE									= 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)

							__SCREAMING_SNAKE_CASE									= []
							__SCREAMING_SNAKE_CASE									= []

							def tee(a__							,       a__							,       a__							,       a__=""       ):
														__SCREAMING_SNAKE_CASE									= 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      __lowercase       (			a__							,       a__=None							,       a__=None							,       a__=1_80							,       a__=False							,       a__=True       )    ->			_RunOutput:
							__SCREAMING_SNAKE_CASE									= asyncio.get_event_loop()
							__SCREAMING_SNAKE_CASE									= loop.run_until_complete(
							    _stream_subprocess(a__							,       env=a__							,       stdin=a__							,       timeout=a__							,       quiet=a__							,       echo=a__       )       )

							__SCREAMING_SNAKE_CASE									= ' '.join(a__       )
							if result.returncode > 0:
														__SCREAMING_SNAKE_CASE									= '\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      __lowercase       (			)    ->			Tuple:
							__SCREAMING_SNAKE_CASE									= os.environ.get('PYTEST_XDIST_WORKER'							,       'gw0'       )
							__SCREAMING_SNAKE_CASE									= re.sub(R'^gw'							,       ''							,       a__							,       0							,       re.M       )
							return int(a__       )






def      __lowercase       (			)    ->			int:
							__SCREAMING_SNAKE_CASE									= 2_95_00
							__SCREAMING_SNAKE_CASE									= pytest_xdist_worker_id()
							return port + uniq_delta











import multiprocessing
from typing import TYPE_CHECKING, Optional, Union

from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream


if TYPE_CHECKING:
			import sqlitea

			import sqlalchemy

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						def __init__(   self				,							_A				,							_A				,							_A = None				,							_A = None				,							_A = False				,							**_A				,							):







													'''simple docstring'''

													super().__init__(features=_A				,							cache_dir=_A				,							keep_in_memory=_A				,							**_A		)
													__SCREAMING_SNAKE_CASE									= Sql(
													    cache_dir=_A				,							features=_A				,							sql=_A				,							con=_A				,							**_A				,							)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None

													self.builder.download_and_prepare(
													    download_config=_A				,							download_mode=_A				,							verification_mode=_A				,							base_path=_A				,							)

													# Build dataset for splits
													__SCREAMING_SNAKE_CASE									= self.builder.as_dataset(
													    split='train'				,							verification_mode=_A				,							in_memory=self.keep_in_memory		)
													return dataset







class        UpperCAmelCase_  :

						'''simple docstring'''




						def __init__(   self				,							_A				,							_A				,							_A				,							_A = None				,							_A = None				,							**_A				,							):







													'''simple docstring'''

													if num_proc is not None and num_proc <= 0:
																				raise ValueError(f"""num_proc {num_proc} must be an integer > 0."""		)

													__SCREAMING_SNAKE_CASE									= dataset
													__SCREAMING_SNAKE_CASE									= name
													__SCREAMING_SNAKE_CASE									= con
													__SCREAMING_SNAKE_CASE									= batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
													__SCREAMING_SNAKE_CASE									= num_proc
													__SCREAMING_SNAKE_CASE									= to_sql_kwargs






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('sql'				,							_A		)
													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('con'				,							_A		)
													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('index'				,							_A		)

													__SCREAMING_SNAKE_CASE									= self._write(index=_A				,							**self.to_sql_kwargs		)
													return written






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= args
													__SCREAMING_SNAKE_CASE									= {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs
													__SCREAMING_SNAKE_CASE									= query_table(
													    table=self.dataset.data				,							key=slice(_A				,							offset + self.batch_size		)				,							indices=self.dataset._indices				,							)
													__SCREAMING_SNAKE_CASE									= batch.to_pandas()
													__SCREAMING_SNAKE_CASE									= df.to_sql(self.name				,							self.con				,							index=_A				,							**_A		)
													return num_rows or len(_A		)






						def 	_A     (   self				,							_A				,							**_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= 0

													if self.num_proc is None or self.num_proc == 1:
																				for offset in logging.tqdm(
																				    range(0				,							len(self.dataset		)				,							self.batch_size		)				,							unit='ba'				,							disable=not logging.is_progress_bar_enabled()				,							desc='Creating SQL from Arrow format'				,							):
																											written += self._batch_sql((offset, index, to_sql_kwargs)		)
													else:
																				__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= len(self.dataset		), self.batch_size
																				with multiprocessing.Pool(self.num_proc		) as pool:
																											for num_rows in logging.tqdm(
																											    pool.imap(
																											        self._batch_sql				,							[(offset, index, to_sql_kwargs) for offset in range(0				,							_A				,							_A		)]				,							)				,							total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size				,							unit='ba'				,							disable=not logging.is_progress_bar_enabled()				,							desc='Creating SQL from Arrow format'				,							):
																																		written += num_rows

													return written






