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


A			      =      parse_flag_from_env('RUN_SLOW', default=False)
A			      =      parse_flag_from_env('RUN_REMOTE', default=False)
A			      =      parse_flag_from_env('RUN_LOCAL', default=True)
A			      =      parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
A			      =      pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
A			      =      pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
A			      =      pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

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

# Windows
A			      =      pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[Any]):
				try:
								import faiss  # noqa
				except ImportError:
								lowerCamelCase					:			int									= unittest.skip('test requires faiss')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							Any):
				try:
								import regex  # noqa
				except ImportError:
								lowerCamelCase					:			List[Any]									= unittest.skip('test requires regex')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							str):
				try:
								import elasticsearch  # noqa
				except ImportError:
								lowerCamelCase					:			Any									= unittest.skip('test requires elasticsearch')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							Any):
				try:
								import sqlalchemy  # noqa
				except ImportError:
								lowerCamelCase					:			Dict									= unittest.skip('test requires sqlalchemy')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[Any]):
				if not config.TORCH_AVAILABLE:
								lowerCamelCase					:			int									= unittest.skip('test requires PyTorch')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							int):
				if not config.TF_AVAILABLE:
								lowerCamelCase					:			List[str]									= unittest.skip('test requires TensorFlow')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[Any]):
				if not config.JAX_AVAILABLE:
								lowerCamelCase					:			List[Any]									= unittest.skip('test requires JAX')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							Dict):
				if not config.PIL_AVAILABLE:
								lowerCamelCase					:			str									= unittest.skip('test requires Pillow')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							Union[str, Any]):
				try:
								import transformers  # noqa F401
				except ImportError:
								return unittest.skip('test requires transformers')(UpperCAmelCase__)
				else:
								return test_case





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





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





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[str]):

				def _require_spacy_model(UpperCAmelCase__							:							List[str]):
								try:
												import spacy  # noqa F401

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

				return _require_spacy_model





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[str]):
				try:
								import pyspark  # noqa F401
				except ImportError:
								return unittest.skip('test requires pyspark')(UpperCAmelCase__)
				else:
								return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							List[Any]):
				try:
								import joblibspark  # noqa F401
				except ImportError:
								return unittest.skip('test requires joblibspark')(UpperCAmelCase__)
				else:
								return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							Any):
				if not _run_slow_tests or _run_slow_tests == 0:
								lowerCamelCase					:			List[Any]									= unittest.skip('test is slow')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							Union[str, Any]):
				if not _run_local_tests or _run_local_tests == 0:
								lowerCamelCase					:			List[Any]									= unittest.skip('test is local')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							Dict):
				if not _run_packaged_tests or _run_packaged_tests == 0:
								lowerCamelCase					:			Optional[Any]									= unittest.skip('test is packaged')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  UpperCAmelCase__							:							str):
				if not _run_remote_tests or _run_remote_tests == 0:
								lowerCamelCase					:			List[str]									= unittest.skip('test requires remote')(UpperCAmelCase__)
				return test_case





def    UpperCAmelCase							(  *UpperCAmelCase__							:							str):
				def decorate(cls							:							Any):
								for name, fn in cls.__dict__.items():
												if callable(UpperCAmelCase__) and name.startswith('test'):
																for decorator in decorators:
																				lowerCamelCase					:			Optional[int]									= decorator(UpperCAmelCase__)
																setattr(cls       ,							UpperCAmelCase__       ,							UpperCAmelCase__)
								return cls

				return decorate




class     __snake_case		(   a__):
					pass





class     __snake_case		(   a__):
					_lowerCAmelCase			     =	0
					_lowerCAmelCase			     =	1
					_lowerCAmelCase			     =	2





@contextmanager
def    UpperCAmelCase							(  UpperCAmelCase__							:							Dict=OfflineSimulationMode.CONNECTION_FAILS       ,							UpperCAmelCase__							:							Any=1E-1_6):
				lowerCamelCase					:			List[str]									= requests.Session().request

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

				def raise_connection_error(UpperCAmelCase__							:							Union[str, Any]       ,							UpperCAmelCase__							:							Dict       ,							**UpperCAmelCase__							:							Tuple):
								raise requests.ConnectionError('Offline mode is enabled.'       ,							request=UpperCAmelCase__)

				if mode is OfflineSimulationMode.CONNECTION_FAILS:
								with patch('requests.Session.send'       ,							UpperCAmelCase__):
												yield
				elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
								# inspired from https://stackoverflow.com/a/904609
								with patch('requests.Session.request'       ,							UpperCAmelCase__):
												yield
				elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
								with patch('datasets.config.HF_DATASETS_OFFLINE'       ,							UpperCAmelCase__):
												yield
				else:
								raise ValueError('Please use a value from the OfflineSimulationMode enum.')





@contextmanager
def    UpperCAmelCase							(  *UpperCAmelCase__							:							List[str]       ,							**UpperCAmelCase__							:							Tuple):
				lowerCamelCase					:			int									= str(Path().resolve())
				with tempfile.TemporaryDirectory(*UpperCAmelCase__       ,							**UpperCAmelCase__) as tmp_dir:
								try:
												os.chdir(UpperCAmelCase__)
												yield
								finally:
												os.chdir(UpperCAmelCase__)





@contextmanager
def    UpperCAmelCase							(  ):
				import gc

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





@contextmanager
def    UpperCAmelCase							(  ):
				import gc

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





def    UpperCAmelCase							(  UpperCAmelCase__							:							Any       ,							UpperCAmelCase__							:							str):
				return deepcopy(UpperCAmelCase__).integers(0       ,							1_00       ,							10).tolist() == deepcopy(UpperCAmelCase__).integers(0       ,							1_00       ,							10).tolist()





def    UpperCAmelCase							(  UpperCAmelCase__							:							int):
				import decorator
				from requests.exceptions import HTTPError

				def _wrapper(UpperCAmelCase__							:							str       ,							*UpperCAmelCase__							:							Optional[int]       ,							**UpperCAmelCase__							:							Tuple):
								try:
												return func(*UpperCAmelCase__       ,							**UpperCAmelCase__)
								except HTTPError as err:
												if str(UpperCAmelCase__).startswith('500') or str(UpperCAmelCase__).startswith('502'):
																pytest.xfail(str(UpperCAmelCase__))
												raise err

				return decorator.decorator(_wrapper       ,							UpperCAmelCase__)




class     __snake_case		:
					def __init__(     self,    A,    A,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			Dict									= returncode
									lowerCamelCase					:			Tuple									= stdout
									lowerCamelCase					:			Tuple									= stderr





async def    UpperCAmelCase							(  UpperCAmelCase__							:							Optional[int]       ,							UpperCAmelCase__							:							str):
				while True:
								lowerCamelCase					:			List[str]									= await stream.readline()
								if line:
												callback(UpperCAmelCase__)
								else:
												break





async def    UpperCAmelCase							(  UpperCAmelCase__							:							str       ,							UpperCAmelCase__							:							List[str]=None       ,							UpperCAmelCase__							:							Union[str, Any]=None       ,							UpperCAmelCase__							:							Any=None       ,							UpperCAmelCase__							:							List[Any]=False       ,							UpperCAmelCase__							:							Tuple=False):
				if echo:
								print('\nRunning: '       ,							' '.join(UpperCAmelCase__))

				lowerCamelCase					:			List[Any]									= await asyncio.create_subprocess_exec(
				    cmd[0]       ,							*cmd[1:]       ,							stdin=UpperCAmelCase__       ,							stdout=asyncio.subprocess.PIPE       ,							stderr=asyncio.subprocess.PIPE       ,							env=UpperCAmelCase__       ,							)

				# 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)

				lowerCamelCase					:			Tuple									= []
				lowerCamelCase					:			List[str]									= []

				def tee(UpperCAmelCase__							:							Union[str, Any]       ,							UpperCAmelCase__							:							Union[str, Any]       ,							UpperCAmelCase__							:							Optional[Any]       ,							UpperCAmelCase__							:							Dict=""):
								lowerCamelCase					:			int									= line.decode('utf-8').rstrip()
								sink.append(UpperCAmelCase__)
								if not quiet:
												print(UpperCAmelCase__       ,							UpperCAmelCase__       ,							file=UpperCAmelCase__)

    # XXX: the timeout doesn't seem to make any difference here
				await asyncio.wait(
				    [
				        _read_stream(p.stdout       ,							lambda UpperCAmelCase__: tee(UpperCAmelCase__       ,							UpperCAmelCase__       ,							sys.stdout       ,							label='stdout:')),
				        _read_stream(p.stderr       ,							lambda UpperCAmelCase__: tee(UpperCAmelCase__       ,							UpperCAmelCase__       ,							sys.stderr       ,							label='stderr:')),
				    ]       ,							timeout=UpperCAmelCase__       ,							)
				return _RunOutput(await p.wait()       ,							UpperCAmelCase__       ,							UpperCAmelCase__)





def    UpperCAmelCase							(  UpperCAmelCase__							:							str       ,							UpperCAmelCase__							:							Dict=None       ,							UpperCAmelCase__							:							Union[str, Any]=None       ,							UpperCAmelCase__							:							Union[str, Any]=1_80       ,							UpperCAmelCase__							:							Union[str, Any]=False       ,							UpperCAmelCase__							:							List[Any]=True):
				lowerCamelCase					:			List[Any]									= asyncio.get_event_loop()
				lowerCamelCase					:			int									= loop.run_until_complete(
				    _stream_subprocess(UpperCAmelCase__       ,							env=UpperCAmelCase__       ,							stdin=UpperCAmelCase__       ,							timeout=UpperCAmelCase__       ,							quiet=UpperCAmelCase__       ,							echo=UpperCAmelCase__))

				lowerCamelCase					:			Optional[int]									= ' '.join(UpperCAmelCase__)
				if result.returncode > 0:
								lowerCamelCase					:			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    UpperCAmelCase							(  ):
				lowerCamelCase					:			List[str]									= os.environ.get('PYTEST_XDIST_WORKER'       ,							'gw0')
				lowerCamelCase					:			Union[str, Any]									= re.sub(R'^gw'       ,							''       ,							UpperCAmelCase__       ,							0       ,							re.M)
				return int(UpperCAmelCase__)





def    UpperCAmelCase							(  ):
				lowerCamelCase					:			List[Any]									= 2_95_00
				lowerCamelCase					:			str									= pytest_xdist_worker_id()
				return port + uniq_delta

'''simple docstring'''






from typing import TYPE_CHECKING

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


A			      =      {
    'configuration_clip': [
        'CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'CLIPConfig',
        'CLIPOnnxConfig',
        'CLIPTextConfig',
        'CLIPVisionConfig',
    ],
    'processing_clip': ['CLIPProcessor'],
    'tokenization_clip': ['CLIPTokenizer'],
}

try:
					if not is_tokenizers_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					A			      =      ['CLIPTokenizerFast']

try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					A			      =      ['CLIPFeatureExtractor']
					A			      =      ['CLIPImageProcessor']

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					A			      =      [
					    'CLIP_PRETRAINED_MODEL_ARCHIVE_LIST',
					    'CLIPModel',
					    'CLIPPreTrainedModel',
					    'CLIPTextModel',
					    'CLIPTextModelWithProjection',
					    'CLIPVisionModel',
					    'CLIPVisionModelWithProjection',
					]

try:
					if not is_tf_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					A			      =      [
					    'TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST',
					    'TFCLIPModel',
					    'TFCLIPPreTrainedModel',
					    'TFCLIPTextModel',
					    'TFCLIPVisionModel',
					]

try:
					if not is_flax_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					A			      =      [
					    'FlaxCLIPModel',
					    'FlaxCLIPPreTrainedModel',
					    'FlaxCLIPTextModel',
					    'FlaxCLIPTextPreTrainedModel',
					    'FlaxCLIPVisionModel',
					    'FlaxCLIPVisionPreTrainedModel',
					]


if TYPE_CHECKING:
					from .configuration_clip import (
					    CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
					    CLIPConfig,
					    CLIPOnnxConfig,
					    CLIPTextConfig,
					    CLIPVisionConfig,
					)
					from .processing_clip import CLIPProcessor
					from .tokenization_clip import CLIPTokenizer

					try:
										if not is_tokenizers_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .tokenization_clip_fast import CLIPTokenizerFast

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .feature_extraction_clip import CLIPFeatureExtractor
										from .image_processing_clip import CLIPImageProcessor

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_clip import (
										    CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
										    CLIPModel,
										    CLIPPreTrainedModel,
										    CLIPTextModel,
										    CLIPTextModelWithProjection,
										    CLIPVisionModel,
										    CLIPVisionModelWithProjection,
										)

					try:
										if not is_tf_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_tf_clip import (
										    TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
										    TFCLIPModel,
										    TFCLIPPreTrainedModel,
										    TFCLIPTextModel,
										    TFCLIPVisionModel,
										)

					try:
										if not is_flax_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_flax_clip import (
										    FlaxCLIPModel,
										    FlaxCLIPPreTrainedModel,
										    FlaxCLIPTextModel,
										    FlaxCLIPTextPreTrainedModel,
										    FlaxCLIPVisionModel,
										    FlaxCLIPVisionPreTrainedModel,
										)


else:
					import sys

					A			      =      _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
