

'''simple docstring'''

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_    (	lowerCAmelCase_		,							lowerCAmelCase_=False							):

				"""simple docstring"""






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

# Compression
__lowerCamelCase : str											=			pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
__lowerCamelCase : Optional[Any]											=			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 : List[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
__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 : int											=			pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
__lowerCamelCase : Any											=			pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				try:
								import faiss  # noqa
				except ImportError:
								lowercase         = unittest.skip("test requires faiss"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				try:
								import regex  # noqa
				except ImportError:
								lowercase         = unittest.skip("test requires regex"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				try:
								import elasticsearch  # noqa
				except ImportError:
								lowercase         = unittest.skip("test requires elasticsearch"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				try:
								import sqlalchemy  # noqa
				except ImportError:
								lowercase         = unittest.skip("test requires sqlalchemy"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				if not config.TORCH_AVAILABLE:
								lowercase         = unittest.skip("test requires PyTorch"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				if not config.TF_AVAILABLE:
								lowercase         = unittest.skip("test requires TensorFlow"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				if not config.JAX_AVAILABLE:
								lowercase         = unittest.skip("test requires JAX"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				if not config.PIL_AVAILABLE:
								lowercase         = unittest.skip("test requires Pillow"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				def _require_spacy_model(lowerCAmelCase_							):
								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 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






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







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				if not _run_slow_tests or _run_slow_tests == 0:
								lowercase         = unittest.skip("test is slow"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				if not _run_local_tests or _run_local_tests == 0:
								lowercase         = unittest.skip("test is local"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				if not _run_packaged_tests or _run_packaged_tests == 0:
								lowercase         = unittest.skip("test is packaged"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				if not _run_remote_tests or _run_remote_tests == 0:
								lowercase         = unittest.skip("test requires remote"							)(snake_case__							)
				return test_case







def 							UpperCAmelCase_    (	*lowerCAmelCase_							):

				"""simple docstring"""






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

				return decorate

class       UpperCAmelCase (						_lowercase  ):
		pass




class       UpperCAmelCase (						_lowercase  ):
		UpperCAmelCase					:	List[str] 			=		0
		UpperCAmelCase					:	Dict 			=		1
		UpperCAmelCase					:	Any 			=		2







@contextmanager
def 							UpperCAmelCase_    (	lowerCAmelCase_=OfflineSimulationMode.CONNECTION_FAILS		,							lowerCAmelCase_=1E-1_6							):

				"""simple docstring"""






				lowercase         = requests.Session().request

				def timeout_request(lowerCAmelCase_		,							lowerCAmelCase_		,							lowerCAmelCase_		,							**lowerCAmelCase_							):
								# Change the url to an invalid url so that the connection hangs
								lowercase         = "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         = 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
												lowercase         = url
												lowercase         = e.args[0]
												lowercase         = (max_retry_error.args[0].replace("10.255.255.1"		,							f'OfflineMock[{url}]'							),)
												lowercase         = (max_retry_error,)
												raise

				def raise_connection_error(lowerCAmelCase_		,							lowerCAmelCase_		,							**lowerCAmelCase_							):
								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 							UpperCAmelCase_    (	*lowerCAmelCase_		,							**lowerCAmelCase_							):

				"""simple docstring"""






				lowercase         = 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 							UpperCAmelCase_    (	):

				"""simple docstring"""






				import gc

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







@contextmanager
def 							UpperCAmelCase_    (	):

				"""simple docstring"""






				import gc

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







def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_							):

				"""simple docstring"""






				return deepcopy(snake_case__							).integers(0		,							100		,							10							).tolist() == deepcopy(snake_case__							).integers(0		,							100		,							10							).tolist()







def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				import decorator
				from requests.exceptions import HTTPError

				def _wrapper(lowerCAmelCase_		,							*lowerCAmelCase_		,							**lowerCAmelCase_							):
								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       UpperCAmelCase :




		def __init__(self      :	Tuple							,			A__      :	Union[str, Any]							,			A__      :	int							,			A__      :	List[Any]				)					-> Any:
						lowercase         = returncode
						lowercase         = stdout
						lowercase         = stderr







async def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_							):

				"""simple docstring"""






				while True:
								lowercase         = await stream.readline()
								if line:
												callback(snake_case__							)
								else:
												break







async def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_=None		,							lowerCAmelCase_=None		,							lowerCAmelCase_=None		,							lowerCAmelCase_=False		,							lowerCAmelCase_=False							):

				"""simple docstring"""






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

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

				lowercase         = []
				lowercase         = []

				def tee(lowerCAmelCase_		,							lowerCAmelCase_		,							lowerCAmelCase_		,							lowerCAmelCase_=""							):
								lowercase         = 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 lowerCAmelCase_							: tee(snake_case__		,							snake_case__		,							sys.stdout		,							label="stdout:"							)							),
				        _read_stream(p.stderr		,							lambda lowerCAmelCase_							: tee(snake_case__		,							snake_case__		,							sys.stderr		,							label="stderr:"							)							),
				    ]		,							timeout=snake_case__		,							)
				return _RunOutput(await p.wait()		,							snake_case__		,							snake_case__							)







def 							UpperCAmelCase_    (	lowerCAmelCase_		,							lowerCAmelCase_=None		,							lowerCAmelCase_=None		,							lowerCAmelCase_=180		,							lowerCAmelCase_=False		,							lowerCAmelCase_=True							):

				"""simple docstring"""






				lowercase         = asyncio.get_event_loop()
				lowercase         = loop.run_until_complete(
				    _stream_subprocess(snake_case__		,							env=snake_case__		,							stdin=snake_case__		,							timeout=snake_case__		,							quiet=snake_case__		,							echo=snake_case__							)							)

				lowercase         = " ".join(snake_case__							)
				if result.returncode > 0:
								lowercase         = "\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_    (	):

				"""simple docstring"""






				lowercase         = os.environ.get("PYTEST_XDIST_WORKER"		,							"gw0"							)
				lowercase         = re.sub(R"^gw"		,							""		,							snake_case__		,							0		,							re.M							)
				return int(snake_case__							)







def 							UpperCAmelCase_    (	):

				"""simple docstring"""






				lowercase         = 2_9500
				lowercase         = pytest_xdist_worker_id()
				return port + uniq_delta











'''simple docstring'''

import warnings

from ...utils import logging
from .image_processing_clip import CLIPImageProcessor


__lowerCamelCase : Union[str, Any]											=			logging.get_logger(__name__)

class       UpperCAmelCase (						_lowercase  ):




		def __init__(self      :	Tuple							,			*A__      :	Union[str, Any]							,			**A__      :	Optional[Any]				)					-> None:
						warnings.warn(
						    "The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
						    " use CLIPImageProcessor instead."							,			A__							,			)
						super().__init__(*A__							,			**A__				)




