






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   (_snake_case				:       int      ,    _snake_case				:       Any=False)					->	int:
   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


_SCREAMING_SNAKE_CASE   =  parse_flag_from_env("RUN_SLOW", default=False)
_SCREAMING_SNAKE_CASE   =  parse_flag_from_env("RUN_REMOTE", default=False)
_SCREAMING_SNAKE_CASE   =  parse_flag_from_env("RUN_LOCAL", default=True)
_SCREAMING_SNAKE_CASE   =  parse_flag_from_env("RUN_PACKAGED", default=True)

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

# Audio
_SCREAMING_SNAKE_CASE   =  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   =  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   =  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   =  pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)





def        _snake_case   (_snake_case				:       Optional[Any])					->	Any:
   try:
      import faiss  # noqa
   except ImportError:
      _lowercase              =unittest.skip('test requires faiss')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       Optional[int])					->	Dict:
   try:
      import regex  # noqa
   except ImportError:
      _lowercase              =unittest.skip('test requires regex')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       Optional[int])					->	List[str]:
   try:
      import elasticsearch  # noqa
   except ImportError:
      _lowercase              =unittest.skip('test requires elasticsearch')(_snake_case)
   return test_case





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





def        _snake_case   (_snake_case				:       List[str])					->	Any:
   if not config.TORCH_AVAILABLE:
      _lowercase              =unittest.skip('test requires PyTorch')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       List[str])					->	str:
   if not config.TF_AVAILABLE:
      _lowercase              =unittest.skip('test requires TensorFlow')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       int)					->	str:
   if not config.JAX_AVAILABLE:
      _lowercase              =unittest.skip('test requires JAX')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       Tuple)					->	Any:
   if not config.PIL_AVAILABLE:
      _lowercase              =unittest.skip('test requires Pillow')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       Optional[Any])					->	int:
   try:
      import transformers  # noqa F401
   except ImportError:
      return unittest.skip('test requires transformers')(_snake_case)
   else:
      return test_case





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





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





def        _snake_case   (_snake_case				:       int)					->	Tuple:

   def _require_spacy_model(_snake_case				:       Tuple):
      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        _snake_case   (_snake_case				:       Any)					->	int:
   try:
      import pyspark  # noqa F401
   except ImportError:
      return unittest.skip('test requires pyspark')(_snake_case)
   else:
      return test_case





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





def        _snake_case   (_snake_case				:       Dict)					->	Dict:
   if not _run_slow_tests or _run_slow_tests == 0:
      _lowercase              =unittest.skip('test is slow')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       Union[str, Any])					->	Dict:
   if not _run_local_tests or _run_local_tests == 0:
      _lowercase              =unittest.skip('test is local')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       int)					->	Dict:
   if not _run_packaged_tests or _run_packaged_tests == 0:
      _lowercase              =unittest.skip('test is packaged')(_snake_case)
   return test_case





def        _snake_case   (_snake_case				:       Dict)					->	Any:
   if not _run_remote_tests or _run_remote_tests == 0:
      _lowercase              =unittest.skip('test requires remote')(_snake_case)
   return test_case





def        _snake_case   (*_snake_case				:       Union[str, Any])					->	Any:
   def decorate(cls				:       Union[str, Any]):
      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 					SCREAMING_SNAKE_CASE_  (       _a ):
       """simple docstring"""


       pass






class 					SCREAMING_SNAKE_CASE_  (       _a ):
       """simple docstring"""


       __lowerCAmelCase    :		int					=0
       __lowerCAmelCase    :		List[Any]					=1
       __lowerCAmelCase    :		int					=2





@contextmanager
def        _snake_case   (_snake_case				:       Optional[int]=OfflineSimulationMode.CONNECTION_FAILS      ,    _snake_case				:       Dict=1E-16)					->	Union[str, Any]:
   _lowercase              =requests.Session().request

   def timeout_request(_snake_case				:       int      ,    _snake_case				:       List[Any]      ,    _snake_case				:       Dict      ,    **_snake_case				:       List[str]):
      # 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(_snake_case				:       str      ,    _snake_case				:       Optional[int]      ,    **_snake_case				:       List[str]):
      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        _snake_case   (*_snake_case				:       Optional[int]      ,    **_snake_case				:       Optional[Any])					->	Optional[Any]:
   _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        _snake_case   ()					->	Optional[Any]:
   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        _snake_case   ()					->	Optional[int]:
   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        _snake_case   (_snake_case				:       Union[str, Any]      ,    _snake_case				:       List[str])					->	Tuple:
   return deepcopy(_snake_case).integers(0      ,    100      ,    10).tolist() == deepcopy(_snake_case).integers(0      ,    100      ,    10).tolist()





def        _snake_case   (_snake_case				:       Union[str, Any])					->	Optional[Any]:
   import decorator
   from requests.exceptions import HTTPError

   def _wrapper(_snake_case				:       List[Any]      ,    *_snake_case				:       Any      ,    **_snake_case				:       Any):
      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 					SCREAMING_SNAKE_CASE_  :
       """simple docstring"""


       def __init__(				self	:Optional[int],      snake_case	:List[Any],      snake_case	:Tuple,      snake_case	:str):



          """simple docstring"""

          _lowercase              =returncode
          _lowercase              =stdout
          _lowercase              =stderr





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





async def        _snake_case   (_snake_case				:       Optional[int]      ,    _snake_case				:       Optional[int]=None      ,    _snake_case				:       Union[str, Any]=None      ,    _snake_case				:       int=None      ,    _snake_case				:       Optional[int]=False      ,    _snake_case				:       Tuple=False)					->	_RunOutput:
   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(_snake_case				:       Tuple      ,    _snake_case				:       str      ,    _snake_case				:       Union[str, Any]      ,    _snake_case				:       Dict=""):
      _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 _snake_case: tee(_snake_case      ,    _snake_case      ,    sys.stdout      ,    label='stdout:')),
           _read_stream(p.stderr      ,    lambda _snake_case: tee(_snake_case      ,    _snake_case      ,    sys.stderr      ,    label='stderr:')),
       ]      ,    timeout=_snake_case      ,    )
   return _RunOutput(await p.wait()      ,    _snake_case      ,    _snake_case)





def        _snake_case   (_snake_case				:       List[str]      ,    _snake_case				:       int=None      ,    _snake_case				:       Dict=None      ,    _snake_case				:       Tuple=180      ,    _snake_case				:       List[Any]=False      ,    _snake_case				:       Any=True)					->	_RunOutput:
   _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        _snake_case   ()					->	Tuple:
   _lowercase              =os.environ.get('PYTEST_XDIST_WORKER'      ,    'gw0')
   _lowercase              =re.sub(R'^gw'      ,    ''      ,    _snake_case      ,    0      ,    re.M)
   return int(_snake_case)





def        _snake_case   ()					->	Tuple:
   _lowercase              =2_9500
   _lowercase              =pytest_xdist_worker_id()
   return port + uniq_delta










from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import BaseOutput, is_torch_available, is_transformers_available






@dataclass
class 					SCREAMING_SNAKE_CASE_  (       _a ):
       """simple docstring"""


       __lowerCAmelCase    :		Union[List[PIL.Image.Image], np.ndarray]
       __lowerCAmelCase    :		Optional[List[bool]]


if is_transformers_available() and is_torch_available():
    from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline


