

"""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 					a__						(						lowerCAmelCase			,	lowerCAmelCase=False    )	-> str:
      try:
            UpperCAmelCase__			:							Union[str, Any]							=    os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            UpperCAmelCase__			:							List[str]							=    default
      else:
            # KEY is set, convert it to True or False.
            try:
                  UpperCAmelCase__			:							Optional[Any]							=    strtobool(lowerCAmelCase    )
            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 					a__						(						lowerCAmelCase    )	-> str:
      try:
            import faiss  # noqa
      except ImportError:
            UpperCAmelCase__			:							List[Any]							=    unittest.skip("""test requires faiss"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> List[Any]:
      try:
            import regex  # noqa
      except ImportError:
            UpperCAmelCase__			:							str							=    unittest.skip("""test requires regex"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> Union[str, Any]:
      try:
            import elasticsearch  # noqa
      except ImportError:
            UpperCAmelCase__			:							Tuple							=    unittest.skip("""test requires elasticsearch"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> Dict:
      try:
            import sqlalchemy  # noqa
      except ImportError:
            UpperCAmelCase__			:							str							=    unittest.skip("""test requires sqlalchemy"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> List[str]:
      if not config.TORCH_AVAILABLE:
            UpperCAmelCase__			:							Any							=    unittest.skip("""test requires PyTorch"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> Union[str, Any]:
      if not config.TF_AVAILABLE:
            UpperCAmelCase__			:							int							=    unittest.skip("""test requires TensorFlow"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> str:
      if not config.JAX_AVAILABLE:
            UpperCAmelCase__			:							Any							=    unittest.skip("""test requires JAX"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> int:
      if not config.PIL_AVAILABLE:
            UpperCAmelCase__			:							str							=    unittest.skip("""test requires Pillow"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> Any:
      try:
            import transformers  # noqa F401
      except ImportError:
            return unittest.skip("""test requires transformers"""    )(lowerCAmelCase    )
      else:
            return test_case




def 					a__						(						lowerCAmelCase    )	-> Union[str, Any]:
      try:
            import tiktoken  # noqa F401
      except ImportError:
            return unittest.skip("""test requires tiktoken"""    )(lowerCAmelCase    )
      else:
            return test_case




def 					a__						(						lowerCAmelCase    )	-> Dict:
      try:
            import spacy  # noqa F401
      except ImportError:
            return unittest.skip("""test requires spacy"""    )(lowerCAmelCase    )
      else:
            return test_case




def 					a__						(						lowerCAmelCase    )	-> List[str]:

      def _require_spacy_model(lowerCAmelCase    ):
            try:
                  import spacy  # noqa F401

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

      return _require_spacy_model




def 					a__						(						lowerCAmelCase    )	-> Optional[Any]:
      try:
            import pyspark  # noqa F401
      except ImportError:
            return unittest.skip("""test requires pyspark"""    )(lowerCAmelCase    )
      else:
            return test_case




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




def 					a__						(						lowerCAmelCase    )	-> Optional[int]:
      if not _run_slow_tests or _run_slow_tests == 0:
            UpperCAmelCase__			:							Union[str, Any]							=    unittest.skip("""test is slow"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> str:
      if not _run_local_tests or _run_local_tests == 0:
            UpperCAmelCase__			:							Union[str, Any]							=    unittest.skip("""test is local"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> Any:
      if not _run_packaged_tests or _run_packaged_tests == 0:
            UpperCAmelCase__			:							Union[str, Any]							=    unittest.skip("""test is packaged"""    )(lowerCAmelCase    )
      return test_case




def 					a__						(						lowerCAmelCase    )	-> Dict:
      if not _run_remote_tests or _run_remote_tests == 0:
            UpperCAmelCase__			:							Tuple							=    unittest.skip("""test requires remote"""    )(lowerCAmelCase    )
      return test_case




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

      return decorate

class       lowerCamelCase	(       lowerCAmelCase__   ):


  '''simple docstring'''







  pass




class       lowerCamelCase	(       lowerCAmelCase__   ):


  '''simple docstring'''







  SCREAMING_SNAKE_CASE					      =  0
  SCREAMING_SNAKE_CASE					      =  1
  SCREAMING_SNAKE_CASE					      =  2




@contextmanager
def 					a__						(						lowerCAmelCase=OfflineSimulationMode.CONNECTION_FAILS			,	lowerCAmelCase=1E-16    )	-> Dict:
      UpperCAmelCase__			:							str							=    requests.Session().request

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

      def raise_connection_error(lowerCAmelCase			,	lowerCAmelCase			,	**lowerCAmelCase    ):
            raise requests.ConnectionError("""Offline mode is enabled."""			,	request=lowerCAmelCase    )

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




@contextmanager
def 					a__						(						*lowerCAmelCase			,	**lowerCAmelCase    )	-> List[Any]:
      UpperCAmelCase__			:							Optional[Any]							=    str(Path().resolve()    )
      with tempfile.TemporaryDirectory(*lowerCAmelCase			,	**lowerCAmelCase    ) as tmp_dir:
            try:
                  os.chdir(lowerCAmelCase    )
                  yield
            finally:
                  os.chdir(lowerCAmelCase    )




@contextmanager
def 					a__						(						)	-> str:
      import gc

      gc.collect()
      UpperCAmelCase__			:							Union[str, Any]							=    pa.total_allocated_bytes()
      yield
      assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."




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

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




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




def 					a__						(						lowerCAmelCase    )	-> List[str]:
      import decorator
      from requests.exceptions import HTTPError

      def _wrapper(lowerCAmelCase			,	*lowerCAmelCase			,	**lowerCAmelCase    ):
            try:
                  return func(*lowerCAmelCase			,	**lowerCAmelCase    )
            except HTTPError as err:
                  if str(lowerCAmelCase    ).startswith("""500"""    ) or str(lowerCAmelCase    ).startswith("""502"""    ):
                        pytest.xfail(str(lowerCAmelCase    )    )
                  raise err

      return decorator.decorator(_wrapper			,	lowerCAmelCase    )

class       lowerCamelCase	:


  '''simple docstring'''







  def __init__(self							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	):


        """simple docstring"""

        UpperCAmelCase__			:							Tuple							=    returncode
        UpperCAmelCase__			:							Optional[int]							=    stdout
        UpperCAmelCase__			:							List[Any]							=    stderr




async def 					a__						(						lowerCAmelCase			,	lowerCAmelCase    )	-> Tuple:
      while True:
            UpperCAmelCase__			:							Optional[Any]							=    await stream.readline()
            if line:
                  callback(lowerCAmelCase    )
            else:
                  break




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

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

      # 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__			:							List[str]							=    []
      UpperCAmelCase__			:							Union[str, Any]							=    []

      def tee(lowerCAmelCase			,	lowerCAmelCase			,	lowerCAmelCase			,	lowerCAmelCase=""    ):
            UpperCAmelCase__			:							Optional[int]							=    line.decode("""utf-8"""    ).rstrip()
            sink.append(lowerCAmelCase    )
            if not quiet:
                  print(lowerCAmelCase			,	lowerCAmelCase			,	file=lowerCAmelCase    )

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




def 					a__						(						lowerCAmelCase			,	lowerCAmelCase=None			,	lowerCAmelCase=None			,	lowerCAmelCase=1_80			,	lowerCAmelCase=False			,	lowerCAmelCase=True    )	-> _RunOutput:
      UpperCAmelCase__			:							List[Any]							=    asyncio.get_event_loop()
      UpperCAmelCase__			:							Union[str, Any]							=    loop.run_until_complete(
          _stream_subprocess(lowerCAmelCase			,	env=lowerCAmelCase			,	stdin=lowerCAmelCase			,	timeout=lowerCAmelCase			,	quiet=lowerCAmelCase			,	echo=lowerCAmelCase    )    )

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





def 					a__						(						)	-> str:
      UpperCAmelCase__			:							List[str]							=    2_95_00
      UpperCAmelCase__			:							Dict							=    pytest_xdist_worker_id()
      return port + uniq_delta




"""simple docstring"""
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_A							=  {"""configuration_sew""": ["""SEW_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SEWConfig"""]}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _A							=  [
        """SEW_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """SEWForCTC""",
        """SEWForSequenceClassification""",
        """SEWModel""",
        """SEWPreTrainedModel""",
    ]

if TYPE_CHECKING:
    from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_sew import (
            SEW_PRETRAINED_MODEL_ARCHIVE_LIST,
            SEWForCTC,
            SEWForSequenceClassification,
            SEWModel,
            SEWPreTrainedModel,
        )


else:
    import sys

    _A							=  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

