




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




 """simple docstring"""







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

# Compression
_lowerCAmelCase  :      Optional[Any]						=      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[Any]						=      pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
_lowerCAmelCase  :      Tuple						=      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  :      Dict						=      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   lowerCAmelCase						(						_lowerCAmelCase							:      List[Any]		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      List[Any]		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      List[str]		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      str		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      int		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      str		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      Any		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      Union[str, Any]		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      Optional[Any]		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      str		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      str		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      List[Any]		):




 """simple docstring"""







 def _require_spacy_model(_lowerCAmelCase							:      Tuple		):
  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   lowerCAmelCase						(						_lowerCAmelCase							:      int		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      Any		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      str		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      Optional[Any]		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      Optional[int]		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      Union[str, Any]		):




 """simple docstring"""







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



def   lowerCAmelCase						(						*_lowerCAmelCase							:      List[Any]		):




 """simple docstring"""







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

 return decorate
class 	_UpperCamelCase					( _A						):
      pass



class 	_UpperCamelCase					( _A						):
      UpperCAmelCase_						=						0
      UpperCAmelCase_						=						1
      UpperCAmelCase_						=						2



@contextmanager
def   lowerCAmelCase						(						_lowerCAmelCase							:      Tuple=OfflineSimulationMode.CONNECTION_FAILS  ,							_lowerCAmelCase							:      List[str]=1E-16		):




 """simple docstring"""







 UpperCAmelCase__							       =  requests.Session().request

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

 def raise_connection_error(_lowerCAmelCase							:      Optional[int]  ,							_lowerCAmelCase							:      Tuple  ,							**_lowerCAmelCase							:      Union[str, Any]		):
  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   lowerCAmelCase						(						*_lowerCAmelCase							:      Optional[int]  ,							**_lowerCAmelCase							:      str		):




 """simple docstring"""







 UpperCAmelCase__							       =  str(Path().resolve()		)
 with tempfile.TemporaryDirectory(*A_  ,							**A_		) as tmp_dir:
  try:
   os.chdir(A_		)
   yield
  finally:
   os.chdir(A_		)



@contextmanager
def   lowerCAmelCase						(						):




 """simple docstring"""







 import gc

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



@contextmanager
def   lowerCAmelCase						(						):




 """simple docstring"""







 import gc

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



def   lowerCAmelCase						(						_lowerCAmelCase							:      Optional[Any]  ,							_lowerCAmelCase							:      Tuple		):




 """simple docstring"""







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



def   lowerCAmelCase						(						_lowerCAmelCase							:      List[Any]		):




 """simple docstring"""







 import decorator
 from requests.exceptions import HTTPError

 def _wrapper(_lowerCAmelCase							:      Tuple  ,							*_lowerCAmelCase							:      Dict  ,							**_lowerCAmelCase							:      Union[str, Any]		):
  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					:
      def __init__(	self      :Optional[Any]       ,					lowerCamelCase      :int       ,					lowerCamelCase      :Dict       ,					lowerCamelCase      :Optional[Any]					)   ->	int:
       UpperCAmelCase__							       =  returncode
       UpperCAmelCase__							       =  stdout
       UpperCAmelCase__							       =  stderr



async def   lowerCAmelCase						(						_lowerCAmelCase							:      Any  ,							_lowerCAmelCase							:      int		):




 """simple docstring"""







 while True:
  UpperCAmelCase__							       =  await stream.readline()
  if line:
   callback(A_		)
  else:
   break



async def   lowerCAmelCase						(						_lowerCAmelCase							:      Union[str, Any]  ,							_lowerCAmelCase							:      Optional[Any]=None  ,							_lowerCAmelCase							:      Union[str, Any]=None  ,							_lowerCAmelCase							:      Union[str, Any]=None  ,							_lowerCAmelCase							:      Any=False  ,							_lowerCAmelCase							:      Union[str, Any]=False		):




 """simple docstring"""







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

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

 UpperCAmelCase__							       =  []
 UpperCAmelCase__							       =  []

 def tee(_lowerCAmelCase							:      Tuple  ,							_lowerCAmelCase							:      Optional[int]  ,							_lowerCAmelCase							:      Dict  ,							_lowerCAmelCase							:      List[Any]=""		):
  UpperCAmelCase__							       =  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 _lowerCAmelCase		: tee(A_  ,							A_  ,							sys.stdout  ,							label="stdout:"		)		),
         _read_stream(p.stderr  ,							lambda _lowerCAmelCase		: tee(A_  ,							A_  ,							sys.stderr  ,							label="stderr:"		)		),
     ]  ,							timeout=A_  ,							)
 return _RunOutput(await p.wait()  ,							A_  ,							A_		)



def   lowerCAmelCase						(						_lowerCAmelCase							:      str  ,							_lowerCAmelCase							:      Tuple=None  ,							_lowerCAmelCase							:      List[Any]=None  ,							_lowerCAmelCase							:      Dict=180  ,							_lowerCAmelCase							:      Dict=False  ,							_lowerCAmelCase							:      Any=True		):




 """simple docstring"""







 UpperCAmelCase__							       =  asyncio.get_event_loop()
 UpperCAmelCase__							       =  loop.run_until_complete(
     _stream_subprocess(A_  ,							env=A_  ,							stdin=A_  ,							timeout=A_  ,							quiet=A_  ,							echo=A_		)		)

 UpperCAmelCase__							       =  " ".join(A_		)
 if result.returncode > 0:
  UpperCAmelCase__							       =  "\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   lowerCAmelCase						(						):




 """simple docstring"""







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



def   lowerCAmelCase						(						):




 """simple docstring"""







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







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available


__lowerCAmelCase			:     List[str]           =   {
    'configuration_xlm': ['XLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMConfig', 'XLMOnnxConfig'],
    'tokenization_xlm': ['XLMTokenizer'],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowerCAmelCase			:     str           =   [
        'XLM_PRETRAINED_MODEL_ARCHIVE_LIST',
        'XLMForMultipleChoice',
        'XLMForQuestionAnswering',
        'XLMForQuestionAnsweringSimple',
        'XLMForSequenceClassification',
        'XLMForTokenClassification',
        'XLMModel',
        'XLMPreTrainedModel',
        'XLMWithLMHeadModel',
    ]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowerCAmelCase			:     Dict           =   [
        'TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST',
        'TFXLMForMultipleChoice',
        'TFXLMForQuestionAnsweringSimple',
        'TFXLMForSequenceClassification',
        'TFXLMForTokenClassification',
        'TFXLMMainLayer',
        'TFXLMModel',
        'TFXLMPreTrainedModel',
        'TFXLMWithLMHeadModel',
    ]


if TYPE_CHECKING:
    from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig
    from .tokenization_xlm import XLMTokenizer

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_xlm import (
            XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
            XLMForMultipleChoice,
            XLMForQuestionAnswering,
            XLMForQuestionAnsweringSimple,
            XLMForSequenceClassification,
            XLMForTokenClassification,
            XLMModel,
            XLMPreTrainedModel,
            XLMWithLMHeadModel,
        )

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_xlm import (
            TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
            TFXLMForMultipleChoice,
            TFXLMForQuestionAnsweringSimple,
            TFXLMForSequenceClassification,
            TFXLMForTokenClassification,
            TFXLMMainLayer,
            TFXLMModel,
            TFXLMPreTrainedModel,
            TFXLMWithLMHeadModel,
        )

else:
    import sys

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

