


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						(				_a:     List[str]		,   _a:     Optional[Any]=False							)->		int:
      '''simple docstring'''


      try:
            lowerCamelCase__           =		os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            lowerCamelCase__           =		default
      else:
            # KEY is set, convert it to True or False.
            try:
                  lowerCamelCase__           =		strtobool(_SCREAMING_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


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

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

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

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



def   snake_case						(				_a:     Optional[int]							)->		List[Any]:
      '''simple docstring'''


      try:
            import faiss  # noqa
      except ImportError:
            lowerCamelCase__           =		unittest.skip('test requires faiss'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     Optional[int]							)->		List[str]:
      '''simple docstring'''


      try:
            import regex  # noqa
      except ImportError:
            lowerCamelCase__           =		unittest.skip('test requires regex'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     int							)->		str:
      '''simple docstring'''


      try:
            import elasticsearch  # noqa
      except ImportError:
            lowerCamelCase__           =		unittest.skip('test requires elasticsearch'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     Dict							)->		Dict:
      '''simple docstring'''


      try:
            import sqlalchemy  # noqa
      except ImportError:
            lowerCamelCase__           =		unittest.skip('test requires sqlalchemy'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     Optional[Any]							)->		Optional[int]:
      '''simple docstring'''


      if not config.TORCH_AVAILABLE:
            lowerCamelCase__           =		unittest.skip('test requires PyTorch'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     List[Any]							)->		Dict:
      '''simple docstring'''


      if not config.TF_AVAILABLE:
            lowerCamelCase__           =		unittest.skip('test requires TensorFlow'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     List[Any]							)->		Optional[int]:
      '''simple docstring'''


      if not config.JAX_AVAILABLE:
            lowerCamelCase__           =		unittest.skip('test requires JAX'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     Optional[Any]							)->		str:
      '''simple docstring'''


      if not config.PIL_AVAILABLE:
            lowerCamelCase__           =		unittest.skip('test requires Pillow'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     Tuple							)->		int:
      '''simple docstring'''


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



def   snake_case						(				_a:     Optional[Any]							)->		List[str]:
      '''simple docstring'''


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



def   snake_case						(				_a:     Optional[Any]							)->		Any:
      '''simple docstring'''


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



def   snake_case						(				_a:     Optional[int]							)->		Dict:
      '''simple docstring'''


      def _require_spacy_model(_a:     Dict							):
            try:
                  import spacy  # noqa F401

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

      return _require_spacy_model



def   snake_case						(				_a:     Tuple							)->		List[Any]:
      '''simple docstring'''


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



def   snake_case						(				_a:     Tuple							)->		int:
      '''simple docstring'''


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



def   snake_case						(				_a:     str							)->		Optional[Any]:
      '''simple docstring'''


      if not _run_slow_tests or _run_slow_tests == 0:
            lowerCamelCase__           =		unittest.skip('test is slow'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     Optional[int]							)->		Tuple:
      '''simple docstring'''


      if not _run_local_tests or _run_local_tests == 0:
            lowerCamelCase__           =		unittest.skip('test is local'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     str							)->		List[str]:
      '''simple docstring'''


      if not _run_packaged_tests or _run_packaged_tests == 0:
            lowerCamelCase__           =		unittest.skip('test is packaged'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				_a:     Union[str, Any]							)->		Optional[int]:
      '''simple docstring'''


      if not _run_remote_tests or _run_remote_tests == 0:
            lowerCamelCase__           =		unittest.skip('test requires remote'							)(_SCREAMING_SNAKE_CASE							)
      return test_case



def   snake_case						(				*_a:     Tuple							)->		Tuple:
      '''simple docstring'''


      def decorate(cls:     str							):
            for name, fn in cls.__dict__.items():
                  if callable(_SCREAMING_SNAKE_CASE							) and name.startswith('test'							):
                        for decorator in decorators:
                              lowerCamelCase__           =		decorator(_SCREAMING_SNAKE_CASE							)
                        setattr(cls		,   _SCREAMING_SNAKE_CASE		,   _SCREAMING_SNAKE_CASE							)
            return cls

      return decorate



class   _a      (      SCREAMING_SNAKE_CASE_ ):
    pass





class   _a      (      SCREAMING_SNAKE_CASE_ ):
    a_    :				List[Any]             =    0
    a_    :				Any             =    1
    a_    :				Optional[Any]             =    2





@contextmanager
def   snake_case						(				_a:     Optional[int]=OfflineSimulationMode.CONNECTION_FAILS		,   _a:     int=1E-16							)->		Tuple:
      '''simple docstring'''


      lowerCamelCase__           =		requests.Session().request

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

      def raise_connection_error(_a:     Optional[Any]		,   _a:     Dict		,   **_a:     str							):
            raise requests.ConnectionError('Offline mode is enabled.'		,   request=_SCREAMING_SNAKE_CASE							)

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



@contextmanager
def   snake_case						(				*_a:     Union[str, Any]		,   **_a:     Dict							)->		Dict:
      '''simple docstring'''


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



@contextmanager
def   snake_case						(				)->		str:
      '''simple docstring'''


      import gc

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



@contextmanager
def   snake_case						(				)->		Tuple:
      '''simple docstring'''


      import gc

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



def   snake_case						(				_a:     List[Any]		,   _a:     Union[str, Any]							)->		Dict:
      '''simple docstring'''


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



def   snake_case						(				_a:     List[Any]							)->		List[str]:
      '''simple docstring'''


      import decorator
      from requests.exceptions import HTTPError

      def _wrapper(_a:     Union[str, Any]		,   *_a:     Any		,   **_a:     Dict							):
            try:
                  return func(*_SCREAMING_SNAKE_CASE		,   **_SCREAMING_SNAKE_CASE							)
            except HTTPError as err:
                  if str(_SCREAMING_SNAKE_CASE							).startswith('500'							) or str(_SCREAMING_SNAKE_CASE							).startswith('502'							):
                        pytest.xfail(str(_SCREAMING_SNAKE_CASE							)							)
                  raise err

      return decorator.decorator(_wrapper		,   _SCREAMING_SNAKE_CASE							)



class   _a      :
    def __init__( self							:					List[str]							,					SCREAMING_SNAKE_CASE__							:					List[Any]							,					SCREAMING_SNAKE_CASE__							:					Any							,					SCREAMING_SNAKE_CASE__							:					Optional[int]				):
          lowerCamelCase__           =		returncode
          lowerCamelCase__           =		stdout
          lowerCamelCase__           =		stderr





async def   snake_case						(				_a:     Any		,   _a:     Optional[Any]							)->		List[Any]:
      '''simple docstring'''


      while True:
            lowerCamelCase__           =		await stream.readline()
            if line:
                  callback(_SCREAMING_SNAKE_CASE							)
            else:
                  break



async def   snake_case						(				_a:     str		,   _a:     Dict=None		,   _a:     int=None		,   _a:     Any=None		,   _a:     int=False		,   _a:     Any=False							)->		_RunOutput:
      '''simple docstring'''


      if echo:
            print('\nRunning: '		,   ' '.join(_SCREAMING_SNAKE_CASE							)							)

      lowerCamelCase__           =		await asyncio.create_subprocess_exec(
          cmd[0]		,   *cmd[1:]		,   stdin=_SCREAMING_SNAKE_CASE		,   stdout=asyncio.subprocess.PIPE		,   stderr=asyncio.subprocess.PIPE		,   env=_SCREAMING_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)

      lowerCamelCase__           =		[]
      lowerCamelCase__           =		[]

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

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



def   snake_case						(				_a:     Optional[int]		,   _a:     Optional[Any]=None		,   _a:     Tuple=None		,   _a:     List[Any]=180		,   _a:     List[str]=False		,   _a:     List[str]=True							)->		_RunOutput:
      '''simple docstring'''


      lowerCamelCase__           =		asyncio.get_event_loop()
      lowerCamelCase__           =		loop.run_until_complete(
          _stream_subprocess(_SCREAMING_SNAKE_CASE		,   env=_SCREAMING_SNAKE_CASE		,   stdin=_SCREAMING_SNAKE_CASE		,   timeout=_SCREAMING_SNAKE_CASE		,   quiet=_SCREAMING_SNAKE_CASE		,   echo=_SCREAMING_SNAKE_CASE							)							)

      lowerCamelCase__           =		' '.join(_SCREAMING_SNAKE_CASE							)
      if result.returncode > 0:
            lowerCamelCase__           =		'\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						(				)->		List[str]:
      '''simple docstring'''


      lowerCamelCase__           =		os.environ.get('PYTEST_XDIST_WORKER'		,   'gw0'							)
      lowerCamelCase__           =		re.sub(R'^gw'		,   ''		,   _SCREAMING_SNAKE_CASE		,   0		,   re.M							)
      return int(_SCREAMING_SNAKE_CASE							)






def   snake_case						(				)->		Optional[int]:
      '''simple docstring'''


      lowerCamelCase__           =		29500
      lowerCamelCase__           =		pytest_xdist_worker_id()
      return port + uniq_delta







"""simple docstring"""


from typing import TYPE_CHECKING

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


_snake_case          =							{
    "configuration_m2m_100": ["M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP", "M2M100Config", "M2M100OnnxConfig"],
    "tokenization_m2m_100": ["M2M100Tokenizer"],
}


try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _snake_case          =							[
       "M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST",
       "M2M100ForConditionalGeneration",
       "M2M100Model",
       "M2M100PreTrainedModel",
   ]


if TYPE_CHECKING:
   from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig
   from .tokenization_mam_aaa import MaMaaaTokenizer

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_mam_aaa import (
          M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST,
          MaMaaaForConditionalGeneration,
          MaMaaaModel,
          MaMaaaPreTrainedModel,
      )


else:
   import sys

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



